
    _Mh                     R   d Z dZg dZddlZddlm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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%m&Z&m'Z' ddl(Z( G d dee          Z)d Z*d Z+d Z,d Z-ddZ.d Z/ G d de)e          Z0 G d dee)          Z1dS )z2 A sparse matrix in COOrdinate or 'triplet' formatzrestructuredtext en)	coo_array
coo_matrixisspmatrix_coo    N)warn   )copy_if_needed   )spmatrix)	coo_tocsrcoo_todensecoo_todense_nd
coo_matveccoo_matvec_ndcoo_matmat_densecoo_matmat_dense_nd)issparseSparseEfficiencyWarning_spbasesparray)_data_matrix_minmax_mixin)upcast_char	to_nativeisshapegetdtypegetdatadowncast_intp_indexget_index_dtypecheck_shapecheck_reshape_kwargsisscalarlikeisdensec                      e Zd ZdZ edd          Zd2dddZed             Zej	        d	             Zed
             Z
e
j	        d             Z
d Zej        j        e_        d3dZej        j        e_        d3dZej        j        e_        d Zd4dZej        j        e_        d5dZej        j        e_        d6dZej        j        e_        d7dZd7dZd7dZd7dZej        j        e_        d7dZej        j        e_        d7dZej        j        e_        d8dZej        j        e_        d Zd9dZd5dZd  Zd! Z d" Z!d# Z"d$ Z#d% Z$d& Z%d' Z&d( Z'd) Z(d* Z)d+ Z*d:d-Z+d. Z,d/ Z-d0 Z.d7d1Z/dS );	_coo_basecoor	   A   NFmaxprintc                p	   t          j        | ||           st          t          |t                    rt          || j                  rt          || j                  | _        | 	                    t          | j                            t          |t                    }t	          fdt          t          | j                            D                       | _        t!          j        g |          | _        d| _        n[	 |\  }}n)# t(          t*          f$ r}	t)          d          |	d }	~	ww xY w|At-          d	 |D                       rt+          d
          t	          d |D                       }t          || j                  | _        | 	                    |t          | j                  d          t	          fd|D                       | _        t1          ||          | _        d| _        nbt3          |          r|j        | j        k    rr~t	          d |j        D                       | _        |j                            t          ||                    | _        t          |j        | j                  | _        |j        | _        n|                                }
t	          |
j                  | _        |
j                            t          ||
          d          | _        t          |
j        | j                  | _        d| _        n=t!          j        |          }t          | t<                    s7t!          j        |          }|j         dk    rt)          d|j          d          t          |j        | j                  | _        |;t          || j                  | j        k    rd| d| j         }t+          |          | 	                    t          | j                            |!                                }t	          fd|D                       | _        t1          ||         |          | _        d| _        t          | j                  dk    r#t	          d | j        D                       | _        | "                                 d S )Nr'   allow_ndmaxval)defaultc              3   D   K   | ]}t          j        g            V  dS dtypeNnparray).0_	idx_dtypes     Q/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/sparse/_coo.py	<genexpr>z%_coo_base.__init__.<locals>.<genexpr>(   sN       $G $G)* %'HRy$A$A$A $G $G $G $G $G $G    r1   Tzinvalid input formatc              3   <   K   | ]}t          |          d k    V  dS )r   Nlenr6   idxs     r9   r:   z%_coo_base.__init__.<locals>.<genexpr>3   s,      ;;S3s88q=;;;;;;r;   z4cannot infer dimensions from zero sized index arraysc              3   h   K   | ]-}t          j        t          j        |                    d z   V  .dS r	   N)operatorindexr4   maxr?   s     r9   r:   z%_coo_base.__init__.<locals>.<genexpr>6   sM       "5 "5&) #+."="="A "5 "5 "5 "5 "5 "5r;   )r-   check_contentsc              3   F   K   | ]}t          j        |           V  dS )copyr2   Nr3   )r6   r@   rI   r8   s     r9   r:   z%_coo_base.__init__.<locals>.<genexpr><   sH       $8 $8), %'HSt9$M$M$M $8 $8 $8 $8 $8 $8r;   rH   Fc              3   >   K   | ]}|                                 V  d S NrI   r?   s     r9   r:   z%_coo_base.__init__.<locals>.<genexpr>C   s*      'J'Js

'J'J'J'J'J'Jr;   rL   r   z!expected 2D array or matrix, not Dzinconsistent shapes: z != c              3   F   K   | ]}|                     d           V  dS FrL   N)astype)r6   r@   index_dtypes     r9   r:   z%_coo_base.__init__.<locals>.<genexpr>]   sG       $8 $8), %(JJ{J$G$G $8 $8 $8 $8 $8 $8r;   c              3   X   K   | ]%}|                     t          j        d           V  &dS rO   )rP   r4   int64r?   s     r9   r:   z%_coo_base.__init__.<locals>.<genexpr>c   s4      XXS

28%
 @ @XXXXXXr;   )#r   __init__r   
isinstancetupler   	_allow_ndr   _shape_get_index_dtyperE   r   floatranger>   coordsr4   r5   datahas_canonical_format	TypeError
ValueErroranyshaper   r   formatrP   tocooasarrayr   
atleast_2dndimnonzero_check)selfarg1rb   r2   rI   r(   
data_dtypeobjr\   er%   Mmessager8   rQ   s       `        @@r9   rT   z_coo_base.__init__   s   dD8<<<< 	"!DdE"" =	1tdn555 2)$HHH 11T[9I9I1JJ	%eU;;;
# $G $G $G $G.3C4D4D.E.E$G $G $G G GHRz:::	,0))C"&KC!:. C C C#$:;;BC =;;F;;;;; ?( *> ? ? ?! "5 "5-3"5 "5 "5 5 5E)%$.III 11&9<TZAE 2 G G	 $ $8 $8 $8 $8 $806$8 $8 $8 8 8#Cd%@@@	,1))~~ 1;$+--$-"''J'Jdk'J'J'J"J"JDK $	 0 0%1F1F G GDI"-dj4>"R"R"RDK040ID--**,,C"'
"3"3DK #0D0D5 Q QDI"-ci$."Q"Q"QDK05D-- Jt$$!$00 Wa((Av{{'(UAF(U(U(UVVV)!'DNKKK$"54>BBBdkQQ"R%"R"RT["R"R(111"333t{;K;K3LL# $8 $8 $8 $806$8 $8 $8 8 8#AfIDFFF	,0)t{aXXDKXXXXXDKs   D D9$D44D9c                     | j         dk    r| j        d         S t          j        | j                  }|                    d           |S )Nr	   F)write)rg   r\   r4   
zeros_likecolsetflags)rj   results     r9   rowz_coo_base.rowg   sC    9q==;r?"tx((e$$$r;   c                     | j         dk     rt          d          t          j        || j        d         j                  }| j        d d         |fz   | j        dd          z   | _        d S )Nr   z8cannot set row attribute of a 1-dimensional sparse arrayrr   r1   )rg   r`   r4   re   r\   r2   )rj   new_rows     r9   rx   z_coo_base.rowp   sf    9q==WXXX*WDKO,ABBBk#2#&'3dk"##6FFr;   c                     | j         d         S )Nrz   r\   )rj   s    r9   ru   z_coo_base.colw   s    {2r;   c                     t          j        || j        d         j                  }| j        d d         |fz   | _        d S )Nrz   r1   )r4   re   r\   r2   )rj   new_cols     r9   ru   z_coo_base.col{   s<    *WDKO,ABBBk#2#&'3r;   c                   	 t          || j        | j                  }t          |          \  }}|| j        k    r|r|                                 S | S t          | j        | j        |          }t          |          dk    r=|dk    rt          ||d                   }n7t          ||d                   d d d         }nt          j
        |||          }|                     | j        t          |                    	t          	fd	|D                       }|r| j                                        }n| j        }|                     ||f|d
          S )Nr*   orderr   Cr	   r   rz   r,   c              3   D   K   | ]}t          j        |           V  dS r0   r4   re   )r6   cor8   s     r9   r:   z$_coo_base.reshape.<locals>.<genexpr>   s2      PPr2:b	:::PPPPPPr;   Frb   rI   )r   rb   rW   r    rI   _ravel_coordsr\   r>   divmodr4   unravel_indexrY   rE   rV   r]   	__class__)
