K iK~ddlmZddlZdZdZGddeZGdd eZed k(rddl Z e jyy) )xrangeN z c4eZdZdZdZdZd(dZdZd)dZdZ d Z d Z d Z d Z d ZdZdZdZdZdZdZeZdZdZdZdZdZdZdZdZdZdZe eedZ!d Z"d!Z#e e"e#d"Z$d#Z%e e%Z&d$Z'd%Z(e e(Z)d&Z*e*Z+d'Z,y)*_matrixa# Numerical matrix. Specify the dimensions or the data as a nested list. Elements default to zero. Use a flat list to create a column vector easily. The datatype of the context (mpf for mp, mpi for iv, and float for fp) is used to store the data. Creating matrices ----------------- Matrices in mpmath are implemented using dictionaries. Only non-zero values are stored, so it is cheap to represent sparse matrices. The most basic way to create one is to use the ``matrix`` class directly. You can create an empty matrix specifying the dimensions: >>> from mpmath import * >>> mp.dps = 15 >>> matrix(2) matrix( [['0.0', '0.0'], ['0.0', '0.0']]) >>> matrix(2, 3) matrix( [['0.0', '0.0', '0.0'], ['0.0', '0.0', '0.0']]) Calling ``matrix`` with one dimension will create a square matrix. To access the dimensions of a matrix, use the ``rows`` or ``cols`` keyword: >>> A = matrix(3, 2) >>> A matrix( [['0.0', '0.0'], ['0.0', '0.0'], ['0.0', '0.0']]) >>> A.rows 3 >>> A.cols 2 You can also change the dimension of an existing matrix. This will set the new elements to 0. If the new dimension is smaller than before, the concerning elements are discarded: >>> A.rows = 2 >>> A matrix( [['0.0', '0.0'], ['0.0', '0.0']]) Internally ``mpmathify`` is used every time an element is set. This is done using the syntax A[row,column], counting from 0: >>> A = matrix(2) >>> A[1,1] = 1 + 1j >>> A matrix( [['0.0', '0.0'], ['0.0', mpc(real='1.0', imag='1.0')]]) A more comfortable way to create a matrix lets you use nested lists: >>> matrix([[1, 2], [3, 4]]) matrix( [['1.0', '2.0'], ['3.0', '4.0']]) Convenient advanced functions are available for creating various standard matrices, see ``zeros``, ``ones``, ``diag``, ``eye``, ``randmatrix`` and ``hilbert``. Vectors ....... Vectors may also be represented by the ``matrix`` class (with rows = 1 or cols = 1). For vectors there are some things which make life easier. A column vector can be created using a flat list, a row vectors using an almost flat nested list:: >>> matrix([1, 2, 3]) matrix( [['1.0'], ['2.0'], ['3.0']]) >>> matrix([[1, 2, 3]]) matrix( [['1.0', '2.0', '3.0']]) Optionally vectors can be accessed like lists, using only a single index:: >>> x = matrix([1, 2, 3]) >>> x[1] mpf('2.0') >>> x[1,0] mpf('2.0') Other ..... Like you probably expected, matrices can be printed:: >>> print randmatrix(3) # doctest:+SKIP [ 0.782963853573023 0.802057689719883 0.427895717335467] [0.0541876859348597 0.708243266653103 0.615134039977379] [ 0.856151514955773 0.544759264818486 0.686210904770947] Use ``nstr`` or ``nprint`` to specify the number of digits to print:: >>> nprint(randmatrix(5), 3) # doctest:+SKIP [2.07e-1 1.66e-1 5.06e-1 1.89e-1 8.29e-1] [6.62e-1 6.55e-1 4.47e-1 4.82e-1 2.06e-2] [4.33e-1 7.75e-1 6.93e-2 2.86e-1 5.71e-1] [1.01e-1 2.53e-1 6.13e-1 3.32e-1 2.59e-1] [1.56e-1 7.27e-2 6.05e-1 6.67e-2 2.79e-1] As matrices are mutable, you will need to copy them sometimes:: >>> A = matrix(2) >>> A matrix( [['0.0', '0.0'], ['0.0', '0.0']]) >>> B = A.copy() >>> B[0,0] = 1 >>> B matrix( [['1.0', '0.0'], ['0.0', '0.0']]) >>> A matrix( [['0.0', '0.0'], ['0.0', '0.0']]) Finally, it is possible to convert a matrix to a nested list. This is very useful, as most Python libraries involving matrices or arrays (namely NumPy or SymPy) support this format:: >>> B.tolist() [[mpf('1.0'), mpf('0.0')], [mpf('0.0'), mpf('0.0')]] Matrix operations ----------------- You can add and subtract matrices of compatible dimensions:: >>> A = matrix([[1, 2], [3, 4]]) >>> B = matrix([[-2, 4], [5, 9]]) >>> A + B matrix( [['-1.0', '6.0'], ['8.0', '13.0']]) >>> A - B matrix( [['3.0', '-2.0'], ['-2.0', '-5.0']]) >>> A + ones(3) # doctest:+ELLIPSIS Traceback (most recent call last): ... ValueError: incompatible dimensions for addition It is possible to multiply or add matrices and scalars. In the latter case the operation will be done element-wise:: >>> A * 2 matrix( [['2.0', '4.0'], ['6.0', '8.0']]) >>> A / 4 matrix( [['0.25', '0.5'], ['0.75', '1.0']]) >>> A - 1 matrix( [['0.0', '1.0'], ['2.0', '3.0']]) Of course you can perform matrix multiplication, if the dimensions are compatible, using ``@`` (for Python >= 3.5) or ``*``. For clarity, ``@`` is recommended (`PEP 465 `), because the meaning of ``*`` is different in many other Python libraries such as NumPy. >>> A @ B # doctest:+SKIP matrix( [['8.0', '22.0'], ['14.0', '48.0']]) >>> A * B # same as A @ B matrix( [['8.0', '22.0'], ['14.0', '48.0']]) >>> matrix([[1, 2, 3]]) * matrix([[-6], [7], [-2]]) matrix( [['2.0']]) .. COMMENT: TODO: the above "doctest:+SKIP" may be removed as soon as we have dropped support for Python 3.5 and below. You can raise powers of square matrices:: >>> A**2 matrix( [['7.0', '10.0'], ['15.0', '22.0']]) Negative powers will calculate the inverse:: >>> A**-1 matrix( [['-2.0', '1.0'], ['1.5', '-0.5']]) >>> A * A**-1 matrix( [['1.0', '1.0842021724855e-19'], ['-2.16840434497101e-19', '1.0']]) Matrix transposition is straightforward:: >>> A = ones(2, 3) >>> A matrix( [['1.0', '1.0', '1.0'], ['1.0', '1.0', '1.0']]) >>> A.T matrix( [['1.0', '1.0'], ['1.0', '1.0'], ['1.0', '1.0']]) Norms ..... Sometimes you need to know how "large" a matrix or vector is. Due to their multidimensional nature it's not possible to compare them, but there are several functions to map a matrix or a vector to a positive real number, the so called norms. For vectors the p-norm is intended, usually the 1-, the 2- and the oo-norm are used. >>> x = matrix([-10, 2, 100]) >>> norm(x, 1) mpf('112.0') >>> norm(x, 2) mpf('100.5186549850325') >>> norm(x, inf) mpf('100.0') Please note that the 2-norm is the most used one, though it is more expensive to calculate than the 1- or oo-norm. It is possible to generalize some vector norms to matrix norm:: >>> A = matrix([[1, -1000], [100, 50]]) >>> mnorm(A, 1) mpf('1050.0') >>> mnorm(A, inf) mpf('1001.0') >>> mnorm(A, 'F') mpf('1006.2310867787777') The last norm (the "Frobenius-norm") is an approximation for the 2-norm, which is hard to calculate and not available. The Frobenius-norm lacks some mathematical properties you might expect from a norm. ci|_d|_d|vrtjdt |dt t frt |ddt t frV|d}t||_t|d|_ t|D]\}}t|D] \}}||||f<!y|d}t||_d|_ t|D] \}} | ||df<yt |dtrSt|dk(r|dx|_|_ yt |dts td|d|_|d|_ yt |dtrh|d}|j|_|j|_ t|jD](}t|jD]}|||f|||f<*yt|ddr`|j j#|dj%}|j|_|j|_|j|_ ytd)N force_typea#The force_type argument was removed, it did not work properly anyway. If you want to force floating-point or interval computations, use the respective methods from `fp` or `mp` instead, e.g., `fp.matrix()` or `iv.matrix()`. If you want to truncate values to integer, use .apply(int) instead.rz expected inttolistz#could not interpret given arguments) _matrix__data_LUwarningswarn isinstancelisttuplelen _matrix__rows _matrix__cols enumerateint TypeErrorrrhasattrctxmatrixr ) selfargskwargsAirowjaves ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/mpmath/matrices/matrices.py__init__z_matrix.__init__s  6 ! MMW X d1ge} -$q'!*tUm4G!!f !!A$i 'l'FAs )#'1%&QT '' G!!f  %aL#DAq!"DAJ# Q %4yA~,0G3 dk!$q'3/#N33"1g "1g Q )QA//DK//DKAHH% )))A!"1a4DAJ) )T!Wh 'Q 01A//DK//DK//DKAB Bc|jj|j|j}t |jD].}t |jD]}||||f|||f<0|S)zR Return a copy of self with the function `f` applied elementwise. )rrrrr)rfnewr r"s r&applyz _matrix.applyNsphhoodkk4;;7 $ (ADKK( (T!A#Y<AaC ( ( r(Nc Zg}dg|jz}t|jD]}|jgt|jD]g}|r$|jj |||f|fi|}nt |||f}|dj|tt|||||<it|D]M\}}t|D]\}} | j||||<dtj|zdz||<Otj|S)Nr[])colsrangerowsappendrnstrstrmaxrrrjustcolsepjoinrowsep) rnrresmaxlenr r"stringr!elems r&__nstr__z_matrix.__nstr__Xs%tyytyy! 8A JJrN499% 8*TXX]]4!9aB6BF ac^FBv&F VAY7q  8 8 n 2FAs$S> /4F1I.A /6;;s++c1CF  2 {{3r(c"|jSN)rArs r&__str__z_matrix.__str__ns}}r(cT|jj}d}t|jD]m}|dz }t|jD]D}|rt |||f|st |||f}ndt|||fzdz}||dzz }F|dd}|dz }o|dd}|dz }|S) zd Create a list string from a matrix. If avoid_type: avoid multiple 'mpf's. r/'z, Nz], r0)rmpfrrrrreprr6)r avoid_typetypsr r"r#s r& _toliststrz_matrix._toliststrqshhll  $ A HADKK( !D1Is)CT!A#YAc$qs)n,s2AQX    #2A LA  crF Sr(c t|jDcgc]*}t|jDcgc] }|||f c},c}}Scc}wcc}}w)z6 Convert the matrix to a nested list. )r2rrrr r"s r&r z_matrix.tolistsBBGt{{ASTAE$++$67qac7TT7TsAA A Ac|jjr|jSd}||jddzz }|S)Nzmatrix( T)rL))rprettyrErO)rrNs r&__repr__z_matrix.__repr__s= 88??<<> !  T___ - 33r(ch||jvr|j|S|jjS)a Fast extraction of the i,j element from the matrix This function is for private use only because is unsafe: 1. Does not check on the value of key it expects key to be a integer tuple (i,j) 2. Does not check bounds )r rzero)rkeys r& __get_elementz_matrix.__get_elements- $++ ;;s# #88== r(c`|r||j|<y||jvr|j|=yy)aQ Fast assignment of the i,j element in the matrix This function is unsafe: 1. Does not check on the value of key it expects key to be a integer tuple (i,j) 2. Does not check bounds 3. Does not check the value type 4. Does not reset the LU cache N)r )rrXvalues r& __set_elementz_matrix.__set_elements2 $DKK  DKK  C  r(c t|tst|tr3|jdk(rd|f}n|jdk(r|df}n t dt|dtst|dtrt|dtr|dj |dj dk\rS|dj|dj|jdzkr%t|dj|j}nt d|dg}t|dtr|dj |dj dk\rS|dj|dj|jdzkr%t|dj|j}nt d|dg}|jjt|t|}t|D]=\}}t|D]*\}}|j||f|j||f,?|S|d|jk\s|d|jk\r t d||j vr|j |S|jj"S)z Getitem function for mp matrix class with slice index enabled it allows the following assingments scalar to a slice of the matrix B = A[:,2:6] r rinsufficient indices for matrixRow index out of boundsColumn index out of boundsmatrix index out of range)rrslicerr IndexErrorstartstoprindicesrrrr_matrix__set_element_matrix__get_elementr rW) rrXr3columnsmr xr"ys r& __getitem__z_matrix.__getitem__sE c3 :c%#8{{a#h!Ah !BCC c!fU #z#a&'?#a&'FLL(CFLLA,=V[[(CFKK4;;q=,H!3q6>>$++#>?D$%>??Ax#a&'FLL(CFLLA,=V[[(CFKK4;;q=,H$c!fnnT[[&ABG$%ABBq6(D #g,7A! E!$W-ECAaOOQqE$*<*>$++#>?D$%>??Ax#a&'FLL(CFLLA,=V[[(CFKK4;;q=,H$c!fnnT[[&ABG$%ABBq6(%0t9 *s7|uzz/I(R!#,W#5RCAa ..!ue6I6I1Q%6PQRR%%>??((/9A$9**Aa5%899 1v$A$++(= !<==HH$$U+E#( C  #KK$ 88DHr(c#Kt|jD]%}t|jD] }|||f 'ywrC)rrrrQs r&__iter__z_matrix.__iter__:sC $ ADKK( 1Q3i  s?Ac t||jjr#|j|jk7r t d|jj|j|j}|jj |jj|jj |jjt|jD]]t|jD]C|jjfdt|jD|f<E_|S|jj|j|j}t|jD]+t|jD]||fz|f<-|S)Nz,dimensions not compatible for multiplicationc3JK|]}|f|ffywrC).0kr r" other_get other_zeroself_get self_zeros r& z"_matrix.__mul__..Ks:.D)*081y/I9VWXYUZ\fKg.h.Ds #) rrrrrrorWr getrfdot) rotherr+r r"ryrzr{r|s @@@@@@r&__mul__z_matrix.__mul__?sf eTXX__ -{{ell* !OPP((//$++u||99  YY!^99 99 r(c|jSrC)rrDs r& __getrowsz_matrix.__getrows {{r(c||jjD]}|d|k\s |j|=||_y)Nr)r rrrr[rXs r& __setrowsz_matrix.__setrows>;;##% %C1vKK$ % r(znumber of rows)docc|jSrC)rrDs r& __getcolsz_matrix.__getcolsrr(c||jjD]}|d|k\s |j|=||_yr)r rrrs r& __setcolsz_matrix.__setcolsrr(znumber of columnsc|jj|j|j}t |jD](}t |jD]}|||f|||f<*|SrC)rrrrr)rr+r r"s r& transposez_matrix.transposesjhhoodkk4;;7 $ %ADKK( %!9AaC % % r(cL|j|jjSrC)r,rconjrDs r& conjugatez_matrix.conjugateszz$((--((r(c>|jjSrC)rrrDs r&transpose_conjz_matrix.transpose_conjs~~))++r(c|jj|j|j}|jj |_|SrC)rrrrr r)rr+s r&rz _matrix.copys7hhoodkk4;;7[[%%'  r(c|jj|jd}t|jD] }|||f||<|Sr)rrr3r2)rr<rjr s r&columnz_matrix.columnsH HHOODIIq )tyy! A!9AaD r(rC)F)-__name__ __module__ __qualname____doc__r'r,rArErOr rUrhrgrmrqrsrrrrr __truediv__rrrrrrrr_matrix__getrows_matrix__setrowspropertyr3_matrix__getcols_matrix__setcolsr1rTrrHr__copy__rrvr(r&rr sM^3Cj ,.U  ! !?%BGR .## 6K"#*  / Iy.> ?D Iy.A BD A),  A Hr(rcVeZdZdZdZdZdZdZd dZddZ d Z d Z dd Z dd Z y) MatrixMethodsctdtfi|_||j_|j|j_y)Nr)typerrrrp)rs r&r'zMatrixMethods.__init__s/(WJ3   [[ r(c Z|j|fi|}t|D] }d|||f< |S)z6 Create square identity matrix n x n. r )rr)rr<rrr s r&rzMatrixMethods.eyes> CJJq #F # AAacF r(c |jt|fi|}tt|D] }|||||f<|S)a& Create square diagonal matrix using given list. Example: >>> from mpmath import diag, mp >>> mp.pretty = False >>> diag([1, 2, 3]) matrix( [['1.0', '0.0', '0.0'], ['0.0', '2.0', '0.0'], ['0.0', '0.0', '3.0']]) )rrr)rdiagonalrrr s r&diagzMatrixMethods.diagsK CJJs8} / /H & !Aa[AacF !r(ct|dk(r|dx}}n0t|dk(r |d}|d}ntdt|z|j||fi|}t|D]}t|D] }d|||f< |S)a& Create matrix m x n filled with zeros. One given dimension will create square matrix n x n. Example: >>> from mpmath import zeros, mp >>> mp.pretty = False >>> zeros(2) matrix( [['0.0', '0.0'], ['0.0', '0.0']]) r rrz*zeros expected at most 2 arguments, got %irrrrrrrrjr<rr r"s r&zeroszMatrixMethods.zeross t9>GOA Y!^QAQAH3t9TU U CJJq! &v & AAY !A#  r(ct|dk(r|dx}}n0t|dk(r |d}|d}ntdt|z|j||fi|}t|D]}t|D] }d|||f< |S)a# Create matrix m x n filled with ones. One given dimension will create square matrix n x n. Example: >>> from mpmath import ones, mp >>> mp.pretty = False >>> ones(2) matrix( [['1.0', '1.0'], ['1.0', '1.0']]) r rrz)ones expected at most 2 arguments, got %irrs r&oneszMatrixMethods.ones(s t9>GOA Y!^QAQAG#d)ST T CJJq! &v & AAY !A#  r(Nc||}|j||}t|D],}t|D]}|j||zdzz |||f<.|S)z Create (pseudo) hilbert matrix m x n. One given dimension will create hilbert matrix n x n. The matrix is very ill-conditioned and symmetric, positive definite if square. r )rrone)rrjr<rr r"s r&hilbertzMatrixMethods.hilbertBsi 9A JJq!  /AAY /AEAI.!A# / /r(c |s|}|j||fi|}t|D]0}t|D] }|j||z z|z|||f<"2|S)aZ Create a random m x n matrix. All values are >= min and >> from mpmath import randmatrix >>> randmatrix(2) # doctest:+SKIP matrix( [['0.53491598236191806', '0.57195669543302752'], ['0.85589992269513615', '0.82444367501382143']]) )rrrand) rrjr<minr7rrr r"s r& randmatrixzMatrixMethods.randmatrixRsqA CJJq! &v & 8AAY 8sSy1C7!A# 8 8r(c||k(ryt||jr4t|jD]}|||f|||fc|||f<|||f<yt|tr||||c||<||<yt d)z( Swap row i with row j. Nzcould not interpret type)rrrr1rr)rrr r"rxs r&swap_rowzMatrixMethods.swap_rowhs 6  a $AFF^ 0!"1Q31Q3!A#!A# 0 4 1qtJAaD!A$67 7r(c:t||js td|jt |k7r t d|j }|xjdz c_t|jD]}|||||jdz f<|S)zB Extend matrix A with column b and return result. z A should be a type of ctx.matrixzValue should be equal to len(b)r ) rrrr3rrorr1r)rrbr s r&extendzMatrixMethods.extendvs!SZZ(>? ? 66SV >? ? FFH !  "AqTAakN "r(c t|tturj j k(rtfd|DSdk(rj|dSdk(r#jj|ddSdkDr*jjfd|DStd#t$rj|cYSwxYw)a Gives the entrywise `p`-norm of an iterable *x*, i.e. the vector norm `\left(\sum_k |x_k|^p\right)^{1/p}`, for any given `1 \le p \le \infty`. Special cases: If *x* is not iterable, this just returns ``absmax(x)``. ``p=1`` gives the sum of absolute values. ``p=2`` is the standard Euclidean vector norm. ``p=inf`` gives the magnitude of the largest element. For *x* a matrix, ``p=2`` is the Frobenius norm. For operator matrix norms, use :func:`~mpmath.mnorm` instead. You can use the string 'inf' as well as float('inf') or mpf('inf') to specify the infinity norm. **Examples** >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> x = matrix([-10, 2, 100]) >>> norm(x, 1) mpf('112.0') >>> norm(x, 2) mpf('100.5186549850325') >>> norm(x, inf) mpf('100.0') c3@K|]}j|ywrC)absmax)rwr rs r&r}z%MatrixMethods.norm..s0szz!}0sr absoluter)rsquaredc3:K|]}t|zywrC)abs)rwr ps r&r}z%MatrixMethods.norm..s'=aA '=szp has to be >= 1) iterrrrrrpinfr7fsumsqrtnthrootro)rrkrs` `r&normzMatrixMethods.normsD ! G 7#  AA <0a00 0 !V88A8* * !V88CHHQAH>? ? U;;sxx'=1'==qA A/0 0 !::a=  !s CC+*C+cjt|turSt|tur1dj |j rj dSj|}jjc|dk(rtfdtDS|jk(rtfdtDStd)a Gives the matrix (operator) `p`-norm of A. Currently ``p=1`` and ``p=inf`` are supported: ``p=1`` gives the 1-norm (maximal column sum) ``p=inf`` gives the `\infty`-norm (maximal row sum). You can use the string 'inf' as well as float('inf') or mpf('inf') ``p=2`` (not implemented) for a square matrix is the usual spectral matrix norm, i.e. the largest singular value. ``p='f'`` (or 'F', 'fro', 'Frobenius, 'frobenius') gives the Frobenius norm, which is the elementwise 2-norm. The Frobenius norm is an approximation of the spectral norm and satisfies .. math :: \frac{1}{\sqrt{\mathrm{rank}(A)}} \|A\|_F \le \|A\|_2 \le \|A\|_F The Frobenius norm lacks some mathematical properties that might be expected of a norm. For general elementwise `p`-norms, use :func:`~mpmath.norm` instead. **Examples** >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> A = matrix([[1, -1000], [100, 50]]) >>> mnorm(A, 1) mpf('1050.0') >>> mnorm(A, inf) mpf('1001.0') >>> mnorm(A, 'F') mpf('1006.2310867787777') frobeniusrr c3lK|]*jfdtDd,yw)c3,K|] }|f ywrCrv)rwr rr"s r&r}z0MatrixMethods.mnorm... ;A1Q3 ;r rNrr)rwr"rrrjs @r&r}z&MatrixMethods.mnorm..(\Qsxx ; ;axH\04c3lK|]*jfdtDd,yw)c3,K|] }|f ywrCrv)rwr"rr s r&r}z0MatrixMethods.mnorm...rrr rNr)rwr rrr<s @r&r}z&MatrixMethods.mnorm..rrzmatrix p-norm for arbitrary p)rrrr6 startswithlowerrrpr3r1r7rrNotImplementedError)rrrrjr<s`` @@r&mnormzMatrixMethods.mnormsN JJqM 7# Aw#~+"8"8"Cxx1~% AAvvqvv1 6\RXYZR[\\ \ #''\\RXYZR[\\ \%&EF Fr(rC)Nrr )r)r )rrrr'rrrrrrrrrrrvr(r&rrs;) $44 , 8 11f2Gr(r__main__) libmp.backendrrr;r9objectrrrdoctesttestmodrvr(r&rsU"  ` f` D~GF~G@ zGOOr(