test_matrices.py 159 KB

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