L idZdZgdZddlZddlZddlZddlmZm Z m Z ddl m Z m Z mZddlmZdd lmZmZdd lmZmZdd lmZmZdd lmZmZdd lmZmZddl m!Z!m"Z"d-dZ#ddddddZ$d.dZ%d/dZ&d0de'dddZ(d1dZ)dde'dfdZ*d0dZ+d0dZ,dZ-dZ.d2dZ/d2dZ0d2dZ1dddd Z2d3d!Z3d2d"Z4e d#d$d%dddd&d'Z5 d4d(Z6e d#d)* d5d+Z7e d#d)*d6d,Z8y)7z2Functions to construct sparse matrices and arrays zrestructuredtext en)spdiagseyeidentitykronkronsumhstackvstackbmatrandrandomdiags block_diag diags_array block_array eye_array random_arrayN)check_random_state rng_integers_transition_to_rng)upcastget_index_dtype isscalarlike) csr_hstack) bsr_matrix bsr_array) coo_matrix coo_array) csc_matrix csc_array) csr_matrix csr_array) dia_matrix dia_array)issparsesparraycz||t|dx}}n||\}}t||f||fj|S)a Return a sparse matrix from diagonals. .. warning:: This function returns a sparse matrix -- not a sparse array. You are encouraged to use `dia_array` to take advantage of the sparse array functionality. (See Notes below.) Parameters ---------- data : array_like Matrix diagonals stored row-wise diags : sequence of int or an int Diagonals to set: * k = 0 the main diagonal * k > 0 the kth upper diagonal * k < 0 the kth lower diagonal m, n : int, tuple, optional Shape of the result. If `n` is None and `m` is a given tuple, the shape is this tuple. If omitted, the matrix is square and its shape is ``len(data[0])``. format : str, optional Format of the result. By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. Returns ------- new_matrix : sparse matrix `dia_matrix` format with values in ``data`` on diagonals from ``diags``. Notes ----- This function can be replaced by an equivalent call to `dia_matrix` as:: dia_matrix((data, diags), shape=(m, n)).asformat(format) See Also -------- diags_array : more convenient form of this function diags : matrix version of diags_array dia_matrix : the sparse DIAgonal format. Examples -------- >>> import numpy as np >>> from scipy.sparse import spdiags >>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) >>> diags = np.array([0, -1, 2]) >>> spdiags(data, diags, 4, 4).toarray() array([[1, 0, 3, 0], [1, 2, 0, 4], [0, 2, 3, 0], [0, 0, 3, 4]]) rshape)lenr#asformat)datar mnformats ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/sparse/_construct.pyrrsNv yQYDG A 1 tUmAq6 2 ; ;F CC)offsetsr)r/dtypecft|r>t|dk(st|drtj|g}n.t dt t tj|}tj|}t|t|k7r t d|*t|dtt|dz}||f}|tj|}|\}}t|Dcgc]!}t||z||z td|z#c}}td|}tjt||f|} t||} t|D]T\} } || }td|} t||z||z | }|dkrt d|d| d | dd|f| | | | |zf<Vt| |f||fj|Scc}w#t$rG}t| |k7r3t| d k7r%t d | d t| d |d |d|d |d}~wwxYw)aA Construct a sparse array from diagonals. Parameters ---------- diagonals : sequence of array_like Sequence of arrays containing the array diagonals, corresponding to `offsets`. offsets : sequence of int or an int, optional Diagonals to set (repeated offsets are not allowed): - k = 0 the main diagonal (default) - k > 0 the kth upper diagonal - k < 0 the kth lower diagonal shape : tuple of int, optional Shape of the result. If omitted, a square array large enough to contain the diagonals is returned. format : {"dia", "csr", "csc", "lil", ...}, optional Matrix format of the result. By default (format=None) an appropriate sparse array format is returned. This choice is subject to change. dtype : dtype, optional Data type of the array. Returns ------- new_array : dia_array `dia_array` holding the values in `diagonals` offset from the main diagonal as indicated in `offsets`. Notes ----- Repeated diagonal offsets are disallowed. The result from ``diags_array`` is the sparse equivalent of:: np.diag(diagonals[0], offsets[0]) + ... + np.diag(diagonals[k], offsets[k]) ``diags_array`` differs from `dia_array` in the way it handles off-diagonals. Specifically, `dia_array` assumes the data input includes padding (ignored values) at the start/end of the rows for positive/negative offset, while ``diags_array`` assumes the input data has no padding. Each value in the input `diagonals` is used. .. versionadded:: 1.11 See Also -------- dia_array : constructor for the sparse DIAgonal format. Examples -------- >>> from scipy.sparse import diags_array >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]] >>> diags_array(diagonals, offsets=[0, -1, 2]).toarray() array([[1., 0., 1., 0.], [1., 2., 0., 2.], [0., 2., 3., 0.], [0., 0., 3., 4.]]) Broadcasting of scalars is supported (but shape needs to be specified): >>> diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4)).toarray() array([[-2., 1., 0., 0.], [ 1., -2., 1., 0.], [ 0., 1., -2., 1.], [ 0., 0., 1., -2.]]) If only one diagonal is wanted (as in `numpy.diag`), the following works as well: >>> diags_array([1, 2, 3], offsets=1).toarray() array([[ 0., 1., 0., 0.], [ 0., 0., 2., 0.], [ 0., 0., 0., 3.], [ 0., 0., 0., 0.]]) rz*Different number of diagonals and offsets.Nr3zOffset z (index z) out of bounds.rzDiagonal length (index : z at offset z") does not agree with array size (z, z).r()rr*np atleast_1d ValueErrorlistmapabsint common_typemaxminzeros enumerater$r+) diagonalsr2r)r/r3r-r.offsetMdata_arrKjdiagonalklengthes r0rr]s`fG y>Q ,y|"<y12IIJ JR]]I67 mmG$G 9~W%EFF }  ! C O 4 4A } * DAq " $VQZ (3q&> 9 $ %A Aq AxxWq)7H Aq A + 8 6NQZVQ/ A:wvhhqcIJ J &.s7F7{&;HQ!F( ] # h(A 7 @ @ HH/ $ 8}&3x=A+= -aS3x=/B%h&H2aSPRT   s2&G&G  H0)AH++H0cTt||||}t|j|S)a Construct a sparse matrix from diagonals. .. warning:: This function returns a sparse matrix -- not a sparse array. You are encouraged to use `diags_array` to take advantage of the sparse array functionality. Parameters ---------- diagonals : sequence of array_like Sequence of arrays containing the matrix diagonals, corresponding to `offsets`. offsets : sequence of int or an int, optional Diagonals to set (repeated offsets are not allowed): - k = 0 the main diagonal (default) - k > 0 the kth upper diagonal - k < 0 the kth lower diagonal shape : tuple of int, optional Shape of the result. If omitted, a square matrix large enough to contain the diagonals is returned. format : {"dia", "csr", "csc", "lil", ...}, optional Matrix format of the result. By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. dtype : dtype, optional Data type of the matrix. Returns ------- new_matrix : dia_matrix `dia_matrix` holding the values in `diagonals` offset from the main diagonal as indicated in `offsets`. Notes ----- Repeated diagonal offsets are disallowed. The result from ``diags`` is the sparse equivalent of:: np.diag(diagonals[0], offsets[0]) + ... + np.diag(diagonals[k], offsets[k]) ``diags`` differs from `dia_matrix` in the way it handles off-diagonals. Specifically, `dia_matrix` assumes the data input includes padding (ignored values) at the start/end of the rows for positive/negative offset, while ``diags`` assumes the input data has no padding. Each value in the input `diagonals` is used. .. versionadded:: 0.11 See Also -------- spdiags : construct matrix from diagonals diags_array : construct sparse array instead of sparse matrix Examples -------- >>> from scipy.sparse import diags >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]] >>> diags(diagonals, [0, -1, 2]).toarray() array([[1., 0., 1., 0.], [1., 2., 0., 2.], [0., 2., 3., 0.], [0., 0., 3., 4.]]) Broadcasting of scalars is supported (but shape needs to be specified): >>> diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)).toarray() array([[-2., 1., 0., 0.], [ 1., -2., 1., 0.], [ 0., 1., -2., 1.], [ 0., 0., 1., -2.]]) If only one diagonal is wanted (as in `numpy.diag`), the following works as well: >>> diags([1, 2, 3], 1).toarray() array([[ 0., 1., 0., 0.], [ 0., 0., 2., 0.], [ 0., 0., 0., 3.], [ 0., 0., 0., 0.]]) r2r)r3)rr#r+)rCr2r)r/r3As r0r r s*r Iwe5IA a= ! !& ))r1c t||||S)a[Identity matrix in sparse format Returns an identity matrix with shape ``(n, n)`` using a given sparse format and dtype. This differs from `eye_array` in that it has a square shape with ones only on the main diagonal. It is thus the multiplicative identity. `eye_array` allows rectangular shapes and the diagonal can be offset from the main one. .. warning:: This function returns a sparse matrix -- not a sparse array. You are encouraged to use `eye_array` to take advantage of the sparse array functionality. Parameters ---------- n : int Shape of the identity matrix. dtype : dtype, optional Data type of the matrix format : str, optional Sparse format of the result, e.g., format="csr", etc. Returns ------- new_matrix : sparse matrix A square sparse matrix with ones on the main diagonal and zeros elsewhere. See Also -------- eye_array : Sparse array of chosen shape with ones on a specified diagonal. eye : Sparse matrix of chosen shape with ones on a specified diagonal. Examples -------- >>> import scipy as sp >>> sp.sparse.identity(3).toarray() array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> sp.sparse.identity(3, dtype='int8', format='dia') >>> sp.sparse.eye_array(3, dtype='int8', format='dia') )r3r/)r)r.r3r/s r0rrBsb q!5 00r1)rJr3r/c t|||||S)aoSparse array of chosen shape with ones on the kth diagonal and zeros elsewhere. Return a sparse array with ones on diagonal. Specifically a sparse array (m x n) where the kth diagonal is all ones and everything else is zeros. Parameters ---------- m : int Number of rows requested. n : int, optional Number of columns. Default: `m`. k : int, optional Diagonal to place ones on. Default: 0 (main diagonal). dtype : dtype, optional Data type of the array format : str, optional (default: "dia") Sparse format of the result, e.g., format="csr", etc. Returns ------- new_array : sparse array Sparse array of chosen shape with ones on the kth diagonal and zeros elsewhere. Examples -------- >>> import numpy as np >>> import scipy as sp >>> sp.sparse.eye_array(3).toarray() array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> sp.sparse.eye_array(3, dtype=np.int8) _eyer-r.rJr3r/s r0rrvsN 1a ''r1c |rt}t}t}t} nt}t }t }t} ||}t|t|}}||k(r|dk(r|dvrjt|} tj|dz| } tj|| } tj||} ||d|}|| | | f||fS|dk(r`t|} tj|| }tj|| }tj||} || ||ff||fStjdtdt||z|f|} | | |g||f|j|S)Nr)csrcscmaxvalrr5coorN)r"r rrr!rrr r=rr7arangeonesr?r@r+)r-r.rJr3r/ as_sparray csr_sparse csc_sparse coo_sparse diags_sparse idx_dtypeindptrindicesr,clsrowcols r0rSrSse   "     y  q63q6qAAv!q& ^ #'q1IYYqs)4Fii3G771E*D$Z8@Cgv.A7 7 u_'q1I))AY/C))AY/C771E*Dtc3Z01a&9 9 77As1c!a%m,-U ;D qc!Qu E N Nv VVr1c"t|||||dS)aUSparse matrix of chosen shape with ones on the kth diagonal and zeros elsewhere. Returns a sparse matrix (m x n) where the kth diagonal is all ones and everything else is zeros. .. warning:: This function returns a sparse matrix -- not a sparse array. You are encouraged to use `eye_array` to take advantage of the sparse array functionality. Parameters ---------- m : int Number of rows in the matrix. n : int, optional Number of columns. Default: `m`. k : int, optional Diagonal to place ones on. Default: 0 (main diagonal). dtype : dtype, optional Data type of the matrix. format : str, optional Sparse format of the result, e.g., format="csr", etc. Returns ------- new_matrix : sparse matrix Sparse matrix of chosen shape with ones on the kth diagonaland zeros elsewhere. See Also -------- eye_array : Sparse array of chosen shape with ones on a specified diagonal. Examples -------- >>> import numpy as np >>> import scipy as sp >>> sp.sparse.eye(3).toarray() array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> sp.sparse.eye(3, dtype=np.int8) FrRrTs r0rrs^ 1a ..r1cPt|tst|trt}t}t}nt }t }t}||}|jdk7rtd|jd||dk(r[d|jz|jd|jdzk\r+||d}|jdk7rtd |jd|jd|jdz|jd|jdzf}|jdk(s|jdk(r||j|S|j}|jj|j j#d |jd|jd}||z}|||j$|j&f| S||}|jdk7rtd |jd|jd|jdz|jd|jdzf}|jdk(s|jdk(r||j|St)|j*t-| }t/j0|j2| j|j} t/j0|j4| j|j} |jj|j}| |jdz} | |jdz} | j#d |j| j#d |j} } | |j2z } | |j4z } | j#d | j#d } } |j#d |j|jz}|j#d }||| | ff| j|S)aFkronecker product of sparse matrices A and B Parameters ---------- A : sparse or dense matrix first matrix of the product B : sparse or dense matrix second matrix of the product format : str, optional (default: 'bsr' or 'coo') format of the result (e.g. "csr") If None, choose 'bsr' for relatively dense array and 'coo' for others Returns ------- kronecker product in a sparse format. Returns a sparse matrix unless either A or B is a sparse array in which case returns a sparse array. Examples -------- >>> import numpy as np >>> import scipy as sp >>> A = sp.sparse.csr_array(np.array([[0, 2], [5, 0]])) >>> B = sp.sparse.csr_array(np.array([[1, 2], [3, 4]])) >>> sp.sparse.kron(A, B).toarray() array([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) >>> sp.sparse.kron(A, [[1, 2], [3, 4]]).toarray() array([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) z&kron requires 2D input arrays. `B` is D.bsrrrTcopyz&kron requires 2D input arrays. `A` is r(rXr5) isinstancer&rr"rrr!rndimr9nnzr)r+toarrayr,repeatsizereshaperdrcrcoordsr?r7asarrayrfrg) rOBr/ bsr_sparser^r` output_shaper,rbrfrgs r0rrsWN!WAw!7      1 Avv{A!&&LMM &E/qw!''!*qwwqz:Q/Q qd # 66Q;EaffXRPQ Q 1771:-qwwqz!''!*/DE 55A:!l+44V< < IIKvv}}QVV$,,R 1771:Fax4 !((3<HH qM 66Q;EaffXRPQ Q 1771:-qwwqz!''!*/DE 55A:!l+44V< <$AHHS5FG jji077>jji077>vv}}QUU# qwwqz qwwqz++b' Bquu(=C quu  quu ++b/#++b/C||Bquu%.||B4S *,?HHPPr1ct|tst|tr t}t}n t}t }||}||}|j dk7rtd|j d|j dk7rtd|j d|jd|jdk7r td|jd|jdk7r tdt|j|j}||jd| }||jd| }t||d }t||d } || zj|S) akronecker sum of square sparse matrices A and B Kronecker sum of two sparse matrices is a sum of two Kronecker products kron(I_n,A) + kron(B,I_m) where A has shape (m,m) and B has shape (n,n) and I_m and I_n are identity matrices of shape (m,m) and (n,n), respectively. Parameters ---------- A square matrix B square matrix format : str format of the result (e.g. "csr") Returns ------- kronecker sum in a sparse matrix format rjz#kronsum requires 2D inputs. `A` is rkz#kronsum requires 2D inputs. `B` is rrzA is not squarezB is not squarer5rZ)r/) rpr&rrrrrqr9r)rr3rr+) rOryr/r`identity_sparser3I_nI_mLRs r0rr]s:.!WAw!7 # "1 A1 Avv{>qvvhbIJJvv{>qvvhbIJJwwqzQWWQZ*++wwqzQWWQZ*++ 177AGG $E !''!*E 2C !''!*E 2C S!E"A QE"A E  F ##r1cdk(rdnd}tj|Dcgc]}|jc}}|dj|}t |Dcgc]}|j c}t |j|}tj|j|}tjtfd|Ddz|} |d} d} d} |D]}|j||k7rtd||j|| | |jjz| |jjz } t| | |jz} |j dd| | <| | xx| z cc<| |jz } | |j dz } | | d<|r)dk(rt||| f| |f St||| f|| f Sdk(rt||| f| |f St!||| f|| f Scc}wcc}w) zh Stacking fast path for CSR/CSC matrices or arrays (i) vstack for CSR, (ii) hstack for CSC. rr)arraysrYr5c3<K|]}|jywN _shape_as_2d.0baxiss r0 z+_compressed_sparse_stack..s?1!...?z!incompatible dimensions for axis Nror()r7 concatenater,rrrcr?ruemptysumr9rdslicer!rr"r )blocksrreturn_spmatrix other_axisrr, constant_dimrbrdrc last_indptrsum_dim sum_indicesidxss ` r0_compressed_sparse_stackrs aiQJ >>62a1662 3D!9))*5L&'AQ'A'*499l'CEIhhtyy 2G XXc???!C9 UFA,KGK  $ >>* % 5@ MN N:;)) K 67qyy~~% Wgt(<<=xx}t t # 1>>$''qxx|#  $F2J 19tWf5%,l$;= =tWf5%17$;= = qy$0!(, 79 9$0!-w 79 9C3'As G:G?c t|}|dk(r td|dk(r|dSdk(rdnd}|Dchc]}|j|}}t|dkDrtd|d||\}|Dcgc]}|j}}t j |Dcgc]}|j c}}tfd|D} td|D} t|t| dz | } t j|Dcgc]}|jc}| } |jdkDrt j || } t j |Dcgc]}|jc}| }t j|dz| }t j|}t j|}t||| | ||||| nRt j |dz| }t jd| }t jd|j" }dk(r|dj%|||f| |f S|dj'|||f|| f Scc}wcc}wcc}wcc}wcc}w) zs Stacking fast path for CSR/CSC matrices along the minor axis (i) hstack for CSR, (ii) vstack for CSC. rzMissing block matricesrz"Mismatching dimensions along axis r6c3<K|]}|jywrrrs r0rz*_stack_along_minor_axis..s71!..&7rc3FK|]}t|jywr)r*rdrrs r0rz*_stack_along_minor_axis..s -c!))n -s!rXr5r()r*r9rrcr7rr,rrr?arrayrurdr empty_likerrAr3_csc_container_csr_container)rrn_blocksrrother_axis_dimsr indptr_listdata_catrrrrb stack_dim_cat indptr_cat indices_catrcrdr,s ` r0_stack_along_minor_axisrsf 6{H1}1221}ayaiQJ;ABaq~~j1BOB ?a=j\+,./ /#ML&,,188,K,~~v6!qvv67H777G -f - -C C! S4IJIHHFCqannT2C9UM}}q^^KyA nn%@Aaii%@ R ,*)<-- ,}}X&8\={H7D *,*)<((1I.xx0 qyay''w(?!(, 7(9 9ay''w(?!-w 7(9 9MC-6D&AsI!3I&I+I0 I5ctj|d}td|jDrt |g||St |g||dS)a Stack sparse matrices horizontally (column wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : str sparse format of the result (e.g., "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. dtype : dtype, optional The data-type of the output matrix. If not given, the dtype is determined from that of `blocks`. Returns ------- new_array : sparse matrix or array If any block in blocks is a sparse array, return a sparse array. Otherwise return a sparse matrix. If you want a sparse array built from blocks that are not sparse arrays, use ``block(hstack(blocks))`` or convert one block e.g. ``blocks[0] = csr_array(blocks[0])``. See Also -------- vstack : stack sparse matrices vertically (row wise) Examples -------- >>> from scipy.sparse import coo_matrix, hstack >>> A = coo_matrix([[1, 2], [3, 4]]) >>> B = coo_matrix([[5], [6]]) >>> hstack([A,B]).toarray() array([[1, 2, 5], [3, 4, 6]]) objectr5c3<K|]}t|tywrrpr&rs r0rzhstack.. 7a:a ! 7Trr7rxanyflat_blockrr/r3s r0rrsKPZZh /F 76;; 77vh..vhtDDr1ctj|d}td|jDrt |Dcgc]}|gc}||St |Dcgc]}|gc}||dScc}wcc}w)a Stack sparse arrays vertically (row wise) Parameters ---------- blocks sequence of sparse arrays with compatible shapes format : str, optional sparse format of the result (e.g., "csr") by default an appropriate sparse array format is returned. This choice is subject to change. dtype : dtype, optional The data-type of the output array. If not given, the dtype is determined from that of `blocks`. Returns ------- new_array : sparse matrix or array If any block in blocks is a sparse array, return a sparse array. Otherwise return a sparse matrix. If you want a sparse array built from blocks that are not sparse arrays, use ``block(vstack(blocks))`` or convert one block e.g. ``blocks[0] = csr_array(blocks[0])``. See Also -------- hstack : stack sparse matrices horizontally (column wise) Examples -------- >>> from scipy.sparse import coo_array, vstack >>> A = coo_array([[1, 2], [3, 4]]) >>> B = coo_array([[5, 6]]) >>> vstack([A, B]).toarray() array([[1, 2], [3, 4], [5, 6]]) rr5c3<K|]}t|tywrrrs r0rzvstack..NrrTrr)rr/r3rs r0rr$siRZZh /F 76;; 77F+qs+VU;;F+qs+VUDQQ,+s A. A3ctj|d}td|jDr t |||St |||dS)a Build a sparse array or matrix from sparse sub-blocks Note: `block_array` is preferred over ``bmat``. They are the same function except that ``bmat`` returns a deprecated sparse matrix when none of the inputs are sparse arrays. .. warning:: This function returns a sparse matrix when no inputs are sparse arrays. You are encouraged to use `block_array` to take advantage of the sparse array functionality. Parameters ---------- blocks : array_like Grid of sparse matrices with compatible shapes. An entry of None implies an all-zero matrix. format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional The sparse format of the result (e.g. "csr"). By default an appropriate sparse matrix format is returned. This choice is subject to change. dtype : dtype, optional The data-type of the output matrix. If not given, the dtype is determined from that of `blocks`. Returns ------- bmat : sparse matrix or array If any block in blocks is a sparse array, return a sparse array. Otherwise return a sparse matrix. If you want a sparse array built from blocks that are not sparse arrays, use ``block_array()``. See Also -------- block_array Examples -------- >>> from scipy.sparse import coo_array, bmat >>> A = coo_array([[1, 2], [3, 4]]) >>> B = coo_array([[5], [6]]) >>> C = coo_array([[7]]) >>> bmat([[A, B], [None, C]]).toarray() array([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> bmat([[A, None], [None, C]]).toarray() array([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) rr5c3<K|]}t|tywrrrs r0rzbmat..rrTrrrs r0r r TsGrZZh /F 76;; 77ffe,,ffeTBBr1)r/r3ct|||S)a Build a sparse array from sparse sub-blocks Parameters ---------- blocks : array_like Grid of sparse arrays with compatible shapes. An entry of None implies an all-zero array. format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional The sparse format of the result (e.g. "csr"). By default an appropriate sparse array format is returned. This choice is subject to change. dtype : dtype, optional The data-type of the output array. If not given, the dtype is determined from that of `blocks`. Returns ------- block : sparse array See Also -------- block_diag : specify blocks along the main diagonals diags : specify (possibly offset) diagonals Examples -------- >>> from scipy.sparse import coo_array, block_array >>> A = coo_array([[1, 2], [3, 4]]) >>> B = coo_array([[5], [6]]) >>> C = coo_array([[7]]) >>> block_array([[A, B], [None, C]]).toarray() array([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> block_array([[A, None], [None, C]]).toarray() array([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) )rrs r0rrsV &&% ((r1c  tj|d}|jdk7r td|j\}}|dvrt d|j Drq|dkDrAt|Dcgc]}t||ddfdg}}tj|d}t|dddfd|}||j|d }|S|d vrt d |j Drr|dkDrBt|Dcgc]}t|dd|fdc}g}tj|d}t|dddfd|}||j|d }|Stj|jt}tj|tj} tj|tj} t|D]} t|D]} || | f t|| | f}||| | f<d || | f<| | dk(r|jd| | <nB| | |jdk7r-d| d| d| d|jdd| | d } t| | | dk(r|jd| | <| | |jdk7sd| d| d| d|jdd| | d } t| t!d||D}|(||Dcgc]}|j"}}|rt%|nd}tj&dtj(| }tj&dtj(| }|d|df}tj*||}t-||Dcgc]}|j.dc}t1|}tj*||}tj*||}d}tj2|\}}t5||D]\} } || | f}t7|||j8z}|j:||<tj<|j>|| |||tj<|j@|| |||||j8z }|r tC|||ff|jE|St|||ff|jE|Scc}wcc}wcc}wcc}w)Nrr5rjzblocks must be 2-D)NrVc3TK|] }t|xr|jdk("yw)rVNr%r/rs r0rz_block..s% C!HQK -AHH- - C&(rrFrm)NrWc3TK|] }t|xr|jdk("yw)rWNrrs r0rz_block..s% EAhqk/ahh%// ErTzblocks[z0,:] has incompatible row dimensions. Got blocks[,z].shape[0] == z , expected .z blocks[:,z1] has incompatible column dimensions. Got blocks[z].shape[1] == c34K|]}|jywr)rr)rblocks r0rz_block..s 8Eeii 8srorX)outr3r()#r7rxrqr9r)allrrangerrastyperAboolint64rrrr3rappendcumsumrrrwr?nonzeroziprrrr,addrfrgrr+)rr/r3rrENrrO block_mask brow_lengths bcol_lengthsirHmsgrrblk all_dtypes row_offsets col_offsetsr)r,rbrfrgiijjryidxs r0rrs ZZh /F {{a-.. ,,CAa - Cv{{ CC q5JOPQ(SQ.vad|Q?@SFSZZh7F %VAqD\1o F  U+A M ! E E E q5INqRA.vad|Q?RSFZZh7F %VAqD\1o F  U+A&,,d3J88ARXX.L88ARXX.L1X*q *Aac{&fQqSk*qs "& 1Q3?a'&'nnQ&7LO!!_q(99$QC())*1QC~annQ>O=PQ''3A&7q:C%S/)?a'&'nnQ&7LO!!_q(99&qc*))*1QC~annQ>O=PQ''3A&7q:C%S/)+ **0  8VJ%7 8 8C }+1*+=>Ccii> >'1 #t))Aryy67K))Aryy67K _k"o .E 88Cu %DfZ6H I! I'*5z3I ((3i (C ((3i (C C ZZ #FBB 1 1a4LCquu%FFS  quuk!n#c()D quuk!n#c()D quu  4#s,E:CCFKK dS#J'u 5 > >v FF_TSP?!Js3S'S,1S1S6ctd|Drt}nt}g}g}g}g}d}d} |D]} t| tt j zrttj| } t| r| j} |sH| jdjtjk(r|j| jd| j\} } |j| j |z|j| j"| z|j| j$n| j&\} } tj(tj*| | z| \} }|j| |z|j|| z|j| j-|| z }| | z } t/|t1|| }tj2||}tj2||}tj2|}|| f}||||ff||j5|S)ab Build a block diagonal sparse matrix or array from provided matrices. Parameters ---------- mats : sequence of matrices or arrays Input matrices or arrays. format : str, optional The sparse format of the result (e.g., "csr"). If not given, the result is returned in "coo" format. dtype : dtype specifier, optional The data-type of the output. If not given, the dtype is determined from that of `blocks`. Returns ------- res : sparse matrix or array If at least one input is a sparse array, the output is a sparse array. Otherwise the output is a sparse matrix. Notes ----- .. versionadded:: 0.11.0 See Also -------- block_array diags_array Examples -------- >>> from scipy.sparse import coo_array, block_diag >>> A = coo_array([[1, 2], [3, 4]]) >>> B = coo_array([[5], [6]]) >>> C = coo_array([[7]]) >>> block_diag((A, B, C)).toarray() array([[1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 5, 0], [0, 0, 6, 0], [0, 0, 0, 7]]) c3<K|]}t|tywrr)ras r0rzblock_diag..Os 0a:a ! 0rrrXr5)r)r3)rrrrpr:numbersNumberr7 atleast_2dr%tocoorwr3rrrrfrgr,r)divmodr[ravelrr?rr+)matsr/r3 containerrfrgr, idx_arraysr_idxc_idxrnrowsncolsa_rowa_colrb new_shapes r0r r "sZ 04 00  C C DJ E E  a$/ 1"--*+A A; A!((1+"3"3rxx"?!!!((1+.>>LE5 JJquuu} % JJquuu} % KK 77LE599RYYuU{%;UCLE5 JJuu} % JJuu} % KK "  %& 3ue3DEI ..I .C ..I .C >>$ DI dS#J'y F O OPV WWr1 random_state{Gz?rZ)densityr/r3rng data_samplerct||||||\}}tt|tfd|D}t ||f|j |S)a/Return a sparse array of uniformly random numbers in [0, 1) Returns a sparse array with the given shape and density where values are generated uniformly randomly in the range [0, 1). Parameters ---------- shape : int or tuple of ints shape of the array density : real, optional (default: 0.01) density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items. format : str, optional (default: 'coo') sparse matrix format. dtype : dtype, optional (default: np.float64) type of the returned matrix values. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. This random state will be used for sampling ``indices`` (the sparsity structure), and by default for the data values too (see `data_sampler`). data_sampler : callable, optional (default depends on dtype) Sampler of random data values with keyword arg ``size``. This function should take a single keyword argument ``size`` specifying the length of its returned ndarray. It is used to generate the nonzero values in the matrix after the locations of those values are chosen. By default, uniform [0, 1) random values are used unless `dtype` is an integer (default uniform integers from that dtype) or complex (default uniform over the unit square in the complex plane). For these, the `rng` is used e.g. ``rng.uniform(size=size)``. Returns ------- res : sparse array Examples -------- Passing a ``np.random.Generator`` instance for better performance: >>> import numpy as np >>> import scipy as sp >>> rng = np.random.default_rng() Default sampling uniformly from [0, 1): >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng) Providing a sampler for the values: >>> rvs = sp.stats.poisson(25, loc=10).rvs >>> S = sp.sparse.random_array((3, 4), density=0.25, ... rng=rng, data_sampler=rvs) >>> S.toarray() array([[ 36., 0., 33., 0.], # random [ 0., 0., 0., 0.], [ 0., 0., 36., 0.]]) Providing a sampler for uint values: >>> def random_uint32_to_100(size=None): ... return rng.integers(100, size=size, dtype=np.uint32) >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng, ... data_sampler=random_uint32_to_100) Building a custom distribution. This example builds a squared normal from np.random: >>> def np_normal_squared(size=None, rng=rng): ... return rng.standard_normal(size) ** 2 >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng, ... data_sampler=np_normal_squared) Or we can build it from sp.stats style rvs functions: >>> def sp_stats_normal_squared(size=None, rng=rng): ... std_normal = sp.stats.distributions.norm_gen().rvs ... return std_normal(size=size, random_state=rng) ** 2 >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng, ... data_sampler=sp_stats_normal_squared) Or we can subclass sp.stats rv_continuous or rv_discrete: >>> class NormalSquared(sp.stats.rv_continuous): ... def _rvs(self, size=None, random_state=rng): ... return rng.standard_normal(size) ** 2 >>> X = NormalSquared() >>> Y = X().rvs >>> S = sp.sparse.random_array((3, 4), density=0.25, ... rng=rng, data_sampler=Y) rXc3LK|]}tj|yw)r5Nr7rxrcorbs r0rzrandom_array..s>B 2Y//>s!$r()_randomrr?tuplerr+) r)rr/r3rrr,indrbs @r0rrvsZBwsLIID# s5z2I >#> >C dC[ . 7 7 ??r1c |dks|dkDr tdtj|}tt ||z}t |at jt jrfd}n6t jt jrfd}n j}tt||t jt jjkrAj||d}t j ||d } t#fd | D} nt%|} t'} t%| |krJ|t%| z } | j)t+t"t-|| | f t%| |krJt#t j.t1|  j2} || j5d} | | fS)Nrrz(density expected to be 0 <= density <= 1cttjjtjj|S)Nr5)rr7iinfor@r?)rur3rs r0rz_random..data_samplers:#C$&HHUO$7$7$&HHUO$7$7$(*/ 11r1cTj|j|dzzS)Nruy?)uniform)rurs r0rz_random..data_samplers.  .  .345r1rXF)rureplaceF)r)orderc3JK|]}tj|ywrrrs r0rz_random..s<"BJJr9->> import scipy as sp >>> import numpy as np >>> rng = np.random.default_rng() >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng) Providing a sampler for the values: >>> rvs = sp.stats.poisson(25, loc=10).rvs >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=rvs) >>> S.toarray() array([[ 36., 0., 33., 0.], # random [ 0., 0., 0., 0.], [ 0., 0., 36., 0.]]) Building a custom distribution. This example builds a squared normal from np.random: >>> def np_normal_squared(size=None, rng=rng): ... return rng.standard_normal(size) ** 2 >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, ... data_rvs=np_normal_squared) Or we can build it from sp.stats style rvs functions: >>> def sp_stats_normal_squared(size=None, rng=rng): ... std_normal = sp.stats.distributions.norm_gen().rvs ... return std_normal(size=size, random_state=rng) ** 2 >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, ... data_rvs=sp_stats_normal_squared) Or we can subclass sp.stats rv_continuous or rv_discrete: >>> class NormalSquared(sp.stats.rv_continuous): ... def _rvs(self, size=None, random_state=rng): ... return rng.standard_normal(size) ** 2 >>> X = NormalSquared() >>> Y = X() # get a frozen version of the distribution >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=Y.rvs) Nc|Sr)rudata_rvss r0 data_rvs_kwzrandom..data_rvs_kwps D> !r1r()r=rrr+) r-r.rr/r3rrrrrs ` r0r r soz y  q63q6qA " A[IID# tSk!Q 0 9 9& AAr1c"t||||||S)aGenerate a sparse matrix of the given shape and density with uniformly distributed values. .. warning:: This function returns a sparse matrix -- not a sparse array. You are encouraged to use `random_array` to take advantage of the sparse array functionality. Parameters ---------- m, n : int shape of the matrix density : real, optional density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items. format : str, optional sparse matrix format. dtype : dtype, optional type of the returned matrix values. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. Returns ------- res : sparse matrix Notes ----- Only float types are supported for now. See Also -------- random : Similar function allowing a custom random data sampler random_array : Similar to random() but returns a sparse array Examples -------- >>> from scipy.sparse import rand >>> matrix = rand(3, 4, density=0.25, format="csr", rng=42) >>> matrix >>> matrix.toarray() array([[0.05641158, 0. , 0. , 0.65088847], # random [0. , 0. , 0. , 0.14286682], [0. , 0. , 0. , 0. ]]) )r )r-r.rr/r3rs r0r r xsl !Q 44r1)NNN)rNNN)dNr)T)NN)F)rNNNN)rrZNNN)rrZNN)9__doc__ __docformat____all__rrnumpyr7scipy._lib._utilrrr_sputilsrrr _sparsetoolsr_bsrrr_coorr_cscrr _csrr!r"_diar#r$_baser%r&rrr rfloatrrSrrrrrrrr rrr rrr r rr1r0r.sZ&  F QQ;;$'''''$?DD*+$t4EIPZ*z11h'(auT'(T"WJQeD//dcQL2$j(9V59p,E^-R`=C@#'d+)\]G@QXhN##'Te@$e@P59#',^N337"fB4fBRN355455r1