L iN>dZdZgdZddlZddlmZddlZddlm Z dd l m Z dd l m Z mZmZmZmZmZmZdd lmZmZmZmZdd lmZmZdd lmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(Z(GddeeZ)dZ*dZ+dZ,dZ-ddZ.dZ/Gdde)eZ0Gdde e)Z1y)z2 A sparse matrix in COOrdinate or 'triplet' formatzrestructuredtext en) coo_array coo_matrixisspmatrix_cooN)warn)copy_if_needed)spmatrix) coo_tocsr coo_todensecoo_todense_nd coo_matvec coo_matvec_ndcoo_matmat_densecoo_matmat_dense_nd)issparseSparseEfficiencyWarning_spbasesparray) _data_matrix _minmax_mixin) upcast_char to_nativeisshapegetdtypegetdatadowncast_intp_indexget_index_dtype check_shapecheck_reshape_kwargs isscalarlikeisdenseceZdZdZeddZd0dddZedZejdZed Z e jd Z d Z e jje _ d1d Ze jje_ d1d Ze jje_ dZd2dZe j"je_ d3dZe j$je_ d4dZe j&je_ d5dZd5dZd5dZd5dZe j.je_ d5dZe j0je_ d5dZe j2je_ d6dZej4je_ dZd7dZd3dZdZdZ dZ!dZ"d Z#d!Z$d"Z%d#Z&d$Z'd%Z(d&Z)d'Z*d8d(Z+d)Z,d*Z-d+Z.d5d,Z/d-Z0d.Z1d/Z2y)9 _coo_basecoor ANmaxprintc tj|||stt|trst ||j rt||j |_|jt|j t|t}t fdtt|jD|_t!j"g||_d|_n |\}}|/t-d |Dr t+d t d |D}t||j |_|j|t|j.d  t  fd |D|_t1|||_d|_nft3|r$|j4|j4k(rrt d|jD|_|j$j7t|||_t|j.|j |_|j&|_n|j9} t | j|_| j$j7t|| d|_t| j.|j |_d|_n6t!j:|} t|t<s=t!j>| } | j@dk7rt)d| j@dt| j.|j |_|At||j |jk7rd|d|j} t+| |jt|j| jC}t fd|D|_t1| |||_d|_t|jdkDr!t d|jD|_|jEy#t(t*f$r} t)d| d} ~ wwxYw)Nr'allow_ndmaxval)defaultc3LK|]}tjgywdtypeNnparray).0_ idx_dtypes W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/sparse/_coo.py z%_coo_base.__init__..(s)$G)*%'HHRy$A$A$G!$r1Tzinvalid input formatc38K|]}t|dk(yw)rNlenr6idxs r9r:z%_coo_base.__init__..3s;S3s8q=;sz4cannot infer dimensions from zero sized index arraysc3rK|]/}tjtj|dz1ywr N)operatorindexr4maxr?s r9r:z%_coo_base.__init__..6s."5&)#+.."="A"5s57)r-check_contentsc3NK|]}tj|yw)copyr2Nr3)r6r@rIr8s r9r:z%_coo_base.__init__..<s)$8),%'HHSt9$M$M$8s"%rHFc3<K|]}|jywNrIr?s r9r:z%_coo_base.__init__..Cs'Js 'JrLrz!expected 2D array or matrix, not Dzinconsistent shapes: z != c3DK|]}|jdywFrLN)astype)r6r@ index_dtypes r9r:z%_coo_base.__init__..]s&$8),%(JJ{J$G$8s c3^K|]%}|jtjd'ywrP)rQr4int64r?s r9r:z%_coo_base.__init__..cs!XS 288% @Xs+-)#r__init__r isinstancetupler _allow_ndr_shape_get_index_dtyperErfloatranger>coordsr4r5datahas_canonical_format TypeError ValueErroranyshaperrformatrQtocooasarrayr atleast_2dndimnonzero_check)selfarg1rcr2rIr( data_dtypeobjr]er%Mmessager8rRs ` @@r9rUz_coo_base.__init__sdD8<!D dE "tdnn5)$H  11T[[9I1J %eU; #$G.3C 4D.E$GG HHRz: ,0)C"&KC=;F;;(*>??!"5-3"55E)%$..I  11&9>"RDK040I0ID-**,C"' "3DK #0D5 QDI"-cii$.."QDK05D-JJt$!$0 a(Avv{'*KAFF8ST(UVV)!''DNNK $"54>>BdkkQ$9%T[[M"R(11"333t{{;K3L #$806$88 #AfIDF ,0) t{{ a XDKKXXDK m":.C#$:;BCs9QQ8' Q33Q8c|jdkDr|jdStj|j}|j d|S)Nr F)write)rhr]r4 zeros_likecolsetflags)rkresults r9rowz _coo_base.rowgs@ 99q=;;r? "txx(e$ c|jdkr tdtj||jdj }|jdd|fz|jddz|_y)Nrz8cannot set row attribute of a 1-dimensional sparse arrayrsr1)rhrar4rfr]r2)rknew_rows r9ryz _coo_base.rowps` 99q=WX X**WDKKO,A,ABkk#2&'3dkk"#6FF rzc |jdSNr|r])rks r9rvz _coo_base.colws{{2rzctj||jdj}|jdd|fz|_y)Nr|r1)r4rfr]r2)rknew_cols r9rvz _coo_base.col{s9**WDKKO,A,ABkk#2&'3 rzc t||j|j}t|\}}||jk(r|r|j S|St |j |j|}t|dk(r+|dk(rt||d}n.t||dddd}ntj|||}|j|j t| t fd |D}|r|jj }n |j}|j||f|d S) Nr*orderrCr rr|r,c3LK|]}tj|ywr0r4rf)r6cor8s r9r:z$_coo_base.reshape..sPr2::b ::Pr;FrcrI)rrcrXr rI _ravel_coordsr]r>divmodr4 unravel_indexrZrErWr^ __class__) rkargskwargsrcrrI flat_coords new_coordsnew_datar8s @r9reshapez_coo_base.reshapesD$**t~~F*62 t DJJ yy{" $DKK5I u:?|#Kq: #Kq:4R4@ ))+uEJJ))$++c%j)I PZPP  yy~~'HyyH~~x4E~NNrzc||dk(r|jdk(rt|jtfd|jDr t d|jjdk7std|jDr t dt S|dkr||jz }||jk\r t dtjt|jd|z |jd|z S) Nrr c3:K|]}t|k7ywrKr=)r6r@nnzs r9r:z$_coo_base._getnnz..s:s3s8s?:sz3all index and data arrays must have the same lengthc3:K|]}|jdk7ywrB)rhr?s r9r:z$_coo_base._getnnz..s)OC#((a-)Oz'coordinates and data arrays must be 1-Daxis out of bounds minlength) rhr>r^rbr]raintr4bincountrrc)rkaxisrs @r9_getnnzz_coo_base._getnnzs .s'5!$JJs)<<5r;rzaxis z index z exceeds matrix dimension znegative axis z index: N)rhr>r]ra enumerater2kindrnamerZrErcrWrr^rmin)rkrr@r8s @r9rjz_coo_base._checks 99DKK( ($$' $4#5[ MN N  , #FAsyy~~$|A3&>syy~~>NaP !# # ))$++c$**o)N 5(, 55 dii( 88a<#DKK0 N3779 1 -$uQCwswwykB99=A&IJJ779q=$~aS %LMM  N rzc|tjddd}n{ttr[t |drt |jk7r t dt t|jk7rt d|dk7r t dtfd|D}tfd|D}jj|f|| S) Nr|__len__z"axes don't match matrix dimensionszrepeated axis in transpose)r rzoSparse matrices do not support an 'axes' parameter because swapping dimensions is the only logical permutation.c3<K|]}j|ywrK)rYr6rrks r9r:z&_coo_base.transpose..s.s=1 A=rr) r\rhrVrhasattrr>rasetrWrr^)rkaxesrIpermuted_shapepermuted_coordss` r9 transposez_coo_base.transposes <#DbD)D g &4+s4yDII/E !EFF3t9~* !=>> V^9: :.sM(#sC#IMsc3(K|] }| ywrKrr6r@rs r9r:z#_coo_base.resize..s#E#CI#E)rrXrhrar>rr]rcmathprodr4rr^rYrrbzip logical_andreduceallrW) rkrcrmax_size tmp_shapetmp is_truncatingr@sizers @r9resizez_coo_base.resizesEDNN; 99q==> > u:>@A A u: !' TZZ@Kyy'H**;y+A5IDK )8,DIDK  u: ! OSZ!^,$))c%j012  ,,y)C**[c%j1DK))KSZ0DKMc$**e6LMM >>((,/ U,C*(sDd *D88:##E#EE  IIdO  *s H0 c @|j||}t|jj}|s!|jjs t d|j dk(rattjdg|j|j |jd|j|jd|n@|j dk(rY|j\}}t|||j|j |j"|j|jd|n|r7tj$dtj&|jdd}nBtj$tj&|jddddddddd}tj(|j}t||j|j ||j|jd||j+|jS)Nz&Output array must be C or F contiguousr rArr|)_process_toarray_argsrflags f_contiguous c_contiguousrarhr r4r5rr]r^ravelrcr ryrvappendcumprod concatenater) rkroutBfortranrpNstridesr]s r9toarrayz_coo_base.toarrays  & &uc 2agg**+qww33EF F 99> 288QC=$((DII;;q>499aggclG M YY!^::DAq 1dhh$((DII g /))Arzz$**Sb/'BC))BJJtzz!"~dd/C$DTrT$JAN^^DKK0F 7DHHdii!499aggclG Eyy$$rzcr|jdk7rtd|jd|jdk(r'|j|j|j Sddlm}|j|j\}}}}|j|||f|}|js|j|S) aQConvert 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]]) rz+Cannot convert. CSC format must be 2D. Got rNrr1r ) csc_arrayrc) rhrar_csc_containerrcr2_cscr_coo_to_compressed_swapr_r)rkrIrindptrindicesr^rcxs r9tocscz_coo_base.tocsc:s( 99>J499+UVWX X 88q=&&tzz&D D '+/+B+B9??+S (FGT5##T7F$;5#IA,,  "Hrzc|jdkDrtd|jd|jdk(r'|j|j|j Sddlm}|j|j|}|\}}}}|j|||f|j }|js|j|S) aNConvert 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]]) rz*Cannot convert. CSR must be 1D or 2D. Got rNrr1r ) csr_arrayrLr) rhrar_csr_containerrcr2_csrrrrr_r) rkrIrarraysrrr^rcrs r9tocsrz_coo_base.tocsr[s( 99q=I$))TUVW W 88q=&&tzz&D D ',,Y__4,HF+1 (FGT5##T7F$;4::#NA,,  "Hrzc ^||j\}}|j|jt|j|}|j dk(r|r|jdj n|jd}t|}tjd|g|}|r|jj n |j} ||| |jfS||j\} } t| }| j|d} | j|d} tj|dz|}tj| |}tj|j|j} t!|||| | |j||| ||| |jfS)z?convert (shape, coords, data) to (indptr, indices, data, shape)r,r rr1FrL) _shape_as_2drZr]rErrhrIr>r4r5r^rcrQempty empty_liker2r ) rkswaprIrprr8rrrr^majorminors r9rz_coo_base._coo_to_compressed}s]D%%&1))$++c$((A>N)O 99>/3dkk!n))+QGg,CXXq#hi8F'+499>>#D7D$**4 4DKK( u%j YU 3 YU 3!a%y1--Y7}}TYYdjj9!QUE499fgtLwdjj00rzc*|r|jS|SrKrL)rkrIs r9rez_coo_base.tocoos 99; Krzc|jdk7rtd|jd|j|j|jz }t j |d\}}t|dkDrtdt|dtd |jjd k(r"t jd |j }nbt jt||jjd zf|j }|j|||jf<|j||f|j S)Nrz+Cannot convert. DIA format must be 2D. Got rNT)return_inversedzConstructing a DIA matrix with z diagonals is inefficientrr)rrr1r r)rhrarrvryr4uniquer>rrr^rzerosr2rE_dia_containerrc)rkrIksdiagsdiag_idxr^s r9todiaz_coo_base.todias 99>J499+UVWX X  XX ))Bt<x u:  23u:,?""(Q 8 99>>Q 88F$**5D88SZ)9:$**MD'+yyD488# $""D%= "CCrzcn|jdkDrtd|jd|j|j|j|j }|jdk(r|j d}nt|j }tt||j|_ |S)Nrz*Cannot convert. DOK must be 1D or 2D. Got rNr1r r) rhrar_dok_containerrcr2r]rdictr^_dict)rkrIdokr]s r9todokz_coo_base.todoks 99q=I$))TUVW W !!$**DJJ!? 99>[[^F$++&FVTYY/0  rzc  |jdk7r td|j\}}|| ks||k\r+tjd|j j Stjt|t|dz|t|dz |j }|j|z|jk( |jr|j }|j }nCt fd|jD}|j||j \\}}}|||t|dz<|S)Nrz diagonal requires two dimensionsrr1c3(K|] }| ywrKr)r6r@ diag_masks r9r:z%_coo_base.diagonal..s?CY?r)rhrarcr4rr^r2rrrEryrvr_rWr]_sum_duplicates) rkkrowscolsdiagryr^indsr7r s @r9diagonalz_coo_base.diagonals 99>?@ @ZZ d :d88ATYY__5 5xxD3q!9,dSAY.>?"jj*XX\dhh.  $ $((9%C99Y'D?4;;??D!11$ )8LMNHS!d $S3q!9_ rzcx|jdk7r td|j\}}|jr t|sy|jj }|j |jz |k7}|dkrt||z|}|jrt|t|}tj||j |k\}tj| | |z|} tj||} nt|||z }|jrt|t|}tj||j|k\}tj||} tj|||z|} |jr|d|} n&tj||j } || ddtj|j|| ftj|j || ff|_ tj|j|| f|_d|_y)Nrz*setting a diagonal requires two dimensionsrr1F)rhrarcr>ryr2rvrr4 logical_orarangerrr]r^r_) rkvaluesrrprr8 full_keep max_indexkeepr}rrs r9_setdiagz_coo_base._setdiags 99>IJ Jzz1 ;;s6{ HHNN HHtxx'1, q5AaC I{{ 3v;7 ==DHH ,ABDiiQBN)DGii ;GAqs I{{ 3v;7 ==DHH ,ABDii ;Gii1y= BG ;;jy)Hxx ? $)!rzc|rtd|jD}n |j}|j||f|j|jS)zReturns a matrix with the same sparsity structure as self, but with different data. By default the index arrays are copied. c3<K|]}|jywrKrLr?s r9r:z'_coo_base._with_data.. s=#388:=rM)rcr2)rWr]rrcr2)rkr^rIr]s r9 _with_dataz_coo_base._with_datasE ===F[[F~~tVnDJJdjj~QQrzc|jry|j|j|j}|\|_|_d|_y)zeEliminate duplicate entries by adding them together This is an *in place* operation NT)r_rr]r^)rksummeds r9rz_coo_base.sum_duplicatess@  $ $ %%dkk499=!' TY$(!rzc t|dk(r||fStj|dddtfd|D}|}tjj |Dcgc] }|dd|ddk7c}tj dtfd|D}tj\}tjj|t||j}||fScc}w)Nrr|c3(K|] }| ywrKr)r6r@rs r9r:z,_coo_base._sum_duplicates.."s4cs5z4rr Tc3(K|] }| ywrKr)r6r@ unique_masks r9r:z,_coo_base._sum_duplicates..(s:Cs;':rr1) r>r4lexsortrWrrrriaddreduceatrr2)rkr]r^r@ unique_indsrr%s @@r9rz_coo_base._sum_duplicatess t9>4<  6$B$<(4V44E{mm**+1, $'CGs3Bx ,  iik2 :6::zz+. vvt%8%ETZZXt|, s&C9c|jdk7|j|_tfd|jD|_y)z[Remove zero entries from the array/matrix This is an *in place* operation rc3(K|] }| ywrKrrs r9r:z,_coo_base.eliminate_zeros..4s=#CI=rN)r^rWr])rkrs @r9eliminate_zerosz_coo_base.eliminate_zeros-s7 yyA~IIdO === rzc |j|jk7r&td|jd|jdt|jj|jj}t j ||d}t|jj}|jdk(ratt j dg|j|j|jd|j|jd|n@|jd k(rY|j \}}t#|||j|j$|j&|j|jd|n|r7t j(dt j*|jdd }nBt j(t j*|jddddd ddd d}t j,|j}t||j|j||j|jd||j/|d S) NIncompatible shapes ( and rT)r2rIr rrrr|FrL)rcrarr2charr4r5rrrrhr rr]r^rrr ryrvrrr _container) rkotherr2rxrrprrr]s r9 _add_densez_coo_base._add_dense:s ;;$** $4TZZLekk]RSTU UDJJOOU[[-=-=>%u48fll//0 99> 288QC=$((DII;;q>499fll36G R YY!^$$DAq 1dhh$((DII S)7 4))Arzz$**Sb/'BC))BJJtzz!"~dd/C$DTrT$JAN^^DKK0F 7DHHdii!499fll3.? JvE22rzc|jdkr|jj|S|j|jk7r&t d|jd|jd|j |}t j|j|jf}tt j|j|jfd}|j ||f|j}|SNrr.r/rr )rr) rhr _add_sparsercrarr4rr^rWr]rkr2rrrs r9r6z_coo_base._add_sparseRs 99q=::<++E2 2 ;;$** $4TZZLekk]RSTU Uu%>>499ejj"9:2>>4;; *EANO NNHj1N Drzc|jdkr|jj|S|j|jk7r&t d|jd|jd|j |}t j|j|j f}tt j|j|jfd}t||f|j}|Sr5) rhr _sub_sparsercrarr4rr^rWr]rr7s r9r9z_coo_base._sub_sparse^s 99q=::<++E2 2 ;;$** $4TZZLekk]RSTU Uu%>>499uzzk":;2>>4;; *EANO x,DJJ ?rzc |jdkDr:tjtj|j ddt |jj|jj}tj|j }tjtj|ddddddddddd}tj|j}t|jt!|j |||j"|||j%|j dd}|S|jdkDr|j dnd}tj|t |jj|jj}|jdk(r|j&}|j(}nL|jdk(r%|jd}tj*|}nt-d|jt/|j|||j"||t1|t2r |dk(r|dS|S)Nrr|r1r rz$coo_matvec not implemented for ndim=)rhr4rrrrcrr2r0r5rrrr]rrr>r^rrvryruNotImplementedErrorrrVr) rkr2rxrcrr] result_shapervrys r9_matmul_vectorz_coo_base._matmul_vectorjs 99q=XXdii 3B8$/ AQAQ$RTFHHTZZ(Eii 5":dd+; ((C((C YY!^++a.C--$C%6tyykBD D 488S#tyy%@ dG $):!9  rzct|r|j|S |j}t t|ddt t|dddddz}|j|}|j}t t|ddt t|dddddz}|j|j|}|turtS|dk(s|dk(rt|j}nIt t|jddt t|jdddddz}|j|S#t$r%t j |}|j}Y\wxYw)Nrsr|r ) r! _mul_scalarrhAttributeErrorr4rfrWr\r_matmul_dispatchNotImplemented)rkr2o_ndimpermtrs_ndimrets r9_rmatmul_dispatchz_coo_base._rmatmul_dispatchs^  ##E* * $vs+,uU6]235G"5M/NND&BYYFvs+,uU6]235G"5M/NND..&77;Cn$%%{fkSXXU388_Sb12U5?23;OPTRTPT;U5VV==& &!" $ 5) $s E*FFct|r|j|St|s_t|sTt j |}|j dk(r#|jtjk(rtS |j|j dkr%|j dkrtj||S|jd}d}|jtjur"|j|fk(r|j!|S|j|dfk(r@|j!|j#}|j$g|jdddS|j dk(r#|d|d|jdd}t'||jd |k(rK|jdd }|jdd }||k7r t j(|||j+|St'|d |d|jd d t|r|j-|St|r]|j dk(} |j dk(} | r|j%|j.}| r |j%|jddf}||jd k7r!t'|d |d|jd d |j d kDs|j d kDr:|jdd }|jdd }||k7r t j(|||j1|}| r@|j%t3|jdd t3|jddz}| r|j%|jdd}|Sy#t$r|}YwxYw#t&$r t'd wxYw#t&$r t'd wxYw)Nrrr|z)matmul: dimension mismatch with signaturer z (n,k=z),(k=z,)->(n,)rsz&Batch dimensions are not broadcastablez (n,..,k=z,..,m)->(n,..,m)r)r!multiplyrr"r4 asanyarrayrhr2object_rBrcr@rrArndarrayr=rrrabroadcast_shapes_matmul_multivectorr?r_matmul_sparserW) rkr2other_ar err_prefixrxmsg batch_shape_A batch_shape_B self_is_1d other_is_1ds r9rAz_coo_base._matmul_dispatchs  ==' '75>mmE*G||q W]]bjj%@&%   99q=UZZ!^++D%8 8 JJrN@ ??bjj ({{qd"**511{{q!f$,,U[[];%v~~:tzz#2:::zzQ# F1#U5;;q>2B(K o%{{2!# $ 3B % CR 0  M1S++M=I//66 !l)A3eEKKO3DDTU  ##E* * E?aJ**/K||D$5$56 u{{1~q&9:EKKO# !l)A3eEKKO3DDTU yy1} Q $ 3B % CR 0  M1S++M=I((/Ffll3B.?(@(-fll23.?(@)AB Sb(9:MM M"  2&S()QRRSN&S()QRRSs*; NN#N; N N #N8;Oc 8t|jj|jj}|jdk\s|jdk\r|jdk(rn|j d|j dj |}|j t|j ddt|j ddzStj|j dd|j dd}||j ddz}||j ddz}|j|}tj||}||j ddz|j ddz}tj||}t|jt|j |j dtj |tj |tj"|j$|j&|j)d| |S|jdk(r7|j d|j df}|j*}|j,} nC|jdk(r4|j df}|j$d}tj.|} tj|}t1|j|j d |j&|j)d||j3t5| S) Nrr rrsr|r1rr)type)rr2r0rhrrcrOrWr4rN _broadcast_to broadcast_torrrr>r5rr]r^rrvryrurviewrY) rkr2 result_dtyperxbroadcast_shape self_shape other_shaper<rvrys r9rOz_coo_base._matmul_multivectorsf"4::??EKK4D4DE 99>UZZ1_yyA~aA7KKER~~eEKK,<&=ekkRTRUFV@W&WXX 11$**Sb/5;;sPRCSTO(4::bc?:J)EKK,<>RSAQQLXXl,?F #djj/5;;r? " 5rxx 7M "t{{ ; $ 5;;s+;V EM 99> JJqM5;;q>:L((C((C YY!^!KKN,L++a.C--$C,l;5;;r?CEKK$4f >{{U {,,rzct|s|t|sqt|sftj|}|j dk(r5|j tjk(rtdt|d |jt|r||zS|jd|jdddk7r&td|jd|jd |j d kr|j d kr||zSt|r|j|S|j|jS#t$r|}YwxYw) aReturn 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) rz"dot argument not supported type: ''r|rsNzshapes r/z are not aligned for n-D dotr)rr"r!r4rKrhr2rLr`rYrcr@ra _dense_dot _sparse_dotre)rkr2o_arrays r9dotz _coo_base.dot$s+l75>\%5HmmE*G||q W]]bjj%@"DT%[MQR STT   %<  ::b>U[[-a0 0wtzzl% };<= = 99q=UZZ!^%<  5>??5) ) ..!"  s< D>> E  E ct||jdz g\}}t|td|jdz g\}}||jz}|j }||z}g}|r||fn|f} t |j | D]*\} } |jtj| | ,t|j|f|S)Nr rrr) _convert_to_2drhrETrerr]extendr4rrr^) rkr2self_2d s_new_shapeother_2d o_new_shapercombined_shaper] new_shapescss r9rdz_coo_base._sparse_dotts .dTYY]OD .us1ejj1n7M6N O+#zz|%{23>k;/[N  Z0 2DAq MM"**1a0 1 2$))V,NCCrzc"|j}|dkr|dk(rdn|jdf}|}nt||jdz g\}}|j}|dkr|dk(rdn|jdf}|}n|jdd|jddz}|dz gt|dz |dz }t j ||} | j |jdtj|f}||z} ||z} | j | S)Nrr rrr|rs) rhrcrhr\r4rrrr) rkr2rFrlrkrCrnrm reorder_dimso_reorgrros r9rcz_coo_base._dense_dots Q; &! "$**Q-1AKG#1$Q#H G[ Q; &! "%++b/1CKH++cr*U[[-==K"QJGvz):GFQJGLll5,7G B;9O'PQH!%{2||N++rzctsqtsftj}|jdk(r5|j tj k(rtdtd jtjj|\}}tfdt||Dr tdtrj||Sj!||S#t$r|YwxYw)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]], [[ 0, 0], [ 0, 0]]], [[[ 0, 1], [ 0, 5]], [[ 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]]) rz#tensordot arg not supported type: 'rbc3bK|]&\}}j|j|k7(ywrKr)r6axbxr2rks r9r:z&_coo_base.tensordot.. s292rzz"~R09s,/z*sizes of the corresponding axes must match)r"rr4rKrhr2rLr`rYrcr@ _process_axesrbrra_dense_tensordot_sparse_tensordot)rkr2r other_array axes_self axes_others`` r9 tensordotz_coo_base.tensordotsru~huo--.K1$):):bjj)H"Ed5k]RS TUU $ !.diiT J : 9 J79 9IJ J 5>(( :F F))%JG G" $# $s3 C>> D  D ctt||\}}t||\}}||jz}t|s|S|j}||z} g} |r||fn|f} t |j | D]-\} } | s | j tj| | /t|j| f| S)Nr) rhrirrerr]rjr4rrr^)rkr2s_axeso_axesrkrlrmrnrror]rprqrrs r9r|z_coo_base._sparse_tensordots .dF; .uf =+#~Kzz|%{23>k;/[N  Z0 6DAq b..q!45 6 $))V,NCCrzc(t|j}t|j}t|Dcgc] }||vs| }}|Dcgc]}|j|}}|Dcgc]}|j|} }t|Dcgc] }||vs| } }|Dcgc]}|j|} }| Dcgc]}|j|} }|j||z} t j|| dd|z| ddz}g| t j |}g| ddt j | | dd}| j|j|j|Scc}wcc}wcc}wcc}wcc}wcc}wr) r>rcr\rr4rrrrf)rkr2rrrFrCr s_non_axes s_axes_shapes_non_axes_shape o_non_axes o_axes_shapeo_non_axes_shapeleftright reshape_left reshape_rights r9r{z_coo_base._dense_tensordot.sTZZU[[!!&vBA!6/aB B/56! 1 6 63=>aDJJqM>>!&vBA!6/aB B0671 A7 74>?qEKKN??~~j612 UJsOf$B7?s/ E6E6 E;(F FF!F =Fc|jdkr%|jdkrtj||S|j}|j}t j |dd|dd}t ||ddz}t ||ddz}|j|}|j|}t|} t|} | | zj} t| g||jd|jdS)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. rNrsr|r) rhrrPrcr4rNrWrZ _block_diagre_extract_block_diag) rkr2r_r`r^self_new_shapeother_new_shapeself_broadcastedother_broadcastedself_block_diagother_block_diagprod_block_diags r9rPz_coo_base._matmul_sparseCs 99q=UZZ!^))$6 6ZZ kk --j"o{3B?OP/*RS/A0;rs3CC--n=!//@&&67&'89+-==DDF# EOETZZ^EU[[_E  rzcb|j|k(r|r|jS|S|j}t|t|kr tddt|t|z zt |z}t dt ||Drtd|d|j|}t|jt|}|j}|j}|dd}d} |d|dk7rY|d} | | z} tj|| }tjtjd | | |j } | f}t#d t|dz dD]} || || k7r|| } | | z} t|} tj|| }t tj|| dzd| }tjtjd | | | } | f|z}tj|| | } | f|z}t%||f|S) NzDNew shape must have at least as many dimensions as the current shaperc3:K|]\}}|dk7xr||k7ywrBr)r6ons r9r:z*_coo_base._broadcast_to..|s$Etq!Q!16!Erzcurrent shape z- cannot be broadcast to new shape {new_shape}r,r|r rr1rs)rcrIr>rarWrbrrrr]rEr^r4tilerepeatrrr\r)rk new_shaperI old_shapercr8r]rr cum_repeat repeat_countnew_dimrrs r9rZz_coo_base._broadcast_toms, :: ""&499; 0D 0JJ  y>C N *56 6IY785;KK Es5)/DE E~i[9BBC C||E"#DKKIG 99BC[  9 " %$R=L , &Jwwx6Hii !\ KTXXVG!JrSZ\?B/ 5AQx9Q<'(| l* (m778\:"277:acd+;\#JK ))BIIaY$OQTU%Z*4 ''&)Z8%Z*4 ! 5$(J/;;rzct||\}}tj|jddf|}||zj ||d<|S)Nr r1.)rhr4onesrcr)rkr res_dtyperA2drrs r9_sum_ndz_coo_base._sum_ndsL'd3Yww ! a( :$J'' 2C rzct||\}}|jd||}tj|jd|}t |j |f|S)Nr r)rh_min_or_max_axisr4rr]rr^)rkr min_or_maxexplicitrrresunraveled_coordss r9_min_or_max_axis_ndz_coo_base._min_or_max_axis_ndsX'd3Y""1j(;++CJJqM9E#(($45yAArzcjt||\}}|jd|||}|j|S)Nr )rh_argminmax_axisr)rkr argminmaxcomparerrrres_flats r9_argminmax_axis_ndz_coo_base._argminmax_axis_nds9'd3Y&&q)WhG **rz)NNFrK)NF)returnN)NN)F)r)T)r)3__name__ __module__ __qualname___formatr\rXrUpropertyrysetterrvrr__doc__rrrjrrrrrrrerr rrrrrrr,r3r6r9r=rHrArOrfrdrcrr|r{rPrZrrrrrzr9r$r$sGa IGTGR ZZGG  ZZ44!OFoo--GO;(oo--GO W$1199MN2?$ ))11I$L^^++FN%2oo--GOB D16 MM))EMD,MM))EM MM))EM($,,44H$*NR )&>30  B'2[z!-FN/`D*,6nH`D4L*( T5rrr\rrW) rkrcrrr^ryrvrtemp_block_idxrrs r9rrs9eBi5E 99DxxC3u:txx02r *0Qx&- 1 '4/0 dE*-.e <.#=rV|+rVG|+=c38K|]}|k\xs| kywrKr)r6ryndim_bs r9r:z _process_axes..rrz/axes indices are out of bounds for input arraysz3axes must be an integer or a tuple/list of integersr) rVrrralistr\rWr>rbr`)rrraxes_aaxes_brs`` r9rzrzs&$ !8tc&&11MN NeFTM623eDk" D%$, ' t9>DE E v;#f+ %KL L =f= = =f= =NO OMNN>D EdtaxdVmT1 EF E>D EdtaxdVmT1 EF E 6>F Es 8D*D/c tfdD}tfdD}t||}tj}tfdt |D}|rctfd|D}tfd|D}t||} | |f} t j |t j |f} n|f} t j |f} d}tj| f| } | |fS)Nc3<K|]}j|ywrKrr6rr%s r9r:z!_convert_to_2d..s4! 1 4rc3<K|]}j|ywrKrrs r9r:z!_convert_to_2d..s2syy|2rc3,K|] }|vs| ywrKr)r6rrs r9r:z!_convert_to_2d..s=1q}Q=s c3<K|]}j|ywrKrrs r9r:z!_convert_to_2d.. s@! 1 @rc3<K|]}j|ywrKrrs r9r:z!_convert_to_2d.. s>syy|>rrr) rWrr>r]r\rrrr^) r%r axis_coords axis_shape axis_ravelrhnon_axisnon_axis_coordsnon_axis_shapenon_axis_ravel coords_2dshape_2dnew_coos `` r9rhrhs4t44K2T22J{J7J szz?D=d ==H@x@@>X>>&G#Z0 IIn-tyy/DEM IIj)+9-X>G N ""rzct|dk(r|dSt|dk(r|\}}|\}}|dk(rI|td|dz ztd|dz z}t|}tj||||zS|dk(rI|td|dz ztd|dz z}t|}tj||||zSt dtj ||| S) z;Like np.ravel_multi_index, but avoids some overflow issues.r rrrr,r1Fz'order' must be 'C' or 'F'r)r>rErr4rJraravel_multi_index) r]rcrnrowsncolsryrvr-r8s r9rrs 6{aay 6{a uS C<c!UQY//#a2CCF'v6I;;uc;cA A c\c!UQY//#a2CCF'v6I;;uc;cA A9: :  U ;;rzc"t|tS)aIs `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 )rVr)rs r9rr-s. a $$rzceZdZdZy)ra  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)rrrrrrzr9rrHskrzrceZdZdZdZy)ra. 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]]) cd|vr%|jd|jdf|d<|jj|y)Nr]ryrv)pop__dict__update)rkstates r9 __setstate__zcoo_matrix.__setstate__(s> 5  %yy/51ABE(O U#rzN)rrrrrrrzr9rrsn`$rzr)r)2r __docformat____all__rwarningsrnumpyr4 _lib._utilr_matrixr _sparsetoolsr r r rrrr_baserrrr_datarr_sputilsrrrrrrrrr r!r"rCr$rrrzrhrrrrrrzr9rs8% 7 '000GF.QQQQ\+ m\+~$F2=2.#,<*%6l 7l^v$9v$rz