rj   argskwargsrb   r   rI   flat_coords
new_coordsnew_datar8   s
            @r9   reshapez_coo_base.reshape   sW   D$*t~FFF*622t DJ yy{{"
 $DK5IIIu::??||#Kq::

#Kq::44R4@

)+uEJJJJ))$+c%jj)II	PPPPZPPPPP
  	!y~~''HHyH~~x4E~NNNr;   c                    ||dk    r| j         dk    rt          | j                  t          fd| j        D                       rt          d          | j        j         dk    st          d | j        D                       rt          d          t                    S |dk     r
|| j         z  }|| j         k    rt          d          t          j        t          | j        d|z
                     | j
        d|z
                     S )	Nr   r	   c              3   >   K   | ]}t          |          k    V  d S rK   r=   )r6   r@   nnzs     r9   r:   z$_coo_base._getnnz.<locals>.<genexpr>   s-      ::s3s88s?::::::r;   z3all index and data arrays must have the same lengthc              3   ,   K   | ]}|j         d k    V  dS rB   )rg   r?   s     r9   r:   z$_coo_base._getnnz.<locals>.<genexpr>   s(      )O)OC#(a-)O)O)O)O)O)Or;   z'coordinates and data arrays must be 1-Daxis out of bounds	minlength)rg   r>   r]   ra   r\   r`   intr4   bincountr   rb   )rj   axisr   s     @r9   _getnnzz_coo_base._getnnz   s   <DAII$)q..di..C::::dk::::: 0  "/ 0 0 0 y~""c)O)O4;)O)O)O&O&O" !JKKKs88O!88DID491222{.t{1t8/DEE%)ZD%9; ; ; 	;r;   c                 d   |                                   |t          j        | j                  S |dk     r
|| j        z  }|dk     s|| j        k    rt          d          | j        dk    }| j        d|z
           |         }t          j        t          |          | j	        d|z
                     S )Nr   r   r	   r   )
sum_duplicatesr4   count_nonzeror]   rg   r`   r\   r   r   rb   )rj   r   maskcoords       r9   r   z_coo_base.count_nonzero   s    <#DI...!88DID!88tty((1222yA~AH%d+{.u55APTHAUVVVVr;   c           
         | j         t          | j                  k    r,t          dt          | j                   d| j                    t	          | j                  D ]7\  }}|j        j        dk    r"t          d| d|j        j         dd           8| 	                    | j        t          | j                  	          t          fd
| j        D                       | _        t          | j                  | _        | j        dk    rt	          | j                  D ]\  }}|
                                | j        |         k    r5t          d| d|
                                 d| j        |                    |                                dk     r't          d| d|                                           dS dS )z' Checks data structure for consistency z2mismatching number of index arrays for shape; got z, expected izindex array z has non-integer dtype ()   
stacklevelr,   c              3   D   K   | ]}t          j        |           V  dS r0   r   )r6   r@   r8   s     r9   r:   z#_coo_base._check.<locals>.<genexpr>   sF       5 5!$ Js)<<< 5 5 5 5 5 5r;   r   zaxis z index z exceeds matrix dimension znegative axis z index: N)rg   r>   r\   r`   	enumerater2   kindr   namerY   rE   rb   rV   r   r]   r   min)rj   r   r@   r8   s      @r9   ri   z_coo_base._check   s   9DK(((( M$'$4$4M MAEM M N N N  ,, 	# 	#FAsy~$$PAPPsy~PPP !# # # # ))$+c$*oo)NN	 5 5 5 5(,5 5 5 5 5di((	8a<<#DK00 N N37799
1--$ &IQ &I &Iswwyy &I &I9=A&I &I J J J7799q==$%La%L%L%L%LMMM ! <N Nr;   c                     |t           j                  d d d         }nt           t                    rlt	          |d          rt          |           j        k    rt          d          t          t          |                     j        k    rt          d          n|dk    rt          d          t           fd|D                       }t           fd|D                       } 	                     j
        |f||	          S )
Nrz   __len__z"axes don't match matrix dimensionszrepeated axis in transpose)r	   r   zoSparse matrices do not support an 'axes' parameter because swapping dimensions is the only logical permutation.c              3   2   K   | ]}j         |         V  d S rK   )rX   r6   r   rj   s     r9   r:   z&_coo_base.transpose.<locals>.<genexpr>   s)      <<!t{1~<<<<<<r;   c              3   2   K   | ]}j         |         V  d S rK   r}   r   s     r9   r:   z&_coo_base.transpose.<locals>.<genexpr>   s)      ==1A======r;   r   )r[   rg   rU   r   hasattrr>   r`   setrV   r   r]   )rj   axesrI   permuted_shapepermuted_coordss   `    r9   	transposez_coo_base.transpose   s&   <##DDbD)DDg&& 	:4++ Gs4yyDI/E/E !EFFF3t99~~** !=>>> +V^^ 9 : : : <<<<t<<<<<=========~~ty/:$2  ? ? 	?r;   returnc                    t          || j                  }| j        dk    rt          d          t	          |          dk    rt          d          t	          |          | j        k    rmt          | j        | j                  }t          j	        |          }t          j        |d |         |          | _        | j        d |         | _        || _        d S t	          |          | j        k     r| j        d t	          |          dz
           dz   d| j        t	          |          z
  z  z   }|                     |          }|j        d t	          |                   | _        |j        d t	          |                   | _        t          d t!          | j        |          D                       }|rt          j                            d	 t!          | j        |          D                                                       s7t)          fd
