K iKbddlmZddlmZmZmZddlmZddlm Z m Z m Z ddl m Z ddlmZmZdZd Zd Zd Zd Zd ZdZefdZdZddZddZddZddZddZy)) expand_mul)Dummyuniquely_named_symbolsymbols)numbered_symbols) ShapeErrorNonSquareMatrixErrorNonInvertibleMatrixError)_fuzzy_positive_definite)_get_intermediate_simp_iszerocjs tdjjk7r tdjjjfdS)aSolves ``Ax = B`` efficiently, where A is a diagonal Matrix, with non-zero diagonal entries. Examples ======== >>> from sympy import Matrix, eye >>> A = eye(2)*2 >>> B = Matrix([[1, 2], [3, 4]]) >>> A.diagonal_solve(B) == B/2 True See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve LDLsolve LUsolve QRsolve pinv_solve cramer_solve zMatrix should be diagonalz Size mismatchc"||f||fz SN)ijMrhss \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/matrices/solvers.pyz!_diagonal_solve..+sQTQq!tW)<) is_diagonal TypeErrorrows_newcols)rrs``r_diagonal_solver sV6 ==?344 xx166(( 66 #((< >>rc Dddlm}js td|jjk7r t dj s tdt}|jj|jt|jD]ltjD]Rfdk(r td||ftfdtDz fz f<TnjS) Solves ``Ax = B``, where A is a lower triangular matrix. See Also ======== upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve cramer_solve rMutableDenseMatrixMatrix must be square.Matrices size mismatch. Matrix must be lower triangular.rMatrix must be non-singular.c3<K|]}|f|fzywrr.0krXrrs r z*_lower_triangular_solve..Ps-+;,-,-QT71QT7?+;)denser# is_squarer rr is_lower ValueErrorr zerosrrangersumrrrr#dpsr,rrs` @@@r_lower_triangular_solver8.s"* ;;"#;<< xx166233 ::;<< "C  " "166388 4A 388_Gqvv GAAw!| >??3q!t9s+;16q+;(;;>?1gFGAadG  GG 66!9rc |js td|j|jk7r td|js t dt }t|jDcgc]}g}}|jD]"\}}}||kDs ||j||f$|j}t|jD]Z}t|jD]@}||D]\}}|||fxx||||fzzcc<||||f|||fz |||f<B\|j|Scc}w)r!r$r%r&) r0r rr r1r2r r4row_listappend as_mutablerr rrr7rrrvr,us r_lower_triangular_solve_sparser@UsN" ;;"#;<< xx166233 ::;<< ! #Caff &1B &D &::<#1a q5 GNNAq6 "# A 388_-sxx -AQ %1!Q$1Qq!tW9$ %!AqD'AadG+,AadG  -- 66!9 's4 Ec rddlm}js td|jjk7r t dj s tdt}|jj|jt|jD]ttjD]`fdk(r td||ftfdtdzjDz fz f<bjS) Solves ``Ax = B``, where A is an upper triangular matrix. See Also ======== lower_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve cramer_solve rr"r$Matrix size mismatch.Matrix is not upper triangular.rr'c3<K|]}|f|fzywrrr)s rr-z*_upper_triangular_solve..s/+G,-,-QT71QT7?+Gr.)r/r#r0r rr is_upperrr r3rr4reversedr2r5rr6s` @@@r_upper_triangular_solverHs("* ;;"#;<< xx166011 ::9:: "C  " "166388 4A 388_S%-( SAAw!| !?@@3q!t9s+G16q1uaff1E+G(GGJKAqD'RSAadG  SS 66!9rc |js td|j|jk7r td|js t dt }t|jDcgc]}g}}|jD]"\}}}||ks ||j||f$|j}t|jD]l}tt|jD]I}t||D]\}}|||fxx||||fzzcc<||||f|||fz |||f<Kn|j|Scc}w)rBr$rCrD)r0r rr rFrr r4r:r;r<rrGrr=s r_upper_triangular_solve_sparserJsX" ;;"#;<< xx166011 ::9:: ! #Caff &1B &D &::<#1a q5 GNNAq6 "# A 388_-%/* -A a) %1!Q$1Qq!tW9$ %!AqD'AadG+,AadG  -- 66!9 's4 Ec|j|jkr tdd}d}|jrd}n|jsd}|s t |dur?|j }|j|}|j|}|j }|j|}|j|}|r|j j|S|jj|S)aSolves ``Ax = B`` using Cholesky decomposition, for a general square non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned. See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve cramer_solve 6Under-determined System. Try M.gauss_jordan_solve(rhs)TF hermitian) rrNotImplementedError is_symmetric is_hermitianr Hmultiplycholeskylower_triangular_solveupper_triangular_solveT)rrrNreformrRLYs r_cholesky_solver[s( vv! DF FIF~~ ^^ )!,5CCJJqMJJsO((  Y 'A   %A++A..++A..rc|j|jkr tdd}d}|jrd}n|jsd}|s t |dur?|j }|j|}|j|}|j }|j|\}}|j|}|j|}|r|j j|S|jj|S)aSolves ``Ax = B`` using LDL decomposition, for a general square and non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned. Examples ======== >>> from sympy import Matrix, eye >>> A = eye(2)*2 >>> B = Matrix([[1, 2], [3, 4]]) >>> A.LDLsolve(B) == B/2 True See Also ======== sympy.matrices.dense.DenseMatrix.LDLdecomposition sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LUsolve QRsolve pinv_solve cramer_solve rLTFrM) rrrOrPrQr rRrSLDLdecompositionrUdiagonal_solverVrW) rrrNrXrRrYDrZZs r _LDLsolveras> vv! DF FIF~~ ^^ )!,5CCJJqMJJsO((    2DAq # #C (A  A A++A..++A..rcn |j|jk7r td|j}|j}||kr td |j |d\}}t |j|j}t|D]:}tt||D] } ||| f |j|| fd"<||kDrNt||D]4}t|jD]} |||| frt d6|d|d d f}t|d z d d D]Q}t|d z|D] } ||| f |j|| fd "|||f |j| fd S|j|S#t $r t dwxYw)aSolve the linear system ``Ax = rhs`` for ``x`` where ``A = M``. This is for symbolic matrices, for real or complex ones use mpmath.lu_solve or mpmath.qr_solve. See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve QRsolve pinv_solve LUdecomposition cramer_solve z4``M`` and ``rhs`` must have the same number of rows.z&Underdetermined systems not supported.T) iszerofunc rankcheck Matrix det == 0; not invertible.c ||zz Srrxyr7scales rrz_LUsolve..hCEAI ,>rzThe system is inconsistent.rNrc ||zz Srrrgs rrz_LUsolve..wrkrc dz|zS)Nrlr)rh_r7rjs rrz_LUsolve..zsUBY]!3r)rr rrOLUdecomposition_Simpler2r r permute_rowsr<r4min zip_row_oprow_op __class__) rrrcmnApermbrrr7rjs @@r_LUsolver{<s* xx166 BD D A A1u!"JKKK**!T+34 ! "C  4 + + -A1X@s1ay! @AadGE LLA> ? @@  1uq! DA166] D!!AqD'*$%BCC D D ac1fI1q5"b !5q1ua @AadGE LLA> ? @!Q$ 34 5 == = K&'IJJKs FF4cttt}|j\}}|j|z}g}|j}t |dz ddD]V}||ddf} t |dz|D]} | ||| f||dz | z zz} || } |j | |||fz X|j|dddS)aSolve the linear system ``Ax = b``. ``M`` is the matrix ``A``, the method argument is the vector ``b``. The method returns the solution vector ``x``. If ``b`` is a matrix, the system is solved for each column of ``b`` and the return value is a matrix of the same shape as ``b``. This method is slower (approximately by a factor of 2) but more stable for floating-point arithmetic than the LUsolve method. However, LUsolve usually uses an exact arithmetic, so you do not need to use QRsolve. This is mainly for educational purposes and symbolic matrices, for real (or complex) matrices use mpmath.qr_solve. See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve pinv_solve QRdecomposition cramer_solve rrlN)r rQRdecompositionrWrr4r;vstack) rrzr7QRrirhrwrtmpr+s r_QRsolvers> "*j 9C   DAq 337A A A 1q5"b ! 1gq1ua *A 1QT7Qq1uqy\) )C *#h qAw  188QttW rcddlm}m}|j}|j |j |j }|j }|ddd| fj\}|jd\} } | ddd| f| dd| df} } ttfd| } t| } t| j D cgc] } | | vs|  }} || |zj}| | dddfjs tdt!d|gd d j"}t%|}|t| z |zDcgc] }t'|c}j)| z |}| d| |f}| d| ddf}|j+|||zz |}||}tD]}||ddf|||ddf<||||}}|r|||fS||fScc} wcc}w) a! Solves ``Ax = B`` using Gauss Jordan elimination. There may be zero, one, or infinite solutions. If one solution exists, it will be returned. If infinite solutions exist, it will be returned parametrically. If no solutions exist, It will throw ValueError. Parameters ========== B : Matrix The right hand side of the equation to be solved for. Must have the same number of rows as matrix A. freevar : boolean, optional Flag, when set to `True` will return the indices of the free variables in the solutions (column Matrix), for a system that is undetermined (e.g. A has more columns than rows), for which infinite solutions are possible, in terms of arbitrary values of free variables. Default `False`. Returns ======= x : Matrix The matrix that will satisfy ``Ax = B``. Will have as many rows as matrix A has columns, and as many columns as matrix B. params : Matrix If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of arbitrary parameters. These arbitrary parameters are returned as params Matrix. free_var_index : List, optional If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of arbitrary values of free variables. Then the indices of the free variables in the solutions (column Matrix) are returned by free_var_index, if the flag `freevar` is set to `True`. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]]) >>> B = Matrix([7, 12, 4]) >>> sol, params = A.gauss_jordan_solve(B) >>> sol Matrix([ [-2*tau0 - 3*tau1 + 2], [ tau0], [ 2*tau1 + 5], [ tau1]]) >>> params Matrix([ [tau0], [tau1]]) >>> taus_zeroes = { tau:0 for tau in params } >>> sol_unique = sol.xreplace(taus_zeroes) >>> sol_unique Matrix([ [2], [0], [5], [0]]) >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> B = Matrix([3, 6, 9]) >>> sol, params = A.gauss_jordan_solve(B) >>> sol Matrix([ [-1], [ 2], [ 0]]) >>> params Matrix(0, 1, []) >>> A = Matrix([[2, -7], [-1, 4]]) >>> B = Matrix([[-21, 3], [12, -2]]) >>> sol, params = A.gauss_jordan_solve(B) >>> sol Matrix([ [0, -2], [3, -1]]) >>> params Matrix(0, 2, []) >>> from sympy import Matrix >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]]) >>> B = Matrix([7, 12, 4]) >>> sol, params, freevars = A.gauss_jordan_solve(B, freevar=True) >>> sol Matrix([ [-2*tau0 - 3*tau1 + 2], [ tau0], [ 2*tau1 + 5], [ tau1]]) >>> params Matrix([ [tau0], [tau1]]) >>> freevars [1, 3] See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv References ========== .. [1] https://en.wikipedia.org/wiki/Gaussian_elimination r)Matrixr3NT)simplifyc|kSrr)pcols rrz%_gauss_jordan_solve..@s a#grzLinear system has no solutiontauc6t|jdS)N 1234567890)strrstrip)rs rrz%_gauss_jordan_solve..Rsc!fmmL9rc d|zS)Nror)ss rrz%_gauss_jordan_solve..Ss S1Wr)comparemodify)sympy.matricesrr3ruhstackcopyrshaperreflistfilterlenr4rWis_zero_matrixr2rnamernextreshaper~)rBfreevarrr3clsaugB_colsrowrxpivotsr>rankcfree_var_index permutationrgenr+rVvtfree_solsolrs @r_gauss_jordan_solversB-{{Cxx!&&(+CvvF1hwh;%%HC$'IAv!XvgX+!fWX+qAV-v67FF D"'qvvBA!6/aBNB.0133K TUAX; % %899 !9$ &&*d  D !C eS4Z,?&@A49A B J J $J C$&'A${Bzz"q3w,,H V C 3Z/!)!A#KNA /3xSCC''CxGC Bs G0G0G5Nclddlm}|}|j}|V|j|j}}t dj ||t }|j|||j}|j|||j|j|z j|zS)a Solve ``Ax = B`` using the Moore-Penrose pseudoinverse. There may be zero, one, or infinite solutions. If one solution exists, it will be returned. If infinite solutions exist, one will be returned based on the value of arbitrary_matrix. If no solutions exist, the least-squares solution is returned. Parameters ========== B : Matrix The right hand side of the equation to be solved for. Must have the same number of rows as matrix A. arbitrary_matrix : Matrix If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of an arbitrary matrix. This parameter may be set to a specific matrix to use for that purpose; if so, it must be the same shape as x, with as many rows as matrix A has columns, and as many columns as matrix B. If left as None, an appropriate matrix containing dummy symbols in the form of ``wn_m`` will be used, with n and m being row and column position of each symbol. Returns ======= x : Matrix The matrix that will satisfy ``Ax = B``. Will have as many rows as matrix A has columns, and as many columns as matrix B. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) >>> B = Matrix([7, 8]) >>> A.pinv_solve(B) Matrix([ [ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18], [-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9], [ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]]) >>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0])) Matrix([ [-55/18], [ 1/9], [ 59/18]]) See Also ======== sympy.matrices.dense.DenseMatrix.lower_triangular_solve sympy.matrices.dense.DenseMatrix.upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv Notes ===== This may return either exact solutions or least squares solutions. To determine which, check ``A * A.pinv() * B == B``. It will be True if exact solutions exist, and False if only a least-squares solution exists. Be aware that the left hand side of that equation may need to be simplified to correctly compare to the right hand side. References ========== .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#Obtaining_all_solutions_of_a_linear_system r)eyezw:{}_:{})r) rrpinvrrformatrrurWrS) rrarbitrary_matrixrrxA_pinvrrws r _pinv_solverks\# A VVXF66166d":#4#4T4#@eL;;tT1577 ??1 QVV OOA " ()9 : ;;rc ddlm}  fd}dk(r ddlm}|}n&dk(r ddlm}|}nt t rfd}n}|}|j} tjdD]K tjd D]. |jgj||z | f<0Mj| S) aeSolves system of linear equations using Cramer's rule. This method is relatively inefficient compared to other methods. However it only uses a single division, assuming a division-free determinant method is provided. This is helpful to minimize the chance of divide-by-zero cases in symbolic solutions to linear systems. Parameters ========== M : Matrix The matrix representing the left hand side of the equation. rhs : Matrix The matrix representing the right hand side of the equation. det_method : str or callable The method to use to calculate the determinant of the matrix. The default is ``'laplace'``. If a callable is passed, it should take a single argument, the matrix, and return the determinant of the matrix. Returns ======= x : Matrix The matrix that will satisfy ``Ax = B``. Will have as many rows as matrix A has columns, and as many columns as matrix B. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[0, -6, 1], [0, -6, -1], [-5, -2, 3]]) >>> B = Matrix([[-30, -9], [-18, -27], [-26, 46]]) >>> x = A.cramer_solve(B) >>> x Matrix([ [ 0, -5], [ 4, 3], [-6, 9]]) References ========== .. [1] https://en.wikipedia.org/wiki/Cramer%27s_rule#Explicit_formulas_for_small_systems r)r3c*|k(r|fS||fSrr)rrrrrrs rentryz_cramer_solve..entrys$3hs1c6{3AadG3rbird) _det_birdlaplace) _det_laplacec(|jS)Nmethod)det)matrix det_methods rrz_cramer_solve..sVZZzZ:rr) r/r3 determinantrr isinstancerrr4ru) rrrr3rrrrdet_Mrhrrs ``` @@r _cramer_solversX4V* y - J $: FE syyASYYq\"D1& DCkakk:177:E:;eCAc3hK DD ;;q>rc|dvr% |j|\}}|r td |S|dk(r|j|S|dk(r|j |S|dk(r|j |S|dk(r|j |S|dk(r|j|S|d k(r|j|S|j| j|S#t$r tdwxYw) aLSolves linear equation where the unique solution exists. Parameters ========== rhs : Matrix Vector representing the right hand side of the linear equation. method : string, optional If set to ``'GJ'`` or ``'GE'``, the Gauss-Jordan elimination will be used, which is implemented in the routine ``gauss_jordan_solve``. If set to ``'LU'``, ``LUsolve`` routine will be used. If set to ``'QR'``, ``QRsolve`` routine will be used. If set to ``'PINV'``, ``pinv_solve`` routine will be used. If set to ``'CRAMER'``, ``cramer_solve`` routine will be used. It also supports the methods available for special linear systems For positive definite systems: If set to ``'CH'``, ``cholesky_solve`` routine will be used. If set to ``'LDL'``, ``LDLsolve`` routine will be used. To use a different method and to compute the solution via the inverse, use a method defined in the .inv() docstring. Returns ======= solutions : Matrix Vector representing the solution. Raises ====== ValueError If there is not a unique solution then a ``ValueError`` will be raised. If ``M`` is not square, a ``ValueError`` and a different routine for solving the system will be suggested. )GJGEzcMatrix det == 0; not invertible. Try ``M.gauss_jordan_solve(rhs)`` to obtain a parametric solution.reLUCHQRLDLPINVCRAMERr) gauss_jordan_solver r2LUsolvecholesky_solveQRsolveLDLsolve pinv_solve cramer_solveinvrS)rrrsolnparams r_solver s b O..s3KD%.0UVV 4yy~ 4$$ 4yy~ 5zz# 6 ||C  8 ~~c""uuFu#,,S11% O*+MN N Os !CC$c|dk(r|j|S|dk(r|j|S|dk(r|j|S|dk(r|j|S|j}||zj ||z|S)a4Return the least-square fit to the data. Parameters ========== rhs : Matrix Vector representing the right hand side of the linear equation. method : string or boolean, optional If set to ``'CH'``, ``cholesky_solve`` routine will be used. If set to ``'LDL'``, ``LDLsolve`` routine will be used. If set to ``'QR'``, ``QRsolve`` routine will be used. If set to ``'PINV'``, ``pinv_solve`` routine will be used. Otherwise, the conjugate of ``M`` will be used to create a system of equations that is passed to ``solve`` along with the hint defined by ``method``. Returns ======= solutions : Matrix Vector representing the solution. Examples ======== >>> from sympy import Matrix, ones >>> A = Matrix([1, 2, 3]) >>> B = Matrix([2, 3, 4]) >>> S = Matrix(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 rrrrr)rrrrrRsolve)rrrts r_solve_least_squaresrXsX~$$ 4yy~ 5zz# 6 ||C  CCA}}QWV}44r)Fr)r)r)r)sympy.core.functionrsympy.core.symbolrrrsympy.utilities.iterablesr exceptionsr r r eigenr utilitiesr rrr8r@rHrJr[rar{rrrrrrrrrrs{*CC6RR+6!>H%N(V%N(V,/^8/v!(@F3lslY;x@FK2\V5r