test_commonmatrix.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. from sympy.assumptions import Q
  2. from sympy.core.expr import Expr
  3. from sympy.core.add import Add
  4. from sympy.core.function import Function
  5. from sympy.core.kind import NumberKind, UndefinedKind
  6. from sympy.core.numbers import I, Integer, oo, pi, Rational
  7. from sympy.core.singleton import S
  8. from sympy.core.symbol import Symbol, symbols
  9. from sympy.functions.elementary.complexes import Abs
  10. from sympy.functions.elementary.exponential import exp
  11. from sympy.functions.elementary.miscellaneous import sqrt
  12. from sympy.functions.elementary.trigonometric import cos, sin
  13. from sympy.matrices.common import (ShapeError, NonSquareMatrixError,
  14. _MinimalMatrix, _CastableMatrix, MatrixShaping, MatrixProperties,
  15. MatrixOperations, MatrixArithmetic, MatrixSpecial, MatrixKind)
  16. from sympy.matrices.matrices import MatrixCalculus
  17. from sympy.matrices import (Matrix, diag, eye,
  18. matrix_multiply_elementwise, ones, zeros, SparseMatrix, banded,
  19. MutableDenseMatrix, MutableSparseMatrix, ImmutableDenseMatrix,
  20. ImmutableSparseMatrix)
  21. from sympy.polys.polytools import Poly
  22. from sympy.utilities.iterables import flatten
  23. from sympy.testing.pytest import raises, XFAIL
  24. from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray as Array
  25. from sympy.abc import x, y, z
  26. # classes to test the basic matrix classes
  27. class ShapingOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixShaping):
  28. pass
  29. def eye_Shaping(n):
  30. return ShapingOnlyMatrix(n, n, lambda i, j: int(i == j))
  31. def zeros_Shaping(n):
  32. return ShapingOnlyMatrix(n, n, lambda i, j: 0)
  33. class PropertiesOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixProperties):
  34. pass
  35. def eye_Properties(n):
  36. return PropertiesOnlyMatrix(n, n, lambda i, j: int(i == j))
  37. def zeros_Properties(n):
  38. return PropertiesOnlyMatrix(n, n, lambda i, j: 0)
  39. class OperationsOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixOperations):
  40. pass
  41. def eye_Operations(n):
  42. return OperationsOnlyMatrix(n, n, lambda i, j: int(i == j))
  43. def zeros_Operations(n):
  44. return OperationsOnlyMatrix(n, n, lambda i, j: 0)
  45. class ArithmeticOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixArithmetic):
  46. pass
  47. def eye_Arithmetic(n):
  48. return ArithmeticOnlyMatrix(n, n, lambda i, j: int(i == j))
  49. def zeros_Arithmetic(n):
  50. return ArithmeticOnlyMatrix(n, n, lambda i, j: 0)
  51. class SpecialOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixSpecial):
  52. pass
  53. class CalculusOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixCalculus):
  54. pass
  55. def test__MinimalMatrix():
  56. x = _MinimalMatrix(2, 3, [1, 2, 3, 4, 5, 6])
  57. assert x.rows == 2
  58. assert x.cols == 3
  59. assert x[2] == 3
  60. assert x[1, 1] == 5
  61. assert list(x) == [1, 2, 3, 4, 5, 6]
  62. assert list(x[1, :]) == [4, 5, 6]
  63. assert list(x[:, 1]) == [2, 5]
  64. assert list(x[:, :]) == list(x)
  65. assert x[:, :] == x
  66. assert _MinimalMatrix(x) == x
  67. assert _MinimalMatrix([[1, 2, 3], [4, 5, 6]]) == x
  68. assert _MinimalMatrix(([1, 2, 3], [4, 5, 6])) == x
  69. assert _MinimalMatrix([(1, 2, 3), (4, 5, 6)]) == x
  70. assert _MinimalMatrix(((1, 2, 3), (4, 5, 6))) == x
  71. assert not (_MinimalMatrix([[1, 2], [3, 4], [5, 6]]) == x)
  72. def test_kind():
  73. assert Matrix([[1, 2], [3, 4]]).kind == MatrixKind(NumberKind)
  74. assert Matrix([[0, 0], [0, 0]]).kind == MatrixKind(NumberKind)
  75. assert Matrix(0, 0, []).kind == MatrixKind(NumberKind)
  76. assert Matrix([[x]]).kind == MatrixKind(NumberKind)
  77. assert Matrix([[1, Matrix([[1]])]]).kind == MatrixKind(UndefinedKind)
  78. assert SparseMatrix([[1]]).kind == MatrixKind(NumberKind)
  79. assert SparseMatrix([[1, Matrix([[1]])]]).kind == MatrixKind(UndefinedKind)
  80. # ShapingOnlyMatrix tests
  81. def test_vec():
  82. m = ShapingOnlyMatrix(2, 2, [1, 3, 2, 4])
  83. m_vec = m.vec()
  84. assert m_vec.cols == 1
  85. for i in range(4):
  86. assert m_vec[i] == i + 1
  87. def test_todok():
  88. a, b, c, d = symbols('a:d')
  89. m1 = MutableDenseMatrix([[a, b], [c, d]])
  90. m2 = ImmutableDenseMatrix([[a, b], [c, d]])
  91. m3 = MutableSparseMatrix([[a, b], [c, d]])
  92. m4 = ImmutableSparseMatrix([[a, b], [c, d]])
  93. assert m1.todok() == m2.todok() == m3.todok() == m4.todok() == \
  94. {(0, 0): a, (0, 1): b, (1, 0): c, (1, 1): d}
  95. def test_tolist():
  96. lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
  97. flat_lst = [S.One, S.Half, x*y, S.Zero, x, y, z, x**2, y, -S.One, z*x, 3]
  98. m = ShapingOnlyMatrix(3, 4, flat_lst)
  99. assert m.tolist() == lst
  100. def test_todod():
  101. m = ShapingOnlyMatrix(3, 2, [[S.One, 0], [0, S.Half], [x, 0]])
  102. dict = {0: {0: S.One}, 1: {1: S.Half}, 2: {0: x}}
  103. assert m.todod() == dict
  104. def test_row_col_del():
  105. e = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
  106. raises(IndexError, lambda: e.row_del(5))
  107. raises(IndexError, lambda: e.row_del(-5))
  108. raises(IndexError, lambda: e.col_del(5))
  109. raises(IndexError, lambda: e.col_del(-5))
  110. assert e.row_del(2) == e.row_del(-1) == Matrix([[1, 2, 3], [4, 5, 6]])
  111. assert e.col_del(2) == e.col_del(-1) == Matrix([[1, 2], [4, 5], [7, 8]])
  112. assert e.row_del(1) == e.row_del(-2) == Matrix([[1, 2, 3], [7, 8, 9]])
  113. assert e.col_del(1) == e.col_del(-2) == Matrix([[1, 3], [4, 6], [7, 9]])
  114. def test_get_diag_blocks1():
  115. a = Matrix([[1, 2], [2, 3]])
  116. b = Matrix([[3, x], [y, 3]])
  117. c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
  118. assert a.get_diag_blocks() == [a]
  119. assert b.get_diag_blocks() == [b]
  120. assert c.get_diag_blocks() == [c]
  121. def test_get_diag_blocks2():
  122. a = Matrix([[1, 2], [2, 3]])
  123. b = Matrix([[3, x], [y, 3]])
  124. c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
  125. A, B, C, D = diag(a, b, b), diag(a, b, c), diag(a, c, b), diag(c, c, b)
  126. A = ShapingOnlyMatrix(A.rows, A.cols, A)
  127. B = ShapingOnlyMatrix(B.rows, B.cols, B)
  128. C = ShapingOnlyMatrix(C.rows, C.cols, C)
  129. D = ShapingOnlyMatrix(D.rows, D.cols, D)
  130. assert A.get_diag_blocks() == [a, b, b]
  131. assert B.get_diag_blocks() == [a, b, c]
  132. assert C.get_diag_blocks() == [a, c, b]
  133. assert D.get_diag_blocks() == [c, c, b]
  134. def test_shape():
  135. m = ShapingOnlyMatrix(1, 2, [0, 0])
  136. assert m.shape == (1, 2)
  137. def test_reshape():
  138. m0 = eye_Shaping(3)
  139. assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
  140. m1 = ShapingOnlyMatrix(3, 4, lambda i, j: i + j)
  141. assert m1.reshape(
  142. 4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
  143. assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
  144. def test_row_col():
  145. m = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
  146. assert m.row(0) == Matrix(1, 3, [1, 2, 3])
  147. assert m.col(0) == Matrix(3, 1, [1, 4, 7])
  148. def test_row_join():
  149. assert eye_Shaping(3).row_join(Matrix([7, 7, 7])) == \
  150. Matrix([[1, 0, 0, 7],
  151. [0, 1, 0, 7],
  152. [0, 0, 1, 7]])
  153. def test_col_join():
  154. assert eye_Shaping(3).col_join(Matrix([[7, 7, 7]])) == \
  155. Matrix([[1, 0, 0],
  156. [0, 1, 0],
  157. [0, 0, 1],
  158. [7, 7, 7]])
  159. def test_row_insert():
  160. r4 = Matrix([[4, 4, 4]])
  161. for i in range(-4, 5):
  162. l = [1, 0, 0]
  163. l.insert(i, 4)
  164. assert flatten(eye_Shaping(3).row_insert(i, r4).col(0).tolist()) == l
  165. def test_col_insert():
  166. c4 = Matrix([4, 4, 4])
  167. for i in range(-4, 5):
  168. l = [0, 0, 0]
  169. l.insert(i, 4)
  170. assert flatten(zeros_Shaping(3).col_insert(i, c4).row(0).tolist()) == l
  171. # issue 13643
  172. assert eye_Shaping(6).col_insert(3, Matrix([[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]])) == \
  173. Matrix([[1, 0, 0, 2, 2, 0, 0, 0],
  174. [0, 1, 0, 2, 2, 0, 0, 0],
  175. [0, 0, 1, 2, 2, 0, 0, 0],
  176. [0, 0, 0, 2, 2, 1, 0, 0],
  177. [0, 0, 0, 2, 2, 0, 1, 0],
  178. [0, 0, 0, 2, 2, 0, 0, 1]])
  179. def test_extract():
  180. m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
  181. assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
  182. assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
  183. assert m.extract(range(4), range(3)) == m
  184. raises(IndexError, lambda: m.extract([4], [0]))
  185. raises(IndexError, lambda: m.extract([0], [3]))
  186. def test_hstack():
  187. m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
  188. m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
  189. assert m == m.hstack(m)
  190. assert m.hstack(m, m, m) == ShapingOnlyMatrix.hstack(m, m, m) == Matrix([
  191. [0, 1, 2, 0, 1, 2, 0, 1, 2],
  192. [3, 4, 5, 3, 4, 5, 3, 4, 5],
  193. [6, 7, 8, 6, 7, 8, 6, 7, 8],
  194. [9, 10, 11, 9, 10, 11, 9, 10, 11]])
  195. raises(ShapeError, lambda: m.hstack(m, m2))
  196. assert Matrix.hstack() == Matrix()
  197. # test regression #12938
  198. M1 = Matrix.zeros(0, 0)
  199. M2 = Matrix.zeros(0, 1)
  200. M3 = Matrix.zeros(0, 2)
  201. M4 = Matrix.zeros(0, 3)
  202. m = ShapingOnlyMatrix.hstack(M1, M2, M3, M4)
  203. assert m.rows == 0 and m.cols == 6
  204. def test_vstack():
  205. m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
  206. m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
  207. assert m == m.vstack(m)
  208. assert m.vstack(m, m, m) == ShapingOnlyMatrix.vstack(m, m, m) == Matrix([
  209. [0, 1, 2],
  210. [3, 4, 5],
  211. [6, 7, 8],
  212. [9, 10, 11],
  213. [0, 1, 2],
  214. [3, 4, 5],
  215. [6, 7, 8],
  216. [9, 10, 11],
  217. [0, 1, 2],
  218. [3, 4, 5],
  219. [6, 7, 8],
  220. [9, 10, 11]])
  221. raises(ShapeError, lambda: m.vstack(m, m2))
  222. assert Matrix.vstack() == Matrix()
  223. # PropertiesOnlyMatrix tests
  224. def test_atoms():
  225. m = PropertiesOnlyMatrix(2, 2, [1, 2, x, 1 - 1/x])
  226. assert m.atoms() == {S.One, S(2), S.NegativeOne, x}
  227. assert m.atoms(Symbol) == {x}
  228. def test_free_symbols():
  229. assert PropertiesOnlyMatrix([[x], [0]]).free_symbols == {x}
  230. def test_has():
  231. A = PropertiesOnlyMatrix(((x, y), (2, 3)))
  232. assert A.has(x)
  233. assert not A.has(z)
  234. assert A.has(Symbol)
  235. A = PropertiesOnlyMatrix(((2, y), (2, 3)))
  236. assert not A.has(x)
  237. def test_is_anti_symmetric():
  238. x = symbols('x')
  239. assert PropertiesOnlyMatrix(2, 1, [1, 2]).is_anti_symmetric() is False
  240. m = PropertiesOnlyMatrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
  241. assert m.is_anti_symmetric() is True
  242. assert m.is_anti_symmetric(simplify=False) is False
  243. assert m.is_anti_symmetric(simplify=lambda x: x) is False
  244. m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in m])
  245. assert m.is_anti_symmetric(simplify=False) is True
  246. m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in [S.One] + list(m)[1:]])
  247. assert m.is_anti_symmetric() is False
  248. def test_diagonal_symmetrical():
  249. m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0])
  250. assert not m.is_diagonal()
  251. assert m.is_symmetric()
  252. assert m.is_symmetric(simplify=False)
  253. m = PropertiesOnlyMatrix(2, 2, [1, 0, 0, 1])
  254. assert m.is_diagonal()
  255. m = PropertiesOnlyMatrix(3, 3, diag(1, 2, 3))
  256. assert m.is_diagonal()
  257. assert m.is_symmetric()
  258. m = PropertiesOnlyMatrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
  259. assert m == diag(1, 2, 3)
  260. m = PropertiesOnlyMatrix(2, 3, zeros(2, 3))
  261. assert not m.is_symmetric()
  262. assert m.is_diagonal()
  263. m = PropertiesOnlyMatrix(((5, 0), (0, 6), (0, 0)))
  264. assert m.is_diagonal()
  265. m = PropertiesOnlyMatrix(((5, 0, 0), (0, 6, 0)))
  266. assert m.is_diagonal()
  267. m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
  268. assert m.is_symmetric()
  269. assert not m.is_symmetric(simplify=False)
  270. assert m.expand().is_symmetric(simplify=False)
  271. def test_is_hermitian():
  272. a = PropertiesOnlyMatrix([[1, I], [-I, 1]])
  273. assert a.is_hermitian
  274. a = PropertiesOnlyMatrix([[2*I, I], [-I, 1]])
  275. assert a.is_hermitian is False
  276. a = PropertiesOnlyMatrix([[x, I], [-I, 1]])
  277. assert a.is_hermitian is None
  278. a = PropertiesOnlyMatrix([[x, 1], [-I, 1]])
  279. assert a.is_hermitian is False
  280. def test_is_Identity():
  281. assert eye_Properties(3).is_Identity
  282. assert not PropertiesOnlyMatrix(zeros(3)).is_Identity
  283. assert not PropertiesOnlyMatrix(ones(3)).is_Identity
  284. # issue 6242
  285. assert not PropertiesOnlyMatrix([[1, 0, 0]]).is_Identity
  286. def test_is_symbolic():
  287. a = PropertiesOnlyMatrix([[x, x], [x, x]])
  288. assert a.is_symbolic() is True
  289. a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, 7, 8]])
  290. assert a.is_symbolic() is False
  291. a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, x, 8]])
  292. assert a.is_symbolic() is True
  293. a = PropertiesOnlyMatrix([[1, x, 3]])
  294. assert a.is_symbolic() is True
  295. a = PropertiesOnlyMatrix([[1, 2, 3]])
  296. assert a.is_symbolic() is False
  297. a = PropertiesOnlyMatrix([[1], [x], [3]])
  298. assert a.is_symbolic() is True
  299. a = PropertiesOnlyMatrix([[1], [2], [3]])
  300. assert a.is_symbolic() is False
  301. def test_is_upper():
  302. a = PropertiesOnlyMatrix([[1, 2, 3]])
  303. assert a.is_upper is True
  304. a = PropertiesOnlyMatrix([[1], [2], [3]])
  305. assert a.is_upper is False
  306. def test_is_lower():
  307. a = PropertiesOnlyMatrix([[1, 2, 3]])
  308. assert a.is_lower is False
  309. a = PropertiesOnlyMatrix([[1], [2], [3]])
  310. assert a.is_lower is True
  311. def test_is_square():
  312. m = PropertiesOnlyMatrix([[1], [1]])
  313. m2 = PropertiesOnlyMatrix([[2, 2], [2, 2]])
  314. assert not m.is_square
  315. assert m2.is_square
  316. def test_is_symmetric():
  317. m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0])
  318. assert m.is_symmetric()
  319. m = PropertiesOnlyMatrix(2, 2, [0, 1, 0, 1])
  320. assert not m.is_symmetric()
  321. def test_is_hessenberg():
  322. A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
  323. assert A.is_upper_hessenberg
  324. A = PropertiesOnlyMatrix(3, 3, [3, 2, 0, 4, 4, 1, 1, 5, 2])
  325. assert A.is_lower_hessenberg
  326. A = PropertiesOnlyMatrix(3, 3, [3, 2, -1, 4, 4, 1, 1, 5, 2])
  327. assert A.is_lower_hessenberg is False
  328. assert A.is_upper_hessenberg is False
  329. A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
  330. assert not A.is_upper_hessenberg
  331. def test_is_zero():
  332. assert PropertiesOnlyMatrix(0, 0, []).is_zero_matrix
  333. assert PropertiesOnlyMatrix([[0, 0], [0, 0]]).is_zero_matrix
  334. assert PropertiesOnlyMatrix(zeros(3, 4)).is_zero_matrix
  335. assert not PropertiesOnlyMatrix(eye(3)).is_zero_matrix
  336. assert PropertiesOnlyMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
  337. assert PropertiesOnlyMatrix([[x, 1], [0, 0]]).is_zero_matrix == False
  338. a = Symbol('a', nonzero=True)
  339. assert PropertiesOnlyMatrix([[a, 0], [0, 0]]).is_zero_matrix == False
  340. def test_values():
  341. assert set(PropertiesOnlyMatrix(2, 2, [0, 1, 2, 3]
  342. ).values()) == {1, 2, 3}
  343. x = Symbol('x', real=True)
  344. assert set(PropertiesOnlyMatrix(2, 2, [x, 0, 0, 1]
  345. ).values()) == {x, 1}
  346. # OperationsOnlyMatrix tests
  347. def test_applyfunc():
  348. m0 = OperationsOnlyMatrix(eye(3))
  349. assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
  350. assert m0.applyfunc(lambda x: 0) == zeros(3)
  351. assert m0.applyfunc(lambda x: 1) == ones(3)
  352. def test_adjoint():
  353. dat = [[0, I], [1, 0]]
  354. ans = OperationsOnlyMatrix([[0, 1], [-I, 0]])
  355. assert ans.adjoint() == Matrix(dat)
  356. def test_as_real_imag():
  357. m1 = OperationsOnlyMatrix(2, 2, [1, 2, 3, 4])
  358. m3 = OperationsOnlyMatrix(2, 2,
  359. [1 + S.ImaginaryUnit, 2 + 2*S.ImaginaryUnit,
  360. 3 + 3*S.ImaginaryUnit, 4 + 4*S.ImaginaryUnit])
  361. a, b = m3.as_real_imag()
  362. assert a == m1
  363. assert b == m1
  364. def test_conjugate():
  365. M = OperationsOnlyMatrix([[0, I, 5],
  366. [1, 2, 0]])
  367. assert M.T == Matrix([[0, 1],
  368. [I, 2],
  369. [5, 0]])
  370. assert M.C == Matrix([[0, -I, 5],
  371. [1, 2, 0]])
  372. assert M.C == M.conjugate()
  373. assert M.H == M.T.C
  374. assert M.H == Matrix([[ 0, 1],
  375. [-I, 2],
  376. [ 5, 0]])
  377. def test_doit():
  378. a = OperationsOnlyMatrix([[Add(x, x, evaluate=False)]])
  379. assert a[0] != 2*x
  380. assert a.doit() == Matrix([[2*x]])
  381. def test_evalf():
  382. a = OperationsOnlyMatrix(2, 1, [sqrt(5), 6])
  383. assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
  384. assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
  385. assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
  386. def test_expand():
  387. m0 = OperationsOnlyMatrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
  388. # Test if expand() returns a matrix
  389. m1 = m0.expand()
  390. assert m1 == Matrix(
  391. [[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
  392. a = Symbol('a', real=True)
  393. assert OperationsOnlyMatrix(1, 1, [exp(I*a)]).expand(complex=True) == \
  394. Matrix([cos(a) + I*sin(a)])
  395. def test_refine():
  396. m0 = OperationsOnlyMatrix([[Abs(x)**2, sqrt(x**2)],
  397. [sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
  398. m1 = m0.refine(Q.real(x) & Q.real(y))
  399. assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
  400. m1 = m0.refine(Q.positive(x) & Q.positive(y))
  401. assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
  402. m1 = m0.refine(Q.negative(x) & Q.negative(y))
  403. assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
  404. def test_replace():
  405. F, G = symbols('F, G', cls=Function)
  406. K = OperationsOnlyMatrix(2, 2, lambda i, j: G(i+j))
  407. M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j))
  408. N = M.replace(F, G)
  409. assert N == K
  410. def test_replace_map():
  411. F, G = symbols('F, G', cls=Function)
  412. K = OperationsOnlyMatrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1) \
  413. : G(1)}), (G(2), {F(2): G(2)})])
  414. M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j))
  415. N = M.replace(F, G, True)
  416. assert N == K
  417. def test_rot90():
  418. A = Matrix([[1, 2], [3, 4]])
  419. assert A == A.rot90(0) == A.rot90(4)
  420. assert A.rot90(2) == A.rot90(-2) == A.rot90(6) == Matrix(((4, 3), (2, 1)))
  421. assert A.rot90(3) == A.rot90(-1) == A.rot90(7) == Matrix(((2, 4), (1, 3)))
  422. assert A.rot90() == A.rot90(-7) == A.rot90(-3) == Matrix(((3, 1), (4, 2)))
  423. def test_simplify():
  424. n = Symbol('n')
  425. f = Function('f')
  426. M = OperationsOnlyMatrix([[ 1/x + 1/y, (x + x*y) / x ],
  427. [ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
  428. assert M.simplify() == Matrix([[ (x + y)/(x * y), 1 + y ],
  429. [ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
  430. eq = (1 + x)**2
  431. M = OperationsOnlyMatrix([[eq]])
  432. assert M.simplify() == Matrix([[eq]])
  433. assert M.simplify(ratio=oo) == Matrix([[eq.simplify(ratio=oo)]])
  434. # https://github.com/sympy/sympy/issues/19353
  435. m = Matrix([[30, 2], [3, 4]])
  436. assert (1/(m.trace())).simplify() == Rational(1, 34)
  437. def test_subs():
  438. assert OperationsOnlyMatrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
  439. assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
  440. Matrix([[-1, 2], [-3, 4]])
  441. assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
  442. Matrix([[-1, 2], [-3, 4]])
  443. assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
  444. Matrix([[-1, 2], [-3, 4]])
  445. assert OperationsOnlyMatrix([[x*y]]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
  446. Matrix([[(x - 1)*(y - 1)]])
  447. def test_trace():
  448. M = OperationsOnlyMatrix([[1, 0, 0],
  449. [0, 5, 0],
  450. [0, 0, 8]])
  451. assert M.trace() == 14
  452. def test_xreplace():
  453. assert OperationsOnlyMatrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
  454. Matrix([[1, 5], [5, 4]])
  455. assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
  456. Matrix([[-1, 2], [-3, 4]])
  457. def test_permute():
  458. a = OperationsOnlyMatrix(3, 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
  459. raises(IndexError, lambda: a.permute([[0, 5]]))
  460. raises(ValueError, lambda: a.permute(Symbol('x')))
  461. b = a.permute_rows([[0, 2], [0, 1]])
  462. assert a.permute([[0, 2], [0, 1]]) == b == Matrix([
  463. [5, 6, 7, 8],
  464. [9, 10, 11, 12],
  465. [1, 2, 3, 4]])
  466. b = a.permute_cols([[0, 2], [0, 1]])
  467. assert a.permute([[0, 2], [0, 1]], orientation='cols') == b ==\
  468. Matrix([
  469. [ 2, 3, 1, 4],
  470. [ 6, 7, 5, 8],
  471. [10, 11, 9, 12]])
  472. b = a.permute_cols([[0, 2], [0, 1]], direction='backward')
  473. assert a.permute([[0, 2], [0, 1]], orientation='cols', direction='backward') == b ==\
  474. Matrix([
  475. [ 3, 1, 2, 4],
  476. [ 7, 5, 6, 8],
  477. [11, 9, 10, 12]])
  478. assert a.permute([1, 2, 0, 3]) == Matrix([
  479. [5, 6, 7, 8],
  480. [9, 10, 11, 12],
  481. [1, 2, 3, 4]])
  482. from sympy.combinatorics import Permutation
  483. assert a.permute(Permutation([1, 2, 0, 3])) == Matrix([
  484. [5, 6, 7, 8],
  485. [9, 10, 11, 12],
  486. [1, 2, 3, 4]])
  487. def test_upper_triangular():
  488. A = OperationsOnlyMatrix([
  489. [1, 1, 1, 1],
  490. [1, 1, 1, 1],
  491. [1, 1, 1, 1],
  492. [1, 1, 1, 1]
  493. ])
  494. R = A.upper_triangular(2)
  495. assert R == OperationsOnlyMatrix([
  496. [0, 0, 1, 1],
  497. [0, 0, 0, 1],
  498. [0, 0, 0, 0],
  499. [0, 0, 0, 0]
  500. ])
  501. R = A.upper_triangular(-2)
  502. assert R == OperationsOnlyMatrix([
  503. [1, 1, 1, 1],
  504. [1, 1, 1, 1],
  505. [1, 1, 1, 1],
  506. [0, 1, 1, 1]
  507. ])
  508. R = A.upper_triangular()
  509. assert R == OperationsOnlyMatrix([
  510. [1, 1, 1, 1],
  511. [0, 1, 1, 1],
  512. [0, 0, 1, 1],
  513. [0, 0, 0, 1]
  514. ])
  515. def test_lower_triangular():
  516. A = OperationsOnlyMatrix([
  517. [1, 1, 1, 1],
  518. [1, 1, 1, 1],
  519. [1, 1, 1, 1],
  520. [1, 1, 1, 1]
  521. ])
  522. L = A.lower_triangular()
  523. assert L == ArithmeticOnlyMatrix([
  524. [1, 0, 0, 0],
  525. [1, 1, 0, 0],
  526. [1, 1, 1, 0],
  527. [1, 1, 1, 1]])
  528. L = A.lower_triangular(2)
  529. assert L == ArithmeticOnlyMatrix([
  530. [1, 1, 1, 0],
  531. [1, 1, 1, 1],
  532. [1, 1, 1, 1],
  533. [1, 1, 1, 1]
  534. ])
  535. L = A.lower_triangular(-2)
  536. assert L == ArithmeticOnlyMatrix([
  537. [0, 0, 0, 0],
  538. [0, 0, 0, 0],
  539. [1, 0, 0, 0],
  540. [1, 1, 0, 0]
  541. ])
  542. # ArithmeticOnlyMatrix tests
  543. def test_abs():
  544. m = ArithmeticOnlyMatrix([[1, -2], [x, y]])
  545. assert abs(m) == ArithmeticOnlyMatrix([[1, 2], [Abs(x), Abs(y)]])
  546. def test_add():
  547. m = ArithmeticOnlyMatrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
  548. assert m + m == ArithmeticOnlyMatrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
  549. n = ArithmeticOnlyMatrix(1, 2, [1, 2])
  550. raises(ShapeError, lambda: m + n)
  551. def test_multiplication():
  552. a = ArithmeticOnlyMatrix((
  553. (1, 2),
  554. (3, 1),
  555. (0, 6),
  556. ))
  557. b = ArithmeticOnlyMatrix((
  558. (1, 2),
  559. (3, 0),
  560. ))
  561. raises(ShapeError, lambda: b*a)
  562. raises(TypeError, lambda: a*{})
  563. c = a*b
  564. assert c[0, 0] == 7
  565. assert c[0, 1] == 2
  566. assert c[1, 0] == 6
  567. assert c[1, 1] == 6
  568. assert c[2, 0] == 18
  569. assert c[2, 1] == 0
  570. try:
  571. eval('c = a @ b')
  572. except SyntaxError:
  573. pass
  574. else:
  575. assert c[0, 0] == 7
  576. assert c[0, 1] == 2
  577. assert c[1, 0] == 6
  578. assert c[1, 1] == 6
  579. assert c[2, 0] == 18
  580. assert c[2, 1] == 0
  581. h = a.multiply_elementwise(c)
  582. assert h == matrix_multiply_elementwise(a, c)
  583. assert h[0, 0] == 7
  584. assert h[0, 1] == 4
  585. assert h[1, 0] == 18
  586. assert h[1, 1] == 6
  587. assert h[2, 0] == 0
  588. assert h[2, 1] == 0
  589. raises(ShapeError, lambda: a.multiply_elementwise(b))
  590. c = b * Symbol("x")
  591. assert isinstance(c, ArithmeticOnlyMatrix)
  592. assert c[0, 0] == x
  593. assert c[0, 1] == 2*x
  594. assert c[1, 0] == 3*x
  595. assert c[1, 1] == 0
  596. c2 = x * b
  597. assert c == c2
  598. c = 5 * b
  599. assert isinstance(c, ArithmeticOnlyMatrix)
  600. assert c[0, 0] == 5
  601. assert c[0, 1] == 2*5
  602. assert c[1, 0] == 3*5
  603. assert c[1, 1] == 0
  604. try:
  605. eval('c = 5 @ b')
  606. except SyntaxError:
  607. pass
  608. else:
  609. assert isinstance(c, ArithmeticOnlyMatrix)
  610. assert c[0, 0] == 5
  611. assert c[0, 1] == 2*5
  612. assert c[1, 0] == 3*5
  613. assert c[1, 1] == 0
  614. # https://github.com/sympy/sympy/issues/22353
  615. A = Matrix(ones(3, 1))
  616. _h = -Rational(1, 2)
  617. B = Matrix([_h, _h, _h])
  618. assert A.multiply_elementwise(B) == Matrix([
  619. [_h],
  620. [_h],
  621. [_h]])
  622. def test_matmul():
  623. a = Matrix([[1, 2], [3, 4]])
  624. assert a.__matmul__(2) == NotImplemented
  625. assert a.__rmatmul__(2) == NotImplemented
  626. #This is done this way because @ is only supported in Python 3.5+
  627. #To check 2@a case
  628. try:
  629. eval('2 @ a')
  630. except SyntaxError:
  631. pass
  632. except TypeError: #TypeError is raised in case of NotImplemented is returned
  633. pass
  634. #Check a@2 case
  635. try:
  636. eval('a @ 2')
  637. except SyntaxError:
  638. pass
  639. except TypeError: #TypeError is raised in case of NotImplemented is returned
  640. pass
  641. def test_non_matmul():
  642. """
  643. Test that if explicitly specified as non-matrix, mul reverts
  644. to scalar multiplication.
  645. """
  646. class foo(Expr):
  647. is_Matrix=False
  648. is_MatrixLike=False
  649. shape = (1, 1)
  650. A = Matrix([[1, 2], [3, 4]])
  651. b = foo()
  652. assert b*A == Matrix([[b, 2*b], [3*b, 4*b]])
  653. assert A*b == Matrix([[b, 2*b], [3*b, 4*b]])
  654. def test_power():
  655. raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
  656. A = ArithmeticOnlyMatrix([[2, 3], [4, 5]])
  657. assert (A**5)[:] == (6140, 8097, 10796, 14237)
  658. A = ArithmeticOnlyMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
  659. assert (A**3)[:] == (290, 262, 251, 448, 440, 368, 702, 954, 433)
  660. assert A**0 == eye(3)
  661. assert A**1 == A
  662. assert (ArithmeticOnlyMatrix([[2]]) ** 100)[0, 0] == 2**100
  663. assert ArithmeticOnlyMatrix([[1, 2], [3, 4]])**Integer(2) == ArithmeticOnlyMatrix([[7, 10], [15, 22]])
  664. A = Matrix([[1,2],[4,5]])
  665. assert A.pow(20, method='cayley') == A.pow(20, method='multiply')
  666. def test_neg():
  667. n = ArithmeticOnlyMatrix(1, 2, [1, 2])
  668. assert -n == ArithmeticOnlyMatrix(1, 2, [-1, -2])
  669. def test_sub():
  670. n = ArithmeticOnlyMatrix(1, 2, [1, 2])
  671. assert n - n == ArithmeticOnlyMatrix(1, 2, [0, 0])
  672. def test_div():
  673. n = ArithmeticOnlyMatrix(1, 2, [1, 2])
  674. assert n/2 == ArithmeticOnlyMatrix(1, 2, [S.Half, S(2)/2])
  675. # SpecialOnlyMatrix tests
  676. def test_eye():
  677. assert list(SpecialOnlyMatrix.eye(2, 2)) == [1, 0, 0, 1]
  678. assert list(SpecialOnlyMatrix.eye(2)) == [1, 0, 0, 1]
  679. assert type(SpecialOnlyMatrix.eye(2)) == SpecialOnlyMatrix
  680. assert type(SpecialOnlyMatrix.eye(2, cls=Matrix)) == Matrix
  681. def test_ones():
  682. assert list(SpecialOnlyMatrix.ones(2, 2)) == [1, 1, 1, 1]
  683. assert list(SpecialOnlyMatrix.ones(2)) == [1, 1, 1, 1]
  684. assert SpecialOnlyMatrix.ones(2, 3) == Matrix([[1, 1, 1], [1, 1, 1]])
  685. assert type(SpecialOnlyMatrix.ones(2)) == SpecialOnlyMatrix
  686. assert type(SpecialOnlyMatrix.ones(2, cls=Matrix)) == Matrix
  687. def test_zeros():
  688. assert list(SpecialOnlyMatrix.zeros(2, 2)) == [0, 0, 0, 0]
  689. assert list(SpecialOnlyMatrix.zeros(2)) == [0, 0, 0, 0]
  690. assert SpecialOnlyMatrix.zeros(2, 3) == Matrix([[0, 0, 0], [0, 0, 0]])
  691. assert type(SpecialOnlyMatrix.zeros(2)) == SpecialOnlyMatrix
  692. assert type(SpecialOnlyMatrix.zeros(2, cls=Matrix)) == Matrix
  693. def test_diag_make():
  694. diag = SpecialOnlyMatrix.diag
  695. a = Matrix([[1, 2], [2, 3]])
  696. b = Matrix([[3, x], [y, 3]])
  697. c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
  698. assert diag(a, b, b) == Matrix([
  699. [1, 2, 0, 0, 0, 0],
  700. [2, 3, 0, 0, 0, 0],
  701. [0, 0, 3, x, 0, 0],
  702. [0, 0, y, 3, 0, 0],
  703. [0, 0, 0, 0, 3, x],
  704. [0, 0, 0, 0, y, 3],
  705. ])
  706. assert diag(a, b, c) == Matrix([
  707. [1, 2, 0, 0, 0, 0, 0],
  708. [2, 3, 0, 0, 0, 0, 0],
  709. [0, 0, 3, x, 0, 0, 0],
  710. [0, 0, y, 3, 0, 0, 0],
  711. [0, 0, 0, 0, 3, x, 3],
  712. [0, 0, 0, 0, y, 3, z],
  713. [0, 0, 0, 0, x, y, z],
  714. ])
  715. assert diag(a, c, b) == Matrix([
  716. [1, 2, 0, 0, 0, 0, 0],
  717. [2, 3, 0, 0, 0, 0, 0],
  718. [0, 0, 3, x, 3, 0, 0],
  719. [0, 0, y, 3, z, 0, 0],
  720. [0, 0, x, y, z, 0, 0],
  721. [0, 0, 0, 0, 0, 3, x],
  722. [0, 0, 0, 0, 0, y, 3],
  723. ])
  724. a = Matrix([x, y, z])
  725. b = Matrix([[1, 2], [3, 4]])
  726. c = Matrix([[5, 6]])
  727. # this "wandering diagonal" is what makes this
  728. # a block diagonal where each block is independent
  729. # of the others
  730. assert diag(a, 7, b, c) == Matrix([
  731. [x, 0, 0, 0, 0, 0],
  732. [y, 0, 0, 0, 0, 0],
  733. [z, 0, 0, 0, 0, 0],
  734. [0, 7, 0, 0, 0, 0],
  735. [0, 0, 1, 2, 0, 0],
  736. [0, 0, 3, 4, 0, 0],
  737. [0, 0, 0, 0, 5, 6]])
  738. raises(ValueError, lambda: diag(a, 7, b, c, rows=5))
  739. assert diag(1) == Matrix([[1]])
  740. assert diag(1, rows=2) == Matrix([[1, 0], [0, 0]])
  741. assert diag(1, cols=2) == Matrix([[1, 0], [0, 0]])
  742. assert diag(1, rows=3, cols=2) == Matrix([[1, 0], [0, 0], [0, 0]])
  743. assert diag(*[2, 3]) == Matrix([
  744. [2, 0],
  745. [0, 3]])
  746. assert diag(Matrix([2, 3])) == Matrix([
  747. [2],
  748. [3]])
  749. assert diag([1, [2, 3], 4], unpack=False) == \
  750. diag([[1], [2, 3], [4]], unpack=False) == Matrix([
  751. [1, 0],
  752. [2, 3],
  753. [4, 0]])
  754. assert type(diag(1)) == SpecialOnlyMatrix
  755. assert type(diag(1, cls=Matrix)) == Matrix
  756. assert Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
  757. assert Matrix.diag([1, 2, 3], unpack=False).shape == (3, 1)
  758. assert Matrix.diag([[1, 2, 3]]).shape == (3, 1)
  759. assert Matrix.diag([[1, 2, 3]], unpack=False).shape == (1, 3)
  760. assert Matrix.diag([[[1, 2, 3]]]).shape == (1, 3)
  761. # kerning can be used to move the starting point
  762. assert Matrix.diag(ones(0, 2), 1, 2) == Matrix([
  763. [0, 0, 1, 0],
  764. [0, 0, 0, 2]])
  765. assert Matrix.diag(ones(2, 0), 1, 2) == Matrix([
  766. [0, 0],
  767. [0, 0],
  768. [1, 0],
  769. [0, 2]])
  770. def test_diagonal():
  771. m = Matrix(3, 3, range(9))
  772. d = m.diagonal()
  773. assert d == m.diagonal(0)
  774. assert tuple(d) == (0, 4, 8)
  775. assert tuple(m.diagonal(1)) == (1, 5)
  776. assert tuple(m.diagonal(-1)) == (3, 7)
  777. assert tuple(m.diagonal(2)) == (2,)
  778. assert type(m.diagonal()) == type(m)
  779. s = SparseMatrix(3, 3, {(1, 1): 1})
  780. assert type(s.diagonal()) == type(s)
  781. assert type(m) != type(s)
  782. raises(ValueError, lambda: m.diagonal(3))
  783. raises(ValueError, lambda: m.diagonal(-3))
  784. raises(ValueError, lambda: m.diagonal(pi))
  785. M = ones(2, 3)
  786. assert banded({i: list(M.diagonal(i))
  787. for i in range(1-M.rows, M.cols)}) == M
  788. def test_jordan_block():
  789. assert SpecialOnlyMatrix.jordan_block(3, 2) == SpecialOnlyMatrix.jordan_block(3, eigenvalue=2) \
  790. == SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) \
  791. == SpecialOnlyMatrix.jordan_block(3, 2, band='upper') \
  792. == SpecialOnlyMatrix.jordan_block(
  793. size=3, eigenval=2, eigenvalue=2) \
  794. == Matrix([
  795. [2, 1, 0],
  796. [0, 2, 1],
  797. [0, 0, 2]])
  798. assert SpecialOnlyMatrix.jordan_block(3, 2, band='lower') == Matrix([
  799. [2, 0, 0],
  800. [1, 2, 0],
  801. [0, 1, 2]])
  802. # missing eigenvalue
  803. raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(2))
  804. # non-integral size
  805. raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(3.5, 2))
  806. # size not specified
  807. raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(eigenvalue=2))
  808. # inconsistent eigenvalue
  809. raises(ValueError,
  810. lambda: SpecialOnlyMatrix.jordan_block(
  811. eigenvalue=2, eigenval=4))
  812. # Using alias keyword
  813. assert SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) == \
  814. SpecialOnlyMatrix.jordan_block(size=3, eigenval=2)
  815. def test_orthogonalize():
  816. m = Matrix([[1, 2], [3, 4]])
  817. assert m.orthogonalize(Matrix([[2], [1]])) == [Matrix([[2], [1]])]
  818. assert m.orthogonalize(Matrix([[2], [1]]), normalize=True) == \
  819. [Matrix([[2*sqrt(5)/5], [sqrt(5)/5]])]
  820. assert m.orthogonalize(Matrix([[1], [2]]), Matrix([[-1], [4]])) == \
  821. [Matrix([[1], [2]]), Matrix([[Rational(-12, 5)], [Rational(6, 5)]])]
  822. assert m.orthogonalize(Matrix([[0], [0]]), Matrix([[-1], [4]])) == \
  823. [Matrix([[-1], [4]])]
  824. assert m.orthogonalize(Matrix([[0], [0]])) == []
  825. n = Matrix([[9, 1, 9], [3, 6, 10], [8, 5, 2]])
  826. vecs = [Matrix([[-5], [1]]), Matrix([[-5], [2]]), Matrix([[-5], [-2]])]
  827. assert n.orthogonalize(*vecs) == \
  828. [Matrix([[-5], [1]]), Matrix([[Rational(5, 26)], [Rational(25, 26)]])]
  829. vecs = [Matrix([0, 0, 0]), Matrix([1, 2, 3]), Matrix([1, 4, 5])]
  830. raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
  831. vecs = [Matrix([1, 2, 3]), Matrix([4, 5, 6]), Matrix([7, 8, 9])]
  832. raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
  833. def test_wilkinson():
  834. wminus, wplus = Matrix.wilkinson(1)
  835. assert wminus == Matrix([
  836. [-1, 1, 0],
  837. [1, 0, 1],
  838. [0, 1, 1]])
  839. assert wplus == Matrix([
  840. [1, 1, 0],
  841. [1, 0, 1],
  842. [0, 1, 1]])
  843. wminus, wplus = Matrix.wilkinson(3)
  844. assert wminus == Matrix([
  845. [-3, 1, 0, 0, 0, 0, 0],
  846. [1, -2, 1, 0, 0, 0, 0],
  847. [0, 1, -1, 1, 0, 0, 0],
  848. [0, 0, 1, 0, 1, 0, 0],
  849. [0, 0, 0, 1, 1, 1, 0],
  850. [0, 0, 0, 0, 1, 2, 1],
  851. [0, 0, 0, 0, 0, 1, 3]])
  852. assert wplus == Matrix([
  853. [3, 1, 0, 0, 0, 0, 0],
  854. [1, 2, 1, 0, 0, 0, 0],
  855. [0, 1, 1, 1, 0, 0, 0],
  856. [0, 0, 1, 0, 1, 0, 0],
  857. [0, 0, 0, 1, 1, 1, 0],
  858. [0, 0, 0, 0, 1, 2, 1],
  859. [0, 0, 0, 0, 0, 1, 3]])
  860. # CalculusOnlyMatrix tests
  861. @XFAIL
  862. def test_diff():
  863. x, y = symbols('x y')
  864. m = CalculusOnlyMatrix(2, 1, [x, y])
  865. # TODO: currently not working as ``_MinimalMatrix`` cannot be sympified:
  866. assert m.diff(x) == Matrix(2, 1, [1, 0])
  867. def test_integrate():
  868. x, y = symbols('x y')
  869. m = CalculusOnlyMatrix(2, 1, [x, y])
  870. assert m.integrate(x) == Matrix(2, 1, [x**2/2, y*x])
  871. def test_jacobian2():
  872. rho, phi = symbols("rho,phi")
  873. X = CalculusOnlyMatrix(3, 1, [rho*cos(phi), rho*sin(phi), rho**2])
  874. Y = CalculusOnlyMatrix(2, 1, [rho, phi])
  875. J = Matrix([
  876. [cos(phi), -rho*sin(phi)],
  877. [sin(phi), rho*cos(phi)],
  878. [ 2*rho, 0],
  879. ])
  880. assert X.jacobian(Y) == J
  881. m = CalculusOnlyMatrix(2, 2, [1, 2, 3, 4])
  882. m2 = CalculusOnlyMatrix(4, 1, [1, 2, 3, 4])
  883. raises(TypeError, lambda: m.jacobian(Matrix([1, 2])))
  884. raises(TypeError, lambda: m2.jacobian(m))
  885. def test_limit():
  886. x, y = symbols('x y')
  887. m = CalculusOnlyMatrix(2, 1, [1/x, y])
  888. assert m.limit(x, 5) == Matrix(2, 1, [Rational(1, 5), y])
  889. def test_issue_13774():
  890. M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  891. v = [1, 1, 1]
  892. raises(TypeError, lambda: M*v)
  893. raises(TypeError, lambda: v*M)
  894. def test_companion():
  895. x = Symbol('x')
  896. y = Symbol('y')
  897. raises(ValueError, lambda: Matrix.companion(1))
  898. raises(ValueError, lambda: Matrix.companion(Poly([1], x)))
  899. raises(ValueError, lambda: Matrix.companion(Poly([2, 1], x)))
  900. raises(ValueError, lambda: Matrix.companion(Poly(x*y, [x, y])))
  901. c0, c1, c2 = symbols('c0:3')
  902. assert Matrix.companion(Poly([1, c0], x)) == Matrix([-c0])
  903. assert Matrix.companion(Poly([1, c1, c0], x)) == \
  904. Matrix([[0, -c0], [1, -c1]])
  905. assert Matrix.companion(Poly([1, c2, c1, c0], x)) == \
  906. Matrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]])
  907. def test_issue_10589():
  908. x, y, z = symbols("x, y z")
  909. M1 = Matrix([x, y, z])
  910. M1 = M1.subs(zip([x, y, z], [1, 2, 3]))
  911. assert M1 == Matrix([[1], [2], [3]])
  912. M2 = Matrix([[x, x, x, x, x], [x, x, x, x, x], [x, x, x, x, x]])
  913. M2 = M2.subs(zip([x], [1]))
  914. assert M2 == Matrix([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])
  915. def test_rmul_pr19860():
  916. class Foo(ImmutableDenseMatrix):
  917. _op_priority = MutableDenseMatrix._op_priority + 0.01
  918. a = Matrix(2, 2, [1, 2, 3, 4])
  919. b = Foo(2, 2, [1, 2, 3, 4])
  920. # This would throw a RecursionError: maximum recursion depth
  921. # since b always has higher priority even after a.as_mutable()
  922. c = a*b
  923. assert isinstance(c, Foo)
  924. assert c == Matrix([[7, 10], [15, 22]])
  925. def test_issue_18956():
  926. A = Array([[1, 2], [3, 4]])
  927. B = Matrix([[1,2],[3,4]])
  928. raises(TypeError, lambda: B + A)
  929. raises(TypeError, lambda: A + B)
  930. def test__eq__():
  931. class My(object):
  932. def __iter__(self):
  933. yield 1
  934. yield 2
  935. return
  936. def __getitem__(self, i):
  937. return list(self)[i]
  938. a = Matrix(2, 1, [1, 2])
  939. assert a != My()
  940. class My_sympy(My):
  941. def _sympy_(self):
  942. return Matrix(self)
  943. assert a == My_sympy()