| j        D                       | _        | j                 | _        || _        d S )Nr*   r   zonly 1-D or 2-D input acceptedz!shape argument must be 1-D or 2-Dr	   )rz   r	   c              3   (   K   | ]\  }}||k    V  d S rK    )r6   oldnews      r9   r:   z#_coo_base.resize.<locals>.<genexpr>  s*      MM(#sC#IMMMMMMr;   c                      g | ]\  }}||k     S r   r   )r6   r@   sizes      r9   
<listcomp>z$_coo_base.resize.<locals>.<listcomp>  s-     * * *(sDd
* * *r;   c              3   (   K   | ]}|         V  d S rK   r   r6   r@   r   s     r9   r:   z#_coo_base.resize.<locals>.<genexpr>  s'      #E#E#CI#E#E#E#E#E#Er;   )r   rW   rg   r`   r>   r   r\   rb   mathprodr4   r   r]   rX   r   ra   ziplogical_andreduceallrV   )rj   rb   r   max_size	tmp_shapetmpis_truncatingr   s          @r9   resizez_coo_base.resize   s   EDN;;;9q===>>>u::>>@AAAu::	!!'TZ@@Ky''H*;yy+A5IIDK	)8),DIDKF u::	!!OSZZ!^O,$)c%jj012 
 ,,y))C*[c%jj[1DK)KSZZK0DK MMc$*e6L6LMMMMM 	,>(( * *,/U,C,C* * *  D 88:: ,##E#E#E#E#E#E#EEE IdO	r;   c                    |                      ||          }t          |j        j                  }|s|j        j        st          d          | j        dk    rWt          t          j	        dg          | j
        | j        | j        d         | j        |                    d          |           n | j        dk    rH| j        \  }}t          ||| j
        | j        | j        | j        |                    d          |           n|r5t          j        dt          j        | j        d d                             }nFt          j        t          j        | j        dd          d d d                   d d d         d          }t          j        | j                  }t          || j
        | j        || j        |                    d          |           |                    | j                  S )Nz&Output array must be C or F contiguousr	   r   Ar   rz   )_process_toarray_argsr   flagsf_contiguousc_contiguousr`   rg   r   r4   r5   r   r\   r]   ravelrb   r   rx   ru   appendcumprodconcatenater   )	rj   r   outBfortranro   Nstridesr\   s	            r9   toarrayz_coo_base.toarray  s   &&uc22ag*++ 	Gqw3 	GEFFF 9>>28QC==$(DI;q>49aggcllGM M M MY!^^:DAq1dh$(DIg/ / / /  O)Arz$*SbS/'B'BCC)BJtz!""~ddd/C$D$DTTrT$JANN^DK00F7DHdi!49aggcllGE E E yy$$$r;   c                 X   | j         dk    rt          d| j          d          | j        dk    r!|                     | j        | j                  S ddlm} |                     |j	                  \  }}}}|                     |||f|          }| j
        s|                                 |S )	aQ  Convert this array/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   z+Cannot convert. CSC format must be 2D. Got rM   r   r1   r	   )	csc_arrayrb   )rg   r`   r   _csc_containerrb   r2   _cscr   _coo_to_compressed_swapr^   r   )rj   rI   r   indptrindicesr]   rb   xs           r9   tocscz_coo_base.tocsc:  s    ( 9>>W49WWWXXX8q==&&tz&DDD''''''+/+B+B9?+S+S(FGT5##T7F$;5#IIA, #  """Hr;   c                 j   | j         dk    rt          d| j          d          | j        dk    r!|                     | j        | j                  S ddlm} |                     |j	        |          }|\  }}}}|                     |||f| j        	          }| j
        s|                                 |S )
aN  Convert this array/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   z*Cannot convert. CSR must be 1D or 2D. Got rM   r   r1   r	   )	csr_arrayrL   r   )rg   r`   r   _csr_containerrb   r2   _csrr   r   r   r^   r   )	rj   rI   r   arraysr   r   r]   rb   r   s	            r9   tocsrz_coo_base.tocsr[  s    ( 9q==V$)VVVWWW8q==&&tz&DDD'''''',,Y_4,HHF+1(FGT5##T7F$;4:#NNA, #  """Hr;   c                 ,    || j                   \  }}|                     | j        t          | j        |                    }| j        dk    r|r| j        d                                         n| j        d         }t          |          }t          j	        d|g|          }|r| j
                                        n| j
        }	|||	| j        fS  || j                  \  }
}t          |
          }|
                    |d          }
|                    |d          }t          j        |dz   |          }t          j        ||          }t          j        | j
        | j                  }	t!          ||||
|| j
        |||		  	         |||	| j        fS )z?convert (shape, coords, data) to (indptr, indices, data, shape)r,   r	   r   r1   FrL   )_shape_as_2drY   r\   rE   r   rg   rI   r>   r4   r5   r]   rb   rP   empty
empty_liker2   r   )rj   swaprI   ro   r   r8   r   r   r   r]   majorminors               r9   r   z_coo_base._coo_to_compressed}  s   tD%&&1 ))$+c$(A>N>N)OO	9>>/3Gdk!n))+++QGg,,CXq#hi888F'+:49>>###D7D$*44 tDK((u%jjYU33YU33!a%y111-Y777}TYdj999!QUE49fgtLLLwdj00r;   c                 2    |r|                                  S | S rK   rL   )rj   rI   s     r9   rd   z_coo_base.tocoo  s     	99;;Kr;   c                 t   | j         dk    rt          d| j          d          |                                  | j        | j        z
  }t          j        |d          \  }}t          |          dk    r(t          dt          |           dt          d	           | j
        j        d
k    rt          j        d| j                  }nUt          j        t          |          | j                                        dz   f| j                  }| j
        ||| j        f<   |                     ||f| j                  S )Nr   z+Cannot convert. DIA format must be 2D. Got rM   T)return_inversed   zConstructing a DIA matrix with z diagonals is inefficientr   r   )r   r   r1   r	   r   )rg   r`   r   ru   rx   r4   uniquer>   r   r   r]   r   zerosr2   rE   _dia_containerrb   )rj   rI   ksdiagsdiag_idxr]   s         r9   todiaz_coo_base.todia  s5   9>>W49WWWXXXX )Bt<<<xu:: "3u:: " " "(Q8 8 8 8
 9>Q8F$*555DD8SZZ)9:$*MMMD'+yD48#$""D%=
"CCCr;   c                 R   | j         dk    rt          d| j          d          |                                  |                     | j        | j                  }| j         dk    r| j        d         }nt          | j         }t          t          || j	                            |_
        |S )Nr   z*Cannot convert. DOK must be 1D or 2D. Got rM   r1   r	   r   )rg   r`   r   _dok_containerrb   r2   r\   r   dictr]   _dict)rj   rI   dokr\   s       r9   todokz_coo_base.todok  s    9q==V$)VVVWWW!!$*DJ!??9>>[^FF$+&FVTY//00	
r;   r   c           
      d  	 | j         dk    rt          d          | 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        	         }nGt          	fd| j        D                       }|                     || j        	                   \  \  }}}|||t          |d          z   <   |S )Nr   z diagonal requires two dimensionsr   r1   c              3   (   K   | ]}|         V  d S rK   r   )r6   r@   	diag_masks     r9   r:   z%_coo_base.diagonal.<locals>.<genexpr>  s'      ??CY??????r;   )rg   r`   rb   r4   r   r]   r2   r   r   rE   rx   ru   r^   rV   r\   _sum_duplicates)
rj   krowscolsdiagrx   r]   indsr7   r
  s
            @r9   diagonalz_coo_base.diagonal  s0   9>>?@@@Z
d::d8ATY_5555xD3q!99,dSAYY.>??"j* * *X\dh.	$ 	N(9%C9Y'DD????4;?????D!11$	)8LMMNHS!d $S3q!99_r;   c                 2   | j         dk    rt          d          | 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          f| _        t          j        | j        |         |f          | _        d| _        d S )Nr   z*setting a diagonal requires two dimensionsr   r1   F)rg   r`   rb   r>   rx   r2   ru   r   r4   
logical_oraranger   r   r\   r]   r^   )rj   valuesr  ro   r   r8   	full_keep	max_indexkeepr{   r   r   s               r9   _setdiagz_coo_base._setdiag  s   9>>IJJJ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 ~tx~w&?@@~tx~w&?@@BNDIdOX#>??	$)!!!r;   Tc                     |rt          d | j        D                       }n| j        }|                     ||f| j        |j                  S )zReturns a matrix with the same sparsity structure as self,
        but with different data. By default the index arrays are copied.
        c              3   >   K   | ]}|                                 V  d S rK   rL   r?   s     r9   r:   z'_coo_base._with_data.<locals>.<genexpr>
  s*      ==#388::======r;   )rb   r2   )rV   r\   r   rb   r2   )rj   r]   rI   r\   s       r9   
_with_dataz_coo_base._with_data  sS      	!=======FF[F~~tVnDJdj~QQQr;   c                     | j         rdS |                     | j        | j                  }|\  | _        | _        d| _         dS )zeEliminate duplicate entries by adding them together

        This is an *in place* operation
        NT)r^   r  r\   r]   )rj   summeds     r9   r   z_coo_base.sum_duplicates  sI    
 $ 	F%%dk49==!'TY$(!!!r;   c                    t          |          dk    r||fS t          j        |d d d                   t          fd|D                       }|         }t          j                            d |D                       t          j        d          t          fd|D                       }t          j                  \  }t          j        	                    |t          |          | j                  }||fS )Nr   rz   c              3   (   K   | ]}|         V  d S rK   r   )r6   r@   r   s     r9   r:   z,_coo_base._sum_duplicates.<locals>.<genexpr>"  s'      44cs5z444444r;   c                 :    g | ]}|d d         |dd         k    S )r	   Nrz   r   r?   s     r9   r   z-_coo_base._sum_duplicates.<locals>.<listcomp>$  s:     ,
 ,
 ,
