L idZddlmZddlZddlZddlZddlmZm Z m Z m Z m Z m Z mZmZmZmZmZddlmZmZddlmZgdZGd d eZGd d eZGd deZidddgdddgdddgdddgdddgdddgdd d!gd"d#d$gd%d&d'gd(d)d*gd+d,d-gd.d/d0gd1d2d3gd4d5d6gd7d8d9gd:d;dd?gd@dAgdBdCgdDdEgdFZeej>ej@ejBejDejFejHejJejLejNejPejRejTejVejXejZej\ej^ej`gZ1dGZ2ejfejhejhejfejjejlejlejjejnejpejpejniZ9ejfdHejldIejpdJejhdKejndLejjdMiZ:GdNdOeZ;GdPdQZ=z<=z!=>d;Z?d<Z@d=ZAd>ZBd?ZCd@ZDdAZEdBZFdCZGdDZHdEZIdFZJdGZKdHZLdIZMdJZNdudKZOdLZPdMZQdNZRdOZSdPZTdQZUdRZVdSZWdTZXdUZYdVZZdvdWZ[dwdXZ\dwdYZ]e\je]_dZZ^d[Z_d\Z`d]Zad^Zbdxd_Zcdxd`ZddsdaZedsdbZfdsdcZgdsddZhdsdeZidvdfZjdsdgZkdhZldydiZmdydjZndtdkZodtdlZpdtdmZqdnZrdoZsdzdpZty){_spbasez This class provides a base class for all sparse arrays. It cannot be instantiated. Most of the work is provided by subclasses. g333333$@rK)r&returnc,t|jSN)len_shapeselfs rndimz _spbase.ndim^s4;;rcH|j}t|dk(rd|dfS|S)Nr)rUrT)rWss r _shape_as_2dz_spbase._shape_as_2dbs( KK Vq[1R5z/a/rcddlm}|S)Nr) bsr_array)_bsrr^)rWr^s r_bsr_containerz_spbase._bsr_containerg #rcddlm}|S)Nr) coo_array)_coorc)rWrcs r_coo_containerz_spbase._coo_containerlrarcddlm}|S)Nr) csc_array)_cscrg)rWrgs r_csc_containerz_spbase._csc_containerqrarcddlm}|S)Nr) csr_array)_csrrk)rWrks r_csr_containerz_spbase._csr_containervrarcddlm}|S)Nr) dia_array)_diaro)rWros r_dia_containerz_spbase._dia_container{rarcddlm}|S)Nr) dok_array)_dokrs)rWrss r_dok_containerz_spbase._dok_containerrarcddlm}|S)Nr) lil_array)_lilrw)rWrws r_lil_containerz_spbase._lil_containerrarNmaxprintcd|_|jjdk(r tdt |t r t j|r td| t|_ y||_ y)NrPz7This class is not intended to be instantiated directly.zEscipy sparse array classes do not support instantiation from a scalar) rU __class__r ValueError isinstancernpisscalarMAXPRINTr{)rWarg1r{s r__init__z_spbase.__init__sf >> " "i /=> > dG $T):W %-$4 ( rc|jSrS)rUrVs rshapez _spbase.shapes {{rct||jtdd}t|\}}||jk(r|r|j S|S|j |j ||dS)areshape(self, shape, order='C', copy=False) Gives a new shape to a sparse array/matrix without changing its data. Parameters ---------- shape : tuple of ints The new shape should be compatible with the original shape. order : {'C', 'F'}, optional Read the elements using this index order. 'C' means to read and write the elements using C-like index order; e.g., read entire first row, then second row, etc. 'F' means to read and write the elements using Fortran-like index order; e.g., read entire first column, then second column, etc. copy : bool, optional Indicates whether or not attributes of self should be copied whenever possible. The degree to which attributes are copied varies depending on the type of sparse array being used. Returns ------- reshaped : sparse array/matrix A sparse array/matrix with the given `shape`, not necessarily of the same format as the current object. See Also -------- numpy.reshape : NumPy's implementation of 'reshape' for ndarrays rA)allow_ndcopyF)orderr)rrrangerrtocooreshape)rWargskwargsrrrs rrz_spbase.reshapesnBD$**uQ|D*62 t DJJ yy{" zztz$,,U%e,LLrcDtt|jd)aResize the array/matrix in-place to dimensions given by ``shape`` Any elements that lie within the new shape will remain at the same indices, while non-zero elements lying outside the new shape are removed. Parameters ---------- shape : (int, int) number of rows and columns in the new array/matrix Notes ----- The semantics are not identical to `numpy.ndarray.resize` or `numpy.resize`. Here, the same data will be maintained at each index before and after reshape, if that index is within the new bounds. In numpy, resizing maintains contiguity of the array, moving elements around in the logical array but not within a flattened representation. We give no guarantees about whether the underlying data attributes (arrays, etc.) will be modified in place or replaced with new objects. z.resize is not implemented)NotImplementedErrortyper)rWrs rresizez_spbase.resizes)0"Dz""##= >@ @rct|}|j|k7r;|jj|||j |j S|r|j S|S)aCast the array/matrix elements to a specified type. Parameters ---------- dtype : string or numpy dtype Typecode or data-type to which to cast the data. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Defaults to 'unsafe' for backwards compatibility. 'no' means the data types should not be cast at all. 'equiv' means only byte-order changes are allowed. 'safe' means only casts which can preserve values are allowed. 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. 'unsafe' means any data conversions may be done. copy : bool, optional If `copy` is `False`, the result might share some memory with this array/matrix. If `copy` is `True`, it is guaranteed that the result and this array/matrix do not share any memory. )castingr)rdtypetocsrastypeasformatformatr)rWrrrs rrz_spbase.astypesa, :: ::<&&wT'33;8DKK3H I 99; Krc ft|trtj|fi|St |fi|SrS) issubclassrrasarrayrclsXrs r _ascontainerz_spbase._ascontainers0 c7 #::a*6* *A(( (rc ft|trtj|fi|St |fi|SrS)rrrarrayr rs r _containerz_spbase._containers0 c7 #88A(( (!&v& &rcgd}|jj|vr|S|D]7}|jtj|ks&|j|cSt d|jj d)z6Upcast array to a floating point format (if necessary))fdFDzcannot upcast [z] to a floating point format)rcharrr TypeErrorname)rWfp_typesfp_types r _asfptypez_spbase._asfptype sv( ::??h &K# 0::'!22;;w// 0!$**//!22NO rc#TKt|jdD] }|| yw)Nr)rr)rWrs r__iter__z_spbase.__iter__s+tzz!}% Aq'M s&(c|jS)z3Maximum number of elements to display when printed.rzrVs r _getmaxprintz_spbase._getmaxprint s }}rcL|jj}td|d)aNumber of non-zero entries, equivalent to np.count_nonzero(a.toarray(), axis=axis) Unlike the nnz property, which return the number of stored entries (the length of the data attribute), this method counts the actual number of non-zero entries in data. Duplicate entries are summed before counting. Parameters ---------- axis : {-2, -1, 0, 1, None} optional Count nonzeros for the whole array, or along a specified axis. .. versionadded:: 1.15.0 Returns ------- numpy array A reduced array (no axis `axis`) holding the number of nonzero values for each of the indices of the nonaxis dimensions. Notes ----- If you want to count nonzero and explicit zero stored values (e.g. nnz) along an axis, two fast idioms are provided by `numpy` functions for the common CSR, CSC, COO formats. For the major axis in CSR (rows) and CSC (cols) use `np.diff`: >>> import numpy as np >>> import scipy as sp >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]]) >>> major_axis_stored_values = np.diff(A.indptr) # -> np.array([2, 1]) For the minor axis in CSR (cols) and CSC (rows) use `numpy.bincount` with minlength ``A.shape[1]`` for CSR and ``A.shape[0]`` for CSC: >>> csr_minor_stored_values = np.bincount(A.indices, minlength=A.shape[1]) For COO, use the minor axis approach for either `axis`: >>> A = A.tocoo() >>> coo_axis0_stored_values = np.bincount(A.coords[0], minlength=A.shape[1]) >>> coo_axis1_stored_values = np.bincount(A.coords[1], minlength=A.shape[0]) Examples -------- >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]]) >>> A.count_nonzero(axis=0) array([2, 1, 0]) z"count_nonzero not implemented for .r}rrrWaxisclsnames r count_nonzeroz_spbase.count_nonzero$s)n..))!$Fwiq"QRRrcL|jj}td|d)a6Number of stored values, including explicit zeros. Parameters ---------- axis : {-2, -1, 0, 1, None} optional Report stored values for the whole array, or along a specified axis. See also -------- count_nonzero : Number of non-zero entries zgetnnz not implemented for rrrs r_getnnzz_spbase._getnnz^s(..))!$?y"JKKrc"|jS)zNumber of stored values, including explicit zeros. See also -------- count_nonzero : Number of non-zero entries rrVs rnnzz _spbase.nnzm||~rc"|jS)zwNumber of stored values. See also -------- count_nonzero : Number of non-zero values. rrVs rsizez _spbase.sizewrrc|jS)zFormat string for matrix.)_formatrVs rrz_spbase.formats||rc"|jS)z Transpose.) transposerVs rTz _spbase.Ts~~rc"|jSrS)_realrVs rrealz _spbase.realzz|rc"|jSrS)_imagrVs rimagz _spbase.imagrrc t|j\}}t|trdnd}d|d|d|jd|j d|j d S) Nrr rNz sparse z of dtype 'z' with z stored elements and shape rM)_formatsrrrrrr)rW_ format_name sparse_clss r__repr__z_spbase.__repr__sb!$++.; *4 9Wx  }HZL DJJ<HhhZ:4::,a I rc|j}|j}d}t|}|jdk(r|S|dz }|j|kDr||dz||t fd|j D|j dz }|dz }|z ||t fd|j D|j  dz }|S|||j |j z }|S)Ncdttd|D|}djd|DS)Nc3<K|]}|jywrS)tolist).0cs r z1_spbase.__str__..tostr..s9Qahhj9s c32K|]\}}d|d|yw)z  Nr)ridxvals rrz1_spbase.__str__..tostr..s!E83r#b.Es)zipjoin)coordsdatapairss rtostrz_spbase.__str__..tostrs.9&9:DAE99EuEE Errz Coords Values r&c3(K|] }|d ywrSrrrhalfs rrz"_spbase.__str__..s:Aq$x:z : : c3*K|] }| d ywrSrrs rrz"_spbase.__str__..s;Qq$y;s)rrreprrtuplerr)rWr{Aroutrs @r__str__z_spbase.__str__s$$& JJL F4j 88q=J %% 88h q=D 5:::AFF5DMJ JC < Cd?D 5;!((;;QVVTEF^L LC  5166* *C rcT|jdk(r|jdk7Std)N)rrrz\The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().)rrr~rVs r__bool__z_spbase.__bool__s1 :: 88q= MN Nrctd)Nz:sparse array length is ambiguous; use getnnz() or shape[0])rrVs r__len__z_spbase.__len__s'( (rc|||jk(r|r|jS|S t|d|z} ||S#t$r}t d|d|d}~wwxYw#t $r |cYSwxYw)aReturn this array/matrix in the passed format. Parameters ---------- format : {str, None} The desired sparse format ("csr", "csc", "lil", "dok", "array", ...) or None for no conversion. copy : bool, optional If True, the result is guaranteed to not share data with self. Returns ------- A : This array/matrix in the passed format. NtozFormat z is unknown.r)rrgetattrAttributeErrorr~r)rWrrconvert_methodes rrz_spbase.asformats >Vt{{2yy{"  H!(tf}!=  (%400 " H 76(,!?@aG H  (%'' (s(AA! A AA!A43A4ct|r|j|S|jdkr |j|St |s_t|sTtj|}|jdk(r#|jtjk(rtS |j|j|jk7r tdt|rqtj|j ||j"}|j%}|j'tj(j+|_|St |rk|j-ddj }|j-ddj }|j/|dj-|jStS#t$r"|j j|cYSwxYw#t$r|}YXwxYw)z4Element-wise multiplication by another array/matrix.r(rzEinconsistent shapes: >2D multiply() does not yet support broadcastingrrZ_elmul_)r _mul_scalarrX_multiply_2d_with_broadcastingrrrr r asanyarrayrobject_NotImplementedrr~multiplyrrrviewndarrayravelr_binopt)rWotherother_arresultcsr_self csr_others rrz_spbase.multiplys  ##E* * 99q= J::5AA75>mmE*G||q W]]bjj%@&%   :: $45 5 5>;;tyy% *<=DYY[F))BJJ/557FKM e_||Ar*002H a,224I##Iy9AA$**M M " !I" Jzz|BB5II J"  s#G G2(G/.G/2 HHcvt|sot|sdt|sYtj|}|j dk(r(|j tjk(r td |jt|r|d|r`|tjk(rdnd}td|jd|dtd |j||j!|S|j dkr|n|j#d d j%}|j'||}|j dkr|S|j)j#|jSt|r||j+|St|r|j|jk7r%t-d |jd |j|j dkr.|j%j/|d|jdS|j#d d j%}|j#d d j%}|j/|d|jd}|j)j#|jSt-d#t$r|}Y\%5HmmE*G||q W]]bjj%@*+HII    Q(-(;*wu~~.hwi@&&'>1N~~eDLLNE&BCC$(IIMDt||Ar7JQQS!00>!%QvVFLLN4J4J4::4VV U^/ / e_zzU[[( #C }Nekk^!TUUyy1}zz|++EQu~~6Fa3HII||Ar*002H a,224I%%i1U^^4DA1FGF<<>))$**5 578 83"  s/ J)) J87J8cB|j|tjS)z;Element-wise maximum between this and another array/matrix.)rrrrWr s rrz_spbase.maximum@$$UBJJ77rcB|j|tjS)z;Element-wise minimum between this and another array/matrix.)rrminimumrs rrz_spbase.minimumDrrc@tj|r||zS||zS)a/Ordinary dot product Examples -------- >>> import numpy as np >>> from scipy.sparse import csr_array >>> A = csr_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) )rrrs rdotz _spbase.dotHs$ ;;u %< %< rcD|jj||S)zElement-wise power.r)rpower)rWnrs rr$z _spbase.powerZszz|!!!5!11rc|j|k(r|r|jS|S|jj||SrS)rrr _broadcast_to)rWrrs rr'z_spbase._broadcast_to^s: :: "&499; 0D 0::<--eT: :rc  t|s{t|spt|set|rtSt j |}|jdk(r#|jt jk(rtS |jt|r|d|st j|r+|j|jt jS|jdkr|n|jddj!}|j#||}|jdkr|S|j%j|jSt'd|dt(|dt(t*|d t,d t j|r>|jt j.|jt jS|jdkr|n|jddj!}|j#|t*|}|jt j.|jt j}||z }|jdkr|S|j%j|jSt|r||j1|St|r|j|jk7r?|t2j4t2j6fvr|t2j6uSt9d |jdkr|n|jddj!}|jdkr|n|jddj!} |ddsZ|j;| d |j<d }|jdkr|S|j%j|jSt'd t(|dt(t*|d t,d |j;| d t*|j<d }|jt j.|jt j}||z }|jdkr|S|j%j|jStS#t$r|}YNwxYw)Nrr#r(rrZzComparing a sparse matrix with z using z is inefficient. Try using z instead.rzinconsistent shaperz$Comparing two sparse matrices using )rr r rrrrrXrrrrisnanr}bool_rrrrrop_symop_negronesroperatoreqner~r r) rWr opr r resinvall_truer rs r _comparisonz_spbase._comparisonds75>\%5H!%(%%mmE*G||q W]]bjj%@&%    a<88E?>>$**BHH>EE(, A 4<<2;NUUWH"11%>"''$**BHH*MNN%)IIMDt||Ar7JQQS--eVBZ@#--bgghnnBHH.UV!C!%QvVFLLN4J4J4::4VV U^dllne, , e_zzU[[((++x{{33,, !566 $ A 4<<23FMMOH"'**q.emmAr6JQQSIa8!)))q Q5GH!%QvVFLLN4J4J4::4VV;F2J<H2282D1EYP,<&&yAfRj6I6I5J!2LM#--bgghnnBHH.UV!C!%QvVFLLN4J4J4::4VV" !m"  s; S SScB|j|tjSrS)r5r.r/rs r__eq__z_spbase.__eq__x{{33rcB|j|tjSrS)r5r.r0rs r__ne__z_spbase.__ne__r8rcB|j|tjSrS)r5r.ltrs r__lt__z_spbase.__lt__r8rcB|j|tjSrS)r5r.gtrs r__gt__z_spbase.__gt__r8rcB|j|tjSrS)r5r.lers r__le__z_spbase.__le__r8rcB|j|tjSrS)r5r.gers r__ge__z_spbase.__ge__r8rc4t|jSrS)absrrVs r__abs__z_spbase.__abs__s4::<  rc8t|j|S)N)ndigits)roundr)rWrKs r __round__z_spbase.__round__sTZZ\733rc@|jj|SrS)r _add_sparsers rrOz_spbase._add_sparsezz|''..rc@|jj|SrS)r _add_densers rrRz_spbase._add_denseszz|&&u--rc@|jj|SrS)r _sub_sparsers rrTz_spbase._sub_sparserPrc(|j|z SrSrrs r _sub_densez_spbase._sub_denses||~%%rc(||jz SrSrVrs r _rsub_densez_spbase._rsub_densest||~%%rc\t|r |dk(r|jStdt|r5|j|jk7r t d|j |St|r1tj||j}|j|StS)Nrz:adding a nonzero scalar to a sparse array is not supportedinconsistent shapes) r rrrrr~rOr r broadcast_torRrrs r__add__z_spbase.__add__s  zyy{"%'FG G e_{{djj( !677##E* * U^OOE4::6E??5) )! !rc$|j|SrS)r]rs r__radd__z_spbase.__radd__s||E""rc\t|r |dk(r|jStdt|r5|j|jk7r t d|j |St|r1tj||j}|j|StS)NrzAsubtracting a nonzero scalar from a sparse array is not supportedr[) r rrrrr~rTr rr\rWrrs r__sub__z_spbase.__sub__s  zyy{"%'FG G e_{{djj( !677##E* * U^OOE4::6E??5) )! !rct|r!|dk(r|j Stdt|r1t j ||j }|j|StS)NrzAsubtracting a sparse array from a nonzero scalar is not supported) r rrr rr\rrYrrs r__rsub__z_spbase.__rsub__sf  z |#%'HI I U^OOE4::6E##E* *! !rc|j\}}|jtjur|j|fk(r|j |S|j|dfk(rQ|j |j }|jdk(r|jdS|j|dS|jdk(r#|jd|k(r|j|St|r|j|Sd}t|rD||jdk7r!t|d|d|jdd|j|Stj|}|jdk(r#|j tj"k(rt$S |j|jdk(s!|jdk(r|jddk(r|jd|k7r!t|d|d|jdd|j tj |}t)|tj*r|j-|}|jdk(rF|jddk(r4|jdk(r|jd}|S|jd d}|S|jdk(r|jd|k7r!t|d|d|jdd|jtj.|}t)|tj*r|j-|}|Std #t&$r|}YwxYw) anp.array-like matmul & `np.matrix`-like mul, i.e. `dot` or `NotImplemented` interpret other and call one of the following self._mul_scalar() self._matmul_vector() self._matmul_multivector() self._matmul_sparse() rr&rz)matmul: dimension mismatch with signaturez (n,k=z),(k=z ,m)->(n,m)z ,1?)->(n,1?)rZzcould not interpret dimensions)r\r}rrr_matmul_vectorrrXr_matmul_multivectorr rrr~_matmul_sparserrrrrrr rr)rWr MNr  err_prefixr s r_matmul_dispatchz_spbase._matmul_dispatchs  1 ??bjj ({{qd"**511A&,,U[[];99>!>>!,,~~a++qU[[^q%8//66  ##E* *@ E?EKKN" !l&5Q0@ K&&u- ---& <<1 "**!<" !  KK ::?ejjAo%++a.A2E{{1~" !l&5Q0@ M((%9F%+**62zzQ5;;q>Q#699>#^^A.FM$^^B2FM ZZ1_{{1~" !l&5Q0@ K--bjj.?@F%+**62M=> >S E s M MMc$|j|SrSrrs r__mul__z_spbase.__mul__c}}U##rc$|j|SrSrmrs r__rmul__z_spbase.__rmul__frorc@|jj|SrS)rrrs rrz_spbase._mul_scalarjrPrc@|jj|SrS)rrers rrez_spbase._matmul_vectormzz|**511rc@|jj|SrS)rrfrs rrfz_spbase._matmul_multivectorpszz|//66rc@|jj|SrS)rrgrs rrgz_spbase._matmul_sparsesrtrc:t|r|j|S |j}|jj |}|turtS|jS#t$r&t j |j}YkwxYwrS)r rrrrrrkr)rWr trrets r_rmatmul_dispatchz_spbase._rmatmul_dispatchvs  ##E* * 3__&.."33B7Cn$%%==? " " 3ZZ&002 3sA++,BBcPt|r td|j|SNz0Scalar operands are not allowed, use '*' instead)r r~rkrs r __matmul__z_spbase.__matmul__s-  /0 0$$U++rcPt|r td|j|Sr|)r r~rzrs r __rmatmul__z_spbase.__rmatmul__s-  /0 0%%e,,rc@t|sjt|s_t|sTtj|}|j dk(r#|j tjk(rtS |jt|rO|rJ|r$tj||jStj||jS|r_tj|j tjr1|j!tjj#d|z S|j#d|z }tj$|j }tj&|j tj(r?tj&|tj(r|j!|j S|St|r|s@|rtjd|}ntjd|}|j+|S|r$tj||jStj||jSt|r|r|j-||dS|j dkr|n|j/ddj1}|j dkr|n|j/ddj1} |r]tj|j tjr/|j!tjj3| } n|j3| } |j dkr| S| j/|jStS#t$r|}Y&wxYw)Nr?F)rdivider(rrZ)rr r rrrXrrrrr true_dividerdividecan_castfloat64rrr issubdtypeintegerr_dividerr_divide_sparse) rWr rrr r scalar_dtyperecipr rr s rrz_spbase._divides75>\%5HmmE*G||q W]]bjj%@&%    >>%@@99UDLLN;;r{{4::rzzB{{2::.::2e8DD$$RX.!zz%066 MM$**bjj9 lBJJ?88DJJ//H U^NN2u5EIIb%0E}}U++>>%@@99UDLLN;; e_}}T;}FF $ A 4<<23FMMOH"&))a-U]]1b5IPPRIr{{4::rzzB!4CCIN!00;!YY]6 Jtzz0J J" !a"  s* N NNc(|j|dSNT)rrrs r __truediv__z_spbase.__truediv__s||Et|44rc(|j|dSrrrs r__div__z_spbase.__div__s||Et|44rctSrSrrs r __rtruediv__z_spbase.__rtruediv__rctSrSrrs r__rdiv__z_spbase.__rdiv__rrc$|j SrS)rrVs r__neg__z_spbase.__neg__s }rctSrSrrs r__iadd__z_spbase.__iadd__rctSrSrrs r__isub__z_spbase.__isub__rrctSrSrrs r__imul__z_spbase.__imul__rrc$|j|SrS) __itruediv__rs r__idiv__z_spbase.__idiv__s  ''rctSrSrrs rrz_spbase.__itruediv__rrc&|j|i|SrS)r$)rWrrs r__pow__z_spbase.__pow__stzz4*6**rcH|j|j|dS)a Reverses the dimensions of the sparse array/matrix. Parameters ---------- axes : None, optional This argument is in the signature *solely* for NumPy compatibility reasons. Do not pass in anything except for the default value. copy : bool, optional Indicates whether or not attributes of `self` should be copied whenever possible. The degree to which attributes are copied varies depending on the type of sparse array/matrix being used. Returns ------- p : `self` with the dimensions reversed. Notes ----- If `self` is a `csr_array` or a `csc_array`, then this will return a `csc_array` or a `csr_array`, respectively. See Also -------- numpy.transpose : NumPy's implementation of 'transpose' for ndarrays rF)axesr)rr)rWrrs rrz_spbase.transposes%:zztz$..Du.EErctj|jtjr"|j |j dS|r|j S|S)aElement-wise complex conjugation. If the array/matrix is of non-complex data type and `copy` is False, this method does nothing and the data is not copied. Parameters ---------- copy : bool, optional If True, the result is guaranteed to not share data with self. Returns ------- A : The element-wise complex conjugate. rF)rrrcomplexfloatingr conjugaterrWrs rrz_spbase.conjugatesO ==R%7%7 8::4:(222> > 99; Krc&|j|S)Nr)rrs rconjz _spbase.conj1s~~4~((rc>|jjSrS)rrrVs rrz _spbase._real6zz|!!##rc>|jjSrS)rrrVs rrz _spbase._imag9rrc~|j}|jdk7tfd|jDS)aNonzero indices of the array/matrix. Returns a tuple of arrays (row,col) containing the indices of the non-zero elements of the array. Examples -------- >>> from scipy.sparse import csr_array >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) >>> A.nonzero() (array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32)) rc3(K|] }| ywrSr)rrnz_masks rrz"_spbase.nonzero..Ns6cS\6r)rrrr)rWrrs @rnonzeroz_spbase.nonzero<s2 JJL&&A+6QXX666rc|jdk(r td|jd}|dkr||z }|dks||k\r td|j dg|gdggf|df|j }||z}|S)zeReturns a copy of column j of the array, as an (m x 1) sparse array (column vector). rz4getcol not provided for 1d arrays. Use indexing A[j]rZrindex out of boundsrr)rXr~r IndexErrorrir)rWjri col_selectorr s r_getcolz_spbase._getcolPs 99>ST T JJrN q5 FA q5AF23 3**QC1#s+<23Qtzz+K  $ rc|jdk(r td|jd}|dkr||z }|dks||k\r td|j dgdg|ggfd|f|j }||zS)z^Returns a copy of row i of the array, as a (1 x n) sparse array (row vector). rz$getrow not meaningful for a 1d arrayrrr)rXr~rrrmr)rWirh row_selectors r_getrowz_spbase._getrowcs 99>CD D JJqM q5 FA q5AF23 3**QC1#s+<23Qtzz+K d""rcF|j|j||S)a6 Return a dense representation of this sparse array. Parameters ---------- order : {'C', 'F'}, optional Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. The default is 'None', which provides no ordering guarantees. Cannot be specified in conjunction with the `out` argument. out : ndarray, 2-D, optional If specified, uses this array as the output buffer instead of allocating a new array to return. The provided array must have the same shape and dtype as the sparse array on which you are calling the method. Returns ------- arr : ndarray, 2-D An array with the same shape and containing the same data represented by the sparse array, with the requested memory order. If `out` was passed, the same object is returned after being modified in-place to contain the appropriate values. rr)rrrWrrs rrz_spbase.todenses"8  Es!CDDrcH|jdj||S)a Return a dense ndarray representation of this sparse array/matrix. Parameters ---------- order : {'C', 'F'}, optional Whether to store multidimensional data in C (row-major) or Fortran (column-major) order in memory. The default is 'None', which provides no ordering guarantees. Cannot be specified in conjunction with the `out` argument. out : ndarray, 2-D, optional If specified, uses this array as the output buffer instead of allocating a new array to return. The provided array must have the same shape and dtype as the sparse array/matrix on which you are calling the method. For most sparse types, `out` is required to be memory contiguous (either C or Fortran ordered). Returns ------- arr : ndarray, 2-D An array with the same shape and containing the same data represented by the sparse array/matrix, with the requested memory order. If `out` was passed, the same object is returned after being modified in-place to contain the appropriate values. Frr)rrrs rrz_spbase.toarrays%<zzuz%--Es-CCrcF|j|jdS)zConvert this array/matrix to Compressed Sparse Row format. With copy=False, the data/indices may be shared between this array/matrix and the resultant csr_array/matrix. rF)rrrs rrz _spbase.tocsr# zztz$***66rcF|j|jdS)zConvert this array/matrix to Dictionary Of Keys format. With copy=False, the data/indices may be shared between this array/matrix and the resultant dok_array/matrix. rF)rtodokrs rrz _spbase.todokrrcF|jdj|S)zConvert this array/matrix to COOrdinate format. With copy=False, the data/indices may be shared between this array/matrix and the resultant coo_array/matrix. Fr)rrrs rrz _spbase.tocoo# zzuz%+++66rcF|jdj|S)zConvert this array/matrix to List of Lists format. With copy=False, the data/indices may be shared between this array/matrix and the resultant lil_array/matrix. Fr)rtolilrs rrz _spbase.tolilrrcF|j|jdS)zConvert this array/matrix to sparse DIAgonal format. With copy=False, the data/indices may be shared between this array/matrix and the resultant dia_array/matrix. rF)rtodiars rrz _spbase.todiarrcH|jdj||S)a+Convert this array/matrix to Block Sparse Row format. With copy=False, the data/indices may be shared between this array/matrix and the resultant bsr_array/matrix. When blocksize=(R, C) is provided, it will be used for construction of the bsr_array/matrix. Fr) blocksizer)rtobsr)rWrrs rrz _spbase.tobsrs%zzuz%++id+KKrcF|j|jdS)zConvert this array/matrix to Compressed Sparse Column format. With copy=False, the data/indices may be shared between this array/matrix and the resultant csc_array/matrix. rF)rtocscrs rrz _spbase.tocscrrc(|j|dS)zReturns a copy of this array/matrix. No data/indices will be shared between the returned value and current array/matrix. Tr)r}rVs rrz _spbase.copys ~~d~..rctjtj}kjdk(r,t j jdg|xs||St j jt||Str(dk(rdjdfnjddf}n(tfdtjD}|+jt j||xs|}n|j|k7r tdjd kDrj||Sdk(rNjt j djdf|}|zj#||d <|Sjt j jddf|}|zj#||d <|S) a Sum the array/matrix elements over a given axis. Parameters ---------- axis : {-2, -1, 0, 1, None} optional Axis along which the sum is computed. The default is to compute the sum of all the array/matrix elements, returning a scalar (i.e., `axis` = `None`). dtype : dtype, optional The type of the returned array/matrix and of the accumulator in which the elements are summed. The dtype of `a` is used by default unless `a` has an integer dtype of less precision than the default platform integer. In that case, if `a` is signed then the platform integer is used while if `a` is unsigned then an unsigned integer of the same precision as the platform integer is used. .. versionadded:: 0.18.0 out : np.matrix, optional Alternative output matrix in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. .. versionadded:: 0.18.0 Returns ------- sum_along_axis : np.matrix A matrix with the same shape as `self`, with the specified axis removed. See Also -------- numpy.matrix.sum : NumPy's implementation of 'sum' for matrices rXr)rrrrc3FK|]}|vsj|ywrSr)rrrrWs rrz_spbase.sum..As WRVdjjmWs !!r#z!out dimensions do not match shaper&.)r rXrrrrsumrr rrrrzerosr~_sum_ndr-r)rWrrr res_dtype new_shaper-s`` rrz _spbase.sum sLDtyy1"$**-  <xx1}vvd//4EPy$QRCyyI% !DEE 99q=<<i5 5 4<$$RWWaA-?y%QRDt ,,Y7CH  $$RWWdjjmQ-?y%QRDt ,,Y7CH rc2t|j}tjjtj xs.tjjtj }|rtjn j}j|}| tjj}ntjfd|D}|d|z zj|||}|||j|dS|S)a Compute the arithmetic mean along the specified axis. Returns the average of the array/matrix elements. The average is taken over all elements in the array/matrix by default, otherwise over the specified axis. `float64` intermediate and return values are used for integer inputs. Parameters ---------- axis : {-2, -1, 0, 1, None} optional Axis along which the mean is computed. The default is to compute the mean of all elements in the array/matrix (i.e., `axis` = `None`). dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for floating point inputs, it is the same as the input dtype. .. versionadded:: 0.18.0 out : np.matrix, optional Alternative output matrix in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. .. versionadded:: 0.18.0 Returns ------- m : np.matrix See Also -------- numpy.matrix.mean : NumPy's implementation of 'mean' for matrices rc3<K|]}j|ywrSr)raxrWs rrz_spbase.mean..s<djjn>> from scipy.sparse import csr_array >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) >>> A.diagonal() array([1, 0, 5]) >>> A.diagonal(k=1) array([2, 3]) k)rdiagonal)rWrs rrz_spbase.diagonals0zz|$$q$))rcB|j|jS)aReturns the sum along diagonals of the sparse array/matrix. Parameters ---------- offset : int, optional Which diagonal to get, corresponding to elements a[i, i+offset]. Default: 0 (the main diagonal). r)rr)rWoffsets rtracez _spbase.traces}}v}&**,,rc|j\}}|dkDr||k\s |dkr| |k\r td|jtj||y)a Set diagonal or off-diagonal elements of the array/matrix. Parameters ---------- values : array_like New values of the diagonal elements. Values may have any length. If the diagonal is longer than values, then the remaining diagonal entries will not be set. If values are longer than the diagonal, then the remaining values are ignored. If a scalar value is given, all of the diagonal is set to it. k : int, optional Which off-diagonal to set, corresponding to elements a[i,i+k]. Default: 0 (the main diagonal). rzk exceeds array dimensionsN)rr~_setdiagrr)rWvaluesrrhris rsetdiagz_spbase.setdiagsO(zz1 Ea1f!a%QB!G9: : bjj(!,rc|j\}}|dkry|jdk(r*t||z|}t|D] }||||z |f<yt||z|t |}|dkryt |d|D]\}}||||z |f<y|jdk(r*t|||z }t|D] }|||||zf<yt|||z t |}|dkryt |d|D]\}}|||||zf<y)zZThis part of the implementation gets overridden by the different formats. rN)rrXminrrT enumerate)rWrrrhri max_indexrvs rrz_spbase._setdiags>zz1 q5{{a!QK y),A%+DQN, !QF 4 >%fZi&89'DAq%&DQN'{{a1Q3K y),A%+DAEN, 1Q3F 4 >%fZi&89'DAq%&DAEN'rc|Q| td|j|jk7s|j|jk7r tdd|d<|Stj|j|j|S)Nz,order cannot be specified if out is not Nonez6out array must be same dtype and shape as sparse arrayg.)rr)r~rrrrrs r_process_toarray_argsz_spbase._process_toarray_argssy ?  "/00yyDJJ&#))tzz*A "011CHJ88DJJdjjF FrcHddlm}||||xrt|t S)a Determine index dtype for array. This wraps _sputils.get_index_dtype, providing compatibility for both array and matrix API sparse matrices. Matrix API sparse matrices would attempt to downcast the indices - which can be computationally expensive and undesirable for users. The array API changes this behaviour. See discussion: https://github.com/scipy/scipy/issues/16774 The get_index_dtype import is due to implementation details of the test suite. It allows the decorator ``with_64bit_maxval_limit`` to mock a lower int32 max value for checks on the matrix API's downcasting behaviour. r)get_index_dtype)_sputilsrrr)rWarraysmaxvalcheck_contentsrs r_get_index_dtypez_spbase._get_index_dtypes/" .v% . Pz$7P3PS Sr)unsafeTrS)Fr)FF)NF)T)NN)NNN)rNF)urrrr__array_priority__r _allow_ndpropertyintrXr\r`rerirmrqruryrrrrr classmethodrrrrrrrrrstrrrrrrrr __nonzero__rrrrrrr!r$r'r5r7r:r=r@rCrFrIrMrOrRrTrWrYr]r_rarcrkrnrqrrerfrgrzr}rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrPrPUsGI  c  00*. C)MV@6>)) ''  8St LSc   4N K ((N,"\%9N88 $2; G"R444444!4/./&&""#" "\?|$$/272 #$, -="~55(+F>.)$$DL$$7(&#LE<DF77777 L7/KZ5p*4 --2'< GSrrPc eZdZdZedZy)rz3A namespace class to separate sparray from spmatrixc ddlm}|||S)a Return a parametrized wrapper around the `~scipy.sparse.sparray` type. .. versionadded:: 1.16.0 Returns ------- alias : types.GenericAlias A parametrized `~scipy.sparse.sparray` type. Examples -------- >>> import numpy as np >>> from scipy.sparse import coo_array >>> coo_array[np.int8, tuple[int]] scipy.sparse._coo.coo_array[numpy.int8, tuple[int]] r) GenericAlias)typesr )rargr s r__class_getitem__zsparray.__class_getitem__s( 'C%%rN)rrrrrrrrrrrs=&&rrc"t|tS)aIs `x` of a sparse matrix type? Parameters ---------- x object to check for being a sparse matrix Returns ------- bool True if `x` is a sparse matrix, False otherwise Examples -------- >>> import numpy as np >>> from scipy.sparse import csr_array, csr_matrix, isspmatrix >>> isspmatrix(csr_matrix([[5]])) True >>> isspmatrix(csr_array([[5]])) False >>> isspmatrix(np.array([[5]])) False >>> isspmatrix(5) False )rr)xs rrr3s4 a ""r)>rwarningsrrnumpyrr.rrrrrr r r r r rrscipy._lib._sparserr_matrixr__all__Warningrr!rr frozensetsintanarcsinarctansinhtanharcsinharctanhrintsignexpm1log1pdeg2radrad2degfloorceiltruncsqrt _ufuncs_with_fixed_point_at_zerorr/r0r<rEr?rBr,r+rPrrrrrr-s$ KKKK3 7 G  -  m  EA12  A./  A+,  A'  A34   A12   A|$   A'(  A<=  Az?  B*+  B89  B-.  B;<  B+,  B./  B)*! "45,- $' 0$-  299bggrww  BGGRWWbhh"** BHHbggrxx.:$;  ++x{{HKK ++x{{HKK ++x{{HKK > ++tX[[$ T ++tX[[#x{{C A}Si}S@.&&6//#r