test_sparse.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. from sympy.core.numbers import (Float, I, Rational)
  2. from sympy.core.singleton import S
  3. from sympy.core.symbol import (Symbol, symbols)
  4. from sympy.functions.elementary.complexes import Abs
  5. from sympy.polys.polytools import PurePoly
  6. from sympy.matrices import \
  7. Matrix, MutableSparseMatrix, ImmutableSparseMatrix, SparseMatrix, eye, \
  8. ones, zeros, ShapeError, NonSquareMatrixError
  9. from sympy.testing.pytest import raises
  10. def test_sparse_creation():
  11. a = SparseMatrix(2, 2, {(0, 0): [[1, 2], [3, 4]]})
  12. assert a == SparseMatrix([[1, 2], [3, 4]])
  13. a = SparseMatrix(2, 2, {(0, 0): [[1, 2]]})
  14. assert a == SparseMatrix([[1, 2], [0, 0]])
  15. a = SparseMatrix(2, 2, {(0, 0): [1, 2]})
  16. assert a == SparseMatrix([[1, 0], [2, 0]])
  17. def test_sparse_matrix():
  18. def sparse_eye(n):
  19. return SparseMatrix.eye(n)
  20. def sparse_zeros(n):
  21. return SparseMatrix.zeros(n)
  22. # creation args
  23. raises(TypeError, lambda: SparseMatrix(1, 2))
  24. a = SparseMatrix((
  25. (1, 0),
  26. (0, 1)
  27. ))
  28. assert SparseMatrix(a) == a
  29. from sympy.matrices import MutableDenseMatrix
  30. a = MutableSparseMatrix([])
  31. b = MutableDenseMatrix([1, 2])
  32. assert a.row_join(b) == b
  33. assert a.col_join(b) == b
  34. assert type(a.row_join(b)) == type(a)
  35. assert type(a.col_join(b)) == type(a)
  36. # make sure 0 x n matrices get stacked correctly
  37. sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)]
  38. assert SparseMatrix.hstack(*sparse_matrices) == Matrix(0, 6, [])
  39. sparse_matrices = [SparseMatrix.zeros(n, 0) for n in range(4)]
  40. assert SparseMatrix.vstack(*sparse_matrices) == Matrix(6, 0, [])
  41. # test element assignment
  42. a = SparseMatrix((
  43. (1, 0),
  44. (0, 1)
  45. ))
  46. a[3] = 4
  47. assert a[1, 1] == 4
  48. a[3] = 1
  49. a[0, 0] = 2
  50. assert a == SparseMatrix((
  51. (2, 0),
  52. (0, 1)
  53. ))
  54. a[1, 0] = 5
  55. assert a == SparseMatrix((
  56. (2, 0),
  57. (5, 1)
  58. ))
  59. a[1, 1] = 0
  60. assert a == SparseMatrix((
  61. (2, 0),
  62. (5, 0)
  63. ))
  64. assert a.todok() == {(0, 0): 2, (1, 0): 5}
  65. # test_multiplication
  66. a = SparseMatrix((
  67. (1, 2),
  68. (3, 1),
  69. (0, 6),
  70. ))
  71. b = SparseMatrix((
  72. (1, 2),
  73. (3, 0),
  74. ))
  75. c = a*b
  76. assert c[0, 0] == 7
  77. assert c[0, 1] == 2
  78. assert c[1, 0] == 6
  79. assert c[1, 1] == 6
  80. assert c[2, 0] == 18
  81. assert c[2, 1] == 0
  82. try:
  83. eval('c = a @ b')
  84. except SyntaxError:
  85. pass
  86. else:
  87. assert c[0, 0] == 7
  88. assert c[0, 1] == 2
  89. assert c[1, 0] == 6
  90. assert c[1, 1] == 6
  91. assert c[2, 0] == 18
  92. assert c[2, 1] == 0
  93. x = Symbol("x")
  94. c = b * Symbol("x")
  95. assert isinstance(c, SparseMatrix)
  96. assert c[0, 0] == x
  97. assert c[0, 1] == 2*x
  98. assert c[1, 0] == 3*x
  99. assert c[1, 1] == 0
  100. c = 5 * b
  101. assert isinstance(c, SparseMatrix)
  102. assert c[0, 0] == 5
  103. assert c[0, 1] == 2*5
  104. assert c[1, 0] == 3*5
  105. assert c[1, 1] == 0
  106. #test_power
  107. A = SparseMatrix([[2, 3], [4, 5]])
  108. assert (A**5)[:] == [6140, 8097, 10796, 14237]
  109. A = SparseMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
  110. assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]
  111. # test_creation
  112. x = Symbol("x")
  113. a = SparseMatrix([[x, 0], [0, 0]])
  114. m = a
  115. assert m.cols == m.rows
  116. assert m.cols == 2
  117. assert m[:] == [x, 0, 0, 0]
  118. b = SparseMatrix(2, 2, [x, 0, 0, 0])
  119. m = b
  120. assert m.cols == m.rows
  121. assert m.cols == 2
  122. assert m[:] == [x, 0, 0, 0]
  123. assert a == b
  124. S = sparse_eye(3)
  125. S.row_del(1)
  126. assert S == SparseMatrix([
  127. [1, 0, 0],
  128. [0, 0, 1]])
  129. S = sparse_eye(3)
  130. S.col_del(1)
  131. assert S == SparseMatrix([
  132. [1, 0],
  133. [0, 0],
  134. [0, 1]])
  135. S = SparseMatrix.eye(3)
  136. S[2, 1] = 2
  137. S.col_swap(1, 0)
  138. assert S == SparseMatrix([
  139. [0, 1, 0],
  140. [1, 0, 0],
  141. [2, 0, 1]])
  142. S.row_swap(0, 1)
  143. assert S == SparseMatrix([
  144. [1, 0, 0],
  145. [0, 1, 0],
  146. [2, 0, 1]])
  147. a = SparseMatrix(1, 2, [1, 2])
  148. b = a.copy()
  149. c = a.copy()
  150. assert a[0] == 1
  151. a.row_del(0)
  152. assert a == SparseMatrix(0, 2, [])
  153. b.col_del(1)
  154. assert b == SparseMatrix(1, 1, [1])
  155. assert SparseMatrix([[1, 2, 3], [1, 2], [1]]) == Matrix([
  156. [1, 2, 3],
  157. [1, 2, 0],
  158. [1, 0, 0]])
  159. assert SparseMatrix(4, 4, {(1, 1): sparse_eye(2)}) == Matrix([
  160. [0, 0, 0, 0],
  161. [0, 1, 0, 0],
  162. [0, 0, 1, 0],
  163. [0, 0, 0, 0]])
  164. raises(ValueError, lambda: SparseMatrix(1, 1, {(1, 1): 1}))
  165. assert SparseMatrix(1, 2, [1, 2]).tolist() == [[1, 2]]
  166. assert SparseMatrix(2, 2, [1, [2, 3]]).tolist() == [[1, 0], [2, 3]]
  167. raises(ValueError, lambda: SparseMatrix(2, 2, [1]))
  168. raises(ValueError, lambda: SparseMatrix(1, 1, [[1, 2]]))
  169. assert SparseMatrix([.1]).has(Float)
  170. # autosizing
  171. assert SparseMatrix(None, {(0, 1): 0}).shape == (0, 0)
  172. assert SparseMatrix(None, {(0, 1): 1}).shape == (1, 2)
  173. assert SparseMatrix(None, None, {(0, 1): 1}).shape == (1, 2)
  174. raises(ValueError, lambda: SparseMatrix(None, 1, [[1, 2]]))
  175. raises(ValueError, lambda: SparseMatrix(1, None, [[1, 2]]))
  176. raises(ValueError, lambda: SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2}))
  177. # test_determinant
  178. x, y = Symbol('x'), Symbol('y')
  179. assert SparseMatrix(1, 1, [0]).det() == 0
  180. assert SparseMatrix([[1]]).det() == 1
  181. assert SparseMatrix(((-3, 2), (8, -5))).det() == -1
  182. assert SparseMatrix(((x, 1), (y, 2*y))).det() == 2*x*y - y
  183. assert SparseMatrix(( (1, 1, 1),
  184. (1, 2, 3),
  185. (1, 3, 6) )).det() == 1
  186. assert SparseMatrix(( ( 3, -2, 0, 5),
  187. (-2, 1, -2, 2),
  188. ( 0, -2, 5, 0),
  189. ( 5, 0, 3, 4) )).det() == -289
  190. assert SparseMatrix(( ( 1, 2, 3, 4),
  191. ( 5, 6, 7, 8),
  192. ( 9, 10, 11, 12),
  193. (13, 14, 15, 16) )).det() == 0
  194. assert SparseMatrix(( (3, 2, 0, 0, 0),
  195. (0, 3, 2, 0, 0),
  196. (0, 0, 3, 2, 0),
  197. (0, 0, 0, 3, 2),
  198. (2, 0, 0, 0, 3) )).det() == 275
  199. assert SparseMatrix(( (1, 0, 1, 2, 12),
  200. (2, 0, 1, 1, 4),
  201. (2, 1, 1, -1, 3),
  202. (3, 2, -1, 1, 8),
  203. (1, 1, 1, 0, 6) )).det() == -55
  204. assert SparseMatrix(( (-5, 2, 3, 4, 5),
  205. ( 1, -4, 3, 4, 5),
  206. ( 1, 2, -3, 4, 5),
  207. ( 1, 2, 3, -2, 5),
  208. ( 1, 2, 3, 4, -1) )).det() == 11664
  209. assert SparseMatrix(( ( 3, 0, 0, 0),
  210. (-2, 1, 0, 0),
  211. ( 0, -2, 5, 0),
  212. ( 5, 0, 3, 4) )).det() == 60
  213. assert SparseMatrix(( ( 1, 0, 0, 0),
  214. ( 5, 0, 0, 0),
  215. ( 9, 10, 11, 0),
  216. (13, 14, 15, 16) )).det() == 0
  217. assert SparseMatrix(( (3, 2, 0, 0, 0),
  218. (0, 3, 2, 0, 0),
  219. (0, 0, 3, 2, 0),
  220. (0, 0, 0, 3, 2),
  221. (0, 0, 0, 0, 3) )).det() == 243
  222. assert SparseMatrix(( ( 2, 7, -1, 3, 2),
  223. ( 0, 0, 1, 0, 1),
  224. (-2, 0, 7, 0, 2),
  225. (-3, -2, 4, 5, 3),
  226. ( 1, 0, 0, 0, 1) )).det() == 123
  227. # test_slicing
  228. m0 = sparse_eye(4)
  229. assert m0[:3, :3] == sparse_eye(3)
  230. assert m0[2:4, 0:2] == sparse_zeros(2)
  231. m1 = SparseMatrix(3, 3, lambda i, j: i + j)
  232. assert m1[0, :] == SparseMatrix(1, 3, (0, 1, 2))
  233. assert m1[1:3, 1] == SparseMatrix(2, 1, (2, 3))
  234. m2 = SparseMatrix(
  235. [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
  236. assert m2[:, -1] == SparseMatrix(4, 1, [3, 7, 11, 15])
  237. assert m2[-2:, :] == SparseMatrix([[8, 9, 10, 11], [12, 13, 14, 15]])
  238. assert SparseMatrix([[1, 2], [3, 4]])[[1], [1]] == Matrix([[4]])
  239. # test_submatrix_assignment
  240. m = sparse_zeros(4)
  241. m[2:4, 2:4] = sparse_eye(2)
  242. assert m == SparseMatrix([(0, 0, 0, 0),
  243. (0, 0, 0, 0),
  244. (0, 0, 1, 0),
  245. (0, 0, 0, 1)])
  246. assert len(m.todok()) == 2
  247. m[:2, :2] = sparse_eye(2)
  248. assert m == sparse_eye(4)
  249. m[:, 0] = SparseMatrix(4, 1, (1, 2, 3, 4))
  250. assert m == SparseMatrix([(1, 0, 0, 0),
  251. (2, 1, 0, 0),
  252. (3, 0, 1, 0),
  253. (4, 0, 0, 1)])
  254. m[:, :] = sparse_zeros(4)
  255. assert m == sparse_zeros(4)
  256. m[:, :] = ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))
  257. assert m == SparseMatrix((( 1, 2, 3, 4),
  258. ( 5, 6, 7, 8),
  259. ( 9, 10, 11, 12),
  260. (13, 14, 15, 16)))
  261. m[:2, 0] = [0, 0]
  262. assert m == SparseMatrix((( 0, 2, 3, 4),
  263. ( 0, 6, 7, 8),
  264. ( 9, 10, 11, 12),
  265. (13, 14, 15, 16)))
  266. # test_reshape
  267. m0 = sparse_eye(3)
  268. assert m0.reshape(1, 9) == SparseMatrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
  269. m1 = SparseMatrix(3, 4, lambda i, j: i + j)
  270. assert m1.reshape(4, 3) == \
  271. SparseMatrix([(0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)])
  272. assert m1.reshape(2, 6) == \
  273. SparseMatrix([(0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)])
  274. # test_applyfunc
  275. m0 = sparse_eye(3)
  276. assert m0.applyfunc(lambda x: 2*x) == sparse_eye(3)*2
  277. assert m0.applyfunc(lambda x: 0 ) == sparse_zeros(3)
  278. # test__eval_Abs
  279. assert abs(SparseMatrix(((x, 1), (y, 2*y)))) == SparseMatrix(((Abs(x), 1), (Abs(y), 2*Abs(y))))
  280. # test_LUdecomp
  281. testmat = SparseMatrix([[ 0, 2, 5, 3],
  282. [ 3, 3, 7, 4],
  283. [ 8, 4, 0, 2],
  284. [-2, 6, 3, 4]])
  285. L, U, p = testmat.LUdecomposition()
  286. assert L.is_lower
  287. assert U.is_upper
  288. assert (L*U).permute_rows(p, 'backward') - testmat == sparse_zeros(4)
  289. testmat = SparseMatrix([[ 6, -2, 7, 4],
  290. [ 0, 3, 6, 7],
  291. [ 1, -2, 7, 4],
  292. [-9, 2, 6, 3]])
  293. L, U, p = testmat.LUdecomposition()
  294. assert L.is_lower
  295. assert U.is_upper
  296. assert (L*U).permute_rows(p, 'backward') - testmat == sparse_zeros(4)
  297. x, y, z = Symbol('x'), Symbol('y'), Symbol('z')
  298. M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z)))
  299. L, U, p = M.LUdecomposition()
  300. assert L.is_lower
  301. assert U.is_upper
  302. assert (L*U).permute_rows(p, 'backward') - M == sparse_zeros(3)
  303. # test_LUsolve
  304. A = SparseMatrix([[2, 3, 5],
  305. [3, 6, 2],
  306. [8, 3, 6]])
  307. x = SparseMatrix(3, 1, [3, 7, 5])
  308. b = A*x
  309. soln = A.LUsolve(b)
  310. assert soln == x
  311. A = SparseMatrix([[0, -1, 2],
  312. [5, 10, 7],
  313. [8, 3, 4]])
  314. x = SparseMatrix(3, 1, [-1, 2, 5])
  315. b = A*x
  316. soln = A.LUsolve(b)
  317. assert soln == x
  318. # test_inverse
  319. A = sparse_eye(4)
  320. assert A.inv() == sparse_eye(4)
  321. assert A.inv(method="CH") == sparse_eye(4)
  322. assert A.inv(method="LDL") == sparse_eye(4)
  323. A = SparseMatrix([[2, 3, 5],
  324. [3, 6, 2],
  325. [7, 2, 6]])
  326. Ainv = SparseMatrix(Matrix(A).inv())
  327. assert A*Ainv == sparse_eye(3)
  328. assert A.inv(method="CH") == Ainv
  329. assert A.inv(method="LDL") == Ainv
  330. A = SparseMatrix([[2, 3, 5],
  331. [3, 6, 2],
  332. [5, 2, 6]])
  333. Ainv = SparseMatrix(Matrix(A).inv())
  334. assert A*Ainv == sparse_eye(3)
  335. assert A.inv(method="CH") == Ainv
  336. assert A.inv(method="LDL") == Ainv
  337. # test_cross
  338. v1 = Matrix(1, 3, [1, 2, 3])
  339. v2 = Matrix(1, 3, [3, 4, 5])
  340. assert v1.cross(v2) == Matrix(1, 3, [-2, 4, -2])
  341. assert v1.norm(2)**2 == 14
  342. # conjugate
  343. a = SparseMatrix(((1, 2 + I), (3, 4)))
  344. assert a.C == SparseMatrix([
  345. [1, 2 - I],
  346. [3, 4]
  347. ])
  348. # mul
  349. assert a*Matrix(2, 2, [1, 0, 0, 1]) == a
  350. assert a + Matrix(2, 2, [1, 1, 1, 1]) == SparseMatrix([
  351. [2, 3 + I],
  352. [4, 5]
  353. ])
  354. # col join
  355. assert a.col_join(sparse_eye(2)) == SparseMatrix([
  356. [1, 2 + I],
  357. [3, 4],
  358. [1, 0],
  359. [0, 1]
  360. ])
  361. # row insert
  362. assert a.row_insert(2, sparse_eye(2)) == SparseMatrix([
  363. [1, 2 + I],
  364. [3, 4],
  365. [1, 0],
  366. [0, 1]
  367. ])
  368. # col insert
  369. assert a.col_insert(2, SparseMatrix.zeros(2, 1)) == SparseMatrix([
  370. [1, 2 + I, 0],
  371. [3, 4, 0],
  372. ])
  373. # symmetric
  374. assert not a.is_symmetric(simplify=False)
  375. # col op
  376. M = SparseMatrix.eye(3)*2
  377. M[1, 0] = -1
  378. M.col_op(1, lambda v, i: v + 2*M[i, 0])
  379. assert M == SparseMatrix([
  380. [ 2, 4, 0],
  381. [-1, 0, 0],
  382. [ 0, 0, 2]
  383. ])
  384. # fill
  385. M = SparseMatrix.eye(3)
  386. M.fill(2)
  387. assert M == SparseMatrix([
  388. [2, 2, 2],
  389. [2, 2, 2],
  390. [2, 2, 2],
  391. ])
  392. # test_cofactor
  393. assert sparse_eye(3) == sparse_eye(3).cofactor_matrix()
  394. test = SparseMatrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]])
  395. assert test.cofactor_matrix() == \
  396. SparseMatrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]])
  397. test = SparseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  398. assert test.cofactor_matrix() == \
  399. SparseMatrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]])
  400. # test_jacobian
  401. x = Symbol('x')
  402. y = Symbol('y')
  403. L = SparseMatrix(1, 2, [x**2*y, 2*y**2 + x*y])
  404. syms = [x, y]
  405. assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]])
  406. L = SparseMatrix(1, 2, [x, x**2*y**3])
  407. assert L.jacobian(syms) == SparseMatrix([[1, 0], [2*x*y**3, x**2*3*y**2]])
  408. # test_QR
  409. A = Matrix([[1, 2], [2, 3]])
  410. Q, S = A.QRdecomposition()
  411. R = Rational
  412. assert Q == Matrix([
  413. [ 5**R(-1, 2), (R(2)/5)*(R(1)/5)**R(-1, 2)],
  414. [2*5**R(-1, 2), (-R(1)/5)*(R(1)/5)**R(-1, 2)]])
  415. assert S == Matrix([
  416. [5**R(1, 2), 8*5**R(-1, 2)],
  417. [ 0, (R(1)/5)**R(1, 2)]])
  418. assert Q*S == A
  419. assert Q.T * Q == sparse_eye(2)
  420. R = Rational
  421. # test nullspace
  422. # first test reduced row-ech form
  423. M = SparseMatrix([[5, 7, 2, 1],
  424. [1, 6, 2, -1]])
  425. out, tmp = M.rref()
  426. assert out == Matrix([[1, 0, -R(2)/23, R(13)/23],
  427. [0, 1, R(8)/23, R(-6)/23]])
  428. M = SparseMatrix([[ 1, 3, 0, 2, 6, 3, 1],
  429. [-2, -6, 0, -2, -8, 3, 1],
  430. [ 3, 9, 0, 0, 6, 6, 2],
  431. [-1, -3, 0, 1, 0, 9, 3]])
  432. out, tmp = M.rref()
  433. assert out == Matrix([[1, 3, 0, 0, 2, 0, 0],
  434. [0, 0, 0, 1, 2, 0, 0],
  435. [0, 0, 0, 0, 0, 1, R(1)/3],
  436. [0, 0, 0, 0, 0, 0, 0]])
  437. # now check the vectors
  438. basis = M.nullspace()
  439. assert basis[0] == Matrix([-3, 1, 0, 0, 0, 0, 0])
  440. assert basis[1] == Matrix([0, 0, 1, 0, 0, 0, 0])
  441. assert basis[2] == Matrix([-2, 0, 0, -2, 1, 0, 0])
  442. assert basis[3] == Matrix([0, 0, 0, 0, 0, R(-1)/3, 1])
  443. # test eigen
  444. x = Symbol('x')
  445. y = Symbol('y')
  446. sparse_eye3 = sparse_eye(3)
  447. assert sparse_eye3.charpoly(x) == PurePoly((x - 1)**3)
  448. assert sparse_eye3.charpoly(y) == PurePoly((y - 1)**3)
  449. # test values
  450. M = Matrix([( 0, 1, -1),
  451. ( 1, 1, 0),
  452. (-1, 0, 1)])
  453. vals = M.eigenvals()
  454. assert sorted(vals.keys()) == [-1, 1, 2]
  455. R = Rational
  456. M = Matrix([[1, 0, 0],
  457. [0, 1, 0],
  458. [0, 0, 1]])
  459. assert M.eigenvects() == [(1, 3, [
  460. Matrix([1, 0, 0]),
  461. Matrix([0, 1, 0]),
  462. Matrix([0, 0, 1])])]
  463. M = Matrix([[5, 0, 2],
  464. [3, 2, 0],
  465. [0, 0, 1]])
  466. assert M.eigenvects() == [(1, 1, [Matrix([R(-1)/2, R(3)/2, 1])]),
  467. (2, 1, [Matrix([0, 1, 0])]),
  468. (5, 1, [Matrix([1, 1, 0])])]
  469. assert M.zeros(3, 5) == SparseMatrix(3, 5, {})
  470. A = SparseMatrix(10, 10, {(0, 0): 18, (0, 9): 12, (1, 4): 18, (2, 7): 16, (3, 9): 12, (4, 2): 19, (5, 7): 16, (6, 2): 12, (9, 7): 18})
  471. assert A.row_list() == [(0, 0, 18), (0, 9, 12), (1, 4, 18), (2, 7, 16), (3, 9, 12), (4, 2, 19), (5, 7, 16), (6, 2, 12), (9, 7, 18)]
  472. assert A.col_list() == [(0, 0, 18), (4, 2, 19), (6, 2, 12), (1, 4, 18), (2, 7, 16), (5, 7, 16), (9, 7, 18), (0, 9, 12), (3, 9, 12)]
  473. assert SparseMatrix.eye(2).nnz() == 2
  474. def test_scalar_multiply():
  475. assert SparseMatrix([[1, 2]]).scalar_multiply(3) == SparseMatrix([[3, 6]])
  476. def test_transpose():
  477. assert SparseMatrix(((1, 2), (3, 4))).transpose() == \
  478. SparseMatrix(((1, 3), (2, 4)))
  479. def test_trace():
  480. assert SparseMatrix(((1, 2), (3, 4))).trace() == 5
  481. assert SparseMatrix(((0, 0), (0, 4))).trace() == 4
  482. def test_CL_RL():
  483. assert SparseMatrix(((1, 2), (3, 4))).row_list() == \
  484. [(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)]
  485. assert SparseMatrix(((1, 2), (3, 4))).col_list() == \
  486. [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)]
  487. def test_add():
  488. assert SparseMatrix(((1, 0), (0, 1))) + SparseMatrix(((0, 1), (1, 0))) == \
  489. SparseMatrix(((1, 1), (1, 1)))
  490. a = SparseMatrix(100, 100, lambda i, j: int(j != 0 and i % j == 0))
  491. b = SparseMatrix(100, 100, lambda i, j: int(i != 0 and j % i == 0))
  492. assert (len(a.todok()) + len(b.todok()) - len((a + b).todok()) > 0)
  493. def test_errors():
  494. raises(ValueError, lambda: SparseMatrix(1.4, 2, lambda i, j: 0))
  495. raises(TypeError, lambda: SparseMatrix([1, 2, 3], [1, 2]))
  496. raises(ValueError, lambda: SparseMatrix([[1, 2], [3, 4]])[(1, 2, 3)])
  497. raises(IndexError, lambda: SparseMatrix([[1, 2], [3, 4]])[5])
  498. raises(ValueError, lambda: SparseMatrix([[1, 2], [3, 4]])[1, 2, 3])
  499. raises(TypeError,
  500. lambda: SparseMatrix([[1, 2], [3, 4]]).copyin_list([0, 1], set()))
  501. raises(
  502. IndexError, lambda: SparseMatrix([[1, 2], [3, 4]])[1, 2])
  503. raises(TypeError, lambda: SparseMatrix([1, 2, 3]).cross(1))
  504. raises(IndexError, lambda: SparseMatrix(1, 2, [1, 2])[3])
  505. raises(ShapeError,
  506. lambda: SparseMatrix(1, 2, [1, 2]) + SparseMatrix(2, 1, [2, 1]))
  507. def test_len():
  508. assert not SparseMatrix()
  509. assert SparseMatrix() == SparseMatrix([])
  510. assert SparseMatrix() == SparseMatrix([[]])
  511. def test_sparse_zeros_sparse_eye():
  512. assert SparseMatrix.eye(3) == eye(3, cls=SparseMatrix)
  513. assert len(SparseMatrix.eye(3).todok()) == 3
  514. assert SparseMatrix.zeros(3) == zeros(3, cls=SparseMatrix)
  515. assert len(SparseMatrix.zeros(3).todok()) == 0
  516. def test_copyin():
  517. s = SparseMatrix(3, 3, {})
  518. s[1, 0] = 1
  519. assert s[:, 0] == SparseMatrix(Matrix([0, 1, 0]))
  520. assert s[3] == 1
  521. assert s[3: 4] == [1]
  522. s[1, 1] = 42
  523. assert s[1, 1] == 42
  524. assert s[1, 1:] == SparseMatrix([[42, 0]])
  525. s[1, 1:] = Matrix([[5, 6]])
  526. assert s[1, :] == SparseMatrix([[1, 5, 6]])
  527. s[1, 1:] = [[42, 43]]
  528. assert s[1, :] == SparseMatrix([[1, 42, 43]])
  529. s[0, 0] = 17
  530. assert s[:, :1] == SparseMatrix([17, 1, 0])
  531. s[0, 0] = [1, 1, 1]
  532. assert s[:, 0] == SparseMatrix([1, 1, 1])
  533. s[0, 0] = Matrix([1, 1, 1])
  534. assert s[:, 0] == SparseMatrix([1, 1, 1])
  535. s[0, 0] = SparseMatrix([1, 1, 1])
  536. assert s[:, 0] == SparseMatrix([1, 1, 1])
  537. def test_sparse_solve():
  538. A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
  539. assert A.cholesky() == Matrix([
  540. [ 5, 0, 0],
  541. [ 3, 3, 0],
  542. [-1, 1, 3]])
  543. assert A.cholesky() * A.cholesky().T == Matrix([
  544. [25, 15, -5],
  545. [15, 18, 0],
  546. [-5, 0, 11]])
  547. A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
  548. L, D = A.LDLdecomposition()
  549. assert 15*L == Matrix([
  550. [15, 0, 0],
  551. [ 9, 15, 0],
  552. [-3, 5, 15]])
  553. assert D == Matrix([
  554. [25, 0, 0],
  555. [ 0, 9, 0],
  556. [ 0, 0, 9]])
  557. assert L * D * L.T == A
  558. A = SparseMatrix(((3, 0, 2), (0, 0, 1), (1, 2, 0)))
  559. assert A.inv() * A == SparseMatrix(eye(3))
  560. A = SparseMatrix([
  561. [ 2, -1, 0],
  562. [-1, 2, -1],
  563. [ 0, 0, 2]])
  564. ans = SparseMatrix([
  565. [Rational(2, 3), Rational(1, 3), Rational(1, 6)],
  566. [Rational(1, 3), Rational(2, 3), Rational(1, 3)],
  567. [ 0, 0, S.Half]])
  568. assert A.inv(method='CH') == ans
  569. assert A.inv(method='LDL') == ans
  570. assert A * ans == SparseMatrix(eye(3))
  571. s = A.solve(A[:, 0], 'LDL')
  572. assert A*s == A[:, 0]
  573. s = A.solve(A[:, 0], 'CH')
  574. assert A*s == A[:, 0]
  575. A = A.col_join(A)
  576. s = A.solve_least_squares(A[:, 0], 'CH')
  577. assert A*s == A[:, 0]
  578. s = A.solve_least_squares(A[:, 0], 'LDL')
  579. assert A*s == A[:, 0]
  580. def test_lower_triangular_solve():
  581. raises(NonSquareMatrixError, lambda:
  582. SparseMatrix([[1, 2]]).lower_triangular_solve(Matrix([[1, 2]])))
  583. raises(ShapeError, lambda:
  584. SparseMatrix([[1, 2], [0, 4]]).lower_triangular_solve(Matrix([1])))
  585. raises(ValueError, lambda:
  586. SparseMatrix([[1, 2], [3, 4]]).lower_triangular_solve(Matrix([[1, 2], [3, 4]])))
  587. a, b, c, d = symbols('a:d')
  588. u, v, w, x = symbols('u:x')
  589. A = SparseMatrix([[a, 0], [c, d]])
  590. B = MutableSparseMatrix([[u, v], [w, x]])
  591. C = ImmutableSparseMatrix([[u, v], [w, x]])
  592. sol = Matrix([[u/a, v/a], [(w - c*u/a)/d, (x - c*v/a)/d]])
  593. assert A.lower_triangular_solve(B) == sol
  594. assert A.lower_triangular_solve(C) == sol
  595. def test_upper_triangular_solve():
  596. raises(NonSquareMatrixError, lambda:
  597. SparseMatrix([[1, 2]]).upper_triangular_solve(Matrix([[1, 2]])))
  598. raises(ShapeError, lambda:
  599. SparseMatrix([[1, 2], [0, 4]]).upper_triangular_solve(Matrix([1])))
  600. raises(TypeError, lambda:
  601. SparseMatrix([[1, 2], [3, 4]]).upper_triangular_solve(Matrix([[1, 2], [3, 4]])))
  602. a, b, c, d = symbols('a:d')
  603. u, v, w, x = symbols('u:x')
  604. A = SparseMatrix([[a, b], [0, d]])
  605. B = MutableSparseMatrix([[u, v], [w, x]])
  606. C = ImmutableSparseMatrix([[u, v], [w, x]])
  607. sol = Matrix([[(u - b*w/d)/a, (v - b*x/d)/a], [w/d, x/d]])
  608. assert A.upper_triangular_solve(B) == sol
  609. assert A.upper_triangular_solve(C) == sol
  610. def test_diagonal_solve():
  611. a, d = symbols('a d')
  612. u, v, w, x = symbols('u:x')
  613. A = SparseMatrix([[a, 0], [0, d]])
  614. B = MutableSparseMatrix([[u, v], [w, x]])
  615. C = ImmutableSparseMatrix([[u, v], [w, x]])
  616. sol = Matrix([[u/a, v/a], [w/d, x/d]])
  617. assert A.diagonal_solve(B) == sol
  618. assert A.diagonal_solve(C) == sol
  619. def test_hermitian():
  620. x = Symbol('x')
  621. a = SparseMatrix([[0, I], [-I, 0]])
  622. assert a.is_hermitian
  623. a = SparseMatrix([[1, I], [-I, 1]])
  624. assert a.is_hermitian
  625. a[0, 0] = 2*I
  626. assert a.is_hermitian is False
  627. a[0, 0] = x
  628. assert a.is_hermitian is None
  629. a[0, 1] = a[1, 0]*I
  630. assert a.is_hermitian is False