$'CGs3B3x,
 ,
 ,
r;   Tc              3   (   K   | ]}|         V  d S rK   r   )r6   r@   unique_masks     r9   r:   z,_coo_base._sum_duplicates.<locals>.<genexpr>(  s(      ::Cs;'::::::r;   r1   )r>   r4   lexsortrV   r  r   r   rh   addreduceatr   r2   )rj   r\   r]   unique_indsr   r#  s       @@r9   r  z_coo_base._sum_duplicates  s
   t99>>4< 
6$$B$<((4444V44444E{m** ,
 ,
+1,
 ,
 ,
   ik22::::6:::::z+..vt%8%E%ETZXXt|r;   c                     | j         dk    | j                  | _         t          fd| j        D                       | _        dS )z[Remove zero entries from the array/matrix

        This is an *in place* operation
        r   c              3   (   K   | ]}|         V  d S rK   r   r   s     r9   r:   z,_coo_base.eliminate_zeros.<locals>.<genexpr>4  s'      ==#CI======r;   N)r]   rV   r\   )rj   r   s    @r9   eliminate_zerosz_coo_base.eliminate_zeros-  sG    
 yA~IdO	=========r;   c                 <   |j         | j         k    r t          d| j          d|j          d          t          | j        j        |j        j                  }t          j        ||d          }t          |j        j	                  }| j
        dk    rWt          t          j        dg          | j        | j
        | j        d         | j        |                    d          |           n | j
        d	k    rH| j        \  }}t#          ||| j        | j        | j        | j        |                    d          |           n|r5t          j        dt          j        | j         d d
                             }nFt          j        t          j        | j         dd          d d d
                   d d d
         d          }t          j        | j                  }t          || j        | j
        || j        |                    d          |           |                     |d          S )NIncompatible shapes ( and r   T)r2   rI   r	   r   r   r   rz   FrL   )rb   r`   r   r2   charr4   r5   r   r   r   rg   r   r   r\   r]   r   r   r   rx   ru   r   r   r   
_container)	rj   otherr2   rw   r   ro   r   r   r\   s	            r9   
_add_densez_coo_base._add_dense:  s   ;$*$$TTZTTekTTTUUUDJOU[-=>>%u4888fl/009>>28QC==$(DI;q>49fll36G6GR R R RY!^^$DAq1dh$(DIS))74 4 4 4  O)Arz$*SbS/'B'BCC)BJtz!""~ddd/C$D$DTTrT$JANN^DK00F7DHdi!49fll3.?.?J J JvE222r;   c                    | j         dk     r'|                                                     |          S |j        | j        k    r t	          d| j         d|j         d          |                     |          }t          j        | j        |j        f          }t          t          j        | j
        |j
        fd                    }|                     ||f| j                  }|S Nr   r,  r-  r   r	   )r   r   )rg   r   _add_sparserb   r`   r   r4   r   r]   rV   r\   rj   r0  r   r   r   s        r9   r4  z_coo_base._add_sparseR  s    9q==::<<++E222;$*$$TTZTTekTTTUUUu%%>49ej"9::2>4;*EANNNOO
