test_matrixbase.py 165 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795
  1. import concurrent.futures
  2. import random
  3. from collections.abc import Hashable
  4. from sympy import (
  5. Abs, Add, Array, DeferredVector, E, Expr, FiniteSet, Float, Function,
  6. GramSchmidt, I, ImmutableDenseMatrix, ImmutableMatrix,
  7. ImmutableSparseMatrix, Integer, KroneckerDelta, MatPow, Matrix,
  8. MatrixSymbol, Max, Min, MutableDenseMatrix, MutableSparseMatrix, Poly, Pow,
  9. PurePoly, Q, Quaternion, Rational, RootOf, S, SparseMatrix, Symbol, Tuple,
  10. Wild, banded, casoratian, cos, diag, diff, exp, expand, eye, floor, hessian,
  11. integrate, log, matrix_multiply_elementwise, nan, ones, oo, pi, randMatrix,
  12. rot_axis1, rot_axis2, rot_axis3, rot_ccw_axis1, rot_ccw_axis2,
  13. rot_ccw_axis3, signsimp, simplify, sin, sqrt, sstr, symbols, sympify, tan,
  14. trigsimp, wronskian, zeros, cancel)
  15. from sympy.abc import a, b, c, d, t, x, y, z
  16. from sympy.core.kind import NumberKind, UndefinedKind
  17. from sympy.matrices.determinant import _find_reasonable_pivot_naive
  18. from sympy.matrices.exceptions import (
  19. MatrixError, NonSquareMatrixError, ShapeError)
  20. from sympy.matrices.kind import MatrixKind
  21. from sympy.matrices.utilities import _dotprodsimp_state, _simplify, dotprodsimp
  22. from sympy.tensor.array.array_derivatives import ArrayDerivative
  23. from sympy.testing.pytest import (
  24. ignore_warnings, raises, skip, skip_under_pyodide, slow,
  25. warns_deprecated_sympy)
  26. from sympy.utilities.iterables import capture, iterable
  27. from importlib.metadata import version
  28. all_classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix)
  29. mutable_classes = (Matrix, SparseMatrix)
  30. immutable_classes = (ImmutableMatrix, ImmutableSparseMatrix)
  31. def test__MinimalMatrix():
  32. x = Matrix(2, 3, [1, 2, 3, 4, 5, 6])
  33. assert x.rows == 2
  34. assert x.cols == 3
  35. assert x[2] == 3
  36. assert x[1, 1] == 5
  37. assert list(x) == [1, 2, 3, 4, 5, 6]
  38. assert list(x[1, :]) == [4, 5, 6]
  39. assert list(x[:, 1]) == [2, 5]
  40. assert list(x[:, :]) == list(x)
  41. assert x[:, :] == x
  42. assert Matrix(x) == x
  43. assert Matrix([[1, 2, 3], [4, 5, 6]]) == x
  44. assert Matrix(([1, 2, 3], [4, 5, 6])) == x
  45. assert Matrix([(1, 2, 3), (4, 5, 6)]) == x
  46. assert Matrix(((1, 2, 3), (4, 5, 6))) == x
  47. assert not (Matrix([[1, 2], [3, 4], [5, 6]]) == x)
  48. def test_kind():
  49. assert Matrix([[1, 2], [3, 4]]).kind == MatrixKind(NumberKind)
  50. assert Matrix([[0, 0], [0, 0]]).kind == MatrixKind(NumberKind)
  51. assert Matrix(0, 0, []).kind == MatrixKind(NumberKind)
  52. assert Matrix([[x]]).kind == MatrixKind(NumberKind)
  53. assert Matrix([[1, Matrix([[1]])]]).kind == MatrixKind(UndefinedKind)
  54. assert SparseMatrix([[1]]).kind == MatrixKind(NumberKind)
  55. assert SparseMatrix([[1, Matrix([[1]])]]).kind == MatrixKind(UndefinedKind)
  56. def test_todok():
  57. a, b, c, d = symbols('a:d')
  58. m1 = MutableDenseMatrix([[a, b], [c, d]])
  59. m2 = ImmutableDenseMatrix([[a, b], [c, d]])
  60. m3 = MutableSparseMatrix([[a, b], [c, d]])
  61. m4 = ImmutableSparseMatrix([[a, b], [c, d]])
  62. assert m1.todok() == m2.todok() == m3.todok() == m4.todok() == \
  63. {(0, 0): a, (0, 1): b, (1, 0): c, (1, 1): d}
  64. def test_tolist():
  65. lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
  66. flat_lst = [S.One, S.Half, x*y, S.Zero, x, y, z, x**2, y, -S.One, z*x, 3]
  67. m = Matrix(3, 4, flat_lst)
  68. assert m.tolist() == lst
  69. def test_todod():
  70. m = Matrix([[S.One, 0], [0, S.Half], [x, 0]])
  71. dict = {0: {0: S.One}, 1: {1: S.Half}, 2: {0: x}}
  72. assert m.todod() == dict
  73. def test_row_col_del():
  74. e = ImmutableMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
  75. raises(IndexError, lambda: e.row_del(5))
  76. raises(IndexError, lambda: e.row_del(-5))
  77. raises(IndexError, lambda: e.col_del(5))
  78. raises(IndexError, lambda: e.col_del(-5))
  79. assert e.row_del(2) == e.row_del(-1) == Matrix([[1, 2, 3], [4, 5, 6]])
  80. assert e.col_del(2) == e.col_del(-1) == Matrix([[1, 2], [4, 5], [7, 8]])
  81. assert e.row_del(1) == e.row_del(-2) == Matrix([[1, 2, 3], [7, 8, 9]])
  82. assert e.col_del(1) == e.col_del(-2) == Matrix([[1, 3], [4, 6], [7, 9]])
  83. def test_get_diag_blocks1():
  84. a = Matrix([[1, 2], [2, 3]])
  85. b = Matrix([[3, x], [y, 3]])
  86. c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
  87. assert a.get_diag_blocks() == [a]
  88. assert b.get_diag_blocks() == [b]
  89. assert c.get_diag_blocks() == [c]
  90. def test_get_diag_blocks2():
  91. a = Matrix([[1, 2], [2, 3]])
  92. b = Matrix([[3, x], [y, 3]])
  93. c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
  94. A, B, C, D = diag(a, b, b), diag(a, b, c), diag(a, c, b), diag(c, c, b)
  95. A = Matrix(A.rows, A.cols, A)
  96. B = Matrix(B.rows, B.cols, B)
  97. C = Matrix(C.rows, C.cols, C)
  98. D = Matrix(D.rows, D.cols, D)
  99. assert A.get_diag_blocks() == [a, b, b]
  100. assert B.get_diag_blocks() == [a, b, c]
  101. assert C.get_diag_blocks() == [a, c, b]
  102. assert D.get_diag_blocks() == [c, c, b]
  103. def test_row_col():
  104. m = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
  105. assert m.row(0) == Matrix(1, 3, [1, 2, 3])
  106. assert m.col(0) == Matrix(3, 1, [1, 4, 7])
  107. def test_row_join():
  108. assert eye(3).row_join(Matrix([7, 7, 7])) == \
  109. Matrix([[1, 0, 0, 7],
  110. [0, 1, 0, 7],
  111. [0, 0, 1, 7]])
  112. def test_col_join():
  113. assert eye(3).col_join(Matrix([[7, 7, 7]])) == \
  114. Matrix([[1, 0, 0],
  115. [0, 1, 0],
  116. [0, 0, 1],
  117. [7, 7, 7]])
  118. def test_row_insert():
  119. r4 = Matrix([[4, 4, 4]])
  120. for i in range(-4, 5):
  121. l = [1, 0, 0]
  122. l.insert(i, 4)
  123. assert eye(3).row_insert(i, r4).col(0).flat() == l
  124. def test_col_insert():
  125. c4 = Matrix([4, 4, 4])
  126. for i in range(-4, 5):
  127. l = [0, 0, 0]
  128. l.insert(i, 4)
  129. assert zeros(3).col_insert(i, c4).row(0).flat() == l
  130. # issue 13643
  131. assert eye(6).col_insert(3, Matrix([[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]])) == \
  132. Matrix([[1, 0, 0, 2, 2, 0, 0, 0],
  133. [0, 1, 0, 2, 2, 0, 0, 0],
  134. [0, 0, 1, 2, 2, 0, 0, 0],
  135. [0, 0, 0, 2, 2, 1, 0, 0],
  136. [0, 0, 0, 2, 2, 0, 1, 0],
  137. [0, 0, 0, 2, 2, 0, 0, 1]])
  138. def test_extract():
  139. m = Matrix(4, 3, lambda i, j: i*3 + j)
  140. assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
  141. assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
  142. assert m.extract(range(4), range(3)) == m
  143. raises(IndexError, lambda: m.extract([4], [0]))
  144. raises(IndexError, lambda: m.extract([0], [3]))
  145. def test_hstack():
  146. m = Matrix(4, 3, lambda i, j: i*3 + j)
  147. m2 = Matrix(3, 4, lambda i, j: i*3 + j)
  148. assert m == m.hstack(m)
  149. assert m.hstack(m, m, m) == Matrix.hstack(m, m, m) == Matrix([
  150. [0, 1, 2, 0, 1, 2, 0, 1, 2],
  151. [3, 4, 5, 3, 4, 5, 3, 4, 5],
  152. [6, 7, 8, 6, 7, 8, 6, 7, 8],
  153. [9, 10, 11, 9, 10, 11, 9, 10, 11]])
  154. raises(ShapeError, lambda: m.hstack(m, m2))
  155. assert Matrix.hstack() == Matrix()
  156. # test regression #12938
  157. M1 = Matrix.zeros(0, 0)
  158. M2 = Matrix.zeros(0, 1)
  159. M3 = Matrix.zeros(0, 2)
  160. M4 = Matrix.zeros(0, 3)
  161. m = Matrix.hstack(M1, M2, M3, M4)
  162. assert m.rows == 0 and m.cols == 6
  163. def test_vstack():
  164. m = Matrix(4, 3, lambda i, j: i*3 + j)
  165. m2 = Matrix(3, 4, lambda i, j: i*3 + j)
  166. assert m == m.vstack(m)
  167. assert m.vstack(m, m, m) == Matrix.vstack(m, m, m) == Matrix([
  168. [0, 1, 2],
  169. [3, 4, 5],
  170. [6, 7, 8],
  171. [9, 10, 11],
  172. [0, 1, 2],
  173. [3, 4, 5],
  174. [6, 7, 8],
  175. [9, 10, 11],
  176. [0, 1, 2],
  177. [3, 4, 5],
  178. [6, 7, 8],
  179. [9, 10, 11]])
  180. raises(ShapeError, lambda: m.vstack(m, m2))
  181. assert Matrix.vstack() == Matrix()
  182. def test_has():
  183. A = Matrix(((x, y), (2, 3)))
  184. assert A.has(x)
  185. assert not A.has(z)
  186. assert A.has(Symbol)
  187. A = Matrix(((2, y), (2, 3)))
  188. assert not A.has(x)
  189. def test_is_anti_symmetric():
  190. x = symbols('x')
  191. assert Matrix(2, 1, [1, 2]).is_anti_symmetric() is False
  192. m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
  193. assert m.is_anti_symmetric() is True
  194. assert m.is_anti_symmetric(simplify=False) is None
  195. assert m.is_anti_symmetric(simplify=lambda x: x) is None
  196. m = Matrix(3, 3, [x.expand() for x in m])
  197. assert m.is_anti_symmetric(simplify=False) is True
  198. m = Matrix(3, 3, [x.expand() for x in [S.One] + list(m)[1:]])
  199. assert m.is_anti_symmetric() is False
  200. def test_is_hermitian():
  201. a = Matrix([[1, I], [-I, 1]])
  202. assert a.is_hermitian
  203. a = Matrix([[2*I, I], [-I, 1]])
  204. assert a.is_hermitian is False
  205. a = Matrix([[x, I], [-I, 1]])
  206. assert a.is_hermitian is None
  207. a = Matrix([[x, 1], [-I, 1]])
  208. assert a.is_hermitian is False
  209. def test_is_symbolic():
  210. a = Matrix([[x, x], [x, x]])
  211. assert a.is_symbolic() is True
  212. a = Matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
  213. assert a.is_symbolic() is False
  214. a = Matrix([[1, 2, 3, 4], [5, 6, x, 8]])
  215. assert a.is_symbolic() is True
  216. a = Matrix([[1, x, 3]])
  217. assert a.is_symbolic() is True
  218. a = Matrix([[1, 2, 3]])
  219. assert a.is_symbolic() is False
  220. a = Matrix([[1], [x], [3]])
  221. assert a.is_symbolic() is True
  222. a = Matrix([[1], [2], [3]])
  223. assert a.is_symbolic() is False
  224. def test_is_square():
  225. m = Matrix([[1], [1]])
  226. m2 = Matrix([[2, 2], [2, 2]])
  227. assert not m.is_square
  228. assert m2.is_square
  229. def test_is_symmetric():
  230. m = Matrix(2, 2, [0, 1, 1, 0])
  231. assert m.is_symmetric()
  232. m = Matrix(2, 2, [0, 1, 0, 1])
  233. assert not m.is_symmetric()
  234. def test_is_hessenberg():
  235. A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
  236. assert A.is_upper_hessenberg
  237. A = Matrix(3, 3, [3, 2, 0, 4, 4, 1, 1, 5, 2])
  238. assert A.is_lower_hessenberg
  239. A = Matrix(3, 3, [3, 2, -1, 4, 4, 1, 1, 5, 2])
  240. assert A.is_lower_hessenberg is False
  241. assert A.is_upper_hessenberg is False
  242. A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
  243. assert not A.is_upper_hessenberg
  244. def test_values():
  245. assert set(Matrix(2, 2, [0, 1, 2, 3]
  246. ).values()) == {1, 2, 3}
  247. x = Symbol('x', real=True)
  248. assert set(Matrix(2, 2, [x, 0, 0, 1]
  249. ).values()) == {x, 1}
  250. def test_conjugate():
  251. M = Matrix([[0, I, 5],
  252. [1, 2, 0]])
  253. assert M.T == Matrix([[0, 1],
  254. [I, 2],
  255. [5, 0]])
  256. assert M.C == Matrix([[0, -I, 5],
  257. [1, 2, 0]])
  258. assert M.C == M.conjugate()
  259. assert M.H == M.T.C
  260. assert M.H == Matrix([[ 0, 1],
  261. [-I, 2],
  262. [ 5, 0]])
  263. def test_doit():
  264. a = Matrix([[Add(x, x, evaluate=False)]])
  265. assert a[0] != 2*x
  266. assert a.doit() == Matrix([[2*x]])
  267. def test_evalf():
  268. a = Matrix(2, 1, [sqrt(5), 6])
  269. assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
  270. assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
  271. assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
  272. def test_replace():
  273. F, G = symbols('F, G', cls=Function)
  274. K = Matrix(2, 2, lambda i, j: G(i+j))
  275. M = Matrix(2, 2, lambda i, j: F(i+j))
  276. N = M.replace(F, G)
  277. assert N == K
  278. def test_replace_map():
  279. F, G = symbols('F, G', cls=Function)
  280. M = Matrix(2, 2, lambda i, j: F(i+j))
  281. N, d = M.replace(F, G, True)
  282. assert N == Matrix(2, 2, lambda i, j: G(i+j))
  283. assert d == {F(0): G(0), F(1): G(1), F(2): G(2)}
  284. def test_numpy_conversion():
  285. try:
  286. from numpy import array, array_equal
  287. except ImportError:
  288. skip('NumPy must be available to test creating matrices from ndarrays')
  289. A = Matrix([[1,2], [3,4]])
  290. np_array = array([[1,2], [3,4]])
  291. assert array_equal(array(A), np_array)
  292. assert array_equal(array(A, copy=True), np_array)
  293. if(int(version('numpy').split('.')[0]) >= 2): #run this test only if numpy is new enough that copy variable is passed properly.
  294. raises(TypeError, lambda: array(A, copy=False))
  295. def test_rot90():
  296. A = Matrix([[1, 2], [3, 4]])
  297. assert A == A.rot90(0) == A.rot90(4)
  298. assert A.rot90(2) == A.rot90(-2) == A.rot90(6) == Matrix(((4, 3), (2, 1)))
  299. assert A.rot90(3) == A.rot90(-1) == A.rot90(7) == Matrix(((2, 4), (1, 3)))
  300. assert A.rot90() == A.rot90(-7) == A.rot90(-3) == Matrix(((3, 1), (4, 2)))
  301. def test_subs():
  302. assert Matrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
  303. assert Matrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
  304. Matrix([[-1, 2], [-3, 4]])
  305. assert Matrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
  306. Matrix([[-1, 2], [-3, 4]])
  307. assert Matrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
  308. Matrix([[-1, 2], [-3, 4]])
  309. assert Matrix([[x*y]]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
  310. Matrix([[(x - 1)*(y - 1)]])
  311. def test_permute():
  312. a = Matrix(3, 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
  313. raises(IndexError, lambda: a.permute([[0, 5]]))
  314. raises(ValueError, lambda: a.permute(Symbol('x')))
  315. b = a.permute_rows([[0, 2], [0, 1]])
  316. assert a.permute([[0, 2], [0, 1]]) == b == Matrix([
  317. [5, 6, 7, 8],
  318. [9, 10, 11, 12],
  319. [1, 2, 3, 4]])
  320. b = a.permute_cols([[0, 2], [0, 1]])
  321. assert a.permute([[0, 2], [0, 1]], orientation='cols') == b ==\
  322. Matrix([
  323. [ 2, 3, 1, 4],
  324. [ 6, 7, 5, 8],
  325. [10, 11, 9, 12]])
  326. b = a.permute_cols([[0, 2], [0, 1]], direction='backward')
  327. assert a.permute([[0, 2], [0, 1]], orientation='cols', direction='backward') == b ==\
  328. Matrix([
  329. [ 3, 1, 2, 4],
  330. [ 7, 5, 6, 8],
  331. [11, 9, 10, 12]])
  332. assert a.permute([1, 2, 0, 3]) == Matrix([
  333. [5, 6, 7, 8],
  334. [9, 10, 11, 12],
  335. [1, 2, 3, 4]])
  336. from sympy.combinatorics import Permutation
  337. assert a.permute(Permutation([1, 2, 0, 3])) == Matrix([
  338. [5, 6, 7, 8],
  339. [9, 10, 11, 12],
  340. [1, 2, 3, 4]])
  341. def test_upper_triangular():
  342. A = Matrix([
  343. [1, 1, 1, 1],
  344. [1, 1, 1, 1],
  345. [1, 1, 1, 1],
  346. [1, 1, 1, 1]
  347. ])
  348. R = A.upper_triangular(2)
  349. assert R == Matrix([
  350. [0, 0, 1, 1],
  351. [0, 0, 0, 1],
  352. [0, 0, 0, 0],
  353. [0, 0, 0, 0]
  354. ])
  355. R = A.upper_triangular(-2)
  356. assert R == Matrix([
  357. [1, 1, 1, 1],
  358. [1, 1, 1, 1],
  359. [1, 1, 1, 1],
  360. [0, 1, 1, 1]
  361. ])
  362. R = A.upper_triangular()
  363. assert R == Matrix([
  364. [1, 1, 1, 1],
  365. [0, 1, 1, 1],
  366. [0, 0, 1, 1],
  367. [0, 0, 0, 1]
  368. ])
  369. def test_lower_triangular():
  370. A = Matrix([
  371. [1, 1, 1, 1],
  372. [1, 1, 1, 1],
  373. [1, 1, 1, 1],
  374. [1, 1, 1, 1]
  375. ])
  376. L = A.lower_triangular()
  377. assert L == Matrix([
  378. [1, 0, 0, 0],
  379. [1, 1, 0, 0],
  380. [1, 1, 1, 0],
  381. [1, 1, 1, 1]])
  382. L = A.lower_triangular(2)
  383. assert L == Matrix([
  384. [1, 1, 1, 0],
  385. [1, 1, 1, 1],
  386. [1, 1, 1, 1],
  387. [1, 1, 1, 1]
  388. ])
  389. L = A.lower_triangular(-2)
  390. assert L == Matrix([
  391. [0, 0, 0, 0],
  392. [0, 0, 0, 0],
  393. [1, 0, 0, 0],
  394. [1, 1, 0, 0]
  395. ])
  396. def test_add():
  397. m = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
  398. assert m + m == Matrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
  399. n = Matrix(1, 2, [1, 2])
  400. raises(ShapeError, lambda: m + n)
  401. def test_matmul():
  402. a = Matrix([[1, 2], [3, 4]])
  403. assert a.__matmul__(2) == NotImplemented
  404. assert a.__rmatmul__(2) == NotImplemented
  405. #This is done this way because @ is only supported in Python 3.5+
  406. #To check 2@a case
  407. try:
  408. eval('2 @ a')
  409. except SyntaxError:
  410. pass
  411. except TypeError: #TypeError is raised in case of NotImplemented is returned
  412. pass
  413. #Check a@2 case
  414. try:
  415. eval('a @ 2')
  416. except SyntaxError:
  417. pass
  418. except TypeError: #TypeError is raised in case of NotImplemented is returned
  419. pass
  420. def test_non_matmul():
  421. """
  422. Test that if explicitly specified as non-matrix, mul reverts
  423. to scalar multiplication.
  424. """
  425. class foo(Expr):
  426. is_Matrix=False
  427. is_MatrixLike=False
  428. shape = (1, 1)
  429. A = Matrix([[1, 2], [3, 4]])
  430. b = foo()
  431. assert b*A == Matrix([[b, 2*b], [3*b, 4*b]])
  432. assert A*b == Matrix([[b, 2*b], [3*b, 4*b]])
  433. def test_neg():
  434. n = Matrix(1, 2, [1, 2])
  435. assert -n == Matrix(1, 2, [-1, -2])
  436. def test_sub():
  437. n = Matrix(1, 2, [1, 2])
  438. assert n - n == Matrix(1, 2, [0, 0])
  439. def test_div():
  440. n = Matrix(1, 2, [1, 2])
  441. assert n/2 == Matrix(1, 2, [S.Half, S(2)/2])
  442. def test_eye():
  443. assert list(Matrix.eye(2, 2)) == [1, 0, 0, 1]
  444. assert list(Matrix.eye(2)) == [1, 0, 0, 1]
  445. assert type(Matrix.eye(2)) == Matrix
  446. assert type(Matrix.eye(2, cls=Matrix)) == Matrix
  447. def test_ones():
  448. assert list(Matrix.ones(2, 2)) == [1, 1, 1, 1]
  449. assert list(Matrix.ones(2)) == [1, 1, 1, 1]
  450. assert Matrix.ones(2, 3) == Matrix([[1, 1, 1], [1, 1, 1]])
  451. assert type(Matrix.ones(2)) == Matrix
  452. assert type(Matrix.ones(2, cls=Matrix)) == Matrix
  453. def test_zeros():
  454. assert list(Matrix.zeros(2, 2)) == [0, 0, 0, 0]
  455. assert list(Matrix.zeros(2)) == [0, 0, 0, 0]
  456. assert Matrix.zeros(2, 3) == Matrix([[0, 0, 0], [0, 0, 0]])
  457. assert type(Matrix.zeros(2)) == Matrix
  458. assert type(Matrix.zeros(2, cls=Matrix)) == Matrix
  459. def test_diag_make():
  460. diag = Matrix.diag
  461. a = Matrix([[1, 2], [2, 3]])
  462. b = Matrix([[3, x], [y, 3]])
  463. c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
  464. assert diag(a, b, b) == Matrix([
  465. [1, 2, 0, 0, 0, 0],
  466. [2, 3, 0, 0, 0, 0],
  467. [0, 0, 3, x, 0, 0],
  468. [0, 0, y, 3, 0, 0],
  469. [0, 0, 0, 0, 3, x],
  470. [0, 0, 0, 0, y, 3],
  471. ])
  472. assert diag(a, b, c) == Matrix([
  473. [1, 2, 0, 0, 0, 0, 0],
  474. [2, 3, 0, 0, 0, 0, 0],
  475. [0, 0, 3, x, 0, 0, 0],
  476. [0, 0, y, 3, 0, 0, 0],
  477. [0, 0, 0, 0, 3, x, 3],
  478. [0, 0, 0, 0, y, 3, z],
  479. [0, 0, 0, 0, x, y, z],
  480. ])
  481. assert diag(a, c, b) == Matrix([
  482. [1, 2, 0, 0, 0, 0, 0],
  483. [2, 3, 0, 0, 0, 0, 0],
  484. [0, 0, 3, x, 3, 0, 0],
  485. [0, 0, y, 3, z, 0, 0],
  486. [0, 0, x, y, z, 0, 0],
  487. [0, 0, 0, 0, 0, 3, x],
  488. [0, 0, 0, 0, 0, y, 3],
  489. ])
  490. a = Matrix([x, y, z])
  491. b = Matrix([[1, 2], [3, 4]])
  492. c = Matrix([[5, 6]])
  493. # this "wandering diagonal" is what makes this
  494. # a block diagonal where each block is independent
  495. # of the others
  496. assert diag(a, 7, b, c) == Matrix([
  497. [x, 0, 0, 0, 0, 0],
  498. [y, 0, 0, 0, 0, 0],
  499. [z, 0, 0, 0, 0, 0],
  500. [0, 7, 0, 0, 0, 0],
  501. [0, 0, 1, 2, 0, 0],
  502. [0, 0, 3, 4, 0, 0],
  503. [0, 0, 0, 0, 5, 6]])
  504. raises(ValueError, lambda: diag(a, 7, b, c, rows=5))
  505. assert diag(1) == Matrix([[1]])
  506. assert diag(1, rows=2) == Matrix([[1, 0], [0, 0]])
  507. assert diag(1, cols=2) == Matrix([[1, 0], [0, 0]])
  508. assert diag(1, rows=3, cols=2) == Matrix([[1, 0], [0, 0], [0, 0]])
  509. assert diag(*[2, 3]) == Matrix([
  510. [2, 0],
  511. [0, 3]])
  512. assert diag(Matrix([2, 3])) == Matrix([
  513. [2],
  514. [3]])
  515. assert diag([1, [2, 3], 4], unpack=False) == \
  516. diag([[1], [2, 3], [4]], unpack=False) == Matrix([
  517. [1, 0],
  518. [2, 3],
  519. [4, 0]])
  520. assert type(diag(1)) == Matrix
  521. assert type(diag(1, cls=Matrix)) == Matrix
  522. assert Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
  523. assert Matrix.diag([1, 2, 3], unpack=False).shape == (3, 1)
  524. assert Matrix.diag([[1, 2, 3]]).shape == (3, 1)
  525. assert Matrix.diag([[1, 2, 3]], unpack=False).shape == (1, 3)
  526. assert Matrix.diag([[[1, 2, 3]]]).shape == (1, 3)
  527. # kerning can be used to move the starting point
  528. assert Matrix.diag(ones(0, 2), 1, 2) == Matrix([
  529. [0, 0, 1, 0],
  530. [0, 0, 0, 2]])
  531. assert Matrix.diag(ones(2, 0), 1, 2) == Matrix([
  532. [0, 0],
  533. [0, 0],
  534. [1, 0],
  535. [0, 2]])
  536. def test_diagonal():
  537. m = Matrix(3, 3, range(9))
  538. d = m.diagonal()
  539. assert d == m.diagonal(0)
  540. assert tuple(d) == (0, 4, 8)
  541. assert tuple(m.diagonal(1)) == (1, 5)
  542. assert tuple(m.diagonal(-1)) == (3, 7)
  543. assert tuple(m.diagonal(2)) == (2,)
  544. assert type(m.diagonal()) == type(m)
  545. s = SparseMatrix(3, 3, {(1, 1): 1})
  546. assert type(s.diagonal()) == type(s)
  547. assert type(m) != type(s)
  548. raises(ValueError, lambda: m.diagonal(3))
  549. raises(ValueError, lambda: m.diagonal(-3))
  550. raises(ValueError, lambda: m.diagonal(pi))
  551. M = ones(2, 3)
  552. assert banded({i: list(M.diagonal(i))
  553. for i in range(1-M.rows, M.cols)}) == M
  554. def test_jordan_block():
  555. assert Matrix.jordan_block(3, 2) == Matrix.jordan_block(3, eigenvalue=2) \
  556. == Matrix.jordan_block(size=3, eigenvalue=2) \
  557. == Matrix.jordan_block(3, 2, band='upper') \
  558. == Matrix.jordan_block(
  559. size=3, eigenval=2, eigenvalue=2) \
  560. == Matrix([
  561. [2, 1, 0],
  562. [0, 2, 1],
  563. [0, 0, 2]])
  564. assert Matrix.jordan_block(3, 2, band='lower') == Matrix([
  565. [2, 0, 0],
  566. [1, 2, 0],
  567. [0, 1, 2]])
  568. # missing eigenvalue
  569. raises(ValueError, lambda: Matrix.jordan_block(2))
  570. # non-integral size
  571. raises(ValueError, lambda: Matrix.jordan_block(3.5, 2))
  572. # size not specified
  573. raises(ValueError, lambda: Matrix.jordan_block(eigenvalue=2))
  574. # inconsistent eigenvalue
  575. raises(ValueError,
  576. lambda: Matrix.jordan_block(
  577. eigenvalue=2, eigenval=4))
  578. # Using alias keyword
  579. assert Matrix.jordan_block(size=3, eigenvalue=2) == \
  580. Matrix.jordan_block(size=3, eigenval=2)
  581. def test_orthogonalize():
  582. m = Matrix([[1, 2], [3, 4]])
  583. assert m.orthogonalize(Matrix([[2], [1]])) == [Matrix([[2], [1]])]
  584. assert m.orthogonalize(Matrix([[2], [1]]), normalize=True) == \
  585. [Matrix([[2*sqrt(5)/5], [sqrt(5)/5]])]
  586. assert m.orthogonalize(Matrix([[1], [2]]), Matrix([[-1], [4]])) == \
  587. [Matrix([[1], [2]]), Matrix([[Rational(-12, 5)], [Rational(6, 5)]])]
  588. assert m.orthogonalize(Matrix([[0], [0]]), Matrix([[-1], [4]])) == \
  589. [Matrix([[-1], [4]])]
  590. assert m.orthogonalize(Matrix([[0], [0]])) == []
  591. n = Matrix([[9, 1, 9], [3, 6, 10], [8, 5, 2]])
  592. vecs = [Matrix([[-5], [1]]), Matrix([[-5], [2]]), Matrix([[-5], [-2]])]
  593. assert n.orthogonalize(*vecs) == \
  594. [Matrix([[-5], [1]]), Matrix([[Rational(5, 26)], [Rational(25, 26)]])]
  595. vecs = [Matrix([0, 0, 0]), Matrix([1, 2, 3]), Matrix([1, 4, 5])]
  596. raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
  597. vecs = [Matrix([1, 2, 3]), Matrix([4, 5, 6]), Matrix([7, 8, 9])]
  598. raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
  599. def test_wilkinson():
  600. wminus, wplus = Matrix.wilkinson(1)
  601. assert wminus == Matrix([
  602. [-1, 1, 0],
  603. [1, 0, 1],
  604. [0, 1, 1]])
  605. assert wplus == Matrix([
  606. [1, 1, 0],
  607. [1, 0, 1],
  608. [0, 1, 1]])
  609. wminus, wplus = Matrix.wilkinson(3)
  610. assert wminus == Matrix([
  611. [-3, 1, 0, 0, 0, 0, 0],
  612. [1, -2, 1, 0, 0, 0, 0],
  613. [0, 1, -1, 1, 0, 0, 0],
  614. [0, 0, 1, 0, 1, 0, 0],
  615. [0, 0, 0, 1, 1, 1, 0],
  616. [0, 0, 0, 0, 1, 2, 1],
  617. [0, 0, 0, 0, 0, 1, 3]])
  618. assert wplus == Matrix([
  619. [3, 1, 0, 0, 0, 0, 0],
  620. [1, 2, 1, 0, 0, 0, 0],
  621. [0, 1, 1, 1, 0, 0, 0],
  622. [0, 0, 1, 0, 1, 0, 0],
  623. [0, 0, 0, 1, 1, 1, 0],
  624. [0, 0, 0, 0, 1, 2, 1],
  625. [0, 0, 0, 0, 0, 1, 3]])
  626. def test_limit():
  627. x, y = symbols('x y')
  628. m = Matrix(2, 1, [1/x, y])
  629. assert m.limit(x, 5) == Matrix(2, 1, [Rational(1, 5), y])
  630. A = Matrix(((1, 4, sin(x)/x), (y, 2, 4), (10, 5, x**2 + 1)))
  631. assert A.limit(x, 0) == Matrix(((1, 4, 1), (y, 2, 4), (10, 5, 1)))
  632. def test_issue_13774():
  633. M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  634. v = [1, 1, 1]
  635. raises(TypeError, lambda: M*v)
  636. raises(TypeError, lambda: v*M)
  637. def test_companion():
  638. x = Symbol('x')
  639. y = Symbol('y')
  640. raises(ValueError, lambda: Matrix.companion(1))
  641. raises(ValueError, lambda: Matrix.companion(Poly([1], x)))
  642. raises(ValueError, lambda: Matrix.companion(Poly([2, 1], x)))
  643. raises(ValueError, lambda: Matrix.companion(Poly(x*y, [x, y])))
  644. c0, c1, c2 = symbols('c0:3')
  645. assert Matrix.companion(Poly([1, c0], x)) == Matrix([-c0])
  646. assert Matrix.companion(Poly([1, c1, c0], x)) == \
  647. Matrix([[0, -c0], [1, -c1]])
  648. assert Matrix.companion(Poly([1, c2, c1, c0], x)) == \
  649. Matrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]])
  650. def test_issue_10589():
  651. x, y, z = symbols("x, y z")
  652. M1 = Matrix([x, y, z])
  653. M1 = M1.subs(zip([x, y, z], [1, 2, 3]))
  654. assert M1 == Matrix([[1], [2], [3]])
  655. M2 = Matrix([[x, x, x, x, x], [x, x, x, x, x], [x, x, x, x, x]])
  656. M2 = M2.subs(zip([x], [1]))
  657. assert M2 == Matrix([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])
  658. def test_rmul_pr19860():
  659. class Foo(ImmutableDenseMatrix):
  660. _op_priority = MutableDenseMatrix._op_priority + 0.01
  661. a = Matrix(2, 2, [1, 2, 3, 4])
  662. b = Foo(2, 2, [1, 2, 3, 4])
  663. # This would throw a RecursionError: maximum recursion depth
  664. # since b always has higher priority even after a.as_mutable()
  665. c = a*b
  666. assert isinstance(c, Foo)
  667. assert c == Matrix([[7, 10], [15, 22]])
  668. def test_issue_18956():
  669. A = Array([[1, 2], [3, 4]])
  670. B = Matrix([[1,2],[3,4]])
  671. raises(TypeError, lambda: B + A)
  672. raises(TypeError, lambda: A + B)
  673. def test__eq__():
  674. class My(object):
  675. def __iter__(self):
  676. yield 1
  677. yield 2
  678. return
  679. def __getitem__(self, i):
  680. return list(self)[i]
  681. a = Matrix(2, 1, [1, 2])
  682. assert a != My()
  683. class My_sympy(My):
  684. def _sympy_(self):
  685. return Matrix(self)
  686. assert a == My_sympy()
  687. def test_args():
  688. for n, cls in enumerate(all_classes):
  689. m = cls.zeros(3, 2)
  690. # all should give back the same type of arguments, e.g. ints for shape
  691. assert m.shape == (3, 2) and all(type(i) is int for i in m.shape)
  692. assert m.rows == 3 and type(m.rows) is int
  693. assert m.cols == 2 and type(m.cols) is int
  694. if not n % 2:
  695. assert type(m.flat()) in (list, tuple, Tuple)
  696. else:
  697. assert type(m.todok()) is dict
  698. def test_deprecated_mat_smat():
  699. for cls in Matrix, ImmutableMatrix:
  700. m = cls.zeros(3, 2)
  701. with warns_deprecated_sympy():
  702. mat = m._mat
  703. assert mat == m.flat()
  704. for cls in SparseMatrix, ImmutableSparseMatrix:
  705. m = cls.zeros(3, 2)
  706. with warns_deprecated_sympy():
  707. smat = m._smat
  708. assert smat == m.todok()
  709. def test_division():
  710. v = Matrix(1, 2, [x, y])
  711. assert v/z == Matrix(1, 2, [x/z, y/z])
  712. def test_sum():
  713. m = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
  714. assert m + m == Matrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
  715. n = Matrix(1, 2, [1, 2])
  716. raises(ShapeError, lambda: m + n)
  717. def test_abs():
  718. m = Matrix([[1, -2], [x, y]])
  719. assert abs(m) == Matrix([[1, 2], [Abs(x), Abs(y)]])
  720. m = Matrix(1, 2, [-3, x])
  721. n = Matrix(1, 2, [3, Abs(x)])
  722. assert abs(m) == n
  723. def test_addition():
  724. a = Matrix((
  725. (1, 2),
  726. (3, 1),
  727. ))
  728. b = Matrix((
  729. (1, 2),
  730. (3, 0),
  731. ))
  732. assert a + b == a.add(b) == Matrix([[2, 4], [6, 1]])
  733. def test_fancy_index_matrix():
  734. for M in (Matrix, SparseMatrix):
  735. a = M(3, 3, range(9))
  736. assert a == a[:, :]
  737. assert a[1, :] == Matrix(1, 3, [3, 4, 5])
  738. assert a[:, 1] == Matrix([1, 4, 7])
  739. assert a[[0, 1], :] == Matrix([[0, 1, 2], [3, 4, 5]])
  740. assert a[[0, 1], 2] == a[[0, 1], [2]]
  741. assert a[2, [0, 1]] == a[[2], [0, 1]]
  742. assert a[:, [0, 1]] == Matrix([[0, 1], [3, 4], [6, 7]])
  743. assert a[0, 0] == 0
  744. assert a[0:2, :] == Matrix([[0, 1, 2], [3, 4, 5]])
  745. assert a[:, 0:2] == Matrix([[0, 1], [3, 4], [6, 7]])
  746. assert a[::2, 1] == a[[0, 2], 1]
  747. assert a[1, ::2] == a[1, [0, 2]]
  748. a = M(3, 3, range(9))
  749. assert a[[0, 2, 1, 2, 1], :] == Matrix([
  750. [0, 1, 2],
  751. [6, 7, 8],
  752. [3, 4, 5],
  753. [6, 7, 8],
  754. [3, 4, 5]])
  755. assert a[:, [0,2,1,2,1]] == Matrix([
  756. [0, 2, 1, 2, 1],
  757. [3, 5, 4, 5, 4],
  758. [6, 8, 7, 8, 7]])
  759. a = SparseMatrix.zeros(3)
  760. a[1, 2] = 2
  761. a[0, 1] = 3
  762. a[2, 0] = 4
  763. assert a.extract([1, 1], [2]) == Matrix([
  764. [2],
  765. [2]])
  766. assert a.extract([1, 0], [2, 2, 2]) == Matrix([
  767. [2, 2, 2],
  768. [0, 0, 0]])
  769. assert a.extract([1, 0, 1, 2], [2, 0, 1, 0]) == Matrix([
  770. [2, 0, 0, 0],
  771. [0, 0, 3, 0],
  772. [2, 0, 0, 0],
  773. [0, 4, 0, 4]])
  774. def test_multiplication():
  775. a = Matrix((
  776. (1, 2),
  777. (3, 1),
  778. (0, 6),
  779. ))
  780. b = Matrix((
  781. (1, 2),
  782. (3, 0),
  783. ))
  784. raises(ShapeError, lambda: b*a)
  785. raises(TypeError, lambda: a*{})
  786. c = a*b
  787. assert c[0, 0] == 7
  788. assert c[0, 1] == 2
  789. assert c[1, 0] == 6
  790. assert c[1, 1] == 6
  791. assert c[2, 0] == 18
  792. assert c[2, 1] == 0
  793. c = a @ b
  794. assert c[0, 0] == 7
  795. assert c[0, 1] == 2
  796. assert c[1, 0] == 6
  797. assert c[1, 1] == 6
  798. assert c[2, 0] == 18
  799. assert c[2, 1] == 0
  800. h = matrix_multiply_elementwise(a, c)
  801. assert h == a.multiply_elementwise(c)
  802. assert h[0, 0] == 7
  803. assert h[0, 1] == 4
  804. assert h[1, 0] == 18
  805. assert h[1, 1] == 6
  806. assert h[2, 0] == 0
  807. assert h[2, 1] == 0
  808. raises(ShapeError, lambda: matrix_multiply_elementwise(a, b))
  809. c = b * Symbol("x")
  810. assert isinstance(c, Matrix)
  811. assert c[0, 0] == x
  812. assert c[0, 1] == 2*x
  813. assert c[1, 0] == 3*x
  814. assert c[1, 1] == 0
  815. c2 = x * b
  816. assert c == c2
  817. c = 5 * b
  818. assert isinstance(c, Matrix)
  819. assert c[0, 0] == 5
  820. assert c[0, 1] == 2*5
  821. assert c[1, 0] == 3*5
  822. assert c[1, 1] == 0
  823. M = Matrix([[oo, 0], [0, oo]])
  824. assert M ** 2 == M
  825. M = Matrix([[oo, oo], [0, 0]])
  826. assert M ** 2 == Matrix([[nan, nan], [nan, nan]])
  827. # https://github.com/sympy/sympy/issues/22353
  828. A = Matrix(ones(3, 1))
  829. _h = -Rational(1, 2)
  830. B = Matrix([_h, _h, _h])
  831. assert A.multiply_elementwise(B) == Matrix([
  832. [_h],
  833. [_h],
  834. [_h]])
  835. def test_power():
  836. raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
  837. A = Matrix([[2, 3], [4, 5]])
  838. assert A**5 == Matrix([[6140, 8097], [10796, 14237]])
  839. A = Matrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
  840. assert A**3 == Matrix([[290, 262, 251], [448, 440, 368], [702, 954, 433]])
  841. assert A**0 == eye(3)
  842. assert A**1 == A
  843. assert (Matrix([[2]]) ** 100)[0, 0] == 2**100
  844. assert Matrix([[1, 2], [3, 4]])**Integer(2) == Matrix([[7, 10], [15, 22]])
  845. A = Matrix([[1,2],[4,5]])
  846. assert A.pow(20, method='cayley') == A.pow(20, method='multiply')
  847. assert A**Integer(2) == Matrix([[9, 12], [24, 33]])
  848. assert eye(2)**10000000 == eye(2)
  849. A = Matrix([[33, 24], [48, 57]])
  850. assert (A**S.Half)[:] == [5, 2, 4, 7]
  851. A = Matrix([[0, 4], [-1, 5]])
  852. assert (A**S.Half)**2 == A
  853. assert Matrix([[1, 0], [1, 1]])**S.Half == Matrix([[1, 0], [S.Half, 1]])
  854. assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1, 0], [0.5, 1]])
  855. from sympy.abc import n
  856. assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]])
  857. assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]])
  858. assert Matrix([
  859. [a**n, a**(n - 1)*n, (a**n*n**2 - a**n*n)/(2*a**2)],
  860. [ 0, a**n, a**(n - 1)*n],
  861. [ 0, 0, a**n]])
  862. assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([
  863. [a**n, a**(n-1)*n, 0],
  864. [0, a**n, 0],
  865. [0, 0, b**n]])
  866. A = Matrix([[1, 0], [1, 7]])
  867. assert A._matrix_pow_by_jordan_blocks(S(3)) == A._eval_pow_by_recursion(3)
  868. A = Matrix([[2]])
  869. assert A**10 == Matrix([[2**10]]) == A._matrix_pow_by_jordan_blocks(S(10)) == \
  870. A._eval_pow_by_recursion(10)
  871. # testing a matrix that cannot be jordan blocked issue 11766
  872. m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
  873. raises(MatrixError, lambda: m._matrix_pow_by_jordan_blocks(S(10)))
  874. # test issue 11964
  875. raises(MatrixError, lambda: Matrix([[1, 1], [3, 3]])._matrix_pow_by_jordan_blocks(S(-10)))
  876. A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) # Nilpotent jordan block size 3
  877. assert A**10.0 == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
  878. raises(ValueError, lambda: A**2.1)
  879. raises(ValueError, lambda: A**Rational(3, 2))
  880. A = Matrix([[8, 1], [3, 2]])
  881. assert A**10.0 == Matrix([[1760744107, 272388050], [817164150, 126415807]])
  882. A = Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 1
  883. assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
  884. A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 2
  885. assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
  886. n = Symbol('n', integer=True)
  887. assert isinstance(A**n, MatPow)
  888. n = Symbol('n', integer=True, negative=True)
  889. raises(ValueError, lambda: A**n)
  890. n = Symbol('n', integer=True, nonnegative=True)
  891. assert A**n == Matrix([
  892. [KroneckerDelta(0, n), KroneckerDelta(1, n), -KroneckerDelta(0, n) - KroneckerDelta(1, n) + 1],
  893. [ 0, KroneckerDelta(0, n), 1 - KroneckerDelta(0, n)],
  894. [ 0, 0, 1]])
  895. assert A**(n + 2) == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
  896. raises(ValueError, lambda: A**Rational(3, 2))
  897. A = Matrix([[0, 0, 1], [3, 0, 1], [4, 3, 1]])
  898. assert A**5.0 == Matrix([[168, 72, 89], [291, 144, 161], [572, 267, 329]])
  899. assert A**5.0 == A**5
  900. A = Matrix([[0, 1, 0],[-1, 0, 0],[0, 0, 0]])
  901. n = Symbol("n")
  902. An = A**n
  903. assert An.subs(n, 2).doit() == A**2
  904. raises(ValueError, lambda: An.subs(n, -2).doit())
  905. assert An * An == A**(2*n)
  906. # concretizing behavior for non-integer and complex powers
  907. A = Matrix([[0,0,0],[0,0,0],[0,0,0]])
  908. n = Symbol('n', integer=True, positive=True)
  909. assert A**n == A
  910. n = Symbol('n', integer=True, nonnegative=True)
  911. assert A**n == diag(0**n, 0**n, 0**n)
  912. assert (A**n).subs(n, 0) == eye(3)
  913. assert (A**n).subs(n, 1) == zeros(3)
  914. A = Matrix ([[2,0,0],[0,2,0],[0,0,2]])
  915. assert A**2.1 == diag (2**2.1, 2**2.1, 2**2.1)
  916. assert A**I == diag (2**I, 2**I, 2**I)
  917. A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]])
  918. raises(ValueError, lambda: A**2.1)
  919. raises(ValueError, lambda: A**I)
  920. A = Matrix([[S.Half, S.Half], [S.Half, S.Half]])
  921. assert A**S.Half == A
  922. A = Matrix([[1, 1],[3, 3]])
  923. assert A**S.Half == Matrix ([[S.Half, S.Half], [3*S.Half, 3*S.Half]])
  924. def test_issue_17247_expression_blowup_1():
  925. M = Matrix([[1+x, 1-x], [1-x, 1+x]])
  926. with dotprodsimp(True):
  927. assert M.exp().expand() == Matrix([
  928. [ (exp(2*x) + exp(2))/2, (-exp(2*x) + exp(2))/2],
  929. [(-exp(2*x) + exp(2))/2, (exp(2*x) + exp(2))/2]])
  930. def test_issue_17247_expression_blowup_2():
  931. M = Matrix([[1+x, 1-x], [1-x, 1+x]])
  932. with dotprodsimp(True):
  933. P, J = M.jordan_form ()
  934. assert P*J*P.inv()
  935. def test_issue_17247_expression_blowup_3():
  936. M = Matrix([[1+x, 1-x], [1-x, 1+x]])
  937. with dotprodsimp(True):
  938. assert M**100 == Matrix([
  939. [633825300114114700748351602688*x**100 + 633825300114114700748351602688, 633825300114114700748351602688 - 633825300114114700748351602688*x**100],
  940. [633825300114114700748351602688 - 633825300114114700748351602688*x**100, 633825300114114700748351602688*x**100 + 633825300114114700748351602688]])
  941. def test_issue_17247_expression_blowup_4():
  942. # This matrix takes extremely long on current master even with intermediate simplification so an abbreviated version is used. It is left here for test in case of future optimizations.
  943. # M = Matrix(S('''[
  944. # [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256, 15/128 - 3*I/32, 19/256 + 551*I/1024],
  945. # [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096, 129/256 - 549*I/512, 42533/16384 + 29103*I/8192],
  946. # [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256],
  947. # [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096],
  948. # [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
  949. # [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
  950. # [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
  951. # [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
  952. # [ -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
  953. # [ 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
  954. # [ -4, 9 - 5*I, -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
  955. # [ -2*I, 119/8 + 29*I/4, 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
  956. # assert M**10 == Matrix([
  957. # [ 7*(-221393644768594642173548179825793834595 - 1861633166167425978847110897013541127952*I)/9671406556917033397649408, 15*(31670992489131684885307005100073928751695 + 10329090958303458811115024718207404523808*I)/77371252455336267181195264, 7*(-3710978679372178839237291049477017392703 + 1377706064483132637295566581525806894169*I)/19342813113834066795298816, (9727707023582419994616144751727760051598 - 59261571067013123836477348473611225724433*I)/9671406556917033397649408, (31896723509506857062605551443641668183707 + 54643444538699269118869436271152084599580*I)/38685626227668133590597632, (-2024044860947539028275487595741003997397402 + 130959428791783397562960461903698670485863*I)/309485009821345068724781056, 3*(26190251453797590396533756519358368860907 - 27221191754180839338002754608545400941638*I)/77371252455336267181195264, (1154643595139959842768960128434994698330461 + 3385496216250226964322872072260446072295634*I)/618970019642690137449562112, 3*(-31849347263064464698310044805285774295286 - 11877437776464148281991240541742691164309*I)/77371252455336267181195264, (4661330392283532534549306589669150228040221 - 4171259766019818631067810706563064103956871*I)/1237940039285380274899124224, (9598353794289061833850770474812760144506 + 358027153990999990968244906482319780943983*I)/309485009821345068724781056, (-9755135335127734571547571921702373498554177 - 4837981372692695195747379349593041939686540*I)/2475880078570760549798248448],
  958. # [(-379516731607474268954110071392894274962069 - 422272153179747548473724096872271700878296*I)/77371252455336267181195264, (41324748029613152354787280677832014263339501 - 12715121258662668420833935373453570749288074*I)/1237940039285380274899124224, (-339216903907423793947110742819264306542397 + 494174755147303922029979279454787373566517*I)/77371252455336267181195264, (-18121350839962855576667529908850640619878381 - 37413012454129786092962531597292531089199003*I)/1237940039285380274899124224, (2489661087330511608618880408199633556675926 + 1137821536550153872137379935240732287260863*I)/309485009821345068724781056, (-136644109701594123227587016790354220062972119 + 110130123468183660555391413889600443583585272*I)/4951760157141521099596496896, (1488043981274920070468141664150073426459593 - 9691968079933445130866371609614474474327650*I)/1237940039285380274899124224, 27*(4636797403026872518131756991410164760195942 + 3369103221138229204457272860484005850416533*I)/4951760157141521099596496896, (-8534279107365915284081669381642269800472363 + 2241118846262661434336333368511372725482742*I)/1237940039285380274899124224, (60923350128174260992536531692058086830950875 - 263673488093551053385865699805250505661590126*I)/9903520314283042199192993792, (18520943561240714459282253753348921824172569 + 24846649186468656345966986622110971925703604*I)/4951760157141521099596496896, (-232781130692604829085973604213529649638644431 + 35981505277760667933017117949103953338570617*I)/9903520314283042199192993792],
  959. # [ (8742968295129404279528270438201520488950 + 3061473358639249112126847237482570858327*I)/4835703278458516698824704, (-245657313712011778432792959787098074935273 + 253113767861878869678042729088355086740856*I)/38685626227668133590597632, (1947031161734702327107371192008011621193 - 19462330079296259148177542369999791122762*I)/9671406556917033397649408, (552856485625209001527688949522750288619217 + 392928441196156725372494335248099016686580*I)/77371252455336267181195264, (-44542866621905323121630214897126343414629 + 3265340021421335059323962377647649632959*I)/19342813113834066795298816, (136272594005759723105646069956434264218730 - 330975364731707309489523680957584684763587*I)/38685626227668133590597632, (27392593965554149283318732469825168894401 + 75157071243800133880129376047131061115278*I)/38685626227668133590597632, 7*(-357821652913266734749960136017214096276154 - 45509144466378076475315751988405961498243*I)/309485009821345068724781056, (104485001373574280824835174390219397141149 - 99041000529599568255829489765415726168162*I)/77371252455336267181195264, (1198066993119982409323525798509037696321291 + 4249784165667887866939369628840569844519936*I)/618970019642690137449562112, (-114985392587849953209115599084503853611014 - 52510376847189529234864487459476242883449*I)/77371252455336267181195264, (6094620517051332877965959223269600650951573 - 4683469779240530439185019982269137976201163*I)/1237940039285380274899124224],
  960. # [ (611292255597977285752123848828590587708323 - 216821743518546668382662964473055912169502*I)/77371252455336267181195264, (-1144023204575811464652692396337616594307487 + 12295317806312398617498029126807758490062855*I)/309485009821345068724781056, (-374093027769390002505693378578475235158281 - 573533923565898290299607461660384634333639*I)/77371252455336267181195264, (47405570632186659000138546955372796986832987 - 2837476058950808941605000274055970055096534*I)/1237940039285380274899124224, (-571573207393621076306216726219753090535121 + 533381457185823100878764749236639320783831*I)/77371252455336267181195264, (-7096548151856165056213543560958582513797519 - 24035731898756040059329175131592138642195366*I)/618970019642690137449562112, (2396762128833271142000266170154694033849225 + 1448501087375679588770230529017516492953051*I)/309485009821345068724781056, (-150609293845161968447166237242456473262037053 + 92581148080922977153207018003184520294188436*I)/4951760157141521099596496896, 5*(270278244730804315149356082977618054486347 - 1997830155222496880429743815321662710091562*I)/1237940039285380274899124224, (62978424789588828258068912690172109324360330 + 44803641177219298311493356929537007630129097*I)/2475880078570760549798248448, 19*(-451431106327656743945775812536216598712236 + 114924966793632084379437683991151177407937*I)/1237940039285380274899124224, (63417747628891221594106738815256002143915995 - 261508229397507037136324178612212080871150958*I)/9903520314283042199192993792],
  961. # [ (-2144231934021288786200752920446633703357 + 2305614436009705803670842248131563850246*I)/1208925819614629174706176, (-90720949337459896266067589013987007078153 - 221951119475096403601562347412753844534569*I)/19342813113834066795298816, (11590973613116630788176337262688659880376 + 6514520676308992726483494976339330626159*I)/4835703278458516698824704, 3*(-131776217149000326618649542018343107657237 + 79095042939612668486212006406818285287004*I)/38685626227668133590597632, (10100577916793945997239221374025741184951 - 28631383488085522003281589065994018550748*I)/9671406556917033397649408, 67*(10090295594251078955008130473573667572549 + 10449901522697161049513326446427839676762*I)/77371252455336267181195264, (-54270981296988368730689531355811033930513 - 3413683117592637309471893510944045467443*I)/19342813113834066795298816, (440372322928679910536575560069973699181278 - 736603803202303189048085196176918214409081*I)/77371252455336267181195264, (33220374714789391132887731139763250155295 + 92055083048787219934030779066298919603554*I)/38685626227668133590597632, 5*(-594638554579967244348856981610805281527116 - 82309245323128933521987392165716076704057*I)/309485009821345068724781056, (128056368815300084550013708313312073721955 - 114619107488668120303579745393765245911404*I)/77371252455336267181195264, 21*(59839959255173222962789517794121843393573 + 241507883613676387255359616163487405826334*I)/618970019642690137449562112],
  962. # [ (-13454485022325376674626653802541391955147 + 184471402121905621396582628515905949793486*I)/19342813113834066795298816, (-6158730123400322562149780662133074862437105 - 3416173052604643794120262081623703514107476*I)/154742504910672534362390528, (770558003844914708453618983120686116100419 - 127758381209767638635199674005029818518766*I)/77371252455336267181195264, (-4693005771813492267479835161596671660631703 + 12703585094750991389845384539501921531449948*I)/309485009821345068724781056, (-295028157441149027913545676461260860036601 - 841544569970643160358138082317324743450770*I)/77371252455336267181195264, (56716442796929448856312202561538574275502893 + 7216818824772560379753073185990186711454778*I)/1237940039285380274899124224, 15*(-87061038932753366532685677510172566368387 + 61306141156647596310941396434445461895538*I)/154742504910672534362390528, (-3455315109680781412178133042301025723909347 - 24969329563196972466388460746447646686670670*I)/618970019642690137449562112, (2453418854160886481106557323699250865361849 + 1497886802326243014471854112161398141242514*I)/309485009821345068724781056, (-151343224544252091980004429001205664193082173 + 90471883264187337053549090899816228846836628*I)/4951760157141521099596496896, (1652018205533026103358164026239417416432989 - 9959733619236515024261775397109724431400162*I)/1237940039285380274899124224, 3*(40676374242956907656984876692623172736522006 + 31023357083037817469535762230872667581366205*I)/4951760157141521099596496896],
  963. # [ (-1226990509403328460274658603410696548387 - 4131739423109992672186585941938392788458*I)/1208925819614629174706176, (162392818524418973411975140074368079662703 + 23706194236915374831230612374344230400704*I)/9671406556917033397649408, (-3935678233089814180000602553655565621193 + 2283744757287145199688061892165659502483*I)/1208925819614629174706176, (-2400210250844254483454290806930306285131 - 315571356806370996069052930302295432758205*I)/19342813113834066795298816, (13365917938215281056563183751673390817910 + 15911483133819801118348625831132324863881*I)/4835703278458516698824704, 3*(-215950551370668982657516660700301003897855 + 51684341999223632631602864028309400489378*I)/38685626227668133590597632, (20886089946811765149439844691320027184765 - 30806277083146786592790625980769214361844*I)/9671406556917033397649408, (562180634592713285745940856221105667874855 + 1031543963988260765153550559766662245114916*I)/77371252455336267181195264, (-65820625814810177122941758625652476012867 - 12429918324787060890804395323920477537595*I)/19342813113834066795298816, (319147848192012911298771180196635859221089 - 402403304933906769233365689834404519960394*I)/38685626227668133590597632, (23035615120921026080284733394359587955057 + 115351677687031786114651452775242461310624*I)/38685626227668133590597632, (-3426830634881892756966440108592579264936130 - 1022954961164128745603407283836365128598559*I)/309485009821345068724781056],
  964. # [ (-192574788060137531023716449082856117537757 - 69222967328876859586831013062387845780692*I)/19342813113834066795298816, (2736383768828013152914815341491629299773262 - 2773252698016291897599353862072533475408743*I)/77371252455336267181195264, (-23280005281223837717773057436155921656805 + 214784953368021840006305033048142888879224*I)/19342813113834066795298816, (-3035247484028969580570400133318947903462326 - 2195168903335435855621328554626336958674325*I)/77371252455336267181195264, (984552428291526892214541708637840971548653 - 64006622534521425620714598573494988589378*I)/77371252455336267181195264, (-3070650452470333005276715136041262898509903 + 7286424705750810474140953092161794621989080*I)/154742504910672534362390528, (-147848877109756404594659513386972921139270 - 416306113044186424749331418059456047650861*I)/38685626227668133590597632, (55272118474097814260289392337160619494260781 + 7494019668394781211907115583302403519488058*I)/1237940039285380274899124224, (-581537886583682322424771088996959213068864 + 542191617758465339135308203815256798407429*I)/77371252455336267181195264, (-6422548983676355789975736799494791970390991 - 23524183982209004826464749309156698827737702*I)/618970019642690137449562112, 7*(180747195387024536886923192475064903482083 + 84352527693562434817771649853047924991804*I)/154742504910672534362390528, (-135485179036717001055310712747643466592387031 + 102346575226653028836678855697782273460527608*I)/4951760157141521099596496896],
  965. # [ (3384238362616083147067025892852431152105 + 156724444932584900214919898954874618256*I)/604462909807314587353088, (-59558300950677430189587207338385764871866 + 114427143574375271097298201388331237478857*I)/4835703278458516698824704, (-1356835789870635633517710130971800616227 - 7023484098542340388800213478357340875410*I)/1208925819614629174706176, (234884918567993750975181728413524549575881 + 79757294640629983786895695752733890213506*I)/9671406556917033397649408, (-7632732774935120473359202657160313866419 + 2905452608512927560554702228553291839465*I)/1208925819614629174706176, (52291747908702842344842889809762246649489 - 520996778817151392090736149644507525892649*I)/19342813113834066795298816, (17472406829219127839967951180375981717322 + 23464704213841582137898905375041819568669*I)/4835703278458516698824704, (-911026971811893092350229536132730760943307 + 150799318130900944080399439626714846752360*I)/38685626227668133590597632, (26234457233977042811089020440646443590687 - 45650293039576452023692126463683727692890*I)/9671406556917033397649408, 3*(288348388717468992528382586652654351121357 + 454526517721403048270274049572136109264668*I)/77371252455336267181195264, (-91583492367747094223295011999405657956347 - 12704691128268298435362255538069612411331*I)/19342813113834066795298816, (411208730251327843849027957710164064354221 - 569898526380691606955496789378230959965898*I)/38685626227668133590597632],
  966. # [ (27127513117071487872628354831658811211795 - 37765296987901990355760582016892124833857*I)/4835703278458516698824704, (1741779916057680444272938534338833170625435 + 3083041729779495966997526404685535449810378*I)/77371252455336267181195264, 3*(-60642236251815783728374561836962709533401 - 24630301165439580049891518846174101510744*I)/19342813113834066795298816, 3*(445885207364591681637745678755008757483408 - 350948497734812895032502179455610024541643*I)/38685626227668133590597632, (-47373295621391195484367368282471381775684 + 219122969294089357477027867028071400054973*I)/19342813113834066795298816, (-2801565819673198722993348253876353741520438 - 2250142129822658548391697042460298703335701*I)/77371252455336267181195264, (801448252275607253266997552356128790317119 - 50890367688077858227059515894356594900558*I)/77371252455336267181195264, (-5082187758525931944557763799137987573501207 + 11610432359082071866576699236013484487676124*I)/309485009821345068724781056, (-328925127096560623794883760398247685166830 - 643447969697471610060622160899409680422019*I)/77371252455336267181195264, 15*(2954944669454003684028194956846659916299765 + 33434406416888505837444969347824812608566*I)/1237940039285380274899124224, (-415749104352001509942256567958449835766827 + 479330966144175743357171151440020955412219*I)/77371252455336267181195264, 3*(-4639987285852134369449873547637372282914255 - 11994411888966030153196659207284951579243273*I)/1237940039285380274899124224],
  967. # [ (-478846096206269117345024348666145495601 + 1249092488629201351470551186322814883283*I)/302231454903657293676544, (-17749319421930878799354766626365926894989 - 18264580106418628161818752318217357231971*I)/1208925819614629174706176, (2801110795431528876849623279389579072819 + 363258850073786330770713557775566973248*I)/604462909807314587353088, (-59053496693129013745775512127095650616252 + 78143588734197260279248498898321500167517*I)/4835703278458516698824704, (-283186724922498212468162690097101115349 - 6443437753863179883794497936345437398276*I)/1208925819614629174706176, (188799118826748909206887165661384998787543 + 84274736720556630026311383931055307398820*I)/9671406556917033397649408, (-5482217151670072904078758141270295025989 + 1818284338672191024475557065444481298568*I)/1208925819614629174706176, (56564463395350195513805521309731217952281 - 360208541416798112109946262159695452898431*I)/19342813113834066795298816, 11*(1259539805728870739006416869463689438068 + 1409136581547898074455004171305324917387*I)/4835703278458516698824704, 5*(-123701190701414554945251071190688818343325 + 30997157322590424677294553832111902279712*I)/38685626227668133590597632, (16130917381301373033736295883982414239781 - 32752041297570919727145380131926943374516*I)/9671406556917033397649408, (650301385108223834347093740500375498354925 + 899526407681131828596801223402866051809258*I)/77371252455336267181195264],
  968. # [ (9011388245256140876590294262420614839483 + 8167917972423946282513000869327525382672*I)/1208925819614629174706176, (-426393174084720190126376382194036323028924 + 180692224825757525982858693158209545430621*I)/9671406556917033397649408, (24588556702197802674765733448108154175535 - 45091766022876486566421953254051868331066*I)/4835703278458516698824704, (1872113939365285277373877183750416985089691 + 3030392393733212574744122057679633775773130*I)/77371252455336267181195264, (-222173405538046189185754954524429864167549 - 75193157893478637039381059488387511299116*I)/19342813113834066795298816, (2670821320766222522963689317316937579844558 - 2645837121493554383087981511645435472169191*I)/77371252455336267181195264, 5*(-2100110309556476773796963197283876204940 + 41957457246479840487980315496957337371937*I)/19342813113834066795298816, (-5733743755499084165382383818991531258980593 - 3328949988392698205198574824396695027195732*I)/154742504910672534362390528, (707827994365259025461378911159398206329247 - 265730616623227695108042528694302299777294*I)/77371252455336267181195264, (-1442501604682933002895864804409322823788319 + 11504137805563265043376405214378288793343879*I)/309485009821345068724781056, (-56130472299445561499538726459719629522285 - 61117552419727805035810982426639329818864*I)/9671406556917033397649408, (39053692321126079849054272431599539429908717 - 10209127700342570953247177602860848130710666*I)/1237940039285380274899124224]])
  969. M = Matrix(S('''[
  970. [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
  971. [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
  972. [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
  973. [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
  974. [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
  975. [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
  976. with dotprodsimp(True):
  977. assert M**10 == Matrix(S('''[
  978. [ 7369525394972778926719607798014571861/604462909807314587353088 - 229284202061790301477392339912557559*I/151115727451828646838272, -19704281515163975949388435612632058035/1208925819614629174706176 + 14319858347987648723768698170712102887*I/302231454903657293676544, -3623281909451783042932142262164941211/604462909807314587353088 - 6039240602494288615094338643452320495*I/604462909807314587353088, 109260497799140408739847239685705357695/2417851639229258349412352 - 7427566006564572463236368211555511431*I/2417851639229258349412352, -16095803767674394244695716092817006641/2417851639229258349412352 + 10336681897356760057393429626719177583*I/1208925819614629174706176, -42207883340488041844332828574359769743/2417851639229258349412352 - 182332262671671273188016400290188468499*I/4835703278458516698824704],
  979. [50566491050825573392726324995779608259/1208925819614629174706176 - 90047007594468146222002432884052362145*I/2417851639229258349412352, 74273703462900000967697427843983822011/1208925819614629174706176 + 265947522682943571171988741842776095421*I/1208925819614629174706176, -116900341394390200556829767923360888429/2417851639229258349412352 - 53153263356679268823910621474478756845*I/2417851639229258349412352, 195407378023867871243426523048612490249/1208925819614629174706176 - 1242417915995360200584837585002906728929*I/9671406556917033397649408, -863597594389821970177319682495878193/302231454903657293676544 + 476936100741548328800725360758734300481*I/9671406556917033397649408, -3154451590535653853562472176601754835575/19342813113834066795298816 - 232909875490506237386836489998407329215*I/2417851639229258349412352],
  980. [ -1715444997702484578716037230949868543/302231454903657293676544 + 5009695651321306866158517287924120777*I/302231454903657293676544, -30551582497996879620371947949342101301/604462909807314587353088 - 7632518367986526187139161303331519629*I/151115727451828646838272, 312680739924495153190604170938220575/18889465931478580854784 - 108664334509328818765959789219208459*I/75557863725914323419136, -14693696966703036206178521686918865509/604462909807314587353088 + 72345386220900843930147151999899692401*I/1208925819614629174706176, -8218872496728882299722894680635296519/1208925819614629174706176 - 16776782833358893712645864791807664983*I/1208925819614629174706176, 143237839169380078671242929143670635137/2417851639229258349412352 + 2883817094806115974748882735218469447*I/2417851639229258349412352],
  981. [ 3087979417831061365023111800749855987/151115727451828646838272 + 34441942370802869368851419102423997089*I/604462909807314587353088, -148309181940158040917731426845476175667/604462909807314587353088 - 263987151804109387844966835369350904919*I/9671406556917033397649408, 50259518594816377378747711930008883165/1208925819614629174706176 - 95713974916869240305450001443767979653*I/2417851639229258349412352, 153466447023875527996457943521467271119/2417851639229258349412352 + 517285524891117105834922278517084871349*I/2417851639229258349412352, -29184653615412989036678939366291205575/604462909807314587353088 - 27551322282526322041080173287022121083*I/1208925819614629174706176, 196404220110085511863671393922447671649/1208925819614629174706176 - 1204712019400186021982272049902206202145*I/9671406556917033397649408],
  982. [ -2632581805949645784625606590600098779/151115727451828646838272 - 589957435912868015140272627522612771*I/37778931862957161709568, 26727850893953715274702844733506310247/302231454903657293676544 - 10825791956782128799168209600694020481*I/302231454903657293676544, -1036348763702366164044671908440791295/151115727451828646838272 + 3188624571414467767868303105288107375*I/151115727451828646838272, -36814959939970644875593411585393242449/604462909807314587353088 - 18457555789119782404850043842902832647*I/302231454903657293676544, 12454491297984637815063964572803058647/604462909807314587353088 - 340489532842249733975074349495329171*I/302231454903657293676544, -19547211751145597258386735573258916681/604462909807314587353088 + 87299583775782199663414539883938008933*I/1208925819614629174706176],
  983. [ -40281994229560039213253423262678393183/604462909807314587353088 - 2939986850065527327299273003299736641*I/604462909807314587353088, 331940684638052085845743020267462794181/2417851639229258349412352 - 284574901963624403933361315517248458969*I/1208925819614629174706176, 6453843623051745485064693628073010961/302231454903657293676544 + 36062454107479732681350914931391590957*I/604462909807314587353088, -147665869053634695632880753646441962067/604462909807314587353088 - 305987938660447291246597544085345123927*I/9671406556917033397649408, 107821369195275772166593879711259469423/2417851639229258349412352 - 11645185518211204108659001435013326687*I/302231454903657293676544, 64121228424717666402009446088588091619/1208925819614629174706176 + 265557133337095047883844369272389762133*I/1208925819614629174706176]]'''))
  984. def test_issue_17247_expression_blowup_5():
  985. M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
  986. with dotprodsimp(True):
  987. assert M.charpoly('x') == PurePoly(x**6 + (-6 - 6*I)*x**5 + 36*I*x**4, x, domain='EX')
  988. def test_issue_17247_expression_blowup_6():
  989. M = Matrix(8, 8, [x+i for i in range (64)])
  990. with dotprodsimp(True):
  991. assert M.det('bareiss') == 0
  992. def test_issue_17247_expression_blowup_7():
  993. M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
  994. with dotprodsimp(True):
  995. assert M.det('berkowitz') == 0
  996. def test_issue_17247_expression_blowup_8():
  997. M = Matrix(8, 8, [x+i for i in range (64)])
  998. with dotprodsimp(True):
  999. assert M.det('lu') == 0
  1000. def test_issue_17247_expression_blowup_9():
  1001. M = Matrix(8, 8, [x+i for i in range (64)])
  1002. with dotprodsimp(True):
  1003. assert M.rref() == (Matrix([
  1004. [1, 0, -1, -2, -3, -4, -5, -6],
  1005. [0, 1, 2, 3, 4, 5, 6, 7],
  1006. [0, 0, 0, 0, 0, 0, 0, 0],
  1007. [0, 0, 0, 0, 0, 0, 0, 0],
  1008. [0, 0, 0, 0, 0, 0, 0, 0],
  1009. [0, 0, 0, 0, 0, 0, 0, 0],
  1010. [0, 0, 0, 0, 0, 0, 0, 0],
  1011. [0, 0, 0, 0, 0, 0, 0, 0]]), (0, 1))
  1012. def test_issue_17247_expression_blowup_10():
  1013. M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
  1014. with dotprodsimp(True):
  1015. assert M.cofactor(0, 0) == 0
  1016. def test_issue_17247_expression_blowup_11():
  1017. M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
  1018. with dotprodsimp(True):
  1019. assert M.cofactor_matrix() == Matrix(6, 6, [0]*36)
  1020. def test_issue_17247_expression_blowup_12():
  1021. M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
  1022. with dotprodsimp(True):
  1023. assert M.eigenvals() == {6: 1, 6*I: 1, 0: 4}
  1024. def test_issue_17247_expression_blowup_13():
  1025. M = Matrix([
  1026. [ 0, 1 - x, x + 1, 1 - x],
  1027. [1 - x, x + 1, 0, x + 1],
  1028. [ 0, 1 - x, x + 1, 1 - x],
  1029. [ 0, 0, 1 - x, 0]])
  1030. ev = M.eigenvects()
  1031. assert ev[0] == (0, 2, [Matrix([0, -1, 0, 1])])
  1032. assert ev[1][0] == x - sqrt(2)*(x - 1) + 1
  1033. assert ev[1][1] == 1
  1034. assert ev[1][2][0].expand(deep=False, numer=True) == Matrix([
  1035. [(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
  1036. [-4*x/(x**2 - 2*x + 1) + (x + 1)*(x - sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
  1037. [(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
  1038. [1]
  1039. ])
  1040. assert ev[2][0] == x + sqrt(2)*(x - 1) + 1
  1041. assert ev[2][1] == 1
  1042. assert ev[2][2][0].expand(deep=False, numer=True) == Matrix([
  1043. [(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
  1044. [-4*x/(x**2 - 2*x + 1) + (x + 1)*(x + sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
  1045. [(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
  1046. [1]
  1047. ])
  1048. def test_issue_17247_expression_blowup_14():
  1049. M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
  1050. with dotprodsimp(True):
  1051. assert M.echelon_form() == Matrix([
  1052. [x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x],
  1053. [ 0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x],
  1054. [ 0, 0, 0, 0, 0, 0, 0, 0],
  1055. [ 0, 0, 0, 0, 0, 0, 0, 0],
  1056. [ 0, 0, 0, 0, 0, 0, 0, 0],
  1057. [ 0, 0, 0, 0, 0, 0, 0, 0],
  1058. [ 0, 0, 0, 0, 0, 0, 0, 0],
  1059. [ 0, 0, 0, 0, 0, 0, 0, 0]])
  1060. def test_issue_17247_expression_blowup_15():
  1061. M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
  1062. with dotprodsimp(True):
  1063. assert M.rowspace() == [Matrix([[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x]]), Matrix([[0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x]])]
  1064. def test_issue_17247_expression_blowup_16():
  1065. M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
  1066. with dotprodsimp(True):
  1067. assert M.columnspace() == [Matrix([[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x]]), Matrix([[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1]])]
  1068. def test_issue_17247_expression_blowup_17():
  1069. M = Matrix(8, 8, [x+i for i in range (64)])
  1070. with dotprodsimp(True):
  1071. assert M.nullspace() == [
  1072. Matrix([[1],[-2],[1],[0],[0],[0],[0],[0]]),
  1073. Matrix([[2],[-3],[0],[1],[0],[0],[0],[0]]),
  1074. Matrix([[3],[-4],[0],[0],[1],[0],[0],[0]]),
  1075. Matrix([[4],[-5],[0],[0],[0],[1],[0],[0]]),
  1076. Matrix([[5],[-6],[0],[0],[0],[0],[1],[0]]),
  1077. Matrix([[6],[-7],[0],[0],[0],[0],[0],[1]])]
  1078. def test_issue_17247_expression_blowup_18():
  1079. M = Matrix(6, 6, ([1+x, 1-x]*3 + [1-x, 1+x]*3)*3)
  1080. with dotprodsimp(True):
  1081. assert not M.is_nilpotent()
  1082. def test_issue_17247_expression_blowup_19():
  1083. M = Matrix(S('''[
  1084. [ -3/4, 0, 1/4 + I/2, 0],
  1085. [ 0, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
  1086. [ 1/2 - I, 0, 0, 0],
  1087. [ 0, 0, 0, -177/128 - 1369*I/128]]'''))
  1088. with dotprodsimp(True):
  1089. assert not M.is_diagonalizable()
  1090. def test_issue_17247_expression_blowup_20():
  1091. M = Matrix([
  1092. [x + 1, 1 - x, 0, 0],
  1093. [1 - x, x + 1, 0, x + 1],
  1094. [ 0, 1 - x, x + 1, 0],
  1095. [ 0, 0, 0, x + 1]])
  1096. with dotprodsimp(True):
  1097. assert M.diagonalize() == (Matrix([
  1098. [1, 1, 0, (x + 1)/(x - 1)],
  1099. [1, -1, 0, 0],
  1100. [1, 1, 1, 0],
  1101. [0, 0, 0, 1]]),
  1102. Matrix([
  1103. [2, 0, 0, 0],
  1104. [0, 2*x, 0, 0],
  1105. [0, 0, x + 1, 0],
  1106. [0, 0, 0, x + 1]]))
  1107. def test_issue_17247_expression_blowup_21():
  1108. M = Matrix(S('''[
  1109. [ -3/4, 45/32 - 37*I/16, 0, 0],
  1110. [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
  1111. [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
  1112. [ 0, 0, 0, -177/128 - 1369*I/128]]'''))
  1113. with dotprodsimp(True):
  1114. assert M.inv(method='GE') == Matrix(S('''[
  1115. [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
  1116. [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
  1117. [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
  1118. [0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
  1119. def test_issue_17247_expression_blowup_22():
  1120. M = Matrix(S('''[
  1121. [ -3/4, 45/32 - 37*I/16, 0, 0],
  1122. [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
  1123. [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
  1124. [ 0, 0, 0, -177/128 - 1369*I/128]]'''))
  1125. with dotprodsimp(True):
  1126. assert M.inv(method='LU') == Matrix(S('''[
  1127. [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
  1128. [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
  1129. [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
  1130. [0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
  1131. def test_issue_17247_expression_blowup_23():
  1132. M = Matrix(S('''[
  1133. [ -3/4, 45/32 - 37*I/16, 0, 0],
  1134. [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
  1135. [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
  1136. [ 0, 0, 0, -177/128 - 1369*I/128]]'''))
  1137. with dotprodsimp(True):
  1138. assert M.inv(method='ADJ').expand() == Matrix(S('''[
  1139. [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
  1140. [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
  1141. [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
  1142. [0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
  1143. def test_issue_17247_expression_blowup_24():
  1144. M = SparseMatrix(S('''[
  1145. [ -3/4, 45/32 - 37*I/16, 0, 0],
  1146. [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
  1147. [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
  1148. [ 0, 0, 0, -177/128 - 1369*I/128]]'''))
  1149. with dotprodsimp(True):
  1150. assert M.inv(method='CH') == Matrix(S('''[
  1151. [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
  1152. [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
  1153. [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
  1154. [0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
  1155. def test_issue_17247_expression_blowup_25():
  1156. M = SparseMatrix(S('''[
  1157. [ -3/4, 45/32 - 37*I/16, 0, 0],
  1158. [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
  1159. [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
  1160. [ 0, 0, 0, -177/128 - 1369*I/128]]'''))
  1161. with dotprodsimp(True):
  1162. assert M.inv(method='LDL') == Matrix(S('''[
  1163. [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
  1164. [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
  1165. [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
  1166. [0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
  1167. def test_issue_17247_expression_blowup_26():
  1168. M = Matrix(S('''[
  1169. [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
  1170. [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
  1171. [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
  1172. [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
  1173. [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
  1174. [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
  1175. [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
  1176. [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
  1177. with dotprodsimp(True):
  1178. assert M.rank() == 4
  1179. def test_issue_17247_expression_blowup_27():
  1180. M = Matrix([
  1181. [ 0, 1 - x, x + 1, 1 - x],
  1182. [1 - x, x + 1, 0, x + 1],
  1183. [ 0, 1 - x, x + 1, 1 - x],
  1184. [ 0, 0, 1 - x, 0]])
  1185. with dotprodsimp(True):
  1186. P, J = M.jordan_form()
  1187. assert P.expand() == Matrix(S('''[
  1188. [ 0, 4*x/(x**2 - 2*x + 1), -(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7), -(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)],
  1189. [x - 1, x/(x - 1) + 1/(x - 1), (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2)), (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)],
  1190. [ 0, 1, -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2)), -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))],
  1191. [1 - x, 0, 1, 1]]''')).expand()
  1192. assert J == Matrix(S('''[
  1193. [0, 1, 0, 0],
  1194. [0, 0, 0, 0],
  1195. [0, 0, x - sqrt(2)*(x - 1) + 1, 0],
  1196. [0, 0, 0, x + sqrt(2)*(x - 1) + 1]]'''))
  1197. def test_issue_17247_expression_blowup_28():
  1198. M = Matrix(S('''[
  1199. [ -3/4, 45/32 - 37*I/16, 0, 0],
  1200. [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
  1201. [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
  1202. [ 0, 0, 0, -177/128 - 1369*I/128]]'''))
  1203. with dotprodsimp(True):
  1204. assert M.singular_values() == S('''[
  1205. sqrt(14609315/131072 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
  1206. sqrt(14609315/131072 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
  1207. sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2),
  1208. sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2)]''')
  1209. def test_issue_16823():
  1210. # This still needs to be fixed if not using dotprodsimp.
  1211. M = Matrix(S('''[
  1212. [1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I,15/128-3/32*I,19/256+551/1024*I],
  1213. [21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I,129/256-549/512*I,42533/16384+29103/8192*I],
  1214. [-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I],
  1215. [1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I],
  1216. [-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I],
  1217. [1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I],
  1218. [-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I],
  1219. [-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I],
  1220. [0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I],
  1221. [1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I],
  1222. [0,-4*I,0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I],
  1223. [0,1/4+1/2*I,1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I]]'''))
  1224. with dotprodsimp(True):
  1225. assert M.rank() == 8
  1226. def test_issue_18531():
  1227. # solve_linear_system still needs fixing but the rref works.
  1228. M = Matrix([
  1229. [1, 1, 1, 1, 1, 0, 1, 0, 0],
  1230. [1 + sqrt(2), -1 + sqrt(2), 1 - sqrt(2), -sqrt(2) - 1, 1, 1, -1, 1, 1],
  1231. [-5 + 2*sqrt(2), -5 - 2*sqrt(2), -5 - 2*sqrt(2), -5 + 2*sqrt(2), -7, 2, -7, -2, 0],
  1232. [-3*sqrt(2) - 1, 1 - 3*sqrt(2), -1 + 3*sqrt(2), 1 + 3*sqrt(2), -7, -5, 7, -5, 3],
  1233. [7 - 4*sqrt(2), 4*sqrt(2) + 7, 4*sqrt(2) + 7, 7 - 4*sqrt(2), 7, -12, 7, 12, 0],
  1234. [-1 + 3*sqrt(2), 1 + 3*sqrt(2), -3*sqrt(2) - 1, 1 - 3*sqrt(2), 7, -5, -7, -5, 3],
  1235. [-3 + 2*sqrt(2), -3 - 2*sqrt(2), -3 - 2*sqrt(2), -3 + 2*sqrt(2), -1, 2, -1, -2, 0],
  1236. [1 - sqrt(2), -sqrt(2) - 1, 1 + sqrt(2), -1 + sqrt(2), -1, 1, 1, 1, 1]
  1237. ])
  1238. with dotprodsimp(True):
  1239. assert M.rref() == (Matrix([
  1240. [1, 0, 0, 0, 0, 0, 0, 0, S(1)/2],
  1241. [0, 1, 0, 0, 0, 0, 0, 0, -S(1)/2],
  1242. [0, 0, 1, 0, 0, 0, 0, 0, S(1)/2],
  1243. [0, 0, 0, 1, 0, 0, 0, 0, -S(1)/2],
  1244. [0, 0, 0, 0, 1, 0, 0, 0, 0],
  1245. [0, 0, 0, 0, 0, 1, 0, 0, -S(1)/2],
  1246. [0, 0, 0, 0, 0, 0, 1, 0, 0],
  1247. [0, 0, 0, 0, 0, 0, 0, 1, -S(1)/2]]), (0, 1, 2, 3, 4, 5, 6, 7))
  1248. def test_creation():
  1249. raises(ValueError, lambda: Matrix(5, 5, range(20)))
  1250. raises(ValueError, lambda: Matrix(5, -1, []))
  1251. raises(IndexError, lambda: Matrix((1, 2))[2])
  1252. with raises(IndexError):
  1253. Matrix((1, 2))[3] = 5
  1254. assert Matrix() == Matrix([]) == Matrix(0, 0, [])
  1255. assert Matrix([[]]) == Matrix(1, 0, [])
  1256. assert Matrix([[], []]) == Matrix(2, 0, [])
  1257. # anything used to be allowed in a matrix
  1258. with warns_deprecated_sympy():
  1259. assert Matrix([[[1], (2,)]]).tolist() == [[[1], (2,)]]
  1260. with warns_deprecated_sympy():
  1261. assert Matrix([[[1], (2,)]]).T.tolist() == [[[1]], [(2,)]]
  1262. M = Matrix([[0]])
  1263. with warns_deprecated_sympy():
  1264. M[0, 0] = S.EmptySet
  1265. a = Matrix([[x, 0], [0, 0]])
  1266. m = a
  1267. assert m.cols == m.rows
  1268. assert m.cols == 2
  1269. assert m[:] == [x, 0, 0, 0]
  1270. b = Matrix(2, 2, [x, 0, 0, 0])
  1271. m = b
  1272. assert m.cols == m.rows
  1273. assert m.cols == 2
  1274. assert m[:] == [x, 0, 0, 0]
  1275. assert a == b
  1276. assert Matrix(b) == b
  1277. c23 = Matrix(2, 3, range(1, 7))
  1278. c13 = Matrix(1, 3, range(7, 10))
  1279. c = Matrix([c23, c13])
  1280. assert c.cols == 3
  1281. assert c.rows == 3
  1282. assert c[:] == [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1283. assert Matrix(eye(2)) == eye(2)
  1284. assert ImmutableMatrix(ImmutableMatrix(eye(2))) == ImmutableMatrix(eye(2))
  1285. assert ImmutableMatrix(c) == c.as_immutable()
  1286. assert Matrix(ImmutableMatrix(c)) == ImmutableMatrix(c).as_mutable()
  1287. assert c is not Matrix(c)
  1288. dat = [[ones(3,2), ones(3,3)*2], [ones(2,3)*3, ones(2,2)*4]]
  1289. M = Matrix(dat)
  1290. assert M == Matrix([
  1291. [1, 1, 2, 2, 2],
  1292. [1, 1, 2, 2, 2],
  1293. [1, 1, 2, 2, 2],
  1294. [3, 3, 3, 4, 4],
  1295. [3, 3, 3, 4, 4]])
  1296. assert M.tolist() != dat
  1297. # keep block form if evaluate=False
  1298. assert Matrix(dat, evaluate=False).tolist() == dat
  1299. A = MatrixSymbol("A", 2, 2)
  1300. dat = [ones(2), A]
  1301. assert Matrix(dat) == Matrix([
  1302. [ 1, 1],
  1303. [ 1, 1],
  1304. [A[0, 0], A[0, 1]],
  1305. [A[1, 0], A[1, 1]]])
  1306. with warns_deprecated_sympy():
  1307. assert Matrix(dat, evaluate=False).tolist() == [[i] for i in dat]
  1308. # 0-dim tolerance
  1309. assert Matrix([ones(2), ones(0)]) == Matrix([ones(2)])
  1310. raises(ValueError, lambda: Matrix([ones(2), ones(0, 3)]))
  1311. raises(ValueError, lambda: Matrix([ones(2), ones(3, 0)]))
  1312. # mix of Matrix and iterable
  1313. M = Matrix([[1, 2], [3, 4]])
  1314. M2 = Matrix([M, (5, 6)])
  1315. assert M2 == Matrix([[1, 2], [3, 4], [5, 6]])
  1316. def test_irregular_block():
  1317. assert Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
  1318. ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) == Matrix([
  1319. [1, 2, 2, 2, 3, 3],
  1320. [1, 2, 2, 2, 3, 3],
  1321. [4, 2, 2, 2, 5, 5],
  1322. [6, 6, 7, 7, 5, 5]])
  1323. def test_slicing():
  1324. m0 = eye(4)
  1325. assert m0[:3, :3] == eye(3)
  1326. assert m0[2:4, 0:2] == zeros(2)
  1327. m1 = Matrix(3, 3, lambda i, j: i + j)
  1328. assert m1[0, :] == Matrix(1, 3, (0, 1, 2))
  1329. assert m1[1:3, 1] == Matrix(2, 1, (2, 3))
  1330. m2 = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
  1331. assert m2[:, -1] == Matrix(4, 1, [3, 7, 11, 15])
  1332. assert m2[-2:, :] == Matrix([[8, 9, 10, 11], [12, 13, 14, 15]])
  1333. def test_submatrix_assignment():
  1334. m = zeros(4)
  1335. m[2:4, 2:4] = eye(2)
  1336. assert m == Matrix(((0, 0, 0, 0),
  1337. (0, 0, 0, 0),
  1338. (0, 0, 1, 0),
  1339. (0, 0, 0, 1)))
  1340. m[:2, :2] = eye(2)
  1341. assert m == eye(4)
  1342. m[:, 0] = Matrix(4, 1, (1, 2, 3, 4))
  1343. assert m == Matrix(((1, 0, 0, 0),
  1344. (2, 1, 0, 0),
  1345. (3, 0, 1, 0),
  1346. (4, 0, 0, 1)))
  1347. m[:, :] = zeros(4)
  1348. assert m == zeros(4)
  1349. m[:, :] = [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)]
  1350. assert m == Matrix(((1, 2, 3, 4),
  1351. (5, 6, 7, 8),
  1352. (9, 10, 11, 12),
  1353. (13, 14, 15, 16)))
  1354. m[:2, 0] = [0, 0]
  1355. assert m == Matrix(((0, 2, 3, 4),
  1356. (0, 6, 7, 8),
  1357. (9, 10, 11, 12),
  1358. (13, 14, 15, 16)))
  1359. def test_reshape():
  1360. m0 = eye(3)
  1361. assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
  1362. m1 = Matrix(3, 4, lambda i, j: i + j)
  1363. assert m1.reshape(
  1364. 4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
  1365. assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
  1366. def test_applyfunc():
  1367. m0 = eye(3)
  1368. assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
  1369. assert m0.applyfunc(lambda x: 0) == zeros(3)
  1370. def test_expand():
  1371. m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
  1372. # Test if expand() returns a matrix
  1373. m1 = m0.expand()
  1374. assert m1 == Matrix(
  1375. [[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
  1376. a = Symbol('a', real=True)
  1377. assert Matrix([exp(I*a)]).expand(complex=True) == \
  1378. Matrix([cos(a) + I*sin(a)])
  1379. assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([
  1380. [1, 1, Rational(3, 2)],
  1381. [0, 1, -1],
  1382. [0, 0, 1]]
  1383. )
  1384. def test_refine():
  1385. m0 = Matrix([[Abs(x)**2, sqrt(x**2)],
  1386. [sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
  1387. m1 = m0.refine(Q.real(x) & Q.real(y))
  1388. assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
  1389. m1 = m0.refine(Q.positive(x) & Q.positive(y))
  1390. assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
  1391. m1 = m0.refine(Q.negative(x) & Q.negative(y))
  1392. assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
  1393. def test_random():
  1394. M = randMatrix(3, 3)
  1395. M = randMatrix(3, 3, seed=3)
  1396. assert M == randMatrix(3, 3, seed=3)
  1397. M = randMatrix(3, 4, 0, 150)
  1398. M = randMatrix(3, seed=4, symmetric=True)
  1399. assert M == randMatrix(3, seed=4, symmetric=True)
  1400. S = M.copy()
  1401. S.simplify()
  1402. assert S == M # doesn't fail when elements are Numbers, not int
  1403. rng = random.Random(4)
  1404. assert M == randMatrix(3, symmetric=True, prng=rng)
  1405. # Ensure symmetry
  1406. for size in (10, 11): # Test odd and even
  1407. for percent in (100, 70, 30):
  1408. M = randMatrix(size, symmetric=True, percent=percent, prng=rng)
  1409. assert M == M.T
  1410. M = randMatrix(10, min=1, percent=70)
  1411. zero_count = 0
  1412. for i in range(M.shape[0]):
  1413. for j in range(M.shape[1]):
  1414. if M[i, j] == 0:
  1415. zero_count += 1
  1416. assert zero_count == 30
  1417. def test_inverse():
  1418. A = eye(4)
  1419. assert A.inv() == eye(4)
  1420. assert A.inv(method="LU") == eye(4)
  1421. assert A.inv(method="ADJ") == eye(4)
  1422. assert A.inv(method="CH") == eye(4)
  1423. assert A.inv(method="LDL") == eye(4)
  1424. assert A.inv(method="QR") == eye(4)
  1425. A = Matrix([[2, 3, 5],
  1426. [3, 6, 2],
  1427. [8, 3, 6]])
  1428. Ainv = A.inv()
  1429. assert A*Ainv == eye(3)
  1430. assert A.inv(method="LU") == Ainv
  1431. assert A.inv(method="ADJ") == Ainv
  1432. assert A.inv(method="CH") == Ainv
  1433. assert A.inv(method="LDL") == Ainv
  1434. assert A.inv(method="QR") == Ainv
  1435. AA = Matrix([[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
  1436. [1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0],
  1437. [1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
  1438. [1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
  1439. [1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0],
  1440. [1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
  1441. [0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0],
  1442. [1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1],
  1443. [0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1],
  1444. [1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0],
  1445. [0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0],
  1446. [1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0],
  1447. [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1],
  1448. [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0],
  1449. [0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0],
  1450. [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0],
  1451. [0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1],
  1452. [0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1],
  1453. [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1],
  1454. [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  1455. [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
  1456. [0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1],
  1457. [0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0],
  1458. [0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
  1459. [0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0]])
  1460. assert AA.inv(method="BLOCK") * AA == eye(AA.shape[0])
  1461. # test that immutability is not a problem
  1462. cls = ImmutableMatrix
  1463. m = cls([[48, 49, 31],
  1464. [ 9, 71, 94],
  1465. [59, 28, 65]])
  1466. assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
  1467. cls = ImmutableSparseMatrix
  1468. m = cls([[48, 49, 31],
  1469. [ 9, 71, 94],
  1470. [59, 28, 65]])
  1471. assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
  1472. def test_inverse_symbolic_float_issue_26821():
  1473. Tau, Tau_syn_in, Tau_syn_ex, C_m, Tau_syn_gap = symbols("Tau Tau_syn_in Tau_syn_ex C_m Tau_syn_gap")
  1474. __h = symbols("__h")
  1475. M = Matrix([
  1476. [0,0,0,0,0,(1.0*Tau*__h-1.0*Tau_syn_in*__h)/(2.0*Tau-1.0*Tau_syn_in),-1.0*Tau*Tau_syn_in/(2.0*Tau-1.0*Tau_syn_in)],
  1477. [0,0,0,0,0,(-1.0*Tau*__h+1.0*Tau_syn_in*__h)/(2.0*Tau*Tau_syn_in-1.0*Tau_syn_in**2),1.0],
  1478. [0,(1.0*Tau*__h-1.0*Tau_syn_ex*__h)/(2.0*Tau-1.0*Tau_syn_ex),-1.0*Tau*Tau_syn_ex/(2.0*Tau-1.0*Tau_syn_ex),0,0,0,0],
  1479. [0,(-1.0*Tau*__h+1.0*Tau_syn_ex*__h)/(2.0*Tau*Tau_syn_ex-1.0*Tau_syn_ex**2),1.0,0,0,0,0],
  1480. [0,0,0,(1.0*Tau*__h-1.0*Tau_syn_gap*__h)/(2.0*Tau-1.0*Tau_syn_gap),-1.0*Tau*Tau_syn_gap/(2.0*Tau-1.0*Tau_syn_gap),0,0],
  1481. [0,0,0,(-1.0*Tau*__h+1.0*Tau_syn_gap*__h)/(2.0*Tau*Tau_syn_gap-1.0*Tau_syn_gap**2),1.0,0,0],
  1482. [1.0,-1.0*Tau*Tau_syn_ex*__h/(2.0*C_m*Tau-1.0*C_m*Tau_syn_ex),0,-1.0*Tau*Tau_syn_gap*__h/(2.0*C_m*Tau-1.0*C_m*Tau_syn_gap),0,-1.0*Tau*Tau_syn_in*__h/(2.0*C_m*Tau-1.0*C_m*Tau_syn_in),0]
  1483. ])
  1484. Mi = M.inv()
  1485. assert (M*Mi - eye(7)).applyfunc(cancel) == zeros(7)
  1486. # https://github.com/sympy/sympy/issues/26821
  1487. # Previously very large floats were in the result.
  1488. assert max(abs(f) for f in Mi.atoms(Float)) < 1e3
  1489. @slow
  1490. def test_matrix_exponential_issue_26821():
  1491. # The symbol names matter in the original bug...
  1492. a, b, c, d, e = symbols("Tau, Tau_syn_in, Tau_syn_ex, C_m, Tau_syn_gap")
  1493. t = symbols("__h")
  1494. M = Matrix([
  1495. [ 0, 1.0, 0, 0, 0, 0, 0],
  1496. [-1/b**2, -2/b, 0, 0, 0, 0, 0],
  1497. [ 0, 0, 0, 1.0, 0, 0, 0],
  1498. [ 0, 0, -1/c**2, -2/c, 0, 0, 0],
  1499. [ 0, 0, 0, 0, 0, 1, 0],
  1500. [ 0, 0, 0, 0, -1/e**2, -2/e, 0],
  1501. [ 1/d, 0, 1/d, 0, 1/d, 0, -1/a]
  1502. ])
  1503. Me = (t*M).exp()
  1504. assert (Me.diff(t) - M*Me).applyfunc(cancel) == zeros(7)
  1505. # https://github.com/sympy/sympy/issues/26821
  1506. # Previously very large floats were in the result.
  1507. assert max(abs(f) for f in Me.atoms(Float)) < 1e3
  1508. def test_jacobian_hessian():
  1509. L = Matrix(1, 2, [x**2*y, 2*y**2 + x*y])
  1510. syms = [x, y]
  1511. assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]])
  1512. L = Matrix(1, 2, [x, x**2*y**3])
  1513. assert L.jacobian(syms) == Matrix([[1, 0], [2*x*y**3, x**2*3*y**2]])
  1514. f = x**2*y
  1515. syms = [x, y]
  1516. assert hessian(f, syms) == Matrix([[2*y, 2*x], [2*x, 0]])
  1517. f = x**2*y**3
  1518. assert hessian(f, syms) == \
  1519. Matrix([[2*y**3, 6*x*y**2], [6*x*y**2, 6*x**2*y]])
  1520. f = z + x*y**2
  1521. g = x**2 + 2*y**3
  1522. ans = Matrix([[0, 2*y],
  1523. [2*y, 2*x]])
  1524. assert ans == hessian(f, Matrix([x, y]))
  1525. assert ans == hessian(f, Matrix([x, y]).T)
  1526. assert hessian(f, (y, x), [g]) == Matrix([
  1527. [ 0, 6*y**2, 2*x],
  1528. [6*y**2, 2*x, 2*y],
  1529. [ 2*x, 2*y, 0]])
  1530. def test_wronskian():
  1531. assert wronskian([cos(x), sin(x)], x) == cos(x)**2 + sin(x)**2
  1532. assert wronskian([exp(x), exp(2*x)], x) == exp(3*x)
  1533. assert wronskian([exp(x), x], x) == exp(x) - x*exp(x)
  1534. assert wronskian([1, x, x**2], x) == 2
  1535. w1 = -6*exp(x)*sin(x)*x + 6*cos(x)*exp(x)*x**2 - 6*exp(x)*cos(x)*x - \
  1536. exp(x)*cos(x)*x**3 + exp(x)*sin(x)*x**3
  1537. assert wronskian([exp(x), cos(x), x**3], x).expand() == w1
  1538. assert wronskian([exp(x), cos(x), x**3], x, method='berkowitz').expand() \
  1539. == w1
  1540. w2 = -x**3*cos(x)**2 - x**3*sin(x)**2 - 6*x*cos(x)**2 - 6*x*sin(x)**2
  1541. assert wronskian([sin(x), cos(x), x**3], x).expand() == w2
  1542. assert wronskian([sin(x), cos(x), x**3], x, method='berkowitz').expand() \
  1543. == w2
  1544. assert wronskian([], x) == 1
  1545. def test_xreplace():
  1546. assert Matrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
  1547. Matrix([[1, 5], [5, 4]])
  1548. assert Matrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
  1549. Matrix([[-1, 2], [-3, 4]])
  1550. for cls in all_classes:
  1551. assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).xreplace({1: 2})
  1552. def test_simplify():
  1553. n = Symbol('n')
  1554. f = Function('f')
  1555. M = Matrix([[ 1/x + 1/y, (x + x*y) / x ],
  1556. [ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
  1557. M.simplify()
  1558. assert M == Matrix([[ (x + y)/(x * y), 1 + y ],
  1559. [ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
  1560. eq = (1 + x)**2
  1561. M = Matrix([[eq]])
  1562. M.simplify()
  1563. assert M == Matrix([[eq]])
  1564. M.simplify(ratio=oo)
  1565. assert M == Matrix([[eq.simplify(ratio=oo)]])
  1566. n = Symbol('n')
  1567. f = Function('f')
  1568. M = ImmutableMatrix([
  1569. [ 1/x + 1/y, (x + x*y) / x ],
  1570. [ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]
  1571. ])
  1572. assert M.simplify() == Matrix([
  1573. [ (x + y)/(x * y), 1 + y ],
  1574. [ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]
  1575. ])
  1576. eq = (1 + x)**2
  1577. M = ImmutableMatrix([[eq]])
  1578. assert M.simplify() == Matrix([[eq]])
  1579. assert M.simplify(ratio=oo) == Matrix([[eq.simplify(ratio=oo)]])
  1580. assert simplify(ImmutableMatrix([[sin(x)**2 + cos(x)**2]])) == \
  1581. ImmutableMatrix([[1]])
  1582. # https://github.com/sympy/sympy/issues/19353
  1583. m = Matrix([[30, 2], [3, 4]])
  1584. assert (1/(m.trace())).simplify() == Rational(1, 34)
  1585. def test_transpose():
  1586. M = Matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
  1587. [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]])
  1588. assert M.T == Matrix( [ [1, 1],
  1589. [2, 2],
  1590. [3, 3],
  1591. [4, 4],
  1592. [5, 5],
  1593. [6, 6],
  1594. [7, 7],
  1595. [8, 8],
  1596. [9, 9],
  1597. [0, 0] ])
  1598. assert M.T.T == M
  1599. assert M.T == M.transpose()
  1600. def test_conj_dirac():
  1601. raises(AttributeError, lambda: eye(3).D)
  1602. M = Matrix([[1, I, I, I],
  1603. [0, 1, I, I],
  1604. [0, 0, 1, I],
  1605. [0, 0, 0, 1]])
  1606. assert M.D == Matrix([[ 1, 0, 0, 0],
  1607. [-I, 1, 0, 0],
  1608. [-I, -I, -1, 0],
  1609. [-I, -I, I, -1]])
  1610. def test_trace():
  1611. M = Matrix([[1, 0, 0],
  1612. [0, 5, 0],
  1613. [0, 0, 8]])
  1614. assert M.trace() == 14
  1615. def test_shape():
  1616. m = Matrix(1, 2, [0, 0])
  1617. assert m.shape == (1, 2)
  1618. M = Matrix([[x, 0, 0],
  1619. [0, y, 0]])
  1620. assert M.shape == (2, 3)
  1621. def test_col_row_op():
  1622. M = Matrix([[x, 0, 0],
  1623. [0, y, 0]])
  1624. M.row_op(1, lambda r, j: r + j + 1)
  1625. assert M == Matrix([[x, 0, 0],
  1626. [1, y + 2, 3]])
  1627. M.col_op(0, lambda c, j: c + y**j)
  1628. assert M == Matrix([[x + 1, 0, 0],
  1629. [1 + y, y + 2, 3]])
  1630. # neither row nor slice give copies that allow the original matrix to
  1631. # be changed
  1632. assert M.row(0) == Matrix([[x + 1, 0, 0]])
  1633. r1 = M.row(0)
  1634. r1[0] = 42
  1635. assert M[0, 0] == x + 1
  1636. r1 = M[0, :-1] # also testing negative slice
  1637. r1[0] = 42
  1638. assert M[0, 0] == x + 1
  1639. c1 = M.col(0)
  1640. assert c1 == Matrix([x + 1, 1 + y])
  1641. c1[0] = 0
  1642. assert M[0, 0] == x + 1
  1643. c1 = M[:, 0]
  1644. c1[0] = 42
  1645. assert M[0, 0] == x + 1
  1646. def test_row_mult():
  1647. M = Matrix([[1,2,3],
  1648. [4,5,6]])
  1649. M.row_mult(1,3)
  1650. assert M[1,0] == 12
  1651. assert M[0,0] == 1
  1652. assert M[1,2] == 18
  1653. def test_row_add():
  1654. M = Matrix([[1,2,3],
  1655. [4,5,6],
  1656. [1,1,1]])
  1657. M.row_add(2,0,5)
  1658. assert M[0,0] == 6
  1659. assert M[1,0] == 4
  1660. assert M[0,2] == 8
  1661. def test_zip_row_op():
  1662. for cls in mutable_classes: # XXX: immutable matrices don't support row ops
  1663. M = cls.eye(3)
  1664. M.zip_row_op(1, 0, lambda v, u: v + 2*u)
  1665. assert M == cls([[1, 0, 0],
  1666. [2, 1, 0],
  1667. [0, 0, 1]])
  1668. M = cls.eye(3)*2
  1669. M[0, 1] = -1
  1670. M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
  1671. assert M == cls([[2, -1, 0],
  1672. [4, 0, 0],
  1673. [0, 0, 2]])
  1674. def test_issue_3950():
  1675. m = Matrix([1, 2, 3])
  1676. a = Matrix([1, 2, 3])
  1677. b = Matrix([2, 2, 3])
  1678. assert not (m in [])
  1679. assert not (m in [1])
  1680. assert m != 1
  1681. assert m == a
  1682. assert m != b
  1683. def test_issue_3981():
  1684. class Index1:
  1685. def __index__(self):
  1686. return 1
  1687. class Index2:
  1688. def __index__(self):
  1689. return 2
  1690. index1 = Index1()
  1691. index2 = Index2()
  1692. m = Matrix([1, 2, 3])
  1693. assert m[index2] == 3
  1694. m[index2] = 5
  1695. assert m[2] == 5
  1696. m = Matrix([[1, 2, 3], [4, 5, 6]])
  1697. assert m[index1, index2] == 6
  1698. assert m[1, index2] == 6
  1699. assert m[index1, 2] == 6
  1700. m[index1, index2] = 4
  1701. assert m[1, 2] == 4
  1702. m[1, index2] = 6
  1703. assert m[1, 2] == 6
  1704. m[index1, 2] = 8
  1705. assert m[1, 2] == 8
  1706. def test_is_upper():
  1707. a = Matrix([[1, 2, 3]])
  1708. assert a.is_upper is True
  1709. a = Matrix([[1], [2], [3]])
  1710. assert a.is_upper is False
  1711. a = zeros(4, 2)
  1712. assert a.is_upper is True
  1713. def test_is_lower():
  1714. a = Matrix([[1, 2, 3]])
  1715. assert a.is_lower is False
  1716. a = Matrix([[1], [2], [3]])
  1717. assert a.is_lower is True
  1718. def test_is_nilpotent():
  1719. a = Matrix(4, 4, [0, 2, 1, 6, 0, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 0])
  1720. assert a.is_nilpotent()
  1721. a = Matrix([[1, 0], [0, 1]])
  1722. assert not a.is_nilpotent()
  1723. a = Matrix([])
  1724. assert a.is_nilpotent()
  1725. def test_zeros_ones_fill():
  1726. n, m = 3, 5
  1727. a = zeros(n, m)
  1728. a.fill( 5 )
  1729. b = 5 * ones(n, m)
  1730. assert a == b
  1731. assert a.rows == b.rows == 3
  1732. assert a.cols == b.cols == 5
  1733. assert a.shape == b.shape == (3, 5)
  1734. assert zeros(2) == zeros(2, 2)
  1735. assert ones(2) == ones(2, 2)
  1736. assert zeros(2, 3) == Matrix(2, 3, [0]*6)
  1737. assert ones(2, 3) == Matrix(2, 3, [1]*6)
  1738. a.fill(0)
  1739. assert a == zeros(n, m)
  1740. def test_empty_zeros():
  1741. a = zeros(0)
  1742. assert a == Matrix()
  1743. a = zeros(0, 2)
  1744. assert a.rows == 0
  1745. assert a.cols == 2
  1746. a = zeros(2, 0)
  1747. assert a.rows == 2
  1748. assert a.cols == 0
  1749. def test_issue_3749():
  1750. a = Matrix([[x**2, x*y], [x*sin(y), x*cos(y)]])
  1751. assert a.diff(x) == Matrix([[2*x, y], [sin(y), cos(y)]])
  1752. assert Matrix([
  1753. [x, -x, x**2],
  1754. [exp(x), 1/x - exp(-x), x + 1/x]]).limit(x, oo) == \
  1755. Matrix([[oo, -oo, oo], [oo, 0, oo]])
  1756. assert Matrix([
  1757. [(exp(x) - 1)/x, 2*x + y*x, x**x ],
  1758. [1/x, abs(x), abs(sin(x + 1))]]).limit(x, 0) == \
  1759. Matrix([[1, 0, 1], [oo, 0, sin(1)]])
  1760. assert a.integrate(x) == Matrix([
  1761. [Rational(1, 3)*x**3, y*x**2/2],
  1762. [x**2*sin(y)/2, x**2*cos(y)/2]])
  1763. def test_inv_iszerofunc():
  1764. A = eye(4)
  1765. A.col_swap(0, 1)
  1766. for method in "GE", "LU":
  1767. assert A.inv(method=method, iszerofunc=lambda x: x == 0) == \
  1768. A.inv(method="ADJ")
  1769. def test_jacobian_metrics():
  1770. rho, phi = symbols("rho,phi")
  1771. X = Matrix([rho*cos(phi), rho*sin(phi)])
  1772. Y = Matrix([rho, phi])
  1773. J = X.jacobian(Y)
  1774. assert J == X.jacobian(Y.T)
  1775. assert J == (X.T).jacobian(Y)
  1776. assert J == (X.T).jacobian(Y.T)
  1777. g = J.T*eye(J.shape[0])*J
  1778. g = g.applyfunc(trigsimp)
  1779. assert g == Matrix([[1, 0], [0, rho**2]])
  1780. def test_jacobian2():
  1781. rho, phi = symbols("rho,phi")
  1782. X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
  1783. Y = Matrix([rho, phi])
  1784. J = Matrix([
  1785. [cos(phi), -rho*sin(phi)],
  1786. [sin(phi), rho*cos(phi)],
  1787. [ 2*rho, 0],
  1788. ])
  1789. assert X.jacobian(Y) == J
  1790. def test_issue_4564():
  1791. X = Matrix([exp(x + y + z), exp(x + y + z), exp(x + y + z)])
  1792. Y = Matrix([x, y, z])
  1793. for i in range(1, 3):
  1794. for j in range(1, 3):
  1795. X_slice = X[:i, :]
  1796. Y_slice = Y[:j, :]
  1797. J = X_slice.jacobian(Y_slice)
  1798. assert J.rows == i
  1799. assert J.cols == j
  1800. for k in range(j):
  1801. assert J[:, k] == X_slice
  1802. def test_nonvectorJacobian():
  1803. X = Matrix([[exp(x + y + z), exp(x + y + z)],
  1804. [exp(x + y + z), exp(x + y + z)]])
  1805. raises(TypeError, lambda: X.jacobian(Matrix([x, y, z])))
  1806. X = X[0, :]
  1807. Y = Matrix([[x, y], [x, z]])
  1808. raises(TypeError, lambda: X.jacobian(Y))
  1809. raises(TypeError, lambda: X.jacobian(Matrix([ [x, y], [x, z] ])))
  1810. def test_vec():
  1811. m = Matrix([[1, 3], [2, 4]])
  1812. m_vec = m.vec()
  1813. assert m_vec.cols == 1
  1814. for i in range(4):
  1815. assert m_vec[i] == i + 1
  1816. def test_vech():
  1817. m = Matrix([[1, 2], [2, 3]])
  1818. m_vech = m.vech()
  1819. assert m_vech.cols == 1
  1820. for i in range(3):
  1821. assert m_vech[i] == i + 1
  1822. m_vech = m.vech(diagonal=False)
  1823. assert m_vech[0] == 2
  1824. m = Matrix([[1, x*(x + y)], [y*x + x**2, 1]])
  1825. m_vech = m.vech(diagonal=False)
  1826. assert m_vech[0] == y*x + x**2
  1827. m = Matrix([[1, x*(x + y)], [y*x, 1]])
  1828. m_vech = m.vech(diagonal=False, check_symmetry=False)
  1829. assert m_vech[0] == y*x
  1830. raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
  1831. raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
  1832. raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
  1833. raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
  1834. def test_diag():
  1835. # mostly tested in testcommonmatrix.py
  1836. assert diag([1, 2, 3]) == Matrix([1, 2, 3])
  1837. m = [1, 2, [3]]
  1838. raises(ValueError, lambda: diag(m))
  1839. assert diag(m, strict=False) == Matrix([1, 2, 3])
  1840. def test_inv_block():
  1841. a = Matrix([[1, 2], [2, 3]])
  1842. b = Matrix([[3, x], [y, 3]])
  1843. c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
  1844. A = diag(a, b, b)
  1845. assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), b.inv())
  1846. A = diag(a, b, c)
  1847. assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), c.inv())
  1848. A = diag(a, c, b)
  1849. assert A.inv(try_block_diag=True) == diag(a.inv(), c.inv(), b.inv())
  1850. A = diag(a, a, b, a, c, a)
  1851. assert A.inv(try_block_diag=True) == diag(
  1852. a.inv(), a.inv(), b.inv(), a.inv(), c.inv(), a.inv())
  1853. assert A.inv(try_block_diag=True, method="ADJ") == diag(
  1854. a.inv(method="ADJ"), a.inv(method="ADJ"), b.inv(method="ADJ"),
  1855. a.inv(method="ADJ"), c.inv(method="ADJ"), a.inv(method="ADJ"))
  1856. def test_creation_args():
  1857. """
  1858. Check that matrix dimensions can be specified using any reasonable type
  1859. (see issue 4614).
  1860. """
  1861. raises(ValueError, lambda: zeros(3, -1))
  1862. raises(TypeError, lambda: zeros(1, 2, 3, 4))
  1863. assert zeros(int(3)) == zeros(3)
  1864. assert zeros(Integer(3)) == zeros(3)
  1865. raises(ValueError, lambda: zeros(3.))
  1866. assert eye(int(3)) == eye(3)
  1867. assert eye(Integer(3)) == eye(3)
  1868. raises(ValueError, lambda: eye(3.))
  1869. assert ones(int(3), Integer(4)) == ones(3, 4)
  1870. raises(TypeError, lambda: Matrix(5))
  1871. raises(TypeError, lambda: Matrix(1, 2))
  1872. raises(ValueError, lambda: Matrix([1, [2]]))
  1873. def test_diagonal_symmetrical():
  1874. m = Matrix(2, 2, [0, 1, 1, 0])
  1875. assert not m.is_diagonal()
  1876. assert m.is_symmetric()
  1877. assert m.is_symmetric(simplify=False)
  1878. m = Matrix(2, 2, [1, 0, 0, 1])
  1879. assert m.is_diagonal()
  1880. m = diag(1, 2, 3)
  1881. assert m.is_diagonal()
  1882. assert m.is_symmetric()
  1883. m = Matrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
  1884. assert m == diag(1, 2, 3)
  1885. m = Matrix(2, 3, zeros(2, 3))
  1886. assert not m.is_symmetric()
  1887. assert m.is_diagonal()
  1888. m = Matrix(((5, 0), (0, 6), (0, 0)))
  1889. assert m.is_diagonal()
  1890. m = Matrix(((5, 0, 0), (0, 6, 0)))
  1891. assert m.is_diagonal()
  1892. m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
  1893. assert m.is_symmetric()
  1894. assert not m.is_symmetric(simplify=False)
  1895. assert m.expand().is_symmetric(simplify=False)
  1896. def test_diagonalization():
  1897. m = Matrix([[1, 2+I], [2-I, 3]])
  1898. assert m.is_diagonalizable()
  1899. m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
  1900. assert not m.is_diagonalizable()
  1901. assert not m.is_symmetric()
  1902. raises(NonSquareMatrixError, lambda: m.diagonalize())
  1903. # diagonalizable
  1904. m = diag(1, 2, 3)
  1905. (P, D) = m.diagonalize()
  1906. assert P == eye(3)
  1907. assert D == m
  1908. m = Matrix(2, 2, [0, 1, 1, 0])
  1909. assert m.is_symmetric()
  1910. assert m.is_diagonalizable()
  1911. (P, D) = m.diagonalize()
  1912. assert P.inv() * m * P == D
  1913. m = Matrix(2, 2, [1, 0, 0, 3])
  1914. assert m.is_symmetric()
  1915. assert m.is_diagonalizable()
  1916. (P, D) = m.diagonalize()
  1917. assert P.inv() * m * P == D
  1918. assert P == eye(2)
  1919. assert D == m
  1920. m = Matrix(2, 2, [1, 1, 0, 0])
  1921. assert m.is_diagonalizable()
  1922. (P, D) = m.diagonalize()
  1923. assert P.inv() * m * P == D
  1924. m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
  1925. assert m.is_diagonalizable()
  1926. (P, D) = m.diagonalize()
  1927. assert P.inv() * m * P == D
  1928. for i in P:
  1929. assert i.as_numer_denom()[1] == 1
  1930. m = Matrix(2, 2, [1, 0, 0, 0])
  1931. assert m.is_diagonal()
  1932. assert m.is_diagonalizable()
  1933. (P, D) = m.diagonalize()
  1934. assert P.inv() * m * P == D
  1935. assert P == Matrix([[0, 1], [1, 0]])
  1936. # diagonalizable, complex only
  1937. m = Matrix(2, 2, [0, 1, -1, 0])
  1938. assert not m.is_diagonalizable(True)
  1939. raises(MatrixError, lambda: m.diagonalize(True))
  1940. assert m.is_diagonalizable()
  1941. (P, D) = m.diagonalize()
  1942. assert P.inv() * m * P == D
  1943. # not diagonalizable
  1944. m = Matrix(2, 2, [0, 1, 0, 0])
  1945. assert not m.is_diagonalizable()
  1946. raises(MatrixError, lambda: m.diagonalize())
  1947. m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4])
  1948. assert not m.is_diagonalizable()
  1949. raises(MatrixError, lambda: m.diagonalize())
  1950. # symbolic
  1951. a, b, c, d = symbols('a b c d')
  1952. m = Matrix(2, 2, [a, c, c, b])
  1953. assert m.is_symmetric()
  1954. assert m.is_diagonalizable()
  1955. def test_issue_15887():
  1956. # Mutable matrix should not use cache
  1957. a = MutableDenseMatrix([[0, 1], [1, 0]])
  1958. assert a.is_diagonalizable() is True
  1959. a[1, 0] = 0
  1960. assert a.is_diagonalizable() is False
  1961. a = MutableDenseMatrix([[0, 1], [1, 0]])
  1962. a.diagonalize()
  1963. a[1, 0] = 0
  1964. raises(MatrixError, lambda: a.diagonalize())
  1965. def test_jordan_form():
  1966. m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
  1967. raises(NonSquareMatrixError, lambda: m.jordan_form())
  1968. # diagonalizable
  1969. m = Matrix(3, 3, [7, -12, 6, 10, -19, 10, 12, -24, 13])
  1970. Jmust = Matrix(3, 3, [-1, 0, 0, 0, 1, 0, 0, 0, 1])
  1971. P, J = m.jordan_form()
  1972. assert Jmust == J
  1973. assert Jmust == m.diagonalize()[1]
  1974. # m = Matrix(3, 3, [0, 6, 3, 1, 3, 1, -2, 2, 1])
  1975. # m.jordan_form() # very long
  1976. # m.jordan_form() #
  1977. # diagonalizable, complex only
  1978. # Jordan cells
  1979. # complexity: one of eigenvalues is zero
  1980. m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
  1981. # The blocks are ordered according to the value of their eigenvalues,
  1982. # in order to make the matrix compatible with .diagonalize()
  1983. Jmust = Matrix(3, 3, [2, 1, 0, 0, 2, 0, 0, 0, 2])
  1984. P, J = m.jordan_form()
  1985. assert Jmust == J
  1986. # complexity: all of eigenvalues are equal
  1987. m = Matrix(3, 3, [2, 6, -15, 1, 1, -5, 1, 2, -6])
  1988. # Jmust = Matrix(3, 3, [-1, 0, 0, 0, -1, 1, 0, 0, -1])
  1989. # same here see 1456ff
  1990. Jmust = Matrix(3, 3, [-1, 1, 0, 0, -1, 0, 0, 0, -1])
  1991. P, J = m.jordan_form()
  1992. assert Jmust == J
  1993. # complexity: two of eigenvalues are zero
  1994. m = Matrix(3, 3, [4, -5, 2, 5, -7, 3, 6, -9, 4])
  1995. Jmust = Matrix(3, 3, [0, 1, 0, 0, 0, 0, 0, 0, 1])
  1996. P, J = m.jordan_form()
  1997. assert Jmust == J
  1998. m = Matrix(4, 4, [6, 5, -2, -3, -3, -1, 3, 3, 2, 1, -2, -3, -1, 1, 5, 5])
  1999. Jmust = Matrix(4, 4, [2, 1, 0, 0,
  2000. 0, 2, 0, 0,
  2001. 0, 0, 2, 1,
  2002. 0, 0, 0, 2]
  2003. )
  2004. P, J = m.jordan_form()
  2005. assert Jmust == J
  2006. m = Matrix(4, 4, [6, 2, -8, -6, -3, 2, 9, 6, 2, -2, -8, -6, -1, 0, 3, 4])
  2007. # Jmust = Matrix(4, 4, [2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, -2])
  2008. # same here see 1456ff
  2009. Jmust = Matrix(4, 4, [-2, 0, 0, 0,
  2010. 0, 2, 1, 0,
  2011. 0, 0, 2, 0,
  2012. 0, 0, 0, 2])
  2013. P, J = m.jordan_form()
  2014. assert Jmust == J
  2015. m = Matrix(4, 4, [5, 4, 2, 1, 0, 1, -1, -1, -1, -1, 3, 0, 1, 1, -1, 2])
  2016. assert not m.is_diagonalizable()
  2017. Jmust = Matrix(4, 4, [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 4])
  2018. P, J = m.jordan_form()
  2019. assert Jmust == J
  2020. # checking for maximum precision to remain unchanged
  2021. m = Matrix([[Float('1.0', precision=110), Float('2.0', precision=110)],
  2022. [Float('3.14159265358979323846264338327', precision=110), Float('4.0', precision=110)]])
  2023. P, J = m.jordan_form()
  2024. for term in J.values():
  2025. if isinstance(term, Float):
  2026. assert term._prec == 110
  2027. def test_jordan_form_complex_issue_9274():
  2028. A = Matrix([[ 2, 4, 1, 0],
  2029. [-4, 2, 0, 1],
  2030. [ 0, 0, 2, 4],
  2031. [ 0, 0, -4, 2]])
  2032. p = 2 - 4*I
  2033. q = 2 + 4*I
  2034. Jmust1 = Matrix([[p, 1, 0, 0],
  2035. [0, p, 0, 0],
  2036. [0, 0, q, 1],
  2037. [0, 0, 0, q]])
  2038. Jmust2 = Matrix([[q, 1, 0, 0],
  2039. [0, q, 0, 0],
  2040. [0, 0, p, 1],
  2041. [0, 0, 0, p]])
  2042. P, J = A.jordan_form()
  2043. assert J == Jmust1 or J == Jmust2
  2044. assert simplify(P*J*P.inv()) == A
  2045. def test_issue_10220():
  2046. # two non-orthogonal Jordan blocks with eigenvalue 1
  2047. M = Matrix([[1, 0, 0, 1],
  2048. [0, 1, 1, 0],
  2049. [0, 0, 1, 1],
  2050. [0, 0, 0, 1]])
  2051. P, J = M.jordan_form()
  2052. assert P == Matrix([[0, 1, 0, 1],
  2053. [1, 0, 0, 0],
  2054. [0, 1, 0, 0],
  2055. [0, 0, 1, 0]])
  2056. assert J == Matrix([
  2057. [1, 1, 0, 0],
  2058. [0, 1, 1, 0],
  2059. [0, 0, 1, 0],
  2060. [0, 0, 0, 1]])
  2061. def test_jordan_form_issue_15858():
  2062. A = Matrix([
  2063. [1, 1, 1, 0],
  2064. [-2, -1, 0, -1],
  2065. [0, 0, -1, -1],
  2066. [0, 0, 2, 1]])
  2067. (P, J) = A.jordan_form()
  2068. assert P.expand() == Matrix([
  2069. [ -I, -I/2, I, I/2],
  2070. [-1 + I, 0, -1 - I, 0],
  2071. [ 0, -S(1)/2 - I/2, 0, -S(1)/2 + I/2],
  2072. [ 0, 1, 0, 1]])
  2073. assert J == Matrix([
  2074. [-I, 1, 0, 0],
  2075. [0, -I, 0, 0],
  2076. [0, 0, I, 1],
  2077. [0, 0, 0, I]])
  2078. def test_Matrix_berkowitz_charpoly():
  2079. UA, K_i, K_w = symbols('UA K_i K_w')
  2080. A = Matrix([[-K_i - UA + K_i**2/(K_i + K_w), K_i*K_w/(K_i + K_w)],
  2081. [ K_i*K_w/(K_i + K_w), -K_w + K_w**2/(K_i + K_w)]])
  2082. charpoly = A.charpoly(x)
  2083. assert charpoly == \
  2084. Poly(x**2 + (K_i*UA + K_w*UA + 2*K_i*K_w)/(K_i + K_w)*x +
  2085. K_i*K_w*UA/(K_i + K_w), x, domain='ZZ(K_i,K_w,UA)')
  2086. assert type(charpoly) is PurePoly
  2087. A = Matrix([[1, 3], [2, 0]])
  2088. assert A.charpoly() == A.charpoly(x) == PurePoly(x**2 - x - 6)
  2089. A = Matrix([[1, 2], [x, 0]])
  2090. p = A.charpoly(x)
  2091. assert p.gen != x
  2092. assert p.as_expr().subs(p.gen, x) == x**2 - 3*x
  2093. def test_exp_jordan_block():
  2094. l = Symbol('lamda')
  2095. m = Matrix.jordan_block(1, l)
  2096. assert m._eval_matrix_exp_jblock() == Matrix([[exp(l)]])
  2097. m = Matrix.jordan_block(3, l)
  2098. assert m._eval_matrix_exp_jblock() == \
  2099. Matrix([
  2100. [exp(l), exp(l), exp(l)/2],
  2101. [0, exp(l), exp(l)],
  2102. [0, 0, exp(l)]])
  2103. def test_exp():
  2104. m = Matrix([[3, 4], [0, -2]])
  2105. m_exp = Matrix([[exp(3), -4*exp(-2)/5 + 4*exp(3)/5], [0, exp(-2)]])
  2106. assert m.exp() == m_exp
  2107. assert exp(m) == m_exp
  2108. m = Matrix([[1, 0], [0, 1]])
  2109. assert m.exp() == Matrix([[E, 0], [0, E]])
  2110. assert exp(m) == Matrix([[E, 0], [0, E]])
  2111. m = Matrix([[1, -1], [1, 1]])
  2112. assert m.exp() == Matrix([[E*cos(1), -E*sin(1)], [E*sin(1), E*cos(1)]])
  2113. def test_log():
  2114. l = Symbol('lamda')
  2115. m = Matrix.jordan_block(1, l)
  2116. assert m._eval_matrix_log_jblock() == Matrix([[log(l)]])
  2117. m = Matrix.jordan_block(4, l)
  2118. assert m._eval_matrix_log_jblock() == \
  2119. Matrix(
  2120. [
  2121. [log(l), 1/l, -1/(2*l**2), 1/(3*l**3)],
  2122. [0, log(l), 1/l, -1/(2*l**2)],
  2123. [0, 0, log(l), 1/l],
  2124. [0, 0, 0, log(l)]
  2125. ]
  2126. )
  2127. m = Matrix(
  2128. [[0, 0, 1],
  2129. [0, 0, 0],
  2130. [-1, 0, 0]]
  2131. )
  2132. raises(MatrixError, lambda: m.log())
  2133. def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero1():
  2134. # Test if matrices._find_reasonable_pivot_naive()
  2135. # finds a guaranteed non-zero pivot when the
  2136. # some of the candidate pivots are symbolic expressions.
  2137. # Keyword argument: simpfunc=None indicates that no simplifications
  2138. # should be performed during the search.
  2139. x = Symbol('x')
  2140. column = Matrix(3, 1, [x, cos(x)**2 + sin(x)**2, S.Half])
  2141. pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
  2142. _find_reasonable_pivot_naive(column)
  2143. assert pivot_val == S.Half
  2144. def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero2():
  2145. # Test if matrices._find_reasonable_pivot_naive()
  2146. # finds a guaranteed non-zero pivot when the
  2147. # some of the candidate pivots are symbolic expressions.
  2148. # Keyword argument: simpfunc=_simplify indicates that the search
  2149. # should attempt to simplify candidate pivots.
  2150. x = Symbol('x')
  2151. column = Matrix(3, 1,
  2152. [x,
  2153. cos(x)**2+sin(x)**2+x**2,
  2154. cos(x)**2+sin(x)**2])
  2155. pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
  2156. _find_reasonable_pivot_naive(column, simpfunc=_simplify)
  2157. assert pivot_val == 1
  2158. def test_find_reasonable_pivot_naive_simplifies():
  2159. # Test if matrices._find_reasonable_pivot_naive()
  2160. # simplifies candidate pivots, and reports
  2161. # their offsets correctly.
  2162. x = Symbol('x')
  2163. column = Matrix(3, 1,
  2164. [x,
  2165. cos(x)**2+sin(x)**2+x,
  2166. cos(x)**2+sin(x)**2])
  2167. pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
  2168. _find_reasonable_pivot_naive(column, simpfunc=_simplify)
  2169. assert len(simplified) == 2
  2170. assert simplified[0][0] == 1
  2171. assert simplified[0][1] == 1+x
  2172. assert simplified[1][0] == 2
  2173. assert simplified[1][1] == 1
  2174. def test_errors():
  2175. raises(ValueError, lambda: Matrix([[1, 2], [1]]))
  2176. raises(IndexError, lambda: Matrix([[1, 2]])[1.2, 5])
  2177. raises(IndexError, lambda: Matrix([[1, 2]])[1, 5.2])
  2178. raises(ValueError, lambda: randMatrix(3, c=4, symmetric=True))
  2179. raises(ValueError, lambda: Matrix([1, 2]).reshape(4, 6))
  2180. raises(ShapeError,
  2181. lambda: Matrix([[1, 2], [3, 4]]).copyin_matrix([1, 0], Matrix([1, 2])))
  2182. raises(TypeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_list([0,
  2183. 1], set()))
  2184. raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [2, 3, 0]]).inv())
  2185. raises(ShapeError,
  2186. lambda: Matrix(1, 2, [1, 2]).row_join(Matrix([[1, 2], [3, 4]])))
  2187. raises(
  2188. ShapeError, lambda: Matrix([1, 2]).col_join(Matrix([[1, 2], [3, 4]])))
  2189. raises(ShapeError, lambda: Matrix([1]).row_insert(1, Matrix([[1,
  2190. 2], [3, 4]])))
  2191. raises(ShapeError, lambda: Matrix([1]).col_insert(1, Matrix([[1,
  2192. 2], [3, 4]])))
  2193. raises(NonSquareMatrixError, lambda: Matrix([1, 2]).trace())
  2194. raises(TypeError, lambda: Matrix([1]).applyfunc(1))
  2195. raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor(4, 5))
  2196. raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor_submatrix(4, 5))
  2197. raises(TypeError, lambda: Matrix([1, 2, 3]).cross(1))
  2198. raises(TypeError, lambda: Matrix([1, 2, 3]).dot(1))
  2199. raises(ShapeError, lambda: Matrix([1, 2, 3]).dot(Matrix([1, 2])))
  2200. raises(ShapeError, lambda: Matrix([1, 2]).dot([]))
  2201. raises(TypeError, lambda: Matrix([1, 2]).dot('a'))
  2202. raises(ShapeError, lambda: Matrix([1, 2]).dot([1, 2, 3]))
  2203. raises(NonSquareMatrixError, lambda: Matrix([1, 2, 3]).exp())
  2204. raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).normalized())
  2205. raises(ValueError, lambda: Matrix([1, 2]).inv(method='not a method'))
  2206. raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_GE())
  2207. raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_GE())
  2208. raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_ADJ())
  2209. raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_ADJ())
  2210. raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_LU())
  2211. raises(NonSquareMatrixError, lambda: Matrix([1, 2]).is_nilpotent())
  2212. raises(NonSquareMatrixError, lambda: Matrix([1, 2]).det())
  2213. raises(ValueError,
  2214. lambda: Matrix([[1, 2], [3, 4]]).det(method='Not a real method'))
  2215. raises(ValueError,
  2216. lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
  2217. [9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc="Not function"))
  2218. raises(ValueError,
  2219. lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
  2220. [9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc=False))
  2221. raises(ValueError,
  2222. lambda: hessian(Matrix([[1, 2], [3, 4]]), Matrix([[1, 2], [2, 1]])))
  2223. raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), []))
  2224. raises(ValueError, lambda: hessian(Symbol('x')**2, 'a'))
  2225. raises(IndexError, lambda: eye(3)[5, 2])
  2226. raises(IndexError, lambda: eye(3)[2, 5])
  2227. M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
  2228. raises(ValueError, lambda: M.det('method=LU_decomposition()'))
  2229. V = Matrix([[10, 10, 10]])
  2230. M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2231. raises(ValueError, lambda: M.row_insert(4.7, V))
  2232. M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2233. raises(ValueError, lambda: M.col_insert(-4.2, V))
  2234. def test_len():
  2235. assert len(Matrix()) == 0
  2236. assert len(Matrix([[1, 2]])) == len(Matrix([[1], [2]])) == 2
  2237. assert len(Matrix(0, 2, lambda i, j: 0)) == \
  2238. len(Matrix(2, 0, lambda i, j: 0)) == 0
  2239. assert len(Matrix([[0, 1, 2], [3, 4, 5]])) == 6
  2240. assert Matrix([1]) == Matrix([[1]])
  2241. assert not Matrix()
  2242. assert Matrix() == Matrix([])
  2243. def test_integrate():
  2244. A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2)))
  2245. assert A.integrate(x) == \
  2246. Matrix(((x, 4*x, x**2/2), (x*y, 2*x, 4*x), (10*x, 5*x, x**3/3)))
  2247. assert A.integrate(y) == \
  2248. Matrix(((y, 4*y, x*y), (y**2/2, 2*y, 4*y), (10*y, 5*y, y*x**2)))
  2249. m = Matrix(2, 1, [x, y])
  2250. assert m.integrate(x) == Matrix(2, 1, [x**2/2, y*x])
  2251. def test_diff():
  2252. A = MutableDenseMatrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
  2253. assert isinstance(A.diff(x), type(A))
  2254. assert A.diff(x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
  2255. assert A.diff(y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
  2256. assert diff(A, x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
  2257. assert diff(A, y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
  2258. A_imm = A.as_immutable()
  2259. assert isinstance(A_imm.diff(x), type(A_imm))
  2260. assert A_imm.diff(x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
  2261. assert A_imm.diff(y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
  2262. assert diff(A_imm, x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
  2263. assert diff(A_imm, y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
  2264. assert A.diff(x, evaluate=False) == ArrayDerivative(A, x, evaluate=False)
  2265. assert diff(A, x, evaluate=False) == ArrayDerivative(A, x, evaluate=False)
  2266. def test_diff_by_matrix():
  2267. # Derive matrix by matrix:
  2268. A = MutableDenseMatrix([[x, y], [z, t]])
  2269. assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
  2270. assert diff(A, A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
  2271. A_imm = A.as_immutable()
  2272. assert A_imm.diff(A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
  2273. assert diff(A_imm, A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
  2274. # Derive a constant matrix:
  2275. assert A.diff(a) == MutableDenseMatrix([[0, 0], [0, 0]])
  2276. B = ImmutableDenseMatrix([a, b])
  2277. assert A.diff(B) == Array.zeros(2, 1, 2, 2)
  2278. assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
  2279. # Test diff with tuples:
  2280. dB = B.diff([[a, b]])
  2281. assert dB.shape == (2, 2, 1)
  2282. assert dB == Array([[[1], [0]], [[0], [1]]])
  2283. f = Function("f")
  2284. fxyz = f(x, y, z)
  2285. assert fxyz.diff([[x, y, z]]) == Array([fxyz.diff(x), fxyz.diff(y), fxyz.diff(z)])
  2286. assert fxyz.diff(([x, y, z], 2)) == Array([
  2287. [fxyz.diff(x, 2), fxyz.diff(x, y), fxyz.diff(x, z)],
  2288. [fxyz.diff(x, y), fxyz.diff(y, 2), fxyz.diff(y, z)],
  2289. [fxyz.diff(x, z), fxyz.diff(z, y), fxyz.diff(z, 2)],
  2290. ])
  2291. expr = sin(x)*exp(y)
  2292. assert expr.diff([[x, y]]) == Array([cos(x)*exp(y), sin(x)*exp(y)])
  2293. assert expr.diff(y, ((x, y),)) == Array([cos(x)*exp(y), sin(x)*exp(y)])
  2294. assert expr.diff(x, ((x, y),)) == Array([-sin(x)*exp(y), cos(x)*exp(y)])
  2295. assert expr.diff(((y, x),), [[x, y]]) == Array([[cos(x)*exp(y), -sin(x)*exp(y)], [sin(x)*exp(y), cos(x)*exp(y)]])
  2296. # Test different notations:
  2297. assert fxyz.diff(x).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[0, 1, 0]
  2298. assert fxyz.diff(z).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[2, 1, 0]
  2299. assert fxyz.diff([[x, y, z]], ((z, y, x),)) == Array([[fxyz.diff(i).diff(j) for i in (x, y, z)] for j in (z, y, x)])
  2300. # Test scalar derived by matrix remains matrix:
  2301. res = x.diff(Matrix([[x, y]]))
  2302. assert isinstance(res, ImmutableDenseMatrix)
  2303. assert res == Matrix([[1, 0]])
  2304. res = (x**3).diff(Matrix([[x, y]]))
  2305. assert isinstance(res, ImmutableDenseMatrix)
  2306. assert res == Matrix([[3*x**2, 0]])
  2307. def test_getattr():
  2308. A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
  2309. raises(AttributeError, lambda: A.nonexistantattribute)
  2310. assert getattr(A, 'diff')(x) == Matrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
  2311. def test_hessenberg():
  2312. A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
  2313. assert A.is_upper_hessenberg
  2314. A = A.T
  2315. assert A.is_lower_hessenberg
  2316. A[0, -1] = 1
  2317. assert A.is_lower_hessenberg is False
  2318. A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
  2319. assert not A.is_upper_hessenberg
  2320. A = zeros(5, 2)
  2321. assert A.is_upper_hessenberg
  2322. def test_cholesky():
  2323. raises(NonSquareMatrixError, lambda: Matrix((1, 2)).cholesky())
  2324. raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky())
  2325. raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).cholesky())
  2326. raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).cholesky())
  2327. raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky(hermitian=False))
  2328. assert Matrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
  2329. [sqrt(5 + I), 0], [0, 1]])
  2330. A = Matrix(((1, 5), (5, 1)))
  2331. L = A.cholesky(hermitian=False)
  2332. assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
  2333. assert L*L.T == A
  2334. A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
  2335. L = A.cholesky()
  2336. assert L * L.T == A
  2337. assert L.is_lower
  2338. assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
  2339. A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
  2340. assert A.cholesky().expand() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
  2341. raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).cholesky())
  2342. raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky())
  2343. raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).cholesky())
  2344. raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).cholesky())
  2345. raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky(hermitian=False))
  2346. assert SparseMatrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
  2347. [sqrt(5 + I), 0], [0, 1]])
  2348. A = SparseMatrix(((1, 5), (5, 1)))
  2349. L = A.cholesky(hermitian=False)
  2350. assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
  2351. assert L*L.T == A
  2352. A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
  2353. L = A.cholesky()
  2354. assert L * L.T == A
  2355. assert L.is_lower
  2356. assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
  2357. A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
  2358. assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
  2359. def test_matrix_norm():
  2360. # Vector Tests
  2361. # Test columns and symbols
  2362. x = Symbol('x', real=True)
  2363. v = Matrix([cos(x), sin(x)])
  2364. assert trigsimp(v.norm(2)) == 1
  2365. assert v.norm(10) == Pow(cos(x)**10 + sin(x)**10, Rational(1, 10))
  2366. # Test Rows
  2367. A = Matrix([[5, Rational(3, 2)]])
  2368. assert A.norm() == Pow(25 + Rational(9, 4), S.Half)
  2369. assert A.norm(oo) == max(A)
  2370. assert A.norm(-oo) == min(A)
  2371. # Matrix Tests
  2372. # Intuitive test
  2373. A = Matrix([[1, 1], [1, 1]])
  2374. assert A.norm(2) == 2
  2375. assert A.norm(-2) == 0
  2376. assert A.norm('frobenius') == 2
  2377. assert eye(10).norm(2) == eye(10).norm(-2) == 1
  2378. assert A.norm(oo) == 2
  2379. # Test with Symbols and more complex entries
  2380. A = Matrix([[3, y, y], [x, S.Half, -pi]])
  2381. assert (A.norm('fro')
  2382. == sqrt(Rational(37, 4) + 2*abs(y)**2 + pi**2 + x**2))
  2383. # Check non-square
  2384. A = Matrix([[1, 2, -3], [4, 5, Rational(13, 2)]])
  2385. assert A.norm(2) == sqrt(Rational(389, 8) + sqrt(78665)/8)
  2386. assert A.norm(-2) is S.Zero
  2387. assert A.norm('frobenius') == sqrt(389)/2
  2388. # Test properties of matrix norms
  2389. # https://en.wikipedia.org/wiki/Matrix_norm#Definition
  2390. # Two matrices
  2391. A = Matrix([[1, 2], [3, 4]])
  2392. B = Matrix([[5, 5], [-2, 2]])
  2393. C = Matrix([[0, -I], [I, 0]])
  2394. D = Matrix([[1, 0], [0, -1]])
  2395. L = [A, B, C, D]
  2396. alpha = Symbol('alpha', real=True)
  2397. for order in ['fro', 2, -2]:
  2398. # Zero Check
  2399. assert zeros(3).norm(order) is S.Zero
  2400. # Check Triangle Inequality for all Pairs of Matrices
  2401. for X in L:
  2402. for Y in L:
  2403. dif = (X.norm(order) + Y.norm(order) -
  2404. (X + Y).norm(order))
  2405. assert (dif >= 0)
  2406. # Scalar multiplication linearity
  2407. for M in [A, B, C, D]:
  2408. dif = simplify((alpha*M).norm(order) -
  2409. abs(alpha) * M.norm(order))
  2410. assert dif == 0
  2411. # Test Properties of Vector Norms
  2412. # https://en.wikipedia.org/wiki/Vector_norm
  2413. # Two column vectors
  2414. a = Matrix([1, 1 - 1*I, -3])
  2415. b = Matrix([S.Half, 1*I, 1])
  2416. c = Matrix([-1, -1, -1])
  2417. d = Matrix([3, 2, I])
  2418. e = Matrix([Integer(1e2), Rational(1, 1e2), 1])
  2419. L = [a, b, c, d, e]
  2420. alpha = Symbol('alpha', real=True)
  2421. for order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity, pi]:
  2422. # Zero Check
  2423. if order > 0:
  2424. assert Matrix([0, 0, 0]).norm(order) is S.Zero
  2425. # Triangle inequality on all pairs
  2426. if order >= 1: # Triangle InEq holds only for these norms
  2427. for X in L:
  2428. for Y in L:
  2429. dif = (X.norm(order) + Y.norm(order) -
  2430. (X + Y).norm(order))
  2431. assert simplify(dif >= 0) is S.true
  2432. # Linear to scalar multiplication
  2433. if order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity]:
  2434. for X in L:
  2435. dif = simplify((alpha*X).norm(order) -
  2436. (abs(alpha) * X.norm(order)))
  2437. assert dif == 0
  2438. # ord=1
  2439. M = Matrix(3, 3, [1, 3, 0, -2, -1, 0, 3, 9, 6])
  2440. assert M.norm(1) == 13
  2441. def test_condition_number():
  2442. x = Symbol('x', real=True)
  2443. A = eye(3)
  2444. A[0, 0] = 10
  2445. A[2, 2] = Rational(1, 10)
  2446. assert A.condition_number() == 100
  2447. A[1, 1] = x
  2448. assert A.condition_number() == Max(10, Abs(x)) / Min(Rational(1, 10), Abs(x))
  2449. M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]])
  2450. Mc = M.condition_number()
  2451. assert all(Float(1.).epsilon_eq(Mc.subs(x, val).evalf()) for val in
  2452. [Rational(1, 5), S.Half, Rational(1, 10), pi/2, pi, pi*Rational(7, 4) ])
  2453. #issue 10782
  2454. assert Matrix([]).condition_number() == 0
  2455. def test_equality():
  2456. A = Matrix(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
  2457. B = Matrix(((9, 8, 7), (6, 5, 4), (3, 2, 1)))
  2458. assert A == A[:, :]
  2459. assert not A != A[:, :]
  2460. assert not A == B
  2461. assert A != B
  2462. assert A != 10
  2463. assert not A == 10
  2464. # A SparseMatrix can be equal to a Matrix
  2465. C = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
  2466. D = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
  2467. assert C == D
  2468. assert not C != D
  2469. def test_normalized():
  2470. assert Matrix([3, 4]).normalized() == \
  2471. Matrix([Rational(3, 5), Rational(4, 5)])
  2472. # Zero vector trivial cases
  2473. assert Matrix([0, 0, 0]).normalized() == Matrix([0, 0, 0])
  2474. # Machine precision error truncation trivial cases
  2475. m = Matrix([0,0,1.e-100])
  2476. assert m.normalized(
  2477. iszerofunc=lambda x: x.evalf(n=10, chop=True).is_zero
  2478. ) == Matrix([0, 0, 0])
  2479. def test_print_nonzero():
  2480. assert capture(lambda: eye(3).print_nonzero()) == \
  2481. '[X ]\n[ X ]\n[ X]\n'
  2482. assert capture(lambda: eye(3).print_nonzero('.')) == \
  2483. '[. ]\n[ . ]\n[ .]\n'
  2484. def test_zeros_eye():
  2485. assert Matrix.eye(3) == eye(3)
  2486. assert Matrix.zeros(3) == zeros(3)
  2487. assert ones(3, 4) == Matrix(3, 4, [1]*12)
  2488. i = Matrix([[1, 0], [0, 1]])
  2489. z = Matrix([[0, 0], [0, 0]])
  2490. for cls in all_classes:
  2491. m = cls.eye(2)
  2492. assert i == m # but m == i will fail if m is immutable
  2493. assert i == eye(2, cls=cls)
  2494. assert type(m) == cls
  2495. m = cls.zeros(2)
  2496. assert z == m
  2497. assert z == zeros(2, cls=cls)
  2498. assert type(m) == cls
  2499. def test_is_zero():
  2500. assert Matrix().is_zero_matrix
  2501. assert Matrix([[0, 0], [0, 0]]).is_zero_matrix
  2502. assert zeros(3, 4).is_zero_matrix
  2503. assert not eye(3).is_zero_matrix
  2504. assert Matrix([[x, 0], [0, 0]]).is_zero_matrix == None
  2505. assert SparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
  2506. assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
  2507. assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
  2508. assert Matrix([[x, 1], [0, 0]]).is_zero_matrix == False
  2509. a = Symbol('a', nonzero=True)
  2510. assert Matrix([[a, 0], [0, 0]]).is_zero_matrix == False
  2511. def test_rotation_matrices():
  2512. # This tests the rotation matrices by rotating about an axis and back.
  2513. theta = pi/3
  2514. r3_plus = rot_axis3(theta)
  2515. r3_minus = rot_axis3(-theta)
  2516. r2_plus = rot_axis2(theta)
  2517. r2_minus = rot_axis2(-theta)
  2518. r1_plus = rot_axis1(theta)
  2519. r1_minus = rot_axis1(-theta)
  2520. assert r3_minus*r3_plus*eye(3) == eye(3)
  2521. assert r2_minus*r2_plus*eye(3) == eye(3)
  2522. assert r1_minus*r1_plus*eye(3) == eye(3)
  2523. # Check the correctness of the trace of the rotation matrix
  2524. assert r1_plus.trace() == 1 + 2*cos(theta)
  2525. assert r2_plus.trace() == 1 + 2*cos(theta)
  2526. assert r3_plus.trace() == 1 + 2*cos(theta)
  2527. # Check that a rotation with zero angle doesn't change anything.
  2528. assert rot_axis1(0) == eye(3)
  2529. assert rot_axis2(0) == eye(3)
  2530. assert rot_axis3(0) == eye(3)
  2531. # Check left-hand convention
  2532. # see Issue #24529
  2533. q1 = Quaternion.from_axis_angle([1, 0, 0], pi / 2)
  2534. q2 = Quaternion.from_axis_angle([0, 1, 0], pi / 2)
  2535. q3 = Quaternion.from_axis_angle([0, 0, 1], pi / 2)
  2536. assert rot_axis1(- pi / 2) == q1.to_rotation_matrix()
  2537. assert rot_axis2(- pi / 2) == q2.to_rotation_matrix()
  2538. assert rot_axis3(- pi / 2) == q3.to_rotation_matrix()
  2539. # Check right-hand convention
  2540. assert rot_ccw_axis1(+ pi / 2) == q1.to_rotation_matrix()
  2541. assert rot_ccw_axis2(+ pi / 2) == q2.to_rotation_matrix()
  2542. assert rot_ccw_axis3(+ pi / 2) == q3.to_rotation_matrix()
  2543. def test_DeferredVector():
  2544. assert str(DeferredVector("vector")[4]) == "vector[4]"
  2545. assert sympify(DeferredVector("d")) == DeferredVector("d")
  2546. raises(IndexError, lambda: DeferredVector("d")[-1])
  2547. assert str(DeferredVector("d")) == "d"
  2548. assert repr(DeferredVector("test")) == "DeferredVector('test')"
  2549. def test_DeferredVector_not_iterable():
  2550. assert not iterable(DeferredVector('X'))
  2551. def test_DeferredVector_Matrix():
  2552. raises(TypeError, lambda: Matrix(DeferredVector("V")))
  2553. def test_GramSchmidt():
  2554. R = Rational
  2555. m1 = Matrix(1, 2, [1, 2])
  2556. m2 = Matrix(1, 2, [2, 3])
  2557. assert GramSchmidt([m1, m2]) == \
  2558. [Matrix(1, 2, [1, 2]), Matrix(1, 2, [R(2)/5, R(-1)/5])]
  2559. assert GramSchmidt([m1.T, m2.T]) == \
  2560. [Matrix(2, 1, [1, 2]), Matrix(2, 1, [R(2)/5, R(-1)/5])]
  2561. # from wikipedia
  2562. assert GramSchmidt([Matrix([3, 1]), Matrix([2, 2])], True) == [
  2563. Matrix([3*sqrt(10)/10, sqrt(10)/10]),
  2564. Matrix([-sqrt(10)/10, 3*sqrt(10)/10])]
  2565. # https://github.com/sympy/sympy/issues/9488
  2566. L = FiniteSet(Matrix([1]))
  2567. assert GramSchmidt(L) == [Matrix([[1]])]
  2568. def test_casoratian():
  2569. assert casoratian([1, 2, 3, 4], 1) == 0
  2570. assert casoratian([1, 2, 3, 4], 1, zero=False) == 0
  2571. def test_zero_dimension_multiply():
  2572. assert (Matrix()*zeros(0, 3)).shape == (0, 3)
  2573. assert zeros(3, 0)*zeros(0, 3) == zeros(3, 3)
  2574. assert zeros(0, 3)*zeros(3, 0) == Matrix()
  2575. def test_slice_issue_2884():
  2576. m = Matrix(2, 2, range(4))
  2577. assert m[1, :] == Matrix([[2, 3]])
  2578. assert m[-1, :] == Matrix([[2, 3]])
  2579. assert m[:, 1] == Matrix([[1, 3]]).T
  2580. assert m[:, -1] == Matrix([[1, 3]]).T
  2581. raises(IndexError, lambda: m[2, :])
  2582. raises(IndexError, lambda: m[2, 2])
  2583. def test_slice_issue_3401():
  2584. assert zeros(0, 3)[:, -1].shape == (0, 1)
  2585. assert zeros(3, 0)[0, :] == Matrix(1, 0, [])
  2586. def test_copyin():
  2587. s = zeros(3, 3)
  2588. s[3] = 1
  2589. assert s[:, 0] == Matrix([0, 1, 0])
  2590. assert s[3] == 1
  2591. assert s[3: 4] == [1]
  2592. s[1, 1] = 42
  2593. assert s[1, 1] == 42
  2594. assert s[1, 1:] == Matrix([[42, 0]])
  2595. s[1, 1:] = Matrix([[5, 6]])
  2596. assert s[1, :] == Matrix([[1, 5, 6]])
  2597. s[1, 1:] = [[42, 43]]
  2598. assert s[1, :] == Matrix([[1, 42, 43]])
  2599. s[0, 0] = 17
  2600. assert s[:, :1] == Matrix([17, 1, 0])
  2601. s[0, 0] = [1, 1, 1]
  2602. assert s[:, 0] == Matrix([1, 1, 1])
  2603. s[0, 0] = Matrix([1, 1, 1])
  2604. assert s[:, 0] == Matrix([1, 1, 1])
  2605. s[0, 0] = SparseMatrix([1, 1, 1])
  2606. assert s[:, 0] == Matrix([1, 1, 1])
  2607. def test_invertible_check():
  2608. # sometimes a singular matrix will have a pivot vector shorter than
  2609. # the number of rows in a matrix...
  2610. assert Matrix([[1, 2], [1, 2]]).rref() == (Matrix([[1, 2], [0, 0]]), (0,))
  2611. raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inv())
  2612. m = Matrix([
  2613. [-1, -1, 0],
  2614. [ x, 1, 1],
  2615. [ 1, x, -1],
  2616. ])
  2617. assert len(m.rref()[1]) != m.rows
  2618. # in addition, unless simplify=True in the call to rref, the identity
  2619. # matrix will be returned even though m is not invertible
  2620. assert m.rref()[0] != eye(3)
  2621. assert m.rref(simplify=signsimp)[0] != eye(3)
  2622. raises(ValueError, lambda: m.inv(method="ADJ"))
  2623. raises(ValueError, lambda: m.inv(method="GE"))
  2624. raises(ValueError, lambda: m.inv(method="LU"))
  2625. def test_issue_3959():
  2626. x, y = symbols('x, y')
  2627. e = x*y
  2628. assert e.subs(x, Matrix([3, 5, 3])) == Matrix([3, 5, 3])*y
  2629. def test_issue_5964():
  2630. assert str(Matrix([[1, 2], [3, 4]])) == 'Matrix([[1, 2], [3, 4]])'
  2631. def test_issue_7604():
  2632. x, y = symbols("x y")
  2633. assert sstr(Matrix([[x, 2*y], [y**2, x + 3]])) == \
  2634. 'Matrix([\n[ x, 2*y],\n[y**2, x + 3]])'
  2635. def test_is_Identity():
  2636. assert eye(3).is_Identity
  2637. assert eye(3).as_immutable().is_Identity
  2638. assert not zeros(3).is_Identity
  2639. assert not ones(3).is_Identity
  2640. # issue 6242
  2641. assert not Matrix([[1, 0, 0]]).is_Identity
  2642. # issue 8854
  2643. assert SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1}).is_Identity
  2644. assert not SparseMatrix(2,3, range(6)).is_Identity
  2645. assert not SparseMatrix(3,3, {(0,0):1, (1,1):1}).is_Identity
  2646. assert not SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1, (0,1):2, (0,2):3}).is_Identity
  2647. def test_dot():
  2648. assert ones(1, 3).dot(ones(3, 1)) == 3
  2649. assert ones(1, 3).dot([1, 1, 1]) == 3
  2650. assert Matrix([1, 2, 3]).dot(Matrix([1, 2, 3])) == 14
  2651. assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I])) == -5 + I
  2652. assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=False) == -5 + I
  2653. assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True) == 13 + I
  2654. assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True, conjugate_convention="physics") == 13 - I
  2655. assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="right") == 4 + 8*I
  2656. assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="left") == 4 - 8*I
  2657. assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), hermitian=False, conjugate_convention="left") == -5
  2658. assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), conjugate_convention="left") == 5
  2659. raises(ValueError, lambda: Matrix([1, 2]).dot(Matrix([3, 4]), hermitian=True, conjugate_convention="test"))
  2660. def test_dual():
  2661. B_x, B_y, B_z, E_x, E_y, E_z = symbols(
  2662. 'B_x B_y B_z E_x E_y E_z', real=True)
  2663. F = Matrix((
  2664. ( 0, E_x, E_y, E_z),
  2665. (-E_x, 0, B_z, -B_y),
  2666. (-E_y, -B_z, 0, B_x),
  2667. (-E_z, B_y, -B_x, 0)
  2668. ))
  2669. Fd = Matrix((
  2670. ( 0, -B_x, -B_y, -B_z),
  2671. (B_x, 0, E_z, -E_y),
  2672. (B_y, -E_z, 0, E_x),
  2673. (B_z, E_y, -E_x, 0)
  2674. ))
  2675. assert F.dual().equals(Fd)
  2676. assert eye(3).dual().equals(zeros(3))
  2677. assert F.dual().dual().equals(-F)
  2678. def test_anti_symmetric():
  2679. assert Matrix([1, 2]).is_anti_symmetric() is False
  2680. m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
  2681. assert m.is_anti_symmetric() is True
  2682. assert m.is_anti_symmetric(simplify=False) is None
  2683. assert m.is_anti_symmetric(simplify=lambda x: x) is None
  2684. # tweak to fail
  2685. m[2, 1] = -m[2, 1]
  2686. assert m.is_anti_symmetric() is None
  2687. # untweak
  2688. m[2, 1] = -m[2, 1]
  2689. m = m.expand()
  2690. assert m.is_anti_symmetric(simplify=False) is True
  2691. m[0, 0] = 1
  2692. assert m.is_anti_symmetric() is False
  2693. def test_normalize_sort_diogonalization():
  2694. A = Matrix(((1, 2), (2, 1)))
  2695. P, Q = A.diagonalize(normalize=True)
  2696. assert P*P.T == P.T*P == eye(P.cols)
  2697. P, Q = A.diagonalize(normalize=True, sort=True)
  2698. assert P*P.T == P.T*P == eye(P.cols)
  2699. assert P*Q*P.inv() == A
  2700. def test_issue_5321():
  2701. raises(ValueError, lambda: Matrix([[1, 2, 3], Matrix(0, 1, [])]))
  2702. def test_issue_5320():
  2703. assert Matrix.hstack(eye(2), 2*eye(2)) == Matrix([
  2704. [1, 0, 2, 0],
  2705. [0, 1, 0, 2]
  2706. ])
  2707. assert Matrix.vstack(eye(2), 2*eye(2)) == Matrix([
  2708. [1, 0],
  2709. [0, 1],
  2710. [2, 0],
  2711. [0, 2]
  2712. ])
  2713. cls = SparseMatrix
  2714. assert cls.hstack(cls(eye(2)), cls(2*eye(2))) == Matrix([
  2715. [1, 0, 2, 0],
  2716. [0, 1, 0, 2]
  2717. ])
  2718. def test_issue_11944():
  2719. A = Matrix([[1]])
  2720. AIm = sympify(A)
  2721. assert Matrix.hstack(AIm, A) == Matrix([[1, 1]])
  2722. assert Matrix.vstack(AIm, A) == Matrix([[1], [1]])
  2723. def test_cross():
  2724. a = [1, 2, 3]
  2725. b = [3, 4, 5]
  2726. col = Matrix([-2, 4, -2])
  2727. row = col.T
  2728. def test(M, ans):
  2729. assert ans == M
  2730. assert type(M) == cls
  2731. for cls in all_classes:
  2732. A = cls(a)
  2733. B = cls(b)
  2734. test(A.cross(B), col)
  2735. test(A.cross(B.T), col)
  2736. test(A.T.cross(B.T), row)
  2737. test(A.T.cross(B), row)
  2738. raises(ShapeError, lambda:
  2739. Matrix(1, 2, [1, 1]).cross(Matrix(1, 2, [1, 1])))
  2740. def test_hat_vee():
  2741. v1 = Matrix([x, y, z])
  2742. v2 = Matrix([a, b, c])
  2743. assert v1.hat() * v2 == v1.cross(v2)
  2744. assert v1.hat().is_anti_symmetric()
  2745. assert v1.hat().vee() == v1
  2746. def test_hash():
  2747. for cls in immutable_classes:
  2748. s = {cls.eye(1), cls.eye(1)}
  2749. assert len(s) == 1 and s.pop() == cls.eye(1)
  2750. # issue 3979
  2751. for cls in mutable_classes:
  2752. assert not isinstance(cls.eye(1), Hashable)
  2753. def test_adjoint():
  2754. dat = [[0, I], [1, 0]]
  2755. ans = Matrix([[0, 1], [-I, 0]])
  2756. for cls in all_classes:
  2757. assert ans == cls(dat).adjoint()
  2758. def test_atoms():
  2759. m = Matrix([[1, 2], [x, 1 - 1/x]])
  2760. assert m.atoms() == {S.One,S(2),S.NegativeOne, x}
  2761. assert m.atoms(Symbol) == {x}
  2762. def test_pinv():
  2763. # Pseudoinverse of an invertible matrix is the inverse.
  2764. A1 = Matrix([[a, b], [c, d]])
  2765. assert simplify(A1.pinv(method="RD")) == simplify(A1.inv())
  2766. # Test the four properties of the pseudoinverse for various matrices.
  2767. As = [Matrix([[13, 104], [2212, 3], [-3, 5]]),
  2768. Matrix([[1, 7, 9], [11, 17, 19]]),
  2769. Matrix([a, b])]
  2770. for A in As:
  2771. A_pinv = A.pinv(method="RD")
  2772. AAp = A * A_pinv
  2773. ApA = A_pinv * A
  2774. assert simplify(AAp * A) == A
  2775. assert simplify(ApA * A_pinv) == A_pinv
  2776. assert AAp.H == AAp
  2777. assert ApA.H == ApA
  2778. # XXX Pinv with diagonalization makes expression too complicated.
  2779. for A in As:
  2780. A_pinv = simplify(A.pinv(method="ED"))
  2781. AAp = A * A_pinv
  2782. ApA = A_pinv * A
  2783. assert simplify(AAp * A) == A
  2784. assert simplify(ApA * A_pinv) == A_pinv
  2785. assert AAp.H == AAp
  2786. assert ApA.H == ApA
  2787. # XXX Computing pinv using diagonalization makes an expression that
  2788. # is too complicated to simplify.
  2789. # A1 = Matrix([[a, b], [c, d]])
  2790. # assert simplify(A1.pinv(method="ED")) == simplify(A1.inv())
  2791. # so this is tested numerically at a fixed random point
  2792. from sympy.core.numbers import comp
  2793. q = A1.pinv(method="ED")
  2794. w = A1.inv()
  2795. reps = {a: -73633, b: 11362, c: 55486, d: 62570}
  2796. assert all(
  2797. comp(i.n(), j.n())
  2798. for i, j in zip(q.subs(reps), w.subs(reps))
  2799. )
  2800. @slow
  2801. def test_pinv_rank_deficient_when_diagonalization_fails():
  2802. # Test the four properties of the pseudoinverse for matrices when
  2803. # diagonalization of A.H*A fails.
  2804. As = [
  2805. Matrix([
  2806. [61, 89, 55, 20, 71, 0],
  2807. [62, 96, 85, 85, 16, 0],
  2808. [69, 56, 17, 4, 54, 0],
  2809. [10, 54, 91, 41, 71, 0],
  2810. [ 7, 30, 10, 48, 90, 0],
  2811. [0, 0, 0, 0, 0, 0]])
  2812. ]
  2813. for A in As:
  2814. A_pinv = A.pinv(method="ED")
  2815. AAp = A * A_pinv
  2816. ApA = A_pinv * A
  2817. assert AAp.H == AAp
  2818. # Here ApA.H and ApA are equivalent expressions but they are very
  2819. # complicated expressions involving RootOfs. Using simplify would be
  2820. # too slow and so would evalf so we substitute approximate values for
  2821. # the RootOfs and then evalf which is less accurate but good enough to
  2822. # confirm that these two matrices are equivalent.
  2823. #
  2824. # assert ApA.H == ApA # <--- would fail (structural equality)
  2825. # assert simplify(ApA.H - ApA).is_zero_matrix # <--- too slow
  2826. # (ApA.H - ApA).evalf() # <--- too slow
  2827. def allclose(M1, M2):
  2828. rootofs = M1.atoms(RootOf)
  2829. rootofs_approx = {r: r.evalf() for r in rootofs}
  2830. diff_approx = (M1 - M2).xreplace(rootofs_approx).evalf()
  2831. return all(abs(e) < 1e-10 for e in diff_approx)
  2832. assert allclose(ApA.H, ApA)
  2833. def test_issue_7201():
  2834. assert ones(0, 1) + ones(0, 1) == Matrix(0, 1, [])
  2835. assert ones(1, 0) + ones(1, 0) == Matrix(1, 0, [])
  2836. def test_free_symbols():
  2837. for M in ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix:
  2838. assert M([[x], [0]]).free_symbols == {x}
  2839. def test_from_ndarray():
  2840. """See issue 7465."""
  2841. try:
  2842. from numpy import array
  2843. except ImportError:
  2844. skip('NumPy must be available to test creating matrices from ndarrays')
  2845. assert Matrix(array([1, 2, 3])) == Matrix([1, 2, 3])
  2846. assert Matrix(array([[1, 2, 3]])) == Matrix([[1, 2, 3]])
  2847. assert Matrix(array([[1, 2, 3], [4, 5, 6]])) == \
  2848. Matrix([[1, 2, 3], [4, 5, 6]])
  2849. assert Matrix(array([x, y, z])) == Matrix([x, y, z])
  2850. raises(NotImplementedError,
  2851. lambda: Matrix(array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])))
  2852. assert Matrix([array([1, 2]), array([3, 4])]) == Matrix([[1, 2], [3, 4]])
  2853. assert Matrix([array([1, 2]), [3, 4]]) == Matrix([[1, 2], [3, 4]])
  2854. assert Matrix([array([]), array([])]) == Matrix(2, 0, []) != Matrix([])
  2855. def test_17522_numpy():
  2856. from sympy.matrices.common import _matrixify
  2857. try:
  2858. from numpy import array, matrix
  2859. except ImportError:
  2860. skip('NumPy must be available to test indexing matrixified NumPy ndarrays and matrices')
  2861. m = _matrixify(array([[1, 2], [3, 4]]))
  2862. assert m[3] == 4
  2863. assert list(m) == [1, 2, 3, 4]
  2864. with ignore_warnings(PendingDeprecationWarning):
  2865. m = _matrixify(matrix([[1, 2], [3, 4]]))
  2866. assert m[3] == 4
  2867. assert list(m) == [1, 2, 3, 4]
  2868. def test_17522_mpmath():
  2869. from sympy.matrices.common import _matrixify
  2870. try:
  2871. from mpmath import matrix
  2872. except ImportError:
  2873. skip('mpmath must be available to test indexing matrixified mpmath matrices')
  2874. m = _matrixify(matrix([[1, 2], [3, 4]]))
  2875. assert m[3] == 4.0
  2876. assert list(m) == [1.0, 2.0, 3.0, 4.0]
  2877. def test_17522_scipy():
  2878. from sympy.matrices.common import _matrixify
  2879. try:
  2880. from scipy.sparse import csr_matrix
  2881. except ImportError:
  2882. skip('SciPy must be available to test indexing matrixified SciPy sparse matrices')
  2883. m = _matrixify(csr_matrix([[1, 2], [3, 4]]))
  2884. assert m[3] == 4
  2885. assert list(m) == [1, 2, 3, 4]
  2886. def test_hermitian():
  2887. a = Matrix([[1, I], [-I, 1]])
  2888. assert a.is_hermitian
  2889. a[0, 0] = 2*I
  2890. assert a.is_hermitian is False
  2891. a[0, 0] = x
  2892. assert a.is_hermitian is None
  2893. a[0, 1] = a[1, 0]*I
  2894. assert a.is_hermitian is False
  2895. def test_issue_9457_9467_9876():
  2896. # for row_del(index)
  2897. M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2898. M.row_del(1)
  2899. assert M == Matrix([[1, 2, 3], [3, 4, 5]])
  2900. N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2901. N.row_del(-2)
  2902. assert N == Matrix([[1, 2, 3], [3, 4, 5]])
  2903. O = Matrix([[1, 2, 3], [5, 6, 7], [9, 10, 11]])
  2904. O.row_del(-1)
  2905. assert O == Matrix([[1, 2, 3], [5, 6, 7]])
  2906. P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2907. raises(IndexError, lambda: P.row_del(10))
  2908. Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2909. raises(IndexError, lambda: Q.row_del(-10))
  2910. # for col_del(index)
  2911. M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2912. M.col_del(1)
  2913. assert M == Matrix([[1, 3], [2, 4], [3, 5]])
  2914. N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2915. N.col_del(-2)
  2916. assert N == Matrix([[1, 3], [2, 4], [3, 5]])
  2917. P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2918. raises(IndexError, lambda: P.col_del(10))
  2919. Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  2920. raises(IndexError, lambda: Q.col_del(-10))
  2921. def test_issue_9422():
  2922. x, y = symbols('x y', commutative=False)
  2923. a, b = symbols('a b')
  2924. M = eye(2)
  2925. M1 = Matrix(2, 2, [x, y, y, z])
  2926. assert y*x*M != x*y*M
  2927. assert b*a*M == a*b*M
  2928. assert x*M1 != M1*x
  2929. assert a*M1 == M1*a
  2930. assert y*x*M == Matrix([[y*x, 0], [0, y*x]])
  2931. def test_issue_10770():
  2932. M = Matrix([])
  2933. a = ['col_insert', 'row_join'], Matrix([9, 6, 3])
  2934. b = ['row_insert', 'col_join'], a[1].T
  2935. c = ['row_insert', 'col_insert'], Matrix([[1, 2], [3, 4]])
  2936. for ops, m in (a, b, c):
  2937. for op in ops:
  2938. f = getattr(M, op)
  2939. new = f(m) if 'join' in op else f(42, m)
  2940. assert new == m and id(new) != id(m)
  2941. def test_issue_10658():
  2942. A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  2943. assert A.extract([0, 1, 2], [True, True, False]) == \
  2944. Matrix([[1, 2], [4, 5], [7, 8]])
  2945. assert A.extract([0, 1, 2], [True, False, False]) == Matrix([[1], [4], [7]])
  2946. assert A.extract([True, False, False], [0, 1, 2]) == Matrix([[1, 2, 3]])
  2947. assert A.extract([True, False, True], [0, 1, 2]) == \
  2948. Matrix([[1, 2, 3], [7, 8, 9]])
  2949. assert A.extract([0, 1, 2], [False, False, False]) == Matrix(3, 0, [])
  2950. assert A.extract([False, False, False], [0, 1, 2]) == Matrix(0, 3, [])
  2951. assert A.extract([True, False, True], [False, True, False]) == \
  2952. Matrix([[2], [8]])
  2953. def test_opportunistic_simplification():
  2954. # this test relates to issue #10718, #9480, #11434
  2955. # issue #9480
  2956. m = Matrix([[-5 + 5*sqrt(2), -5], [-5*sqrt(2)/2 + 5, -5*sqrt(2)/2]])
  2957. assert m.rank() == 1
  2958. # issue #10781
  2959. m = Matrix([[3+3*sqrt(3)*I, -9],[4,-3+3*sqrt(3)*I]])
  2960. assert simplify(m.rref()[0] - Matrix([[1, -9/(3 + 3*sqrt(3)*I)], [0, 0]])) == zeros(2, 2)
  2961. # issue #11434
  2962. ax,ay,bx,by,cx,cy,dx,dy,ex,ey,t0,t1 = symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1')
  2963. m = Matrix([[ax,ay,ax*t0,ay*t0,0],[bx,by,bx*t0,by*t0,0],[cx,cy,cx*t0,cy*t0,1],[dx,dy,dx*t0,dy*t0,1],[ex,ey,2*ex*t1-ex*t0,2*ey*t1-ey*t0,0]])
  2964. assert m.rank() == 4
  2965. def test_partial_pivoting():
  2966. # example from https://en.wikipedia.org/wiki/Pivot_element
  2967. # partial pivoting with back substitution gives a perfect result
  2968. # naive pivoting give an error ~1e-13, so anything better than
  2969. # 1e-15 is good
  2970. mm=Matrix([[0.003, 59.14, 59.17], [5.291, -6.13, 46.78]])
  2971. assert (mm.rref()[0] - Matrix([[1.0, 0, 10.0],
  2972. [ 0, 1.0, 1.0]])).norm() < 1e-15
  2973. # issue #11549
  2974. m_mixed = Matrix([[6e-17, 1.0, 4],
  2975. [ -1.0, 0, 8],
  2976. [ 0, 0, 1]])
  2977. m_float = Matrix([[6e-17, 1.0, 4.],
  2978. [ -1.0, 0., 8.],
  2979. [ 0., 0., 1.]])
  2980. m_inv = Matrix([[ 0, -1.0, 8.0],
  2981. [1.0, 6.0e-17, -4.0],
  2982. [ 0, 0, 1]])
  2983. # this example is numerically unstable and involves a matrix with a norm >= 8,
  2984. # this comparing the difference of the results with 1e-15 is numerically sound.
  2985. assert (m_mixed.inv() - m_inv).norm() < 1e-15
  2986. assert (m_float.inv() - m_inv).norm() < 1e-15
  2987. def test_iszero_substitution():
  2988. """ When doing numerical computations, all elements that pass
  2989. the iszerofunc test should be set to numerically zero if they
  2990. aren't already. """
  2991. # Matrix from issue #9060
  2992. m = Matrix([[0.9, -0.1, -0.2, 0],[-0.8, 0.9, -0.4, 0],[-0.1, -0.8, 0.6, 0]])
  2993. m_rref = m.rref(iszerofunc=lambda x: abs(x)<6e-15)[0]
  2994. m_correct = Matrix([[1.0, 0, -0.301369863013699, 0],[ 0, 1.0, -0.712328767123288, 0],[ 0, 0, 0, 0]])
  2995. m_diff = m_rref - m_correct
  2996. assert m_diff.norm() < 1e-15
  2997. # if a zero-substitution wasn't made, this entry will be -1.11022302462516e-16
  2998. assert m_rref[2,2] == 0
  2999. def test_issue_11238():
  3000. from sympy.geometry.point import Point
  3001. xx = 8*tan(pi*Rational(13, 45))/(tan(pi*Rational(13, 45)) + sqrt(3))
  3002. yy = (-8*sqrt(3)*tan(pi*Rational(13, 45))**2 + 24*tan(pi*Rational(13, 45)))/(-3 + tan(pi*Rational(13, 45))**2)
  3003. p1 = Point(0, 0)
  3004. p2 = Point(1, -sqrt(3))
  3005. p0 = Point(xx,yy)
  3006. m1 = Matrix([p1 - simplify(p0), p2 - simplify(p0)])
  3007. m2 = Matrix([p1 - p0, p2 - p0])
  3008. m3 = Matrix([simplify(p1 - p0), simplify(p2 - p0)])
  3009. # This system has expressions which are zero and
  3010. # cannot be easily proved to be such, so without
  3011. # numerical testing, these assertions will fail.
  3012. Z = lambda x: abs(x.n()) < 1e-20
  3013. assert m1.rank(simplify=True, iszerofunc=Z) == 1
  3014. assert m2.rank(simplify=True, iszerofunc=Z) == 1
  3015. assert m3.rank(simplify=True, iszerofunc=Z) == 1
  3016. def test_as_real_imag():
  3017. m1 = Matrix(2,2,[1,2,3,4])
  3018. m2 = m1*S.ImaginaryUnit
  3019. m3 = m1 + m2
  3020. for kls in all_classes:
  3021. a,b = kls(m3).as_real_imag()
  3022. assert list(a) == list(m1)
  3023. assert list(b) == list(m1)
  3024. def test_deprecated():
  3025. # Maintain tests for deprecated functions. We must capture
  3026. # the deprecation warnings. When the deprecated functionality is
  3027. # removed, the corresponding tests should be removed.
  3028. m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
  3029. P, Jcells = m.jordan_cells()
  3030. assert Jcells[1] == Matrix(1, 1, [2])
  3031. assert Jcells[0] == Matrix(2, 2, [2, 1, 0, 2])
  3032. def test_issue_14489():
  3033. from sympy.core.mod import Mod
  3034. A = Matrix([-1, 1, 2])
  3035. B = Matrix([10, 20, -15])
  3036. assert Mod(A, 3) == Matrix([2, 1, 2])
  3037. assert Mod(B, 4) == Matrix([2, 0, 1])
  3038. def test_issue_14943():
  3039. # Test that __array__ accepts the optional dtype argument
  3040. try:
  3041. from numpy import array
  3042. except ImportError:
  3043. skip('NumPy must be available to test creating matrices from ndarrays')
  3044. M = Matrix([[1,2], [3,4]])
  3045. assert array(M, dtype=float).dtype.name == 'float64'
  3046. def test_case_6913():
  3047. m = MatrixSymbol('m', 1, 1)
  3048. a = Symbol("a")
  3049. a = m[0, 0]>0
  3050. assert str(a) == 'm[0, 0] > 0'
  3051. def test_issue_11948():
  3052. A = MatrixSymbol('A', 3, 3)
  3053. a = Wild('a')
  3054. assert A.match(a) == {a: A}
  3055. def test_gramschmidt_conjugate_dot():
  3056. vecs = [Matrix([1, I]), Matrix([1, -I])]
  3057. assert Matrix.orthogonalize(*vecs) == \
  3058. [Matrix([[1], [I]]), Matrix([[1], [-I]])]
  3059. vecs = [Matrix([1, I, 0]), Matrix([I, 0, -I])]
  3060. assert Matrix.orthogonalize(*vecs) == \
  3061. [Matrix([[1], [I], [0]]), Matrix([[I/2], [S(1)/2], [-I]])]
  3062. mat = Matrix([[1, I], [1, -I]])
  3063. Q, R = mat.QRdecomposition()
  3064. assert Q * Q.H == Matrix.eye(2)
  3065. def test_issue_8207():
  3066. a = Matrix(MatrixSymbol('a', 3, 1))
  3067. b = Matrix(MatrixSymbol('b', 3, 1))
  3068. c = a.dot(b)
  3069. d = diff(c, a[0, 0])
  3070. e = diff(d, a[0, 0])
  3071. assert d == b[0, 0]
  3072. assert e == 0
  3073. def test_func():
  3074. from sympy.simplify.simplify import nthroot
  3075. A = Matrix([[1, 2],[0, 3]])
  3076. assert A.analytic_func(sin(x*t), x) == Matrix([[sin(t), sin(3*t) - sin(t)], [0, sin(3*t)]])
  3077. A = Matrix([[2, 1],[1, 2]])
  3078. assert (pi * A / 6).analytic_func(cos(x), x) == Matrix([[sqrt(3)/4, -sqrt(3)/4], [-sqrt(3)/4, sqrt(3)/4]])
  3079. raises(ValueError, lambda : zeros(5).analytic_func(log(x), x))
  3080. raises(ValueError, lambda : (A*x).analytic_func(log(x), x))
  3081. A = Matrix([[0, -1, -2, 3], [0, -1, -2, 3], [0, 1, 0, -1], [0, 0, -1, 1]])
  3082. assert A.analytic_func(exp(x), x) == A.exp()
  3083. raises(ValueError, lambda : A.analytic_func(sqrt(x), x))
  3084. A = Matrix([[41, 12],[12, 34]])
  3085. assert simplify(A.analytic_func(sqrt(x), x)**2) == A
  3086. A = Matrix([[3, -12, 4], [-1, 0, -2], [-1, 5, -1]])
  3087. assert simplify(A.analytic_func(nthroot(x, 3), x)**3) == A
  3088. A = Matrix([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]])
  3089. assert A.analytic_func(exp(x), x) == A.exp()
  3090. A = Matrix([[0, 2, 1, 6], [0, 0, 1, 2], [0, 0, 0, 3], [0, 0, 0, 0]])
  3091. assert A.analytic_func(exp(x*t), x) == expand(simplify((A*t).exp()))
  3092. @skip_under_pyodide("Cannot create threads under pyodide.")
  3093. def test_issue_19809():
  3094. def f():
  3095. assert _dotprodsimp_state.state == None
  3096. m = Matrix([[1]])
  3097. m = m * m
  3098. return True
  3099. with dotprodsimp(True):
  3100. with concurrent.futures.ThreadPoolExecutor() as executor:
  3101. future = executor.submit(f)
  3102. assert future.result()
  3103. def test_issue_23276():
  3104. M = Matrix([x, y])
  3105. assert integrate(M, (x, 0, 1), (y, 0, 1)) == Matrix([
  3106. [S.Half],
  3107. [S.Half]])
  3108. def test_issue_27225():
  3109. # https://github.com/sympy/sympy/issues/27225
  3110. raises(TypeError, lambda : floor(Matrix([1, 1, 0])))