K iQ9ddlmZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z mZdd lmZdd lmZmZmZmZdd lmZmZGd d eZGddee ZeZy))Callable)Dict)sympy_deprecation_warning is_sequence)as_int) MatrixBase)MutableRepMatrix RepMatrix)_iszero)_liupc _row_structure_symbolic_cholesky_cholesky_sparse_LDLdecomposition_sparse)_lower_triangular_solve_sparse_upper_triangular_solve_sparseceZdZdZefdZedZdZdZ dZ dZ dZ d Z d Zd Zdd Zdd ZeedddZee dddZdZdZddZddZdZdZeje_eje_eje_eje_eje_eje_xZS)SparseRepMatrixa A sparse matrix (a matrix with a large number of zero elements). Examples ======== >>> from sympy import SparseMatrix, ones >>> SparseMatrix(2, 2, range(4)) Matrix([ [0, 1], [2, 3]]) >>> SparseMatrix(2, 2, {(1, 1): 2}) Matrix([ [0, 0], [0, 2]]) A SparseMatrix can be instantiated from a ragged list of lists: >>> SparseMatrix([[1, 2, 3], [1, 2], [1]]) Matrix([ [1, 2, 3], [1, 2, 0], [1, 0, 0]]) For safety, one may include the expected size and then an error will be raised if the indices of any element are out of range or (for a flat list) if the total number of elements does not match the expected shape: >>> SparseMatrix(2, 2, [1, 2]) Traceback (most recent call last): ... ValueError: List length (2) != rows*columns (4) Here, an error is not raised because the list is not flat and no element is out of range: >>> SparseMatrix(2, 2, [[1, 2]]) Matrix([ [1, 2], [0, 0]]) But adding another element to the first (and only) row will cause an error to be raised: >>> SparseMatrix(2, 2, [[1, 2, 3]]) Traceback (most recent call last): ... ValueError: The location (0, 2) is out of designated range: (1, 1) To autosize the matrix, pass None for rows: >>> SparseMatrix(None, [[1, 2, 3]]) Matrix([[1, 2, 3]]) >>> SparseMatrix(None, {(1, 1): 1, (3, 3): 3}) Matrix([ [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 3]]) Values that are themselves a Matrix are automatically expanded: >>> SparseMatrix(4, 4, {(1, 1): ones(2)}) Matrix([ [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]) A ValueError is raised if the expanding matrix tries to overwrite a different element already present: >>> SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2}) Traceback (most recent call last): ... ValueError: collision at (1, 1) See Also ======== DenseMatrix MutableSparseMatrix ImmutableSparseMatrix c , t|dk(rIt|dtr6|dj}|dj}|dj ||fSit|dk(r |ddd|dg}t|dk(rq|dd\}}||cxurnndx}}n-d||fvr t dt|dt|d}}t|dtr|d}d||fvrt dj||t|Dcgc]}|j|} }t|D cgc]} |j| } } | D]8}| D]1} |j||| } | |jk7s+| || f<3:||fSt|dttfrfd} |djD]\\}}}t|tr:|j jD]\\}} }| ||z|| z|St|t t"fr7|j$|fi|\}}D]\}} | ||z|| z|| f|j|}| |||j|nt'|drt)d|dD }|s|j$|dfi|\}}n|d}t|||zk7r%t d jt|||t|D]E}t|D]5} |||z| z} |j| } | |jk7s/| || f<7G|Cj+}|rt-d |Ddznd}|rt-d |Ddznd}nMj+D]:\}} |r||k\s | s| |k\st d j|| fd|dz d|dz ||fSt|dk(rt|dt t"fr|d}d}t/|D]l\}}t|t t"fs|g}t/|D]+\} }||jk7s|j||| f<-t-|t|}n|r t|nd}|}||fSt1|H|\}}}t|D]4}t|D]$} |||z| z} | |jk7s| || f<&6||fScc}wcc} w) Nr rz*Pass rows=None and no cols for autosizing.z2{} and {} must be integers for this specification.c |r;||fvr-|||fk7r#tdj||f|||f|||f<yy)Nz)There is a collision at {} for {} and {}.) ValueErrorformat)ijvsmats [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/matrices/sparse.pyupdatez7SparseRepMatrix._handle_creation_inputs..updates]q6T>a41:o", K!'A41:!>#&'QT c32K|]}t|ywNr).0rs r z:SparseRepMatrix._handle_creation_inputs..s?!{1~?szMThe length of the flat list ({}) does not match the specified size ({} * {}).c3&K|] \}}| ywr$)r%r_s r r&z:SparseRepMatrix._handle_creation_inputs...A1.c3&K|] \}}| ywr$r()r%r*cs r r&z:SparseRepMatrix._handle_creation_inputs..r+r,z?The location {} is out of the designated range[{}, {}]x[{}, {}])len isinstancer rowscolstodokrrrrrange_sympifyzerodictritemslisttuple_handle_creation_inputsranykeysmax enumeratesuper)clsargskwargsr1r2r)r.opr row_indicesr col_indicesvaluer!rvvr*flat flat_listr=rowmatr __class__s @r r;z'SparseRepMatrix._handle_creation_inputsks t9>ja*=7<d1go$Q(D t9>8DAqA~""t!Q @BB$DG_fT!Wod$q'8,!WD$<'$))/d);==9>d D1s||AD D8=d D1s||AD D$/A(/ # R1X 6 CHH,).DAJ// T4''DGdD\2'"&a 6IFQA!!Z0*+'')//*;5JFQB"1q5!a%45#Ae}5%@S%@%@%Mf%M 1d$(=DAq"1q5!a%ad<= LLOq!S\\!_5 6T!W%?tAw???333DGFvFAq$!%QI9~4(B#VC ND$? #4[3!&t3A$-afqj$9E$'LL$7E$0-2QT 33|yy{6:s...26:s...2!IIKDAqQ$Y!T (0#VQFAtaxD1HEt# # Y!^ 47T5M BQAA#A, %3!#e}5%C&s^6EArSXX~%(\\"%5QT 63s8$  %3q6ADDt# #$g=tDOD$4[ +t+AQ OE(%*QT + + t# #AEDs T 7Tc>tddd|jS)Nz The private _smat attribute of SparseMatrix is deprecated. Use the .todok() method instead. z1.9z$deprecated-private-matrix-attributes)deprecated_since_versionactive_deprecations_target)rr3selfs r _smatzSparseRepMatrix._smats' " &+'M  zz|r"c |j|jdd|jdt|jddS)NmethodLDL iszerofunctry_block_diagF)rUrWrX)invgetr )rRrCs r _eval_inversezSparseRepMatrix._eval_inversesDxxvzz(E:#)::lG#D'-zz2BE'JL Lr"ct|s tdi}|jjD]\}}||}|dk7s|||<|j |j |j |S)aXApply a function to each element of the matrix. Examples ======== >>> from sympy import SparseMatrix >>> m = SparseMatrix(2, 2, lambda i, j: i*2+j) >>> m Matrix([ [0, 1], [2, 3]]) >>> m.applyfunc(lambda i: 2*i) Matrix([ [0, 2], [4, 6]]) z`f` must be callable.r)callable TypeErrorr3r8_newr1r2)rRfdokkrfvs r applyfunczSparseRepMatrix.applyfuncsv${34 4 JJL&&( DAq1BQwA  yyDIIs33r"cddlm}||S)z,Returns an Immutable version of this Matrix.r )ImmutableSparseMatrix) immutablerf)rRrfs r as_immutablezSparseRepMatrix.as_immutables4$T**r"ct|S)aCReturns a mutable version of this matrix. Examples ======== >>> from sympy import ImmutableMatrix >>> X = ImmutableMatrix([[1, 2], [3, 4]]) >>> Y = X.as_mutable() >>> Y[1, 1] = 5 # Can set values in Y >>> Y Matrix([ [1, 2], [3, 5]]) )MutableSparseMatrixrQs r as_mutablezSparseRepMatrix.as_mutable$s#4((r"ct|jjdDcgc]}t|||fzc}Scc}w)aReturns a column-sorted list of non-zero elements of the matrix. Examples ======== >>> from sympy import SparseMatrix >>> a=SparseMatrix(((1, 2), (3, 4))) >>> a Matrix([ [1, 2], [3, 4]]) >>> a.CL [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)] See Also ======== sympy.matrices.sparse.SparseMatrix.row_list c*tt|Sr$)r9reversed)rbs r z*SparseRepMatrix.col_list..IsY]^fgh^iYjr"key)sortedr3r=r:rRrbs r col_listzSparseRepMatrix.col_list5s>(06djjl6G6G6IOj/kl!a47*n%lllsA c4t|jS)z2Returns the number of non-zero elements in Matrix.)r/r3rQs r nnzzSparseRepMatrix.nnzKs4::<  r"ct|jjtDcgc]}t |||fzc}Scc}w)aReturns a row-sorted list of non-zero elements of the matrix. Examples ======== >>> from sympy import SparseMatrix >>> a = SparseMatrix(((1, 2), (3, 4))) >>> a Matrix([ [1, 2], [3, 4]]) >>> a.RL [(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)] See Also ======== sympy.matrices.sparse.SparseMatrix.col_list rp)rrr3r=r9r:rss r row_listzSparseRepMatrix.row_listOsE* 4::<$$&D 13!a47*n%3 33sA c ||zS)z"Scalar element-wise multiplicationr()rRscalars r scalar_multiplyzSparseRepMatrix.scalar_multiplyfs }r"cP|j}||zj||z|zS)aReturn the least-square fit to the data. By default the cholesky_solve routine is used (method='CH'); other methods of matrix inversion can be used. To find out which are available, see the docstring of the .inv() method. Examples ======== >>> from sympy import SparseMatrix, Matrix, ones >>> A = Matrix([1, 2, 3]) >>> B = Matrix([2, 3, 4]) >>> S = SparseMatrix(A.row_join(B)) >>> S Matrix([ [1, 2], [2, 3], [3, 4]]) If each line of S represent coefficients of Ax + By and x and y are [2, 3] then S*xy is: >>> r = S*Matrix([2, 3]); r Matrix([ [ 8], [13], [18]]) But let's add 1 to the middle value and then solve for the least-squares value of xy: >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy Matrix([ [ 5/3], [10/3]]) The error is given by S*xy - r: >>> S*xy - r Matrix([ [1/3], [1/3], [1/3]]) >>> _.norm().n(2) 0.58 If a different xy is used, the norm will be higher: >>> xy += ones(2, 1)/10 >>> (S*xy - r).norm().n(2) 1.5 rU)TrY)rRrhsrUts r solve_least_squaresz#SparseRepMatrix.solve_least_squaresjs-l FF$||6|*1,S00r"c|jsI|j|jkr td|j|jkDr tdy|j |j |S)zReturn solution to self*soln = rhs using given inversion method. For a list of possible inversion methods, see the .inv() docstring. zUnder-determined system.z]For over-determined system, M, having more rows than columns, try M.solve_least_squares(rhs).r}N) is_squarer1r2rrYmultiply)rRrrUs r solvezSparseRepMatrix.solveso ~~yy499$ !;<<TYY& "NOO'8868*33C8 8r"NzAlternate faster representationct|Sr$)rrQs r liupczSparseRepMatrix.liupcs d|r"ct|Sr$)rrQs r row_structure_symbolic_choleskyz/SparseRepMatrix.row_structure_symbolic_choleskys /55r"ct||SN) hermitian)rrRrs r choleskyzSparseRepMatrix.choleskys ::r"ct||Sr)rrs r LDLdecompositionz SparseRepMatrix.LDLdecompositions' BBr"ct||Sr$)rrRrs r lower_triangular_solvez&SparseRepMatrix.lower_triangular_solve-dC88r"ct||Sr$)rrs r upper_triangular_solvez&SparseRepMatrix.upper_triangular_solverr")rV)T)__name__ __module__ __qualname____doc__ classmethodr;propertyrSr[rdrhrkrtrvrxr{rrRLCLrrrrrrrrrr __classcell__)rMs@r rrsSj~$~$@  L 4@+ )"m,!3.71r 9 (D$(I JB (D$(I JB6;C99/5nnEM.N.V.V#+.>.F.FH.F.N.N.D.L.L".D.L.L""r"rceZdZedZy)rjcv|j|i|\}}}|j|||}|j|Sr$)r;_smat_to_DomainMatrix_fromrep)rArBrCr1r2rreps r r_zMutableSparseMatrix._newsC6366GGdD''dD9||C  r"N)rrrrr_r(r"r rjrjs!!r"rjN)collections.abcrsympy.core.containersrsympy.utilities.exceptionsrsympy.utilities.iterablesrsympy.utilities.miscr matrixbaser repmatrixr r utilitiesr decompositionsrrrrsolversrrrrj SparseMatrixr(r"r rsT$&@1'"2DvMivMr !/+;!# r"