NNHj1NDDr;   c                    | j         dk     r'|                                                     |          S |j        | j        k    r t	          d| j         d|j         d          |                     |          }t          j        | j        |j         f          }t          t          j        | j
        |j
        fd                    }t          ||f| j                  }|S r3  )rg   r   _sub_sparserb   r`   r   r4   r   r]   rV   r\   r   r5  s        r9   r7  z_coo_base._sub_sparse_  s    9q==::<<++E222;$*$$TTZTTekTTTUUUu%%>49uzk":;;2>4;*EANNNOO
x,DJ???r;   c           	      N   | j         dk    r't          j        t          j        | j        d d                   t          | j        j        |j        j                            }t          j	        | j                  }t          j
        t          j        |d d         d d d                   d d d         dd          d          }t          j        | j                  }t          | j        t!          | j                  ||| j        ||           |                    | j        d d                   }|S | j         dk    r| j        d         nd}t          j        |t          | j        j        |j        j                            }| j         dk    r| j        }| j        }nD| j         dk    r"| j        d         }t          j        |          }nt-          d| j                    t/          | j        ||| j        ||           t1          | t2                    r|dk    r|d         S |S )Nr   rz   r1   r	   r   z$coo_matvec not implemented for ndim=)rg   r4   r   r   r   rb   r   r2   r.  r5   r   r   r   r\   r   r   r>   r]   r   ru   rx   rt   NotImplementedErrorr   rU   r   )	rj   r0  rw   rb   r   r\   result_shaperu   rx   s	            r9   _matmul_vectorz_coo_base._matmul_vectorl  s   9q==Xdi
3B388$/
AQ$R$RT T TFHTZ((Ei
5":ddd+; < <TTrT B122 FJJG^DK00F$(C
OOWfdi) ) ) ^^DJssO44FM )-	Atz!}}1, +DJOU[=M N NP P P9>>(C(CCY!^^+a.C-$$CC%BtyBBD D D 	48S#ty%@@@dG$$ 	):):!9r;   c                    t          |          r|                     |          S 	 |j        }n+# t          $ r t	          j        |          }|j        }Y nw xY wt          t          |          d d                   t          t          |          dd          d d d                   z   }|                    |          }| j        }t          t          |          d d                   t          t          |          dd          d d d                   z   }|                     |          	                    |          }|t          u rt          S |dk    s|dk    rt          |j                  }n\t          t          |j                  d d                   t          t          |j                  dd          d d d                   z   }|                    |          S )Nrr   rz   r	   )r!   _mul_scalarrg   AttributeErrorr4   re   rV   r[   r   _matmul_dispatchNotImplemented)rj   r0  o_ndimpermtrs_ndimrets          r9   _rmatmul_dispatchz_coo_base._rmatmul_dispatch  s    	'##E***$! $ $ $
5))$ vss+,,uU6]]2335G"5M/N/NND&&BYFvss+,,uU6]]2335G"5M/N/NND..&&77;;Cn$$%%{{fkkSXU38__SbS122U5??233;OPTPTRTPT;U5V5VV==&&&s   . %AAc                    t          |          r|                     |          S t          |          set          |          sVt	          j        |          }|j        dk    r|j        t          j        k    rt          S 	 |j
         n# t          $ r |}Y nw xY w| j        dk     r |j        dk     rt          j        | |          S | j
        d         }d}|j        t          j        u rB|j
        |fk    r|                     |          S |j
        |dfk    rC|                     |                                          } |j        g | j
        d d         dR  S |j        dk    r%| d| d|j
        d          d}t'          |          |j
        d	         |k    rm| j
        d d	         }|j
        d d	         }||k    r4	 t	          j        ||           n# t&          $ r t'          d
          w xY w|                     |          S t'          | d| d|j
        d	          d          t          |          r|                     |          S t          |          r| j        dk    }	|j        dk    }
|	r|                     | j                  } |
r"|                    |j
        d         df          }||j
        d	         k    r#t'          | d| d|j
        d	          d          | j        dk    s|j        dk    rX| j
        d d	         }|j
        d d	         }||k    r4	 t	          j        ||           n# t&          $ r t'          d
          w xY w|                     |          }|	rL|                    t3          |j
        d d	                   t3          |j
        dd                    z             }|
r"|                    |j
        d d                   }|S d S )Nr   r   rz   z)matmul: dimension mismatch with signaturer	   z (n,k=z),(k=z,)->(n,)rr   z&Batch dimensions are not broadcastablez	 (n,..,k=z,..,m)->(n,..,m)r   )r!   multiplyr   r"   r4   
asanyarrayrg   r2   object_r@  rb   r>  r   r?  r   ndarrayr;  r   r   r`   broadcast_shapes_matmul_multivectorr=  r   _matmul_sparserV   )rj   r0  other_ar   
err_prefixrw   msgbatch_shape_Abatch_shape_B
self_is_1dother_is_1ds              r9   r?  z_coo_base._matmul_dispatch  sd    	(==''' 	 75>> 	 mE**G|q  W]bj%@%@ &% !        9q==UZ!^^+D%888JrN@
?bj(({qd""**5111{q!f$$,,U[[]];;%v~:tz#2#:::::zQ#KK1KK5;q>KKK oo%{2!## $
3B3 %CRC 0 M11S+M=IIII% S S S()QRRRS //666 !UUAUUEKOUUU  
  	+##E***E?? &	aJ*/K  7||D$566 ;u{1~q&9:: EKO## !UUAUUEKOUUU   y1}}
Q $
3B3 %CRC 0 M11S+M=IIII% S S S()QRRRS ((//F  Bfl3B3.?(@(@(-fl233.?(@(@)A B B ;SbS(9::MM&	 &	s*   ?B BB>G G."L8 8Mc                    t          | j        j        |j        j                  }| j        dk    s|j        dk    r| j        dk    r|                     d| j        d                                       |          }|                    t          |j        d d                   t          |j        dd                    z             S t          j	        | j        d d         |j        d d                   }|| j        dd          z   }||j        dd          z   }| 
                    |          } t          j        ||          }|| j        dd         z   |j        dd          z   }t          j        ||          }t          | j        t          | j                  |j        d         t          j        |          t          j        |          t          j        | j                  | j        |                    d          |	  	         |S | j        dk    r)| j        d         |j        d         f}| j        }| j        }	n:| j        dk    r/|j        d         f}| j        d         }t          j        |          }	t          j        ||          }t1          | j        |j        d         |	|| j        |                    d          |           |                    t5          |          	          S )
Nr   r	   r   rr   rz   r1   r   r   )type)r   r2   r.  rg   r   rb   rM  rV   r4   rL  _broadcast_tobroadcast_tor   r   r   r>   r5   r   r\   r]   r   ru   rx   rt   r   viewrW  )
rj   r0  result_dtyperw   broadcast_shape
self_shapeother_shaper:  ru   rx   s
             r9   rM  z_coo_base._matmul_multivector  s   "4:?EK4DEE9>>UZ1__yA~~aA77KKERR~~eEK,<&=&=ekRTRURUFV@W@W&WXXX 1$*SbS/5;sPRsCSTTO(4:bcc?:J)EK,<<K%%j11DOE;77E*TZ2->>RSSAQQLXl,???F#dj//5;r? " 5 5rx7M7M "t{ ; ; $	5;;s+;+;VE E E M9>> JqM5;q>:L(C(CCY!^^!KN,L+a.C-$$C,l;;;5;r?CEKK$4$4f	> 	> 	>{{U{,,,r;   c                    t          |          st          |          s~t          |          sot          j        |          }|j        dk    r5|j        t          j        k    r t          dt          |           d          	 |j
         n# t          $ r |}Y nw xY w| j        dk     r4t          j        |          s|j        dk     rt          j        | |          S t          j        |          r| |z  S t          |          r|                     |          S |j        dk    rt          d          | j        dk    rL|j        dk    rA| j
        d         |j
        d         k    r t#          d| j
         d	|j
         d
          | |z  S | j        dk    rL|j        dk    rA| j
        d         |j
        d         k    r t#          d| j
         d	|j
         d          | |z  S |                     |          S )a  Return the dot product of two arrays.

        Strictly speaking a dot product involves two vectors.
        But in the sense that an array with ndim >= 1 is a collection
        of vectors, the function computes the collection of dot products
        between each vector in the first array with each vector in the
        second array. The axis upon which the sum of products is performed
        is the last axis of the first array and the second to last axis of
        the second array. If the second array is 1-D, the last axis is used.

        Thus, if both arrays are 1-D, the inner product is returned.
        If both are 2-D, we have matrix multiplication. If `other` is 1-D,
        the sum product is taken along the last axis of each array. If
        `other` is N-D for N>=2, the sum product is over the last axis of
        the first array and the second-to-last axis of the second array.

        Parameters
        ----------
        other : array_like (dense or sparse)
            Second array

        Returns
        -------
        output : array (sparse or dense)
            The dot product of this array with `other`.
            It will be dense/sparse if `other` is dense/sparse.

        Examples
        --------

        >>> import numpy as np
        >>> from scipy.sparse import coo_array
        >>> A = coo_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
        >>> v = np.array([1, 0, -1])
        >>> A.dot(v)
        array([ 1, -3, -1], dtype=int64)

        For 2-D arrays it is the matrix product:

        >>> A = coo_array([[1, 0], [0, 1]])
        >>> B = coo_array([[4, 1], [2, 2]])
        >>> A.dot(B).toarray()
        array([[4, 1],
               [2, 2]])

        For 3-D arrays the shape extends unused axes by other unused axes.

        >>> A = coo_array(np.arange(3*4*5*6)).reshape((3,4,5,6))
        >>> B = coo_array(np.arange(3*4*5*6)).reshape((5,4,6,3))
        >>> A.dot(B).shape
        (3, 4, 5, 5, 4, 3)
        r   z"dot argument not supported type: ''r   r%   z input must be a COO matrix/arrayr	   shapes r-  z" are not aligned for inner productr   z are not aligned for matmul)r   r"   r!   r4   rI  rg   r2   rJ  r_   rW  rb   r>  isscalarr   dot
_dense_dotrc   r`   _sparse_dot)rj   r0  o_arrays      r9   rc  z_coo_base.dot+  s6   j  		 75>> 		 \%5H5H 		 mE**G|q  W]bj%@%@ ST%[[ S S STTT !        9q==bk%00=EJqLL;tU+++;u 	 %<5>> 	+??5)))\U"">???Y!^^
az!}A..  "F4: "F "FEK "F "F "F G G G%<Y!^^
az!}A..  "?4: "? "?EK "? "? "? @ @ @%<##E***s   B BBc                    | j         dk    }|j         dk    }|r|                     | j                  } |r"|                    |j        d         df          }| j        d         |j        d         k    r t	          d| j         d|j         d          t          | j        | j        | j         dz
  g          }t          |j        |j        |j         dz
  g          }| j        d d         }|j        d d         |j        dd          z   }t          j        |          | j        d         f}|j        d         t          j        |          f}	|| j        d         f}
|j        d         |f}t          | j
        |
f|          }t          |j
        |f|	          }||z                                  }||z   }||f}g }t          |j        |          D ]-\  }}|                    t          j        ||                     .t          |j
        |f|          }|r|                    |dd                    }|r|                    |d d                   }|S )	Nr	   r   rz   rr   ra  r-   are not aligned for n-D dotr   )rg   r   r   rb   r`   _ravel_non_reduced_axesr\   r   r   r   r]   rd   r   extendr4   r   )rj   r0  rT  rU  self_raveled_coordsother_raveled_coordsself_nonreduced_shapeother_nonreduced_shaperavel_coords_shape_selfravel_coords_shape_otherself_2d_coordsother_2d_coordsself_2dother_2dr   combined_shapeshapesprod_coordscsprod_arrs                        r9   re  z_coo_base._sparse_dot  s   Y!^
jAo  	3<< 122D 	7MM5;q>1"566E:b>U[_,,  "@4: "@ "@EK "@ "@ "@ A A A
 6dk6:j49Q;-Q Q6u|7<{UZPQ\N T  T !%
3B3!&SbS!1EK4D!D $(9-B#C#CTZPR^"T$)KOTY?U5V5V#W -t{2? <+-ABTY79PQQej/:<TUU("))++ /1GG ()?@V,, 	7 	7DAqr/1556666di5~FF  	<''qrr(:;;H 	=''ss(;<<Hr;   c                 <   | j         dk    }|j         dk    }|r|                     | j                  } |r"|                    |j        d         df          }| j        d         |j        d         k    r t	          d| j         d|j         d          | j        d d         dt          |j                  dz
  z  z   | j        dd          z   }dt          | j                  dz
  z  |j        z   }| j        d d         |j        d d         z   |j        dd          z   }|                     |          |                    |          z  }|                    |          }|r|                    |dd                    }|r|                    |d d                   }|S )	Nr	   r   rz   rr   ra  r-  rh  r   )rg   r   r   rb   r`   r>   )	rj   r0  rT  rU  new_shape_selfnew_shape_otherr:  rw   rz  s	            r9   rd  z_coo_base._dense_dot  s   Y!^
jAo  	3<< 122D 	7MM5;q>1"566E:b>U[_,,  "@4: "@ "@EK "@ "@ "@ A A A JssOdc%+&6&6&:;;djoM 	 #dj//A"56Dz#2#SbS)99EK<LLn--o0N0NN>>,//  	:''QRR(899H 	;''SbS(9::Hr;   r   c                 H    t                    s~t                    sot          j                  }|j        dk    r5|j        t          j        k    r t          dt                     d          	 j	         n# t          $ r |Y nw xY wt           j        j        |          \  }}t           fdt          ||          D                       rt          d          t                    r                     ||          S                      ||          S )a  Return the tensordot product with another array along the given axes.

        The tensordot differs from dot and matmul in that any axis can be
        chosen for each of the first and second array and the sum of the
        products is computed just like for matrix multiplication, only not
        just for the rows of the first times the columns of the second. It
        takes the dot product of the collection of vectors along the specified
        axes.  Here we can even take the sum of the products along two or even
        more axes if desired. So, tensordot is a dot product computation
        applied to arrays of any dimension >= 1. It is like matmul but over
        arbitrary axes for each matrix.

        Given two tensors, `a` and `b`, and the desired axes specified as a
        2-tuple/list/array containing two sequences of axis numbers,
        ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements
        (components) over the axes specified by ``a_axes`` and ``b_axes``.
        The `axes` input can be a single non-negative integer, ``N``;
        if it is, then the last ``N`` dimensions of `a` and the first
        ``N`` dimensions of `b` are summed over.

        Parameters
        ----------
        a, b : array_like
            Tensors to "dot".

        axes : int or (2,) array_like
            * integer_like
              If an int N, sum over the last N axes of `a` and the first N axes
              of `b` in order. The sizes of the corresponding axes must match.
            * (2,) array_like
              A 2-tuple of sequences of axes to be summed over, the first applying
              to `a`, the second to `b`. The sequences must be the same length.
              The shape of the corresponding axes must match between `a` and `b`.

        Returns
        -------
        output : coo_array
            The tensor dot product of this array with `other`.
            It will be dense/sparse if `other` is dense/sparse.

        See Also
        --------
        dot

        Examples
        --------
        >>> import numpy as np
        >>> import scipy.sparse
        >>> A = scipy.sparse.coo_array([[[2, 3], [0, 0]], [[0, 1], [0, 5]]])
        >>> A.shape
        (2, 2, 2)

        Integer axes N are shorthand for (range(-N, 0), range(0, N)):

        >>> A.tensordot(A, axes=1).toarray()
        array([[[[ 4,  9],
                 [ 0, 15]],
        <BLANKLINE>
                [[ 0,  0],
                 [ 0,  0]]],
        <BLANKLINE>
        <BLANKLINE>
               [[[ 0,  1],
                 [ 0,  5]],
        <BLANKLINE>
                [[ 0,  5],
                 [ 0, 25]]]])
        >>> A.tensordot(A, axes=2).toarray()
        array([[ 4,  6],
               [ 0, 25]])
        >>> A.tensordot(A, axes=3)
        array(39)

        Using tuple for axes:

        >>> a = scipy.sparse.coo_array(np.arange(60).reshape(3,4,5))
        >>> b = np.arange(24).reshape(4,3,2)
        >>> c = a.tensordot(b, axes=([1,0],[0,1]))
        >>> c.shape
        (5, 2)
        >>> c
        array([[4400, 4730],
               [4532, 4874],
               [4664, 5018],
               [4796, 5162],
               [4928, 5306]])

        r   z#tensordot arg not supported type: 'r`  c              3   V   K   | ]#\  }}j         |         j         |         k    V  $d S rK   r   )r6   axbxr0  rj   s      r9   r:   z&_coo_base.tensordot.<locals>.<genexpr>C  sL       9 92r z"~R0 9 9 9 9 9 9r;   z*sizes of the corresponding axes must match)r"   r   r4   rI  rg   r2   rJ  r_   rW  rb   r>  _process_axesra   r   r`   _dense_tensordot_sparse_tensordot)rj   r0  r   other_array	axes_self
axes_others   ``    r9   	tensordotz_coo_base.tensordot  sT   r u~~ 		$huoo 		$-..K1$$):bj)H)H Td5kk T T TUUU$! $ $ $#$ !.diT J J	:  9 9 9 9 9 J779 9 9 9 9 	KIJJJ5>> 	H((	:FFF))%JGGGs   6A> >BBc                     t           j                  }t          j                  }t           j         j                  }t	          j         fdD              fdD                       }t          j        j                  }t	          j        fdD             fdD                       }	t           fdt          |          D                       }
t          fdt          |          D                       }t          j	        |
          t          j	         fdD                       f}t          j	        fdD                       t          j	        |          f}||f}|	|f}t           j        |f|          }t          j        |f|          }||z                                  }|
|z   }g }t          |j        |
|f          D ]/\  }}|r(|                    t	          j        ||                     0|g k    rt!          |j                  S t          |j        |f|	          S )
Nc                 *    g | ]}j         |         S r   r}   r6   r  rj   s     r9   r   z/_coo_base._sparse_tensordot.<locals>.<listcomp>V  s    111T[_111r;   c                 *    g | ]}j         |         S r   r   r  s     r9   r   z/_coo_base._sparse_tensordot.<locals>.<listcomp>V  s    3W3W3WrDJrN3W3W3Wr;   c                 *    g | ]}j         |         S r   r}   r6   ar0  s     r9   r   z/_coo_base._sparse_tensordot.<locals>.<listcomp>Z  s    111U\!_111r;   c                 *    g | ]}j         |         S r   r   r  s     r9   r   z/_coo_base._sparse_tensordot.<locals>.<listcomp>Z  s    3W3W3WqEKN3W3W3Wr;   c              3   :   K   | ]}|vj         |         V  d S rK   r   )r6   r  r  rj   s     r9   r:   z._coo_base._sparse_tensordot.<locals>.<genexpr>]  s?       &6 &6!#9!4!4 '+jn!4!4!4!4&6 &6r;   c              3   :   K   | ]}|vj         |         V  d S rK   r   )r6   r  r  r0  s     r9   r:   z._coo_base._sparse_tensordot.<locals>.<genexpr>_  s?       '8 '82"$J"6"6 (-{2"6"6"6"6'8 '8r;   c                 *    g | ]}j         |         S r   r   r  s     r9   r   z/_coo_base._sparse_tensordot.<locals>.<listcomp>d  s    *N*N*Nb4:b>*N*N*Nr;   c                 *    g | ]}j         |         S r   r   )r6   r  r0  s     r9   r   z/_coo_base._sparse_tensordot.<locals>.<listcomp>e  s    .T.T.T2u{2.T.T.Tr;   r   )r>   rb   ri  r\   r4   ravel_multi_indexrV   r[   r   r   r   r]   rd   r   rj  r   sum)rj   r0  r  r  	ndim_self
ndim_otherself_non_red_coordsself_reduced_coordsother_non_red_coordsother_reduced_coordsrm  rn  ro  rp  rq  rr  rs  rt  r   ru  r\   rx  ry  s   ````                   r9   r  z_coo_base._sparse_tensordotM  s   
OO	%%
 6dk4:6?A A 21111y1113W3W3W3WY3W3W3WY Y6u|U[7A C  C!31111j1113W3W3W3WJ3W3W3W 
  
 !& &6 &6 &6 &6 &6uY?O?O &6 &6 &6 !6 !6!& '8 '8 '8 '8 '8zARAR '8 '8 '8 "8 "8 $(9-B#C#C $	*N*N*N*NI*N*N*N O O#Q$(I.T.T.T.T.T.T.T$U$U$(I.D$E$E$G  ./BC/1EFTY79PQQej/:<TUU ("))++ /1GG &;=S%TUU 	6 	6DAq 6b.q!44555R<<ty>>! $)V,NCCCCr;   c                     t           j                  }t          j                  }fdt          |          D             } fdD             } fd|D             }fdt          |          D             }	fdD             }
fd|	D             }|z   }|	d d         z   |	dd          z   }                     |           t	          j        |          g |t          j        |          R }g |d d         t          j        |
          |dd          R }                     |                                                  |                    S )Nc                     g | ]}|v|	S r   r   )r6   r  r  s     r9   r   z._coo_base._dense_tensordot.<locals>.<listcomp>  s#     V V V"IBUBUBUBUBUr;   c                 *    g | ]}j         |         S r   r   r6   ry  rj   s     r9   r   z._coo_base._dense_tensordot.<locals>.<listcomp>  s    ???djm???r;   c                 *    g | ]}j         |         S r   r   r  s     r9   r   z._coo_base._dense_tensordot.<locals>.<listcomp>  s    !O!O!OA$*Q-!O!O!Or;   c                     g | ]}|v|	S r   r   )r6   r  r  s     r9   r   z._coo_base._dense_tensordot.<locals>.<listcomp>  s-     "; "; ";%'z%9%9 #%%9%9%9r;   c                 *    g | ]}j         |         S r   r   r6   ry  r0  s     r9   r   z._coo_base._dense_tensordot.<locals>.<listcomp>  s    BBB!u{1~BBBr;   c                 *    g | ]}j         |         S r   r   r  s     r9   r   z._coo_base._dense_tensordot.<locals>.<listcomp>  s    "R"R"Ra5;q>"R"R"Rr;   rz   )	r>   rb   r[   r   r4   r   r   r   rc  )rj   r0  r  r  r  r  non_reduced_axes_selfreduced_shape_selfnon_reduced_shape_selfnon_reduced_axes_otherreduced_shape_othernon_reduced_shape_otherpermute_selfpermute_otherreshape_selfreshape_others   ````            r9   r  z_coo_base._dense_tensordot  s   
OO	%%
 V V V VeI.>.> V V V????Y???!O!O!O!O9N!O!O!O"; "; "; ";uZ/@/@ "; "; ";BBBBzBBB"R"R"R"R;Q"R"R"R,y8"3B3'*47Mbcc7RR 	 ~~l++UM22O/O;M1N1NOO71#2#6 7	BU8V8V 7057 7 ||L))--emmM.J.JKKKr;   c                 @   | j         dk     r |j         dk     rt          j        | |          S | j        }|j        }t	          j        |dd         |dd                   }t          |          |dd         z   }t          |          |dd         z   }|                     |          }|                    |          }t          |          }	t          |          }
|	|
z  	                                }t          |g || j        d         |j        d         R           S )a  
        Perform sparse-sparse matrix multiplication for two n-D COO arrays.
        The method converts input n-D arrays to 2-D block array format,
        uses csr_matmat to multiply them, and then converts the
        result back to n-D COO array.

        Parameters:
        self (COO): The first n-D sparse array in COO format.
        other (COO): The second n-D sparse array in COO format.

        Returns:
        prod (COO): The resulting n-D sparse array after multiplication.
        r   Nrr   rz   r   )rg   r   rN  rb   r4   rL  rV   rX  _block_diagrd   _extract_block_diag)rj   r0  r]  r^  r\  self_new_shapeother_new_shapeself_broadcastedother_broadcastedself_block_diagother_block_diagprod_block_diags               r9   rN  z_coo_base._matmul_sparse  s3    9q==UZ!^^)$666 Z
k -j"o{3B3?OPP//*RSS/A00;rss3CC--n==!//@@ &&677&'899 +-==DDFF #EOETZ^EU[_EE
 
 
 	
r;   c                    | j         |k    r|r|                                 n| S | j         }t          |          t          |          k     rt          d          dt          |          t          |          z
  z  t	          |          z   }t          d t          ||          D                       rt          d| d          |                     |          } t          | j	        t          |                    }| j	        }| j        }|dd          }d}	|d         |d         k    rT|d         }
|	|
z  }	t          j        ||
          }t          j        t          j        d	|
|
          | j                  }|f}t#          dt          |          dz    d          D ]}||         ||         k    r||         }
|	|
z  }	t          |          }t          j        ||
          }t	          t          j        ||dz   d          |
                    }t          j        t          j        d	|
|
          |          }|f|z   }t          j        ||         |	          }|f|z   }t%          ||f|          S )NzDNew shape must have at least as many dimensions as the current shaper   c              3   4   K   | ]\  }}|d k    o||k    V  dS rB   r   )r6   ons      r9   r:   z*_coo_base._broadcast_to.<locals>.<genexpr>  s3      EEtq!Q!16EEEEEEr;   zcurrent shape z- cannot be broadcast to new shape {new_shape}r,   rz   r	   r   r1   rr   )rb   rI   r>   r`   rV   ra   r   r   r   r\   rE   r]   r4   tilerepeatr  r   r[   r   )rj   	new_shaperI   	old_shaperb   r8   r\   r   r   
cum_repeatrepeat_countnew_dimr   r   s                 r9   rX  z_coo_base._broadcast_to  s   :"""&0499;;;D0J	 y>>C	NN** 5 6 6 6 IY785;K;KK EEs5)/D/DEEEEE 	C Bi B B B C C C ||E""#DKIGGG	9BCC[

9	"%%$R=L,&Jwx66Hi	!\ K K KTXVVG!JrSZZ\?B// 	5 	5AQx9Q<''(|l*
(mm 78\::"27:acdd+;\#J#JKK
 )BIaY$O$O$OQTUU%Z*4

 '&)Z88%Z*4

(J/;;;r;   )NNFrK   )NF)r   N)NN)Fr   )T)r   )0__name__
__module____qualname___formatr[   rW   rT   propertyrx   setterru   r   r   __doc__r   r   ri   r   r   r   r   r   r   rd   r  r  r  r   r  r  r   r  r*  r1  r4  r7  r;  rF  r?  rM  rc  re  rd  r  r  r  rN  rX  r   r;   r9   r$   r$      s       GaIGT G G G G GR   X 	ZG G ZG   X 	Z4 4 Z4!O !O !OF o-GO; ; ; ;( o-GOW W W W $19MN N N2? ? ? ?$  )1I$ $ $ $L ^+FN% % % %2 o-GO   B       D1 1 1 16    M)EMD D D D, M)EM    M)EM   ( $,4H$* $* $*NR R R R	) 	) 	) 	)  &> > >3 3 30
 
 

 
 
  D' ' '4\ \ \~!- !- !-HV+ V+ V+r7 7 7r  >nH nH nH nHb1D 1D 1DhL L L6(
 (
 (
V5< 5< 5< 5< 5< 5<r;   r$   c                    | j         dk     rt          d          t          j        | j        dd                   }| j        d         }| j        d         }|                     |||f          }|j        d         |j        d         |j        d         z  z   |j        d         |j        d         |j        d         z  z   f}||z  ||z  f}t          | j        t          |          f|          S )	z
    Converts an N-D COO array into a 2-D COO array in block diagonal form.

    Parameters:
    self (coo_array): An N-Dimensional COO sparse array.

    Returns:
    coo_array: A 2-Dimensional COO sparse array in block diagonal form.
    r   zarray must have atleast dim=2Nrr   rz   r	   r   r   )
rg   r`   r   r   rb   r   r\   r   r]   rV   )rj   
num_blocksn_coln_rowres_arrr   r  s          r9   r  r    s     y{{89994:crc?++JJrNEJrNEllJu566GqGN1-a0@@@qGN1-a0@@@J
 e#Z%%78Idiz!2!239EEEEr;   c                    |d         |d         }}| j         }| j        | j        }}t          j        t          |          | j        ft                    }||z  |d<   ||z  |d<   ||z  }t          t          |          dz
  dd          D ]}	||	         }
||
z  ||	<   ||
z  }t          |t          |          f|          S )Nrr   rz   r1   r   r   )r]   rx   ru   r4   r   r>   r   r   r[   r   rV   )rj   rb   r  r  r]   rx   ru   r   temp_block_idxr   r   s              r9   r  r    s    9eBi5E 9DxC 3u::tx0<<<J 5[JrN5[JrN E\N3u::>2r** 0 0Qx&-
1'4/ dE*--.e<<<<r;   c                     t          |t                    rf|dk     s|t                     k    rt          d          t	          t           |z
                       }t	          t          |                    }nt          |t          t          f          rt          |          dk    rt          d          |\  }}t          |          t          |          k    rt          d          t           fd|D                       st          fd|D                       rt          d          nt          d	           fd
|D             }fd|D             }||fS )Nr	   z.axes integer is out of bounds for input arraysr   z%axes must be a tuple/list of length 2z,axes lists/tuples must be of the same lengthc              3   2   K   | ]}|k    p| k     V  d S rK   r   )r6   r  ndim_as     r9   r:   z _process_axes.<locals>.<genexpr>=  2      ==rV|+rVG|======r;   c              3   2   K   | ]}|k    p| k     V  d S rK   r   )r6   r  ndim_bs     r9   r:   z _process_axes.<locals>.<genexpr>>  r  r;   z/axes indices are out of bounds for input arraysz3axes must be an integer or a tuple/list of integersc                 *    g | ]}|d k     r|z   n|S r  r   )r6   r   r  s     r9   r   z!_process_axes.<locals>.<listcomp>C  )    EEEdtaxxdVmmTEEEr;   c                 *    g | ]}|d k     r|z   n|S r  r   )r6   r   r  s     r9   r   z!_process_axes.<locals>.<listcomp>D  r  r;   )
rU   r   r   r`   listr[   rV   r>   ra   r_   )r  r  r   axes_aaxes_bs   ``   r9   r  r  1  s   $ O!88tc&&1111MNNNeFTM62233eDkk""	D5$-	(	( 
Ot99>>DEEEv;;#f++%%KLLL====f===== 	P====f=====	PNOOO	P MNNNEEEEfEEEFEEEEfEEEF6>r;   c                     t                    }fdt          |          D             }|st          j         d                   S fd|D             }t	           fd|D                       }t          j        ||          S )Nc                     g | ]}|v|	S r   r   )r6   r  r   s     r9   r   z+_ravel_non_reduced_axes.<locals>.<listcomp>J  s    CCCrBdNNNNNr;   r   c                      g | ]
}|         S r   r   )r6   r  rb   s     r9   r   z+_ravel_non_reduced_axes.<locals>.<listcomp>Q  s    >>>rr>>>r;   c              3   (   K   | ]}|         V  d S rK   r   )r6   r@   r\   s     r9   r:   z*_ravel_non_reduced_axes.<locals>.<genexpr>T  s'      GGsvc{GGGGGGr;   )r>   r[   r4   rt   rV   r  )r\   rb   r   rg   non_reduced_axesnon_reduced_shapenon_reduced_coordss   ```    r9   ri  ri  H  s    u::DCCCCU4[[CCC (}VAY''' ?>>>-=>>> GGGG6FGGGGG  24EFFFr;   r   c                 &   t          |           dk    r| d         S t          |           dk    r|\  }}| \  }}|dk    rT|t          d|dz
            z  t          d|dz
            z   }t          |          }t          j        |||          |z   S |dk    rT|t          d|dz
            z  t          d|dz
            z   }t          |          }t          j        |||          |z   S t          d          t          j        | ||	          S )
