K it bdZddlmZddlmZddlmZddlmZddl m Z ddl m Z ddl mZmZdd lmZdd lmZdd lmZmZdd lmZdd lmZddlmZddlmZddlm Z ddl!m"Z"m#Z#m$Z$ddl%m&Z&ddl'm(Z(m)Z)ddl*m+Z+ddl,m-Z-m.Z.ddl/m0Z0m1Z1ddl2m3Z3ddl'm4Z4ddl5m6Z6m7Z7m8Z8m9Z9m:Z:dZ;Gdde<Z=Gdde= Z>Gd!d"e>Z?Gd#d$e>Z@Gd%d&e>ZAGd'd(e>ZBGd)d*e>ZCGd+d,eCeBeAe@e?ZDGd-d.ZEGd/d0ZFGd1d2ZGd3ZHd7d5ZId6ZJy4)8au A module containing deprecated matrix mixin classes. The classes in this module are deprecated and will be removed in a future release. They are kept here for backwards compatibility in case downstream code was subclassing them. Importing anything else from this module is deprecated so anything here should either not be used or should be imported from somewhere else. ) annotations) defaultdict)Iterable) isfunction)reducerefine) SympifyErrorAdd)Atom)call_highest_priority) fuzzy_and FuzzyBool)IntegerMod)S)Symbol)sympify)Absreim)sympy_deprecation_warning) _dotprodsimp _simplify)Poly)flatten is_sequence)as_int filldedent) NDimArray)_get_intermediate_simp_bool) MatrixError ShapeErrorNonSquareMatrixErrorNonInvertibleMatrixErrorNonPositiveDefiniteMatrixError) MatrixShaping MatrixSpecialMatrixPropertiesMatrixOperationsMatrixArithmetic MatrixCommonMatrixDeterminantMatrixReductionsMatrixSubspaces MatrixEigenMatrixCalculusMatrixDeprecatedceZdZfdZxZS)_MatrixDeprecatedMetac td|jd|jdddddd lm}dd lm}m}m}m}m }m }tttttt t"||||||f } || vr t%||ry t& |Q|S) Nz: Checking whether an object is an instance of zc is deprecated. Use `isinstance(obj, Matrix)` instead of `isinstance(obj, z)`. 1.13deprecated-matrix-mixinsdeprecated_since_versionactive_deprecations_target stacklevelr MatrixBase)r/r0r1r2r3r4T)r__name__sympy.matrices.matrixbaser@sympy.matrices.matricesr/r0r1r2r3r4MatrixRequiredr)r*r+r,r-r. isinstancesuper__instancecheck__) clsinstancer@r/r0r1r2r3r4 all_mixins __class__s [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/matrices/common.pyrGz'_MatrixDeprecatedMeta.__instancecheck__Qs!::=,,HGHK||nU   &,'A  9                * Hj!A7,X6 6)rA __module__ __qualname__rG __classcell__rKs@rLr6r6?s $+7+7rMr6cneZdZUdZded<ded<dZfdZedZdZ d Z d Z e d Z xZS) rDz1Deprecated mixin class for making matrix classes.introwscolsNc |jtvrtd|jddddt|di|y)Nzd Inheriting from the Matrix mixin classes is deprecated. The class z4 is subclassing a deprecated mixin. r8r9r:r;)rA_DEPRECATED_MIXINSrrF__init_subclass__)rHkwargsrKs rLrYz MatrixRequired.__init_subclass__sQ <<1 1 %<<.) *0+E  !+F+rMctd)z`_new` must, at minimum, be callable as `_new(rows, cols, mat) where mat is a flat list of the elements of the matrix.Subclasses must implement this.NotImplementedErrorrHargsrZs rL_newzMatrixRequired._new ""CDDrMctdNr\r]selfothers rL__eq__zMatrixRequired.__eq__s!"CDDrMctd)aImplementations of __getitem__ should accept ints, in which case the matrix is indexed as a flat list, tuples (i,j) in which case the (i,j) entry is returned, slices, or mixed tuples (a,b) where a and b are any combination of slices and integers.r\r]rfkeys rL __getitem__zMatrixRequired.__getitem__rbrMctd)z*The total number of entries in the matrix.r\r]rfs rL__len__zMatrixRequired.__len__!"CDDrMctdrdr]rns rLshapezMatrixRequired.shaperprM)rArNrO__doc____annotations__rrY classmethodrarhrlropropertyrrrPrQs@rLrDrDsX; I II,6EE EEEEErMrD) metaclassceZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZedZdZdZdZdZd#dZdZedZdZ dZ!dZ"dZ#d$d Z$ed!Z%y")%r)z;Provides basic matrix shaping and extracting of submatricescffd}jjjdz |S)Nc0|kr||fS||dzfSNrrW)ijcolrfs rLentryz*MatrixShaping._eval_col_del..entrys(!"S41: .entrysY3wAqDz!,C%**,,QCZ((1uzz>)* *rMr)rfrrgrs``` rL_eval_col_insertzMatrixShaping._eval_col_inserts. +yyDII $:EBBrMcjfd}tjjjzj|S)Nc0|kr||fS|z |fSrrW)r|r}rgrTrfs rLrz+MatrixShaping._eval_col_join..entrys+4xAqDz!T1% %rM)rTclassofrarU)rfrgrrTs`` @rL_eval_col_joinzMatrixShaping._eval_col_joinsEyy & tU#((UZZ)?).0 0rMc t|}|jfd|D}|jt|t|Dcgc]}|| c}Scc}w)Nc3<K|]}D] }|z|zywrrW).0r|r}rUcolsLists rL z.MatrixShaping._eval_extract..s%DA8Da1t8a<D<D)listrUralen)rfrowsListrmatindicesr|rUs ` @rL _eval_extractzMatrixShaping._eval_extractsQ4jyyDDyyXH *12Q#a&24 42s A c*gfd|S)Ncntd|jddzD]}|dk(r|d|df}||ddf}n|d||df}||dd|f}t|s t|rHj|d|d|f|j|d|d|fjk7r||d|dfyyNrr)rangerranyappend)Mr| to_the_right to_the_bottomrecurse_sub_blocks sub_blockss rLrz?MatrixShaping._eval_get_diag_blocks..recurse_sub_blockss1aggaj1n- 6#$QU8L$%ab!eHM#$RaRV9L$%ab"1"fIM|$M(:!!!BQBF),77aBQBioo-&qQRy1 rMrW)rfrrs @@rL_eval_get_diag_blocksz#MatrixShaping._eval_get_diag_blockss   4 rMcffd}jjdz j|S)Nc0|kr||fS|dz|fSr{rW)r|r}rowrfs rLrz*MatrixShaping._eval_row_del..entrys(!"S41: .entrys+4xAqDz!AH% %rM)rUrrarT)rfrgrrUs`` @rL_eval_row_joinzMatrixShaping._eval_row_joinsEyy & tU#((DII 4J).0 0rMc rt|jDcgc]}t||ddfc}Scc}wr)rrTrrfr|s rL _eval_tolistzMatrixShaping._eval_tolist s+).tyy)9:AT!A#Y:::s4ci}|j\}}t|D]0}t|D] }|||f}||jk7s||||f<"2|Sr)rrrzero)rfdokrTrUr|r}vals rL _eval_todokzMatrixShaping._eval_todoksgZZ dt $A4[ $1a4j$))# #C1I $ $  rMcbjfd}jtd|S)Nc,|z}||zz }||fSrrW)n_r}r|rTrfs rLrz&MatrixShaping._eval_vec..entrys'T AAH A1: rMr)rTrar)rfrrTs` @rL _eval_veczMatrixShaping._eval_vecs*yy  yyTAu--rMc>|j}g}|r8t|D])}t||D]}|j|||f+n:t|D],}t|dz|D]}|j|||f.|jt |d|Sr{)rUrrrar)rfdiagonalcvr}r|s rL _eval_vechzMatrixShaping._eval_vech#s II  1X )q!)AHHT!Q$Z() )1X )q1ua)AHHT!Q$Z() )yyQA&&rMc|dkr||jz }d|cxkr|jksntdj||j|S)zDelete the specified column.rzColumn {} is out of range.)rU IndexErrorformatr)rfr~s rLcol_delzMatrixShaping.col_del0sP 7 499 CC#$))#9@@EF F!!#&&rMc`|st||St|}|dkr|j|z}|dkrd}n||jkDr |j}|j|jk7r/t dj |j|j|j ||S)ayInsert one or more columns at the given column position. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(3, 1) >>> M.col_insert(1, V) Matrix([ [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]]) See Also ======== col row_insert r9The matrices have incompatible number of rows ({} and {}))typer rUrTr%rrrfrrgs rL col_insertzMatrixShaping.col_insert8s,4:e$ $Sk 7))c/C 7C 499_))C 99 "K 5::.0 0$$S%00rMc\|jdk(rE|j|jk7r,|jd|jgj|S|j|jk7r/t dj |j|j|j |S)aConcatenates two matrices along self's last and other's first row. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(1, 3) >>> M.col_join(V) Matrix([ [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 1, 1]]) See Also ======== col row_join rdii5::599Q B/88? ? 99 "N 5::.0 0""5))rMc|dd|fS)aElementary column selector. Examples ======== >>> from sympy import eye >>> eye(2).col(0) Matrix([ [1], [0]]) See Also ======== row col_del col_join col_insert NrW)rfr}s rLr~zMatrixShaping.cols(AqDzrMct|r t|s td|r2td|Dr t|Dcgc] \}}|s | }}}|r2td|Dr t|Dcgc] \}}|s | }}}|Dcgc]}t ||j }}|Dcgc]}t ||j }}|j||Scc}}wcc}}wcc}wcc}w)aReturn a submatrix by specifying a list of rows and columns. Negative indices can be given. All indices must be in the range $-n \le i < n$ where $n$ is the number of rows or columns. Examples ======== >>> from sympy import Matrix >>> m = Matrix(4, 3, range(12)) >>> m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) >>> m.extract([0, 1, 3], [0, 1]) Matrix([ [0, 1], [3, 4], [9, 10]]) Rows or columns can be repeated: >>> m.extract([0, 0, 1], [-1]) Matrix([ [2], [2], [5]]) Every other row can be taken by using range to provide the indices: >>> m.extract(range(0, m.rows, 2), [-1]) Matrix([ [2], [8]]) RowsList or colsList can also be a list of booleans, in which case the rows or columns corresponding to the True values will be selected: >>> m.extract([0, 1, 2, 3], [True, False, True]) Matrix([ [0, 2], [3, 5], [6, 8], [9, 11]]) z&rowsList and colsList must be iterablec3<K|]}t|tywrrEboolrr|s rLrz(MatrixShaping.extract..BAJq$/Bc3<K|]}t|tywrrrs rLrz(MatrixShaping.extract..rr)r TypeErrorall enumeratea2idxrTrUr)rfrrindexitemks rLextractzMatrixShaping.extracts`8$K,ADE E BBB1:81DM+%MHM BBB1:81DM+%MHM2::AE!TYY'::19:AE!TYY'::!!(H55NM;:s$ C"C"8 C(C(C.1C3c"|jS)azObtains the square sub-matrices on the main diagonal of a square matrix. Useful for inverting symbolic matrices or solving systems of linear equations which may be decoupled by having a block diagonal structure. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y, z >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]]) >>> a1, a2, a3 = A.get_diag_blocks() >>> a1 Matrix([ [1, 3], [y, z**2]]) >>> a2 Matrix([[x]]) >>> a3 Matrix([[0]]) )rrns rLget_diag_blockszMatrixShaping.get_diag_blockss0))++rMct|dk(r|jSt|d}t|j|S)a(Return a matrix formed by joining args horizontally (i.e. by repeated application of row_join). Examples ======== >>> from sympy import Matrix, eye >>> Matrix.hstack(eye(2), 2*eye(2)) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2]]) r)rrarrrow_joinrHr`klss rLhstackzMatrixShaping.hstacks9 t9>88: 47mcllD))rMcjjz|zk7rtd|fzj|fdS)aReshape the matrix. Total number of elements must remain the same. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 3, lambda i, j: 1) >>> m Matrix([ [1, 1, 1], [1, 1, 1]]) >>> m.reshape(1, 6) Matrix([[1, 1, 1, 1, 1, 1]]) >>> m.reshape(3, 2) Matrix([ [1, 1], [1, 1], [1, 1]]) z Invalid reshape parameters %d %dc|z|zSrrW)r|r}rUrfs rLz'MatrixShaping.reshape..s$q4x!|2DrM)rTrU ValueErrorra)rfrTrUs` `rLreshapezMatrixShaping.reshapesG* 99tyy D4K /?4,NO Oyyt%DEErMc|dkr||jz }d|cxkr|jksntdj||j|S)zDelete the specified row.rzRow {} is out of range.)rTrrr)rfrs rLrow_delzMatrixShaping.row_delsP 7 499 CC#$))#6==cBC C!!#&&rMc`|s|j|St|}|dkr|j|z}|dkrd}n||jkDr |j}|j|jk7r/t dj |j|j|j ||S)a}Insert one or more rows at the given row position. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(1, 3) >>> M.row_insert(1, V) Matrix([ [0, 0, 0], [1, 1, 1], [0, 0, 0], [0, 0, 0]]) See Also ======== row col_insert rr)rar rTrUr%rrrs rL row_insertzMatrixShaping.row_insert%s.99U# #Sk 7))c/C 7C 499_))C 99 "N 5::.0 0$$S%00rMc\|jdk(rE|j|jk7r,|j|jdgj|S|j|jk7r/t dj |j|j|j |S)a|Concatenates two matrices along self's last and rhs's first column Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(3, 1) >>> M.row_join(V) Matrix([ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]]) See Also ======== row col_join rr)rUrTrarr%rrres rLrzMatrixShaping.row_joinOs, 99>dii5::599UZZB/88? ? 99 "K 5::.0 0""5))rMc jg}t|}|dkDrdn| }|rdn|} ||jk(s||jk(rn!|j|||f|dz }|dz }@|s8t t d|dd|jz d|jdz d|j dt||S)aReturns the kth diagonal of self. The main diagonal corresponds to `k=0`; diagonals above and below correspond to `k > 0` and `k < 0`, respectively. The values of `self[i, j]` for which `j - i = k`, are returned in order of increasing `i + j`, starting with `i + j = |k|`. Examples ======== >>> from sympy import Matrix >>> m = Matrix(3, 3, lambda i, j: j - i); m Matrix([ [ 0, 1, 2], [-1, 0, 1], [-2, -1, 0]]) >>> _.diagonal() Matrix([[0, 0, 0]]) >>> m.diagonal(1) Matrix([[1, 1]]) >>> m.diagonal(-2) Matrix([[-2]]) Even though the diagonal is returned as a Matrix, the element retrieval can be done with a single index: >>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1] 2 See Also ======== diag rrz The z diagonal is out of range [, ])r rTrUrrr!rar)rfrrvrrs rLrzMatrixShaping.diagonalnsD 1IQAQBADII~dii IId1a4j ! FA FA  Z q499}dii!m)-./ /yyCGR((rMc||ddfS)zElementary row selector. Examples ======== >>> from sympy import eye >>> eye(2).row(0) Matrix([[1, 0]]) See Also ======== col row_del row_join row_insert NrWrs rLrzMatrixShaping.rows$AqDzrMc2|j|jfS)a The shape (dimensions) of the matrix as the 2-tuple (rows, cols). Examples ======== >>> from sympy import zeros >>> M = zeros(2, 3) >>> M.shape (2, 3) >>> M.rows 2 >>> M.cols 3 rTrUrns rLrrzMatrixShaping.shapes  499%%rMc"|jS)zReturn the matrix as dictionary of keys. Examples ======== >>> from sympy import Matrix >>> M = Matrix.eye(3) >>> M.todok() {(0, 0): 1, (1, 1): 1, (2, 2): 1} )rrns rLtodokzMatrixShaping.todoks!!rMc|jsgS|js#t|jDcgc]}gc}S|jScc}w)a Return the Matrix as a nested Python list. Examples ======== >>> from sympy import Matrix, ones >>> m = Matrix(3, 3, range(9)) >>> m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> m.tolist() [[0, 1, 2], [3, 4, 5], [6, 7, 8]] >>> ones(3, 0).tolist() [[], [], []] When there are no rows then it will not be possible to tell how many columns were in the original matrix: >>> ones(0, 3).tolist() [] )rTrUrrrs rLtolistzMatrixShaping.tolistsE2yyIyy %dii 011B1 1  ""2s Aci}|j}t|D].\}}t|Dcic] \}}|s || }}}|s*|||<0|Scc}}w)a;Returns matrix as dict of dicts containing non-zero elements of the Matrix Examples ======== >>> from sympy import Matrix >>> A = Matrix([[0, 1],[0, 3]]) >>> A Matrix([ [0, 1], [0, 3]]) >>> A.todod() {0: {1: 1}, 1: {1: 3}} )rr)rrowsdictMlolr|Mir}Mijrs rLtododzMatrixShaping.tododsd"xxzt_ "EAr(1" =fa1c6=C=!  ">s AAc"|jS)aReturn the Matrix converted into a one column matrix by stacking columns Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 3], [2, 4]]) >>> m Matrix([ [1, 3], [2, 4]]) >>> m.vec() Matrix([ [1], [2], [3], [4]]) See Also ======== vech )rrns rLveczMatrixShaping.vec s0~~rMc|jst|r|js td|j |S)a{Reshapes the matrix into a column vector by stacking the elements in the lower triangle. Parameters ========== diagonal : bool, optional If ``True``, it includes the diagonal elements. check_symmetry : bool, optional If ``True``, it checks whether the matrix is symmetric. Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 2], [2, 3]]) >>> m Matrix([ [1, 2], [2, 3]]) >>> m.vech() Matrix([ [1], [2], [3]]) >>> m.vech(diagonal=False) Matrix([[2]]) Notes ===== This should work for symmetric matrices and ``vech`` can represent symmetric matrices in vector form with less size than ``vec``. See Also ======== vec zThe matrix is not symmetric.) is_squarer& is_symmetricrr)rfrcheck_symmetrys rLvechzMatrixShaping.vech%s;T~~& & $"3"3"5;< <x((rMct|dk(r|jSt|d}t|j|S)a:Return a matrix formed by joining args vertically (i.e. by repeated application of col_join). Examples ======== >>> from sympy import Matrix, eye >>> Matrix.vstack(eye(2), 2*eye(2)) Matrix([ [1, 0], [0, 1], [2, 0], [0, 2]]) r)rrarrrrs rLvstackzMatrixShaping.vstackWs9 t9>88: 47mcllD))rMNr)TT)&rArNrOrsrrrrrrrrrrrrrrrr~rrrurrrrrrrrvrrrrrrrr rWrMrLr)r)sE: C 04*: E 0; . '''1R*@,<6|,4**&F2'(1T*>0)d(&&" "#>2 40)d**rMr)ceZdZdZedZedZedddZedZedZ edZ ed d d d d d Z eddZ eddddZ eddZeddZedZedZy )r*z Construction of special matricesc4fd}|j|||S)zUdiag_dict is a defaultdict containing all the entries of the diagonal matrix.c||fSrrW)r|r} diag_dicts rLrz'MatrixSpecial._eval_diag..entryusaV$ $rMra)rHrTrUrrs ` rL _eval_diagzMatrixSpecial._eval_diagqs %xxdE**rMc|jg||zz}|jgt||z|dd|dz<|j|||dS)NrFcopy)roneminra)rHrTrUvalss rL _eval_eyezMatrixSpecial._eval_eyeysOz49%''3tT?2XtAvXxxdDux55rMuppercP|dk(rfd}nfd}j|||S)NlowercR||k(rS|dz|k(r jSjSr{rrr|r}rH eigenvalues rLrz/MatrixSpecial._eval_jordan_block..entry-6%%UaZ77NxxrMcR||k(rS|dz|k(r jSjSr{rrs rLrz/MatrixSpecial._eval_jordan_block..entryrrMr)rHsizerbandrs` ` rL_eval_jordan_blockz MatrixSpecial._eval_jordan_blocks) 7?  xxdE**rMc4fd}j|||S)NcjSrrr|r}rHs rLrz'MatrixSpecial._eval_ones..entrys 77NrMr)rHrTrUrs` rL _eval_oneszMatrixSpecial._eval_oness xxdE**rMcN|j|||jg||zzdS)NFr)rar)rHrTrUs rL _eval_zeroszMatrixSpecial._eval_zeross(xxdSXXJT $:xGGrMc Nfd}jd|zdzd|zdz|}jtt| |dzd|z|jz}t jtt| |dzd|z|jz}||fS)NcD|dz|k(r jSjSr{rr's rLrz,MatrixSpecial._eval_wilkinson..entrys !eqj377 6chh 6rMrT)unpack)radiagrrTabs)rHrrDwminuswpluss` rL_eval_wilkinsonzMatrixSpecial._eval_wilkinsons 7 HHQqS1WacAgu -$uaRQ/0>BQSSHCHHT%AE"23DHABQFLu}rMFTN)strictr.rTrUc xddlm}ddlm}ddlm} |j d|} |r0t|dk(r"t|drt|d|s|d}tt} dx} } |D]}t|trj|r(||}|j\}}|j}n~| j|\}}}|j!D]\\}}}|| || z|| zf<g}n>t#|dr |j\}}|j}n|| | | f<| dz } | dz } t%|D]%\}}t%|D]\}}|| || z|| zf<'| |z } | |z } |||}}|| | }}n||n|}|| ks|| kr&t't)dj+| | ||| j-||| S) aX Returns a matrix with the specified diagonal. If matrices are passed, a block-diagonal matrix is created (i.e. the "direct sum" of the matrices). kwargs ====== rows : rows of the resulting matrix; computed if not given. cols : columns of the resulting matrix; computed if not given. cls : class for the resulting matrix unpack : bool which, when True (default), unpacks a single sequence rather than interpreting it as a Matrix. strict : bool which, when False (default), allows Matrices to have variable-length rows. Examples ======== >>> from sympy import Matrix >>> Matrix.diag(1, 2, 3) Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) The current default is to unpack a single sequence. If this is not desired, set `unpack=False` and it will be interpreted as a matrix. >>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3) True When more than one element is passed, each is interpreted as something to put on the diagonal. Lists are converted to matrices. Filling of the diagonal always continues from the bottom right hand corner of the previous item: this will create a block-diagonal matrix whether the matrices are square or not. >>> col = [1, 2, 3] >>> row = [[4, 5]] >>> Matrix.diag(col, row) Matrix([ [1, 0, 0], [2, 0, 0], [3, 0, 0], [0, 4, 5]]) When `unpack` is False, elements within a list need not all be of the same length. Setting `strict` to True would raise a ValueError for the following: >>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False) Matrix([ [1, 2, 3], [4, 5, 0], [6, 0, 0]]) The type of the returned matrix can be set with the ``cls`` keyword. >>> from sympy import ImmutableMatrix >>> from sympy.utilities.misc import func_name >>> func_name(Matrix.diag(1, cls=ImmutableMatrix)) 'ImmutableDenseMatrix' A zero dimension matrix can be used to position the start of the filling at the start of an arbitrary row or column: >>> from sympy import ones >>> r2 = ones(0, 2) >>> Matrix.diag(r2, 1, 2) Matrix([ [0, 0, 1, 0], [0, 0, 0, 2]]) See Also ======== eye diagonal .dense.diag .expressions.blockmatrix.BlockMatrix .sparsetools.banded rr?)Matrix) SparseMatrixrHrrrzg The constructed matrix is {} x {} but a size of {} x {} was specified.)rBr@sympy.matrices.denser8sympy.matricesr9getrrrErrSrrrr_handle_creation_inputsitemshasattrrrr!rr)rr6r.rTrUr`rZr@r8r9klass diag_entriesrmaxcmaxmrrrsmatr|r}mis rLr/zMatrixSpecial.diagsx 9// 5#& c$i1nT!W)=tAw 37D#3' t A!T"q A77DAq A!-!E!Ea!HJAq$%)ZZ\? A=> a$hD%9:?AG$ww1HHJ-. dD\*  "1 ;2%bM;DAq9:L!d(AH!56; ; AID AID5 6 <t$D <t$D<4TD $;$+Z)""(&tT4"@BC CdL99rMc ||}|dks|dkrtdj|||jd|}t|t|}}|j ||S)zReturns an identity matrix. Parameters ========== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix r@Cannot create a {} x {} matrix. Both dimensions must be positiverH)rrr<r rrrTrUrZr@s rLeyezMatrixSpecial.eye5sn <D !8tax@@FtT@RT T 5#&D\6$>> from sympy import Matrix >>> from sympy.abc import x >>> Matrix.jordan_block(4, x) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) Creating an alternative Jordan block matrix where `1` is on lower off-diagonal: >>> Matrix.jordan_block(4, x, band='lower') Matrix([ [x, 0, 0, 0], [1, x, 0, 0], [0, 1, x, 0], [0, 0, 1, x]]) Creating a Jordan block with keyword arguments >>> Matrix.jordan_block(size=4, eigenvalue=x) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) References ========== .. [1] https://en.wikipedia.org/wiki/Jordan_matrix rHeigenvalNzMust supply an eigenvaluez=Inconsistent values are given: 'eigenval'={}, 'eigenvalue'={}zMust supply a matrix size)popr<rrr r#)rr!rr"rZr@rLs rL jordan_blockzMatrixSpecial.jordan_blockMs^ 5#&::j$/  ("289 9 8 #Xz4J(J""(&:">@ @#% <89 9d|''j$??rMc ~||}|jd|}t|t|}}|j||S)zReturns a matrix of ones. Parameters ========== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix rH)r<r r(rIs rLoneszMatrixSpecial.onessB <D 5#&D\6$>> from sympy import Matrix, Poly, Symbol, symbols >>> x = Symbol('x') >>> c0, c1, c2, c3, c4 = symbols('c0:5') >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x) >>> Matrix.companion(p) Matrix([ [0, 0, 0, 0, -c0], [1, 0, 0, 0, -c1], [0, 1, 0, 0, -c2], [0, 0, 1, 0, -c3], [0, 0, 0, 1, -c4]]) z{} must be a Poly instance.z{} must be a monic polynomial.z#{} must be a univariate polynomial.rz${} must have degree not less than 1.cf|dz k(r d|z  S||dzk(r jSjS)Nrr)r|r}coeffsrr!s rLrz&MatrixSpecial.companion..entrys;D1H}rAv&a!eww88OrM) _sympifyrErrris_monic is_univariatedegree all_coeffsra)rpolyrrVr!s` @@rL companionzMatrixSpecial.companions&||D!$%:AA$GH H}}=DDTJK K!!5<>> from sympy import Matrix >>> wminus, wplus = Matrix.wilkinson(3) >>> wminus Matrix([ [-3, 1, 0, 0, 0, 0, 0], [ 1, -2, 1, 0, 0, 0, 0], [ 0, 1, -1, 1, 0, 0, 0], [ 0, 0, 1, 0, 1, 0, 0], [ 0, 0, 0, 1, 1, 1, 0], [ 0, 0, 0, 0, 1, 2, 1], [ 0, 0, 0, 0, 0, 1, 3]]) >>> wplus Matrix([ [3, 1, 0, 0, 0, 0, 0], [1, 2, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 2, 1], [0, 0, 0, 0, 0, 1, 3]]) References ========== .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/ .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp. rH)r<r r5)rrrZr@s rL wilkinsonzMatrixSpecial.wilkinsons/H 5#& 1I$$Q''rM)r)r!rSr)NN)rArNrOrsrurrr#r(r*r5r/rJrNrPrRr]r_rWrMrLr*r*ns$*++66 ++"++ HH   %dDK:K:Z++._@g_@_@B,,(--.'+'+T%(%(rMr*cReZdZdZdZdZdZdZdZdZ d%dZ d Z d Z d Z d Zd ZdZdZdZdZdZedZdZd&dZdZedZedZedZed%dZedZedZedZ dZ!d&dZ"ed Z#ed!Z$ed"Z%d#Z&y$)'r+z&Provides basic properties of a matrix.cdt}|D] }|j|j|"|Sr)setupdateatoms)rftypesresultr|s rL _eval_atomszMatrixProperties._eval_atoms2s3 +A MM'!''5/ * + rMc>tjd|DS)Nc3:K|]}|s|jywr) free_symbolsrs rLrz6MatrixProperties._eval_free_symbols..9s?QQ^^?s)rbunionrns rL_eval_free_symbolsz#MatrixProperties._eval_free_symbols8ssu{{?T?@@rMc,tfd|DS)Nc3<K|]}|jywr)has)rapatternss rLrz-MatrixProperties._eval_has..<s25155(#2rrrfrqs `rL _eval_haszMatrixProperties._eval_has;s2T222rMcZtfdtjDsyy)Nc3K|]=}tjD]#}||f||fzj%?ywrrrUis_zero)rr|r}rfsimpfuncs rLrz;MatrixProperties._eval_is_anti_symmetric..?sLq`efjfofo`pq[\8DAJad34<<q<qsAAFTrrrT)rfrys``rL_eval_is_anti_symmetricz(MatrixProperties._eval_is_anti_symmetric>s qeDIIFVqqrMct|jD],}t|jD]}||k7s |||fsy.y)NFT)rrTrU)rfr|r}s rL_eval_is_diagonalz"MatrixProperties._eval_is_diagonalCsKtyy! !A499% !6d1a4j  ! !rMctjjjfd}|jS)NcJ||f||fjz Sr conjugater|r}rfrys rLrz.Ns/8DAJQUVWYZVZQ[QeQeQgDg;hrMrarTrUis_zero_matrixrfryrs`` rL_eval_is_matrix_hermitianz*MatrixProperties._eval_is_matrix_hermitianMs*ii 499.hi!!!rMc\dtfdtjDS)Nc||k(ryyrrWr|r}s rLdiracz1MatrixProperties._eval_is_Identity..diracRsAvrMc3tK|]/}tjD]}||f||k(1ywr)rrU)rr|r}rrfs rLrz5MatrixProperties._eval_is_Identity..WsH+tyy)+1:q!,+,+s58rz)rfrs`@rL_eval_is_Identityz"MatrixProperties._eval_is_IdentityQs-  +tyy)++ +rMcRtfdtjDS)Nc3|K|]3}t|dzjD]}||fj5yw)r-Nrwrr|r}rfs rLrz=MatrixProperties._eval_is_lower_hessenberg..\I5!!a%351:%%5%59<rzrns`rL_eval_is_lower_hessenbergz*MatrixProperties._eval_is_lower_hessenberg[&5!$)),55 5rMcRtfdtjDS)Nc3|K|]3}t|dzjD]}||fj5ywrNrwrs rLrz2MatrixProperties._eval_is_lower..arrrzrns`rL_eval_is_lowerzMatrixProperties._eval_is_lower`rrMc,|jtSr)rorrns rL_eval_is_symbolicz"MatrixProperties._eval_is_symbolicesxxrMctjjjfd}|jS)Nc.||f||fz SrrWrs rLrz5MatrixProperties._eval_is_symmetric..is&8DAJQUVWYZVZQ[D[;\rMrrs`` rL_eval_is_symmetricz#MatrixProperties._eval_is_symmetrichs*ii 499.\]!!!rMcPtd|Drytd|Dryy)Nc3:K|]}|jdk(yw)FNrxrs rLrz8MatrixProperties._eval_is_zero_matrix..ms0aqyyE!0sFc38K|]}|jduywrrrs rLrz8MatrixProperties._eval_is_zero_matrix..os/QqyyD /sTrrrns rL_eval_is_zero_matrixz%MatrixProperties._eval_is_zero_matrixls' 040 0 /$/ /rMcTtfdtdjDS)Nc3K|]<}ttj|dz D]}||fj>ywrrrrUrxrs rLrz=MatrixProperties._eval_is_upper_hessenberg..tsN<!#dii!a%"9:<1:%%<%.|A1DAJAc34K|]}|jywr) is_positiverxs rLrz;MatrixProperties._has_positive_diagonals..}sA1ArrTrrfdiagonal_entriess` rL_has_positive_diagonalsz(MatrixProperties._has_positive_diagonals{s)Adii0@AA0@AAArMcdfdtjD}td|DS)Nc3,K|] }||f ywrrWrs rLrz>MatrixProperties._has_nonnegative_diagonals..rrc34K|]}|jywr)is_nonnegativers rLrz>MatrixProperties._has_nonnegative_diagonals..sDa))Drrrs` rL_has_nonnegative_diagonalsz+MatrixProperties._has_nonnegative_diagonalss)Adii0@AD3CDDDrMcVtd|D}|stf}|j|S)avReturns the atoms that form the current object. Examples ======== >>> from sympy.abc import x, y >>> from sympy import Matrix >>> Matrix([[x]]) Matrix([[x]]) >>> _.atoms() {x} >>> Matrix([[x, y], [y, x]]) Matrix([ [x, y], [y, x]]) >>> _.atoms() {x, y} c3VK|]!}t|tr|n t|#ywr)rEr)rts rLrz)MatrixProperties.atoms..s"K:a.aDG;Ks'))tupler rg)rfres rLrdzMatrixProperties.atomss1(KUKKGEt''rMc"|jS)zReturns the free symbols within the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy import Matrix >>> Matrix([[x], [1]]).free_symbols {x} )rlrns rLrjzMatrixProperties.free_symbolss&&((rMc |j|S)aTest whether any subexpression matches any of the patterns. Examples ======== >>> from sympy import Matrix, SparseMatrix, Float >>> from sympy.abc import x, y >>> A = Matrix(((1, x), (0.2, 3))) >>> B = SparseMatrix(((1, x), (0.2, 3))) >>> A.has(x) True >>> A.has(y) False >>> A.has(Float) True >>> B.has(x) True >>> B.has(y) False >>> B.has(Float) True )rtrss rLrozMatrixProperties.hass.t~~x((rMcn|}t|s |rtnd}|jsy|j|S)aCheck if matrix M is an antisymmetric matrix, that is, M is a square matrix with all M[i, j] == -M[j, i]. When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is simplified before testing to see if it is zero. By default, the SymPy simplify function is used. To use a custom function set simplify to a function that accepts a single argument which returns a simplified expression. To skip simplification, set simplify to False but note that although this will be faster, it may induce false negatives. Examples ======== >>> from sympy import Matrix, symbols >>> m = Matrix(2, 2, [0, 1, -1, 0]) >>> m Matrix([ [ 0, 1], [-1, 0]]) >>> m.is_anti_symmetric() True >>> x, y = symbols('x y') >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0]) >>> m Matrix([ [ 0, 0, x], [-y, 0, 0]]) >>> m.is_anti_symmetric() False >>> from sympy.abc import x, y >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, ... -(x + 1)**2, 0, x*y, ... -y, -x*y, 0]) Simplification of matrix elements is done by default so even though two elements which should be equal and opposite would not pass an equality test, the matrix is still reported as anti-symmetric: >>> m[0, 1] == -m[1, 0] False >>> m.is_anti_symmetric() True If ``simplify=False`` is used for the case when a Matrix is already simplified, this will speed things up. Here, we see that without simplification the matrix does not appear anti-symmetric: >>> print(m.is_anti_symmetric(simplify=False)) None But if the matrix were already expanded, then it would appear anti-symmetric and simplification in the is_anti_symmetric routine is not needed: >>> m = m.expand() >>> m.is_anti_symmetric(simplify=False) True c|SrrWrs rLrz4MatrixProperties.is_anti_symmetric..ArMF)rrrr{rfsimplifyrys rLis_anti_symmetricz"MatrixProperties.is_anti_symmetrics6~(#$,y+H~~++H55rMc"|jS)a.Check if matrix is diagonal, that is matrix in which the entries outside the main diagonal are all zero. Examples ======== >>> from sympy import Matrix, diag >>> m = Matrix(2, 2, [1, 0, 0, 2]) >>> m Matrix([ [1, 0], [0, 2]]) >>> m.is_diagonal() True >>> m = Matrix(2, 2, [1, 1, 0, 2]) >>> m Matrix([ [1, 1], [0, 2]]) >>> m.is_diagonal() False >>> m = diag(1, 2, 3) >>> m Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> m.is_diagonal() True See Also ======== is_lower is_upper sympy.matrices.matrixbase.MatrixCommon.is_diagonalizable diagonalize )r}rns rL is_diagonalzMatrixProperties.is_diagonal sR%%''rMcjsyj\}fdtfdt|DS)aTests if the matrix is row weakly diagonally dominant. Explanation =========== A $n, n$ matrix $A$ is row weakly diagonally dominant if .. math:: \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1} \left|A_{i, j}\right| \quad {\text{for all }} i \in \{ 0, ..., n-1 \} Examples ======== >>> from sympy import Matrix >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) >>> A.is_weakly_diagonally_dominant True >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) >>> A.is_weakly_diagonally_dominant False >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) >>> A.is_weakly_diagonally_dominant True Notes ===== If you want to test whether a matrix is column diagonally dominant, you can apply the test after transposing the matrix. Fcj}tD]}||k7s |t||fz }t||f|z jSr)rrrrr| summationr}rUrfs rLtest_rowz@MatrixProperties.is_weakly_diagonally_dominant..test_row^s[ I4[ 16T!Q$Z0I 1QT Oi/?? ?rMc3.K|] }|ywrrWrr|rs rLrzAMatrixProperties.is_weakly_diagonally_dominant..e:!:rrrrrrfrTrUrs` @@rLis_weakly_diagonally_dominantz.MatrixProperties.is_weakly_diagonally_dominant5s:H~~ZZ d @:eDk:::rMcjsyj\}fdtfdt|DS)aTests if the matrix is row strongly diagonally dominant. Explanation =========== A $n, n$ matrix $A$ is row strongly diagonally dominant if .. math:: \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1} \left|A_{i, j}\right| \quad {\text{for all }} i \in \{ 0, ..., n-1 \} Examples ======== >>> from sympy import Matrix >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) >>> A.is_strongly_diagonally_dominant False >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) >>> A.is_strongly_diagonally_dominant False >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) >>> A.is_strongly_diagonally_dominant True Notes ===== If you want to test whether a matrix is column diagonally dominant, you can apply the test after transposing the matrix. Fcj}tD]}||k7s |t||fz }t||f|z jSr)rrrrrs rLrzBMatrixProperties.is_strongly_diagonally_dominant..test_rows[ I4[ 16T!Q$Z0I 1QT Oi/<< .rrrrs` @@rLis_strongly_diagonally_dominantz0MatrixProperties.is_strongly_diagonally_dominantgs9H~~ZZ d =:eDk:::rMcF|jsy|jtS)agChecks if the matrix is Hermitian. In a Hermitian matrix element i,j is the complex conjugate of element j,i. Examples ======== >>> from sympy import Matrix >>> from sympy import I >>> from sympy.abc import x >>> a = Matrix([[1, I], [-I, 1]]) >>> a Matrix([ [ 1, I], [-I, 1]]) >>> a.is_hermitian True >>> a[0, 0] = 2*I >>> a.is_hermitian False >>> a[0, 0] = x >>> a.is_hermitian >>> a[0, 1] = a[1, 0]*I >>> a.is_hermitian False F)rrrrns rL is_hermitianzMatrixProperties.is_hermitians:~~--i88rMc<|jsy|jSNF)rrrns rL is_IdentityzMatrixProperties.is_Identitys~~%%''rMc"|jS)a-Checks if the matrix is in the lower-Hessenberg form. The lower hessenberg matrix has zero entries above the first superdiagonal. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) >>> a Matrix([ [1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) >>> a.is_lower_hessenberg True See Also ======== is_upper_hessenberg is_lower )rrns rLis_lower_hessenbergz$MatrixProperties.is_lower_hessenberg6--//rMc"|jS)alCheck if matrix is a lower triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_lower True >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5]) >>> m Matrix([ [0, 0, 0], [2, 0, 0], [1, 4, 0], [6, 6, 5]]) >>> m.is_lower True >>> from sympy.abc import x, y >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y]) >>> m Matrix([ [x**2 + y, x + y**2], [ 0, x + y]]) >>> m.is_lower False See Also ======== is_upper is_diagonal is_lower_hessenberg )rrns rLis_lowerzMatrixProperties.is_lowersV""$$rMc4|j|jk(S)a/Checks if a matrix is square. A matrix is square if the number of rows equals the number of columns. The empty matrix is square by definition, since the number of rows and the number of columns are both zero. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 2, 3], [4, 5, 6]]) >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> c = Matrix([]) >>> a.is_square False >>> b.is_square True >>> c.is_square True rrns rLrzMatrixProperties.is_square s,yyDII%%rMc"|jS)zChecks if any elements contain Symbols. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.is_symbolic() True )rrns rL is_symboliczMatrixProperties.is_symbolic#s%%''rMcn|}t|s |rtnd}|jsy|j|S)aCheck if matrix is symmetric matrix, that is square matrix and is equal to its transpose. By default, simplifications occur before testing symmetry. They can be skipped using 'simplify=False'; while speeding things a bit, this may however induce false negatives. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [0, 1, 1, 2]) >>> m Matrix([ [0, 1], [1, 2]]) >>> m.is_symmetric() True >>> m = Matrix(2, 2, [0, 1, 2, 0]) >>> m Matrix([ [0, 1], [2, 0]]) >>> m.is_symmetric() False >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0]) >>> m Matrix([ [0, 0, 0], [0, 0, 0]]) >>> m.is_symmetric() False >>> from sympy.abc import x, y >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) >>> m Matrix([ [ 1, x**2 + 2*x + 1, y], [(x + 1)**2, 2, 0], [ y, 0, 3]]) >>> m.is_symmetric() True If the matrix is already simplified, you may speed-up is_symmetric() test by using 'simplify=False'. >>> bool(m.is_symmetric(simplify=False)) False >>> m1 = m.expand() >>> m1.is_symmetric(simplify=False) True c|SrrWrs rLrz/MatrixProperties.is_symmetric..krrMF)rrrrrs rLrzMatrixProperties.is_symmetric2s6n(#$,y+H~~&&x00rMc"|jS)a(Checks if the matrix is the upper-Hessenberg form. The upper hessenberg matrix has zero entries below the first subdiagonal. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) >>> a Matrix([ [1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) >>> a.is_upper_hessenberg True See Also ======== is_lower_hessenberg is_upper )rrns rLis_upper_hessenbergz$MatrixProperties.is_upper_hessenbergrrrMcTtfdtdjDS)a$Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_upper True >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0]) >>> m Matrix([ [5, 1, 9], [0, 4, 6], [0, 0, 5], [0, 0, 0]]) >>> m.is_upper True >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) >>> m Matrix([ [4, 2, 5], [6, 1, 1]]) >>> m.is_upper False See Also ======== is_lower is_diagonal is_upper_hessenberg c3K|]9}tt|jD]}||fj;ywrrrs rLrz,MatrixProperties.is_upper..sJ6!#a"3461:%%6%6s?Arrzrns`rLis_upperzMatrixProperties.is_uppers+T6!!TYY/66 6rMc"|jS)a,Checks if a matrix is a zero matrix. A matrix is zero if every element is zero. A matrix need not be square to be considered zero. The empty matrix is zero by the principle of vacuous truth. For a matrix that may or may not be zero (e.g. contains a symbol), this will be None Examples ======== >>> from sympy import Matrix, zeros >>> from sympy.abc import x >>> a = Matrix([[0, 0], [0, 0]]) >>> b = zeros(3, 4) >>> c = Matrix([[0, 1], [0, 0]]) >>> d = Matrix([]) >>> e = Matrix([[x, 0], [0, 0]]) >>> a.is_zero_matrix True >>> b.is_zero_matrix True >>> c.is_zero_matrix False >>> d.is_zero_matrix True >>> e.is_zero_matrix )rrns rLrzMatrixProperties.is_zero_matrixs:((**rMc"|jS)zReturn non-zero values of self.)rrns rLvalueszMatrixProperties.valuess  ""rMN)returnrT)'rArNrOrsrgrlrtr{r}rrrrrrrrrrrrdrvrjrorrrrrrrrrrrrrrrrWrMrLr+r+/s`0 A3 "+5 5  "< 2BE(2 ) ))2E6N)(V/;/;b/;/;b99B(( 008*%*%X&&. (>1@008+6+6Z++<#rMr+ceZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d%d Zd ZdZd&dZ d'dZedZd(dZd)dZd)dZd%dZd*dZd+dZdZdZdZdZedZedZ dZ!d Z"d!Z#d"Z$d,d#Z%d,d$Z&y)-r,zaProvides basic matrix shape and elementwise operations. Should not be instantiated directly.c>|jjSr) transposerrns rL _eval_adjointzMatrixOperations._eval_adjoints~~))++rMc |j|j|j|Dcgc] }|| c}}|Scc}wrr)rffrouts rL_eval_applyfuncz MatrixOperations._eval_applyfuncs6ii 499T.Bqt.BC /Cs> cV|jt|jtfSr) applyfuncrrrns rL_eval_as_real_imagz#MatrixOperations._eval_as_real_imagsr"DNN2$677rMc&|jdS)Nc"|jSrrrs rLrz2MatrixOperations._eval_conjugate..s  rMrrns rL_eval_conjugatez MatrixOperations._eval_conjugates~~566rMcvt|fd}jjj|S)Nc||fSrrWr|r}mappingrfs rLrz2MatrixOperations._eval_permute_cols..entrys71: & &rMrrarTrUrfpermrrs` @rL_eval_permute_colsz#MatrixOperations._eval_permute_cols.t* 'yyDIIu55rMcvt|fd}jjj|S)Nc||fSrrWrs rLrz2MatrixOperations._eval_permute_rows..entrys A & &rMrrs` @rL_eval_permute_rowsz#MatrixOperations._eval_permute_rowsr rMcRtfdtjDS)Nc3,K|] }||f ywrrWrs rLrz/MatrixOperations._eval_trace..s8!41:8r)sumrrTrns`rL _eval_tracezMatrixOperations._eval_traces8uTYY'7888rMcXjjjfdS)Nc||fSrrWr|r}rfs rLrz2MatrixOperations._eval_transpose..sDAJrM)rarUrTrns`rL_eval_transposez MatrixOperations._eval_transposesyyDII/FGGrMc"|jS)z-Conjugate transpose or Hermitian conjugation.)rrns rLadjointzMatrixOperations.adjoint s!!##rMcPt|s td|j|S)aLApply a function to each element of the matrix. Examples ======== >>> from sympy import Matrix >>> m = Matrix(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.)callablerr)rfrs rLrzMatrixOperations.applyfuncs(${34 4##A&&rMc "|jS)z@Returns a tuple containing the (real, imaginary) part of matrix.)r)rfdeephintss rL as_real_imagzMatrixOperations.as_real_imag%s&&((rMc"|jS)a#Return the by-element conjugation. Examples ======== >>> from sympy import SparseMatrix, I >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I))) >>> a Matrix([ [1, 2 + I], [3, 4], [I, -I]]) >>> a.C Matrix([ [ 1, 2 - I], [ 3, 4], [-I, I]]) See Also ======== transpose: Matrix transposition H: Hermite conjugation sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation )rrns rLrzMatrixOperations.conjugate*s4##%%rMc ,|jfdS)Nc(|jdiSNrW)doit)rrs rLrz'MatrixOperations.doit..GsrMr)rfrs `rLr"zMatrixOperations.doitFs~~788rMNcB||||||d|jfdS)&Apply evalf() to each element of self.)subsmaxnchopr6quadverbosec*|jfiSrevalf)r|roptionss rLrz(MatrixOperations.evalf..Ms(=W(=rMr) rfrr%r&r'r6r(r)r-s ` @rLr,zMatrixOperations.evalfIs(tD6w0~~=>>rMc L |j f dS)a$Apply core.function.expand to each entry of the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy import Matrix >>> Matrix(1, 1, [x*(x+1)]) Matrix([[x*(x + 1)]]) >>> _.expand() Matrix([[x**2 + x]]) c 8 |j fiSr)expand) rbasicrrlogmodulusmul multinomial power_base power_exps rLrz)MatrixOperations.expand..^s+ ':y#sK))rMr) rfrr3r6r7r4r2r5r1rs `````````rLr0zMatrixOperations.expandOs!~~ rMc.|jjS)aReturn Hermite conjugate. Examples ======== >>> from sympy import Matrix, I >>> m = Matrix((0, 1 + I, 2, 3)) >>> m Matrix([ [ 0], [1 + I], [ 2], [ 3]]) >>> m.H Matrix([[0, 1 - I, 2, 3]]) See Also ======== conjugate: By-element conjugation sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation )r0Crns rLHzMatrixOperations.Hbs0vvxxrMcddlm}|dk(rd}|dk(rd}|dk(rd}|d vrtd j||d vrtd j|t ||t fst d j||dk(r |jn |jtfdtt|Ds td|rFt ||s:t |dt r'|dk(rtt|}||dz}n ||dz}|dk(r|j|S|dk(r|j|Sy)a Permute the rows or columns of a matrix by the given list of swaps. Parameters ========== perm : Permutation, list, or list of lists A representation for the permutation. If it is ``Permutation``, it is used directly with some resizing with respect to the matrix size. If it is specified as list of lists, (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed from applying the product of cycles. The direction how the cyclic product is applied is described in below. If it is specified as a list, the list should represent an array form of a permutation. (e.g., ``[1, 2, 0]``) which would would form the swapping function `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`. orientation : 'rows', 'cols' A flag to control whether to permute the rows or the columns direction : 'forward', 'backward' A flag to control whether to apply the permutations from the start of the list first, or from the back of the list first. For example, if the permutation specification is ``[[0, 1], [0, 2]]``, If the flag is set to ``'forward'``, the cycle would be formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`. If the flag is set to ``'backward'``, the cycle would be formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`. If the argument ``perm`` is not in a form of list of lists, this flag takes no effect. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward') Matrix([ [0, 0, 1], [1, 0, 0], [0, 1, 0]]) >>> from sympy import eye >>> M = eye(3) >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward') Matrix([ [0, 1, 0], [0, 0, 1], [1, 0, 0]]) Notes ===== If a bijective function `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the permutation. If the matrix `A` is the matrix to permute, represented as a horizontal or a vertical stack of vectors: .. math:: A = \begin{bmatrix} a_0 \\ a_1 \\ \vdots \\ a_{n-1} \end{bmatrix} = \begin{bmatrix} \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1} \end{bmatrix} If the matrix `B` is the result, the permutation of matrix rows is defined as: .. math:: B := \begin{bmatrix} a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)} \end{bmatrix} And the permutation of matrix columns is defined as: .. math:: B := \begin{bmatrix} \alpha_{\sigma(0)} & \alpha_{\sigma(1)} & \cdots & \alpha_{\sigma(n-1)} \end{bmatrix} r) Permutationforwardsforward backwardsbackwardcolumnsrU)r>r@z?direction='{}' is an invalid kwarg. Try 'forward' or 'backward'rz:orientation='{}' is an invalid kwarg. Try 'rows' or 'cols'zB{} must be a list, a list of lists, or a SymPy permutation object.rTc3>K|]}d|cxkxrkncyw)rNrW)rr max_indexs rLrz+MatrixOperations.permute..sD11&Y&&Dsz`swap` indices out of range.r)r!N)sympy.combinatoricsr<rrrErrrTrUrrrrreversedr r )rfr orientation directionr<rCs @rLpermutezMatrixOperations.permute|snB 4  "!I  #"I ) # K 3 3::@&:KM M . .3396+3FH H$h 78117? ? "-!6DIIDII DT 0CDD;< <  45 tAw )I%HTN+t)A+6Dt)A+6D & **40 0 & **40 0 !rMc*|j|d|S)zAlias for ``self.permute(swaps, orientation='cols', direction=direction)`` See Also ======== permute rUrFrGrHrfswapsrGs rL permute_colszMatrixOperations.permute_cols ||Ev|KKrMc*|j|d|S)zAlias for ``self.permute(swaps, orientation='rows', direction=direction)`` See Also ======== permute rTrJrKrLs rL permute_rowszMatrixOperations.permute_rows rOrMc,|jfdS)aApply refine to each element of the matrix. Examples ======== >>> from sympy import Symbol, Matrix, Abs, sqrt, Q >>> x = Symbol('x') >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]]) Matrix([ [ Abs(x)**2, sqrt(x**2)], [sqrt(x**2), Abs(x)**2]]) >>> _.refine(Q.real(x)) Matrix([ [ x**2, Abs(x)], [Abs(x), x**2]]) ct|Srr)r assumptionss rLrz)MatrixOperations.refine..- sq+(>rMr)rfrTs `rLr zMatrixOperations.refine s$~~>??rMc<|jfdS)aReplaces Function F in Matrix entries with Function G. Examples ======== >>> from sympy import symbols, Function, Matrix >>> F, G = symbols('F, G', cls=Function) >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M Matrix([ [F(0), F(1)], [F(1), F(2)]]) >>> N = M.replace(F,G) >>> N Matrix([ [G(0), G(1)], [G(1), G(2)]]) c0|jS)N)map simultaneousexact)replace)rFGrYrWrXs rLrz*MatrixOperations.replace..B saii1#LPUiVrMr)rfr[r\rWrXrYs `````rLrZzMatrixOperations.replace/ s$~~ VX XrMc|dz}|dk(r|S|dk(r|dddddfjS|dk(r |ddddddfS|dk(r|dddddfjSy)aRotates Matrix by 90 degrees Parameters ========== k : int Specifies how many times the matrix is rotated by 90 degrees (clockwise when positive, counter-clockwise when negative). Examples ======== >>> from sympy import Matrix, symbols >>> A = Matrix(2, 2, symbols('a:d')) >>> A Matrix([ [a, b], [c, d]]) Rotating the matrix clockwise one time: >>> A.rot90(1) Matrix([ [c, a], [d, b]]) Rotating the matrix anticlockwise two times: >>> A.rot90(-2) Matrix([ [d, c], [b, a]]) rrNrUr-r:)r0)rfrmods rLrot90zMatrixOperations.rot90D s{Fc !8K !8"b>## # !8"dd # # !8DbD>## # rMc ,|jfdS)aOApply simplify to each element of the matrix. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, sin, cos >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2]) Matrix([[x*sin(y)**2 + x*cos(y)**2]]) >>> _.simplify() Matrix([[x]]) c(|jdiSr!)r)rrZs rLrz+MatrixOperations.simplify..~ s  (>> from sympy.abc import x, y >>> from sympy import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.subs(x, y) Matrix([[y]]) >>> Matrix(_).subs(y, x) Matrix([[x]]) rrc(|jiSr)r%)rr`rZs rLrz'MatrixOperations.subs.. s(?(?rM)rrEdictrbiterrrrrfr`rZs ``rLr%zMatrixOperations.subs s[ t9>:d1gc{#CTRSW ^ijnopjq^raM#D~~?@@rMch|j|jk7r t|jS)z Returns the trace of a square matrix i.e. the sum of the diagonal elements. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.trace() 5 )rTrUr&rrns rLtracezMatrixOperations.trace s, 99 !&( (!!rMc"|jS)aa Returns the transpose of the matrix. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.transpose() Matrix([ [1, 3], [2, 4]]) >>> from sympy import Matrix, I >>> m=Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m.transpose() Matrix([ [ 1, 3], [2 + I, 4]]) >>> m.T == m.transpose() True See Also ======== conjugate: By-element conjugation )rrns rLrzMatrixOperations.transpose sB##%%rMc"|jS)zMatrix transposition)rrns rLr0zMatrixOperations.T ~~rMc"|jS)zBy-element conjugationrrns rLr9zMatrixOperations.C rmrMc&|j|i|S)r$r+rhs rLrzMatrixOperations.n stzz4*6**rMc,|jfdS)akReturn a new matrix with xreplace applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.xreplace({x: y}) Matrix([[y]]) >>> Matrix(_).xreplace({y: x}) Matrix([[x]]) c&|jSr)xreplace)rrules rLrz+MatrixOperations.xreplace.. s 4(8rMr)rfrss `rLrrzMatrixOperations.xreplace s~~899rMc .tj|fi|Sr)r,rrcs rL_eval_simplifyzMatrixOperations._eval_simplify s ((888rMc <ddlm|jfdS)Nr)trigsimpc|fiSrrW)roptsrws rLrz1MatrixOperations._eval_trigsimp.. s(;d(;rM)sympy.simplify.trigsimprwr)rfryrws `@rL_eval_trigsimpzMatrixOperations._eval_trigsimp s4~~;<>> from sympy import ones >>> A = ones(4) >>> A.upper_triangular() Matrix([ [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1]]) >>> A.upper_triangular(2) Matrix([ [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> A.upper_triangular(-1) Matrix([ [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1]]) c:|z|kr||fSjSrrr|r}rrfs rLrz0MatrixOperations.upper_triangular..entry $!"Q!41: : :rMrrfrrs`` rLupper_triangularz!MatrixOperations.upper_triangular &B ;yyDIIu55rMc`fd}jjj|S)aReturn the elements on and below the kth diagonal of a matrix. If k is not specified then simply returns lower-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.lower_triangular() Matrix([ [1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]) >>> A.lower_triangular(-2) Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0]]) >>> A.lower_triangular(1) Matrix([ [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1]]) c:|z|k\r||fSjSrr~rs rLrz0MatrixOperations.lower_triangular..entry: rrMrrs`` rLlower_triangularz!MatrixOperations.lower_triangular rrMr)NdFFNF)TNTTTTTT)rTr>)r>)FTN)rr )'rArNrOrsrrrrr r rrrrrrr"r,r0rvr:rHrNrQr rZr`rr%rjrr0r9rrrrur{rrrWrMrLr,r,s9,87669H$'.) &89? JN;?&2G1R L L@(X*+$Z >A*"$!&F    +:"9 =$6N$6rMr,ceZdZdZdZdZdZdZdZdZ dZ d Z d*d Z d Z d ZdZdZeddZeddZeddZdZeddZd*dZdZdZeddZd*dZedd Zed!d"Zed#d$Zd*d%Zed&d'Z ed(d)Z!y )+r-zUProvides basic matrix arithmetic operations. Should not be instantiated directly.gQ$@cXjjjfdS)Nc$t||fSr)rrs rLrz,MatrixArithmetic._eval_Abs..H sCQT OrMrrns`rL _eval_AbszMatrixArithmetic._eval_AbsG syyDII/KLLrMc\jjjfdS)Nc"||f||fzSrrWr|r}rgrfs rLrz,MatrixArithmetic._eval_add..L sd1a4j5A;&>rMrres``rL _eval_addzMatrixArithmetic._eval_addJ s%yyDII>@ @rMc`fd}jjj|S)NctjDcgc]}||f||fz}} t|Scc}w#ttf$rt d|cYSwxYw)Nc ||zSrrW)rpbs rLrzBMatrixArithmetic._eval_matrix_mul..entry..W s 1q5rM)rrUr rr r)r|r}rrrgrfs rLrz0MatrixArithmetic._eval_matrix_mul..entryO so16tyy1ABA4!9U1Q3Z'BCB 7Cy C|, 70#66  7s:?AArrfrgrs`` rL_eval_matrix_mulz!MatrixArithmetic._eval_matrix_mulN s% 7yyEJJ66rMc\jjjfdS)Nc"||f||fzSrrWrs rLrz?MatrixArithmetic._eval_matrix_mul_elementwise..\ sD1IeAaCj.entry..` s&GuQqSz$qs)+Gr)rrrUrs``rLrz1MatrixArithmetic._eval_matrix_rmul..entry_ sGU5::5FGG GrMrrs`` rL_eval_matrix_rmulz"MatrixArithmetic._eval_matrix_rmul^ s$ HyyTYY66rMc|dk(r|S|dzdk(r||j|dz }}n|j|dzx}}|j|S)Nrr-)_eval_pow_by_recursionmultiply)rfnumrprs rLrz'MatrixArithmetic._eval_pow_by_recursionc sX !8K 7a<44S1W=qA//q9 9Azz!}rMcddlm}|jd}|j}| j dd}|||}|j |}|j |}t|D]}||||zz }||z}|S)Nr) linrec_coeffsr)sympy.discrete.recurrencesrrrcharpolyr[rJrRr) rfexprrprVnew_matansr|s rL_eval_pow_by_cayleyz$MatrixArithmetic._eval_pow_by_cayleyn s<jjm MMO""12&vs+((3-jjos A 6!9W$ $C tOG  rMNc|dgt|z}|dk(r|S|dzdk(r||j|dz |}}n|j|dz|x}}|j|d}t|}dg|z}t|D])}||rt ||d\||<||<"||||<+|j |j |j|S)NTrr-)prevsimpF) dotprodsimp)withsimp)r"_eval_pow_by_recursion_dotprodsimprrrrarTrU) rfrrrprrDlenmelemsr|s rLrz3MatrixArithmetic._eval_pow_by_recursion_dotprodsimp~ s  vc$i'H !8K 7a<@@q%A'qA;;C1H%<' 'A 1% 0At t A{(4QqTD(I%a(1+Q4a  vvaffaffe,,rMc\jjjfdS)Nc||fzSrrWrs rLrz3MatrixArithmetic._eval_scalar_mul.. sD1IeOrMrres``rL_eval_scalar_mulz!MatrixArithmetic._eval_scalar_mul yyDII/KLLrMc\jjjfdS)Nc||fzSrrWrs rLrz4MatrixArithmetic._eval_scalar_rmul.. sE$qs)OrMrres``rL_eval_scalar_rmulz"MatrixArithmetic._eval_scalar_rmul rrMc\jjjfdS)Nc&t||fSrrrs rLrz,MatrixArithmetic._eval_Mod.. sCQT E|j |j k7r%t d|j d|j t|ddr2||}}|jt||k7r||}}|j|St|ddrtj||Stdt|dt|) z?Return self + other, raising ShapeError if shapes do not match.rrMatrix size mismatch: z + is_MatrixF is_MatrixLikez cannot add z and )rEr"NotImplemented _matrixifyr?rrr%getattrrKrrr-rr)rfrgrprs rL__add__zMatrixArithmetic.__add__ s eY '! !5! 5' "zzU[[( JJ "-.. 5+u -qA{{gam+!1;;q> ! 5/5 1#--dE: :$t*d5kJKKrM __rtruediv__c&||j|z zSrr&res rL __truediv__zMatrixArithmetic.__truediv__ stxx%'((rM __rmatmul__czt|}t|ddst|ddstS|j|SNrFr)rrr__mul__res rL __matmul__zMatrixArithmetic.__matmul__ s95!uk51'%Z_:`! !||E""rMc,|jfdS)Nc|zSrrW)rrgs rLrz*MatrixArithmetic.__mod__.. s E rMrres `rL__mod__zMatrixArithmetic.__mod__ s~~122rM__rmul__c$|j|S)avReturn self*other where other is either a scalar or a matrix of compatible dimensions. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]]) True >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> A*B Matrix([ [30, 36, 42], [66, 81, 96]]) >>> B*A Traceback (most recent call last): ... ShapeError: Matrices size mismatch. >>> See Also ======== matrix_multiply_elementwise )rres rLrzMatrixArithmetic.__mul__ s:}}U##rMc td|}t|}t|drwt|jdk(r_t |dds t |ddrE|jd|jdk7r&t d |jd |jd t |ddrS|j|}|r>|j|j|j|Dcgc] }t|c}S|St |ddrtj||St|ts |j|St"Scc}w#t $rYt"SwxYw) a\Same as __mul__() but with optional simplification. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off. Frrr-rTrrrrz * .)r#rr?rrrrr%rrarTrUrr-rErrrrrfrgr isimpboolrDes rLrzMatrixArithmetic.multiply s@0{C 5! E7 #EKK(8A(= UK . UOT 2zz!} A. JJ "-.. 5+u -%%e,Avvaffaff.J1|A.JKKH 5/5 1#44T5A A%* ,,U33/K  s E /E EEc|j|jk7r/tdj|j|j|j|S)aReturn the Hadamard product (elementwise product) of A and B Examples ======== >>> from sympy import Matrix >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) >>> A.multiply_elementwise(B) Matrix([ [ 0, 10, 200], [300, 40, 5]]) See Also ======== sympy.matrices.matrixbase.MatrixBase.cross sympy.matrices.matrixbase.MatrixBase.dot multiply z!Matrix shapes must agree {} != {})rrr%rrres rLmultiply_elementwisez%MatrixArithmetic.multiply_elementwise sI* :: $@GG TYT_T_`a a0077rMc$|jdS)NrU)rrns rL__neg__zMatrixArithmetic.__neg__3 s$$R((rM__rpow__c$|j|S)z$Return self**exp a scalar or symbol.)pow)rfrs rL__pow__zMatrixArithmetic.__pow__6 sxx}rMcl||dvr td|j|jk7r t|t dd}t j r(jjjdSdk(rSt dd}|2|r+jjjfdSjrHdzd k(r@jdk(rjd zggSd kr j|d k(r |S|d k(r0jrdzd k7r td jS|d k(r0jrdzd k7r tdjS|dk(r0jrdzd k7r tdjS|jrdzd k(rwjr t!jdk(r dkDr|St#ddrjSdkDrjSjS|r |Sd dlm}|S#t$r |d k(rY+wxYw#t$$r j&dusj(durYLwxYw)aReturn self**exp a scalar or symbol. Parameters ========== method : multiply, mulsimp, jordan, cayley If multiply then it returns exponentiation using recursion. If jordan then Jordan form exponentiation will be used. If cayley then the exponentiation is done using Cayley-Hamilton theorem. If mulsimp then the exponentiation is done using recursion with dotprodsimp. This specifies whether intermediate term algebraic simplification is used during naive matrix power to control expression blowup and thus speed up calculation. If None, then it heuristically decides which method to use. N)rmulsimpjordancayleyzNo such method_matrix_pow_by_jordan_blocksct||k(Sr)rSrs rLrz&MatrixArithmetic.pow..Y ss16{rMrrc&||k(r ||fzSdS)NrrW)r|r}rprs rLrz&MatrixArithmetic.pow.._ sa1fq1vs{RSrMrrrz.cayley method is only valid for integer powersrz/mulsimp method is only valid for integer powersrz0multiply method is only valid for integer powersr-iTi'F)MatPow)rrTrUr&rrrxra is_Numberinvr$rrrris_Floatrr#r' is_integerrsympy.matrices.expressionsr)rfrmethod jordan_powrrrps ` @rLrzMatrixArithmetic.pow= s&  &0["[,- - 99 !&( ( Q >E cl ;;66!&&!&&*BC C !8H1mT2  HJ66!&&!&&*ST T ==S1W\vv{vv!c {m,,QwdEEG X  !#& x ==C!GqL !QRR((- - y ==C!GqL !RSS77< < z !==C!GqL !STT++C0 0 ^ #'Q,||clvv{sV|!#&,T48;;C@@u,,S11//44  !#& 6a~Y X%& F,  >>U*c.@.@E.I/J  s$'I5J 5JJ &J32J3rc ||zSrrWres rLrzMatrixArithmetic.__radd__ s e|rMrczt|}t|ddst|ddstS|j|Sr)rrrrres rLrzMatrixArithmetic.__rmatmul__ s95!uk51'%Z_:`! !}}U##rMrc$|j|Sr) rmultiplyres rLrzMatrixArithmetic.__rmul__ s~~e$$rMc td|}t|}t|dr\t|jdk(rDt |dds t |ddr*|jd|jdk7r t d t |ddrS|j|}|r>|j|j|j|Dcgc] }t|c}S|St |ddrtj||St|ts |j|St"Scc}w#t $rYt"SwxYw) a]Same as __rmul__() but with optional simplification. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off. Frrr-rTrrrzMatrix size mismatch.)r#rr?rrrrr%rrarTrUrr-rErrrrrs rLrzMatrixArithmetic.rmultiply s+0{C 5! E7 #EKK(8A(= UK . UOT 2zz!} A. !899 5+u -&&u-Avvaffaff.J1|A.JKKH 5/5 1#55dEB B%* --e44/K  sD+ D00 EE__sub__c| |zSrrWrfrps rL__rsub__zMatrixArithmetic.__rsub__ s{rMrc|| zSrrWrs rLrzMatrixArithmetic.__sub__ sr{rMr)"rArNrOrs _op_priorityrrrrrrrrrrrrr rrrrrrrrrrrrrrrrrWrMrLr-r-A sn,LM@ 7R7  -4MMT :&L'L2>*)+)=)#*#3:&$'$<)V84):&' \|9%&<($)$9%%&%&P9%&:&'rMr-c eZdZUdZdZded<y)r.zsAll common matrix operations including basic arithmetic, shaping, and special matrices like `zeros`, and `eye`.Tr _diff_wrtN)rArNrOrsrrtrWrMrLr.r. s5ItrMr.ceZdZdZdZeeZdZe jZ e jZ dZdZedZd dZdZd Zd Zd Zed Zy)_MinimalMatrixaClass providing the minimum functionality for a matrix-like object and implementing every method required for a `MatrixRequired`. This class does not have everything needed to become a full-fledged SymPy object, but it will satisfy the requirements of anything inheriting from `MatrixRequired`. If you wish to make a specialized matrix type, make sure to implement these methods and properties with the exception of `__init__` and `__repr__` which are included for convenience.Tr:Fc||i|SrrWr_s rLraz_MinimalMatrix._new sD#F##rMNc t|r1t|Dcgc]}t|D] }||| }}}|||}t|d||f\}} |||}t|d}t|}|Dcgc] }|D]}| }}}t fd|D_||c__ j j tdycc}}wcc}}w#tt f$rYiwxYw)Nrrrc3@K|]}j|ywr)rW)rrrfs rLrz*_MinimalMatrix.__init__.. s7aq)7sz.Cannot initialize matrix with given parameters) rrrrrrrrrTrUr^) rfrTrUrrr|r}lrs ` rL__init__z_MinimalMatrix.__init__ s  c?&+DkG5;Ga3q!9G9GCG ._normalize_slices szi/!)Y]DA y00;._coord_to_index styy=1$ $rMc3PK|]}D]}|jz|zywrr)rr|r}rrfs rLrz-_MinimalMatrix.__getitem__.., s4%#%11tyy=1,%,%s#&) rErrrrrTrUrarr) rfrkr r r|r}rrrs ` @rLrlz_MinimalMatrix.__getitem__ s * % c5 !DAq!U#z!U';)A.1%)% *:%;A%>%)% *:%;A%>#(%h%yyXH 7>!?!$((1+!?AA "!Q'Cxx} "@sC5 c t|||j|jk(xrt|t|k(S#t$rYywxYwr)rrrrrres rLrhz_MinimalMatrix.__eq__6 sO  D%  JJ%++ % C$t*U *C E  s A A  A c4|j|jzSrrrns rLroz_MinimalMatrix.__len__> syy""rMcddj|j|j|jS)Nz_MinimalMatrix({}, {}, {}))rrTrUrrns rL__repr__z_MinimalMatrix.__repr__A s(+22499dii3788= =rMc2|j|jfSrrrns rLrrz_MinimalMatrix.shapeE s 499%%rM)NNF)rArNrOrsr staticmethodrrW_class_priorityrZerorOnerr is_MatrixExprrurarrlrhrorrvrrrWrMrLrr s{+MG$HO 66D %%CIM$$X*%NE#=&&rMrceZdZdZdZy)_CastableMatrixc|SrrWrns rL as_mutablez_CastableMatrix.as_mutableK  rMc|SrrWrns rL as_immutablez_CastableMatrix.as_immutableN rrMN)rArNrOrrrWrMrLrrJ s rMrc*eZdZdZdZdZdZdZdZy)_MatrixWrapperaWrapper class providing the minimum functionality for a matrix-like object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix math operations should work on matrix-like objects. This one is intended for matrix-like objects which use the same indexing format as SymPy with respect to returning matrix elements instead of rows for non-tuple indexes. FTc>||_||_|\|_|_yr)rrrrTrU)rfrrrs rLrz_MatrixWrapper.__init__] s $ 49rMct|tr$t|jj |St|jj ||j z||j zfSr)rErrrrlrTrUrjs rLrlz_MatrixWrapper.__getitem__b sV c5 !488//45 5txx++SDII-=sTYY,OPQQrMc|j|jtfdt|jDS)Nc3^K|]$}tD]}t||f&ywr)rr)rrrrUrs rLrz*_MatrixWrapper.__iter__..l s0V1%PT+VQGC1I&V&Vs*-)rrUrgrrT)rfrUrs @@rL__iter__z_MatrixWrapper.__iter__h s/hhyyVdii0@VVVrMN) rArNrOrsrrrrlr$rWrMrLrrR s$IM% R WrMrcXt|dds t|ddr|St|ddst|dds|Sd}t|dr%t|jdk(r=|j}n0t|dr$t|d r|j|j f}|r t ||S|S) zIf `mat` is a Matrix or is matrix-like, return a Matrix or MatrixWrapper object. Otherwise `mat` is passed through without modification.rFrTNrrr-rTrU)rr?rrrrTrUr)rrrs rLrro s sK'73+O 3 T *gc?D.Q EsG syy>Q IIE f '#v"6388$ c5)) JrMNct|ts&t|dd}||}ntd|d|#|dkr||z }|dk\r||kstd|dt|S)z>Return integer after making positive and validating against n. __index__NzInvalid index a[rrzIndex out of range: a[)rErSrr)r}rjindexs rLrr sn a K.  Aa9: :} q5 FAQ1q5A?@ @ q6MrMct|dd}t|dd}d||fvr1|j|jkDr |jS|jS ddl}t ||j r |jSt ||j r |jStd|jd|j#t $rY0wxYw)a Get the type of the result when combining matrices of different types. Currently the strategy is that immutability is contagious. Examples ======== >>> from sympy import Matrix, ImmutableMatrix >>> from sympy.matrices.matrixbase import classof >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix >>> IM = ImmutableMatrix([[1, 2], [3, 4]]) >>> classof(M, IM) rNrzIncompatible classes r)rrrKnumpyrEndarray ImportErrorr)AB priority_A priority_Br*s rLrr s -t4J-t4J J ++  q00 0;; ;;  a ';;  a ';;  Q[[!++N OO    sC C  C r)Krs __future__r collectionsrcollections.abcrinspectr functoolsrsympy.assumptions.refiner sympy.corer r sympy.core.basicr sympy.core.decoratorsr sympy.core.logicrrsympy.core.numbersrsympy.core.modrsympy.core.singletonrsympy.core.symbolrsympy.core.sympifyr$sympy.functions.elementary.complexesrrrsympy.utilities.exceptionsr utilitiesrrsympy.polys.polytoolsrsympy.utilities.iterablesrrsympy.utilities.miscr r!sympy.tensor.arrayr"r# exceptionsr$r%r&r'r(rXrr6rDr)r*r+r,r-r.rrrrrrrWrMrLrHs ##$+(!71&"$&<<@.&:3(2   =7D=7@9E49Exp *Np *f(N(Bo #~o #d\ 6~\ 6@X~Xv #%57Gd&d&NWW:2  "PrM