z;Like np.ravel_multi_index, but avoids some overflow issues.r	   r   r   r   r,   r1   Fz'order' must be 'C' or 'F'r   )r>   rE   r   r4   rH  r`   r  )	r\   rb   r   nrowsncolsrx   ru   r-   r8   s	            r9   r   r   Z  s'   
6{{aay
6{{auSC<<c!UQY///#a2C2CCF'v666I;uc;;;cAAc\\c!UQY///#a2C2CCF'v666I;uc;;;cAA9:::U;;;;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
    )rU   r   )r   s    r9   r   r   o  s    . a$$$r;   c                       e Zd ZdZdS )r   a  
    A sparse array in COOrdinate format.

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

    This can be instantiated in several ways:
        coo_array(D)
            where D is an ndarray

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

        coo_array(shape, [dtype])
            to construct an empty sparse array with shape `shape`
            dtype is optional, defaulting to dtype='d'.

        coo_array((data, coords), [shape])
            to construct from existing data and index arrays:
                1. data[:]       the entries of the sparse array, in any order
                2. coords[i][:]  the axis-i coordinates of the data entries

            Where ``A[coords] = data``, and coords is a tuple of index arrays.
            When shape is not specified, it is inferred from the index arrays.

    Attributes
    ----------
    dtype : dtype
        Data type of the sparse array
    shape : tuple of integers
        Shape of the sparse array
    ndim : int
        Number of dimensions of the sparse array
    nnz
    size
    data
        COO format data array of the sparse array
    coords
        COO format tuple of index arrays
    has_canonical_format : bool
        Whether the matrix has sorted coordinates and no duplicates
    format
    T

    Notes
    -----

    Sparse arrays 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 arrays
        - Once a COO array 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 coordinates sorted by row, then column.
        - There are no duplicate entries (i.e. duplicate (i,j) locations)
        - Data arrays MAY have explicit zeros.

    Examples
    --------

    >>> # Constructing an empty sparse array
    >>> 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 sparse array 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 sparse array with duplicate coordinates
    >>> 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 coordinates 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]])

    N)r  r  r  r  r   r;   r9   r   r     s"        k k k kr;   r   c                       e Zd ZdZd ZdS )r   a.  
    A sparse matrix in COOrdinate format.

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

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

        coo_matrix(S)
            with another sparse array or matrix S (equivalent to S.tocoo())

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

        coo_matrix((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
    size
    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
    has_canonical_format : bool
        Whether the matrix has sorted indices and no duplicates
    format
    T

    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 COO 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 coordinates sorted by row, then column.
        - There are no duplicate entries (i.e. duplicate (i,j) locations)
        - Data arrays MAY have explicit zeros.

    Examples
    --------

    >>> # Constructing an empty matrix
    >>> import numpy as np
    >>> from scipy.sparse import coo_matrix
    >>> coo_matrix((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_matrix((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 coordinates
    >>> 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_matrix((data, (row, col)), shape=(4, 4))
    >>> # Duplicate coordinates 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]])

    c                     d|vr-|                     d          |                     d          f|d<   | j                            |           d S )Nr\   rx   ru   )pop__dict__update)rj   states     r9   __setstate__zcoo_matrix.__setstate__j  sQ    5    %yy//51A1ABE(OU#####r;   N)r  r  r  r  r  r   r;   r9   r   r     s0        n n`$ $ $ $ $r;   r   )r   )2r  __docformat____all__r   warningsr   numpyr4   
_lib._utilr   _matrixr
   _sparsetoolsr   r   r   r   r   r   r   _baser   r   r   r   _datar   r   _sputilsr   r   r   r   r   r   r   r   r    r!   r"   rC   r$   r  r  r  ri  r   r   r   r   r   r;   r9   <module>r     s   8 8%
7
7
7            ' ' ' ' ' '      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 G F F F F F F F F F F F . . . . . . . .Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q b< b< b< b< b<m b< b< b<J'F F F2= = =2  .G G G$< < < <*% % %6l l l l l	7 l l l^v$ v$ v$ v$ v$9 v$ v$ v$ v$ v$r;   