test_defmatrix.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import collections.abc
  2. import numpy as np
  3. from numpy import matrix, asmatrix, bmat
  4. from numpy.testing import (
  5. assert_, assert_equal, assert_almost_equal, assert_array_equal,
  6. assert_array_almost_equal, assert_raises
  7. )
  8. from numpy.linalg import matrix_power
  9. from numpy.matrixlib import mat
  10. class TestCtor:
  11. def test_basic(self):
  12. A = np.array([[1, 2], [3, 4]])
  13. mA = matrix(A)
  14. assert_(np.all(mA.A == A))
  15. B = bmat("A,A;A,A")
  16. C = bmat([[A, A], [A, A]])
  17. D = np.array([[1, 2, 1, 2],
  18. [3, 4, 3, 4],
  19. [1, 2, 1, 2],
  20. [3, 4, 3, 4]])
  21. assert_(np.all(B.A == D))
  22. assert_(np.all(C.A == D))
  23. E = np.array([[5, 6], [7, 8]])
  24. AEresult = matrix([[1, 2, 5, 6], [3, 4, 7, 8]])
  25. assert_(np.all(bmat([A, E]) == AEresult))
  26. vec = np.arange(5)
  27. mvec = matrix(vec)
  28. assert_(mvec.shape == (1, 5))
  29. def test_exceptions(self):
  30. # Check for ValueError when called with invalid string data.
  31. assert_raises(ValueError, matrix, "invalid")
  32. def test_bmat_nondefault_str(self):
  33. A = np.array([[1, 2], [3, 4]])
  34. B = np.array([[5, 6], [7, 8]])
  35. Aresult = np.array([[1, 2, 1, 2],
  36. [3, 4, 3, 4],
  37. [1, 2, 1, 2],
  38. [3, 4, 3, 4]])
  39. mixresult = np.array([[1, 2, 5, 6],
  40. [3, 4, 7, 8],
  41. [5, 6, 1, 2],
  42. [7, 8, 3, 4]])
  43. assert_(np.all(bmat("A,A;A,A") == Aresult))
  44. assert_(np.all(bmat("A,A;A,A", ldict={'A':B}) == Aresult))
  45. assert_raises(TypeError, bmat, "A,A;A,A", gdict={'A':B})
  46. assert_(
  47. np.all(bmat("A,A;A,A", ldict={'A':A}, gdict={'A':B}) == Aresult))
  48. b2 = bmat("A,B;C,D", ldict={'A':A,'B':B}, gdict={'C':B,'D':A})
  49. assert_(np.all(b2 == mixresult))
  50. class TestProperties:
  51. def test_sum(self):
  52. """Test whether matrix.sum(axis=1) preserves orientation.
  53. Fails in NumPy <= 0.9.6.2127.
  54. """
  55. M = matrix([[1, 2, 0, 0],
  56. [3, 4, 0, 0],
  57. [1, 2, 1, 2],
  58. [3, 4, 3, 4]])
  59. sum0 = matrix([8, 12, 4, 6])
  60. sum1 = matrix([3, 7, 6, 14]).T
  61. sumall = 30
  62. assert_array_equal(sum0, M.sum(axis=0))
  63. assert_array_equal(sum1, M.sum(axis=1))
  64. assert_equal(sumall, M.sum())
  65. assert_array_equal(sum0, np.sum(M, axis=0))
  66. assert_array_equal(sum1, np.sum(M, axis=1))
  67. assert_equal(sumall, np.sum(M))
  68. def test_prod(self):
  69. x = matrix([[1, 2, 3], [4, 5, 6]])
  70. assert_equal(x.prod(), 720)
  71. assert_equal(x.prod(0), matrix([[4, 10, 18]]))
  72. assert_equal(x.prod(1), matrix([[6], [120]]))
  73. assert_equal(np.prod(x), 720)
  74. assert_equal(np.prod(x, axis=0), matrix([[4, 10, 18]]))
  75. assert_equal(np.prod(x, axis=1), matrix([[6], [120]]))
  76. y = matrix([0, 1, 3])
  77. assert_(y.prod() == 0)
  78. def test_max(self):
  79. x = matrix([[1, 2, 3], [4, 5, 6]])
  80. assert_equal(x.max(), 6)
  81. assert_equal(x.max(0), matrix([[4, 5, 6]]))
  82. assert_equal(x.max(1), matrix([[3], [6]]))
  83. assert_equal(np.max(x), 6)
  84. assert_equal(np.max(x, axis=0), matrix([[4, 5, 6]]))
  85. assert_equal(np.max(x, axis=1), matrix([[3], [6]]))
  86. def test_min(self):
  87. x = matrix([[1, 2, 3], [4, 5, 6]])
  88. assert_equal(x.min(), 1)
  89. assert_equal(x.min(0), matrix([[1, 2, 3]]))
  90. assert_equal(x.min(1), matrix([[1], [4]]))
  91. assert_equal(np.min(x), 1)
  92. assert_equal(np.min(x, axis=0), matrix([[1, 2, 3]]))
  93. assert_equal(np.min(x, axis=1), matrix([[1], [4]]))
  94. def test_ptp(self):
  95. x = np.arange(4).reshape((2, 2))
  96. assert_(x.ptp() == 3)
  97. assert_(np.all(x.ptp(0) == np.array([2, 2])))
  98. assert_(np.all(x.ptp(1) == np.array([1, 1])))
  99. def test_var(self):
  100. x = np.arange(9).reshape((3, 3))
  101. mx = x.view(np.matrix)
  102. assert_equal(x.var(ddof=0), mx.var(ddof=0))
  103. assert_equal(x.var(ddof=1), mx.var(ddof=1))
  104. def test_basic(self):
  105. import numpy.linalg as linalg
  106. A = np.array([[1., 2.],
  107. [3., 4.]])
  108. mA = matrix(A)
  109. assert_(np.allclose(linalg.inv(A), mA.I))
  110. assert_(np.all(np.array(np.transpose(A) == mA.T)))
  111. assert_(np.all(np.array(np.transpose(A) == mA.H)))
  112. assert_(np.all(A == mA.A))
  113. B = A + 2j*A
  114. mB = matrix(B)
  115. assert_(np.allclose(linalg.inv(B), mB.I))
  116. assert_(np.all(np.array(np.transpose(B) == mB.T)))
  117. assert_(np.all(np.array(np.transpose(B).conj() == mB.H)))
  118. def test_pinv(self):
  119. x = matrix(np.arange(6).reshape(2, 3))
  120. xpinv = matrix([[-0.77777778, 0.27777778],
  121. [-0.11111111, 0.11111111],
  122. [ 0.55555556, -0.05555556]])
  123. assert_almost_equal(x.I, xpinv)
  124. def test_comparisons(self):
  125. A = np.arange(100).reshape(10, 10)
  126. mA = matrix(A)
  127. mB = matrix(A) + 0.1
  128. assert_(np.all(mB == A+0.1))
  129. assert_(np.all(mB == matrix(A+0.1)))
  130. assert_(not np.any(mB == matrix(A-0.1)))
  131. assert_(np.all(mA < mB))
  132. assert_(np.all(mA <= mB))
  133. assert_(np.all(mA <= mA))
  134. assert_(not np.any(mA < mA))
  135. assert_(not np.any(mB < mA))
  136. assert_(np.all(mB >= mA))
  137. assert_(np.all(mB >= mB))
  138. assert_(not np.any(mB > mB))
  139. assert_(np.all(mA == mA))
  140. assert_(not np.any(mA == mB))
  141. assert_(np.all(mB != mA))
  142. assert_(not np.all(abs(mA) > 0))
  143. assert_(np.all(abs(mB > 0)))
  144. def test_asmatrix(self):
  145. A = np.arange(100).reshape(10, 10)
  146. mA = asmatrix(A)
  147. A[0, 0] = -10
  148. assert_(A[0, 0] == mA[0, 0])
  149. def test_noaxis(self):
  150. A = matrix([[1, 0], [0, 1]])
  151. assert_(A.sum() == matrix(2))
  152. assert_(A.mean() == matrix(0.5))
  153. def test_repr(self):
  154. A = matrix([[1, 0], [0, 1]])
  155. assert_(repr(A) == "matrix([[1, 0],\n [0, 1]])")
  156. def test_make_bool_matrix_from_str(self):
  157. A = matrix('True; True; False')
  158. B = matrix([[True], [True], [False]])
  159. assert_array_equal(A, B)
  160. class TestCasting:
  161. def test_basic(self):
  162. A = np.arange(100).reshape(10, 10)
  163. mA = matrix(A)
  164. mB = mA.copy()
  165. O = np.ones((10, 10), np.float64) * 0.1
  166. mB = mB + O
  167. assert_(mB.dtype.type == np.float64)
  168. assert_(np.all(mA != mB))
  169. assert_(np.all(mB == mA+0.1))
  170. mC = mA.copy()
  171. O = np.ones((10, 10), np.complex128)
  172. mC = mC * O
  173. assert_(mC.dtype.type == np.complex128)
  174. assert_(np.all(mA != mB))
  175. class TestAlgebra:
  176. def test_basic(self):
  177. import numpy.linalg as linalg
  178. A = np.array([[1., 2.], [3., 4.]])
  179. mA = matrix(A)
  180. B = np.identity(2)
  181. for i in range(6):
  182. assert_(np.allclose((mA ** i).A, B))
  183. B = np.dot(B, A)
  184. Ainv = linalg.inv(A)
  185. B = np.identity(2)
  186. for i in range(6):
  187. assert_(np.allclose((mA ** -i).A, B))
  188. B = np.dot(B, Ainv)
  189. assert_(np.allclose((mA * mA).A, np.dot(A, A)))
  190. assert_(np.allclose((mA + mA).A, (A + A)))
  191. assert_(np.allclose((3*mA).A, (3*A)))
  192. mA2 = matrix(A)
  193. mA2 *= 3
  194. assert_(np.allclose(mA2.A, 3*A))
  195. def test_pow(self):
  196. """Test raising a matrix to an integer power works as expected."""
  197. m = matrix("1. 2.; 3. 4.")
  198. m2 = m.copy()
  199. m2 **= 2
  200. mi = m.copy()
  201. mi **= -1
  202. m4 = m2.copy()
  203. m4 **= 2
  204. assert_array_almost_equal(m2, m**2)
  205. assert_array_almost_equal(m4, np.dot(m2, m2))
  206. assert_array_almost_equal(np.dot(mi, m), np.eye(2))
  207. def test_scalar_type_pow(self):
  208. m = matrix([[1, 2], [3, 4]])
  209. for scalar_t in [np.int8, np.uint8]:
  210. two = scalar_t(2)
  211. assert_array_almost_equal(m ** 2, m ** two)
  212. def test_notimplemented(self):
  213. '''Check that 'not implemented' operations produce a failure.'''
  214. A = matrix([[1., 2.],
  215. [3., 4.]])
  216. # __rpow__
  217. with assert_raises(TypeError):
  218. 1.0**A
  219. # __mul__ with something not a list, ndarray, tuple, or scalar
  220. with assert_raises(TypeError):
  221. A*object()
  222. class TestMatrixReturn:
  223. def test_instance_methods(self):
  224. a = matrix([1.0], dtype='f8')
  225. methodargs = {
  226. 'astype': ('intc',),
  227. 'clip': (0.0, 1.0),
  228. 'compress': ([1],),
  229. 'repeat': (1,),
  230. 'reshape': (1,),
  231. 'swapaxes': (0, 0),
  232. 'dot': np.array([1.0]),
  233. }
  234. excluded_methods = [
  235. 'argmin', 'choose', 'dump', 'dumps', 'fill', 'getfield',
  236. 'getA', 'getA1', 'item', 'nonzero', 'put', 'putmask', 'resize',
  237. 'searchsorted', 'setflags', 'setfield', 'sort',
  238. 'partition', 'argpartition',
  239. 'take', 'tofile', 'tolist', 'tostring', 'tobytes', 'all', 'any',
  240. 'sum', 'argmax', 'argmin', 'min', 'max', 'mean', 'var', 'ptp',
  241. 'prod', 'std', 'ctypes', 'itemset',
  242. ]
  243. for attrib in dir(a):
  244. if attrib.startswith('_') or attrib in excluded_methods:
  245. continue
  246. f = getattr(a, attrib)
  247. if isinstance(f, collections.abc.Callable):
  248. # reset contents of a
  249. a.astype('f8')
  250. a.fill(1.0)
  251. if attrib in methodargs:
  252. args = methodargs[attrib]
  253. else:
  254. args = ()
  255. b = f(*args)
  256. assert_(type(b) is matrix, "%s" % attrib)
  257. assert_(type(a.real) is matrix)
  258. assert_(type(a.imag) is matrix)
  259. c, d = matrix([0.0]).nonzero()
  260. assert_(type(c) is np.ndarray)
  261. assert_(type(d) is np.ndarray)
  262. class TestIndexing:
  263. def test_basic(self):
  264. x = asmatrix(np.zeros((3, 2), float))
  265. y = np.zeros((3, 1), float)
  266. y[:, 0] = [0.8, 0.2, 0.3]
  267. x[:, 1] = y > 0.5
  268. assert_equal(x, [[0, 1], [0, 0], [0, 0]])
  269. class TestNewScalarIndexing:
  270. a = matrix([[1, 2], [3, 4]])
  271. def test_dimesions(self):
  272. a = self.a
  273. x = a[0]
  274. assert_equal(x.ndim, 2)
  275. def test_array_from_matrix_list(self):
  276. a = self.a
  277. x = np.array([a, a])
  278. assert_equal(x.shape, [2, 2, 2])
  279. def test_array_to_list(self):
  280. a = self.a
  281. assert_equal(a.tolist(), [[1, 2], [3, 4]])
  282. def test_fancy_indexing(self):
  283. a = self.a
  284. x = a[1, [0, 1, 0]]
  285. assert_(isinstance(x, matrix))
  286. assert_equal(x, matrix([[3, 4, 3]]))
  287. x = a[[1, 0]]
  288. assert_(isinstance(x, matrix))
  289. assert_equal(x, matrix([[3, 4], [1, 2]]))
  290. x = a[[[1], [0]], [[1, 0], [0, 1]]]
  291. assert_(isinstance(x, matrix))
  292. assert_equal(x, matrix([[4, 3], [1, 2]]))
  293. def test_matrix_element(self):
  294. x = matrix([[1, 2, 3], [4, 5, 6]])
  295. assert_equal(x[0][0], matrix([[1, 2, 3]]))
  296. assert_equal(x[0][0].shape, (1, 3))
  297. assert_equal(x[0].shape, (1, 3))
  298. assert_equal(x[:, 0].shape, (2, 1))
  299. x = matrix(0)
  300. assert_equal(x[0, 0], 0)
  301. assert_equal(x[0], 0)
  302. assert_equal(x[:, 0].shape, x.shape)
  303. def test_scalar_indexing(self):
  304. x = asmatrix(np.zeros((3, 2), float))
  305. assert_equal(x[0, 0], x[0][0])
  306. def test_row_column_indexing(self):
  307. x = asmatrix(np.eye(2))
  308. assert_array_equal(x[0,:], [[1, 0]])
  309. assert_array_equal(x[1,:], [[0, 1]])
  310. assert_array_equal(x[:, 0], [[1], [0]])
  311. assert_array_equal(x[:, 1], [[0], [1]])
  312. def test_boolean_indexing(self):
  313. A = np.arange(6)
  314. A.shape = (3, 2)
  315. x = asmatrix(A)
  316. assert_array_equal(x[:, np.array([True, False])], x[:, 0])
  317. assert_array_equal(x[np.array([True, False, False]),:], x[0,:])
  318. def test_list_indexing(self):
  319. A = np.arange(6)
  320. A.shape = (3, 2)
  321. x = asmatrix(A)
  322. assert_array_equal(x[:, [1, 0]], x[:, ::-1])
  323. assert_array_equal(x[[2, 1, 0],:], x[::-1,:])
  324. class TestPower:
  325. def test_returntype(self):
  326. a = np.array([[0, 1], [0, 0]])
  327. assert_(type(matrix_power(a, 2)) is np.ndarray)
  328. a = mat(a)
  329. assert_(type(matrix_power(a, 2)) is matrix)
  330. def test_list(self):
  331. assert_array_equal(matrix_power([[0, 1], [0, 0]], 2), [[0, 0], [0, 0]])
  332. class TestShape:
  333. a = np.array([[1], [2]])
  334. m = matrix([[1], [2]])
  335. def test_shape(self):
  336. assert_equal(self.a.shape, (2, 1))
  337. assert_equal(self.m.shape, (2, 1))
  338. def test_numpy_ravel(self):
  339. assert_equal(np.ravel(self.a).shape, (2,))
  340. assert_equal(np.ravel(self.m).shape, (2,))
  341. def test_member_ravel(self):
  342. assert_equal(self.a.ravel().shape, (2,))
  343. assert_equal(self.m.ravel().shape, (1, 2))
  344. def test_member_flatten(self):
  345. assert_equal(self.a.flatten().shape, (2,))
  346. assert_equal(self.m.flatten().shape, (1, 2))
  347. def test_numpy_ravel_order(self):
  348. x = np.array([[1, 2, 3], [4, 5, 6]])
  349. assert_equal(np.ravel(x), [1, 2, 3, 4, 5, 6])
  350. assert_equal(np.ravel(x, order='F'), [1, 4, 2, 5, 3, 6])
  351. assert_equal(np.ravel(x.T), [1, 4, 2, 5, 3, 6])
  352. assert_equal(np.ravel(x.T, order='A'), [1, 2, 3, 4, 5, 6])
  353. x = matrix([[1, 2, 3], [4, 5, 6]])
  354. assert_equal(np.ravel(x), [1, 2, 3, 4, 5, 6])
  355. assert_equal(np.ravel(x, order='F'), [1, 4, 2, 5, 3, 6])
  356. assert_equal(np.ravel(x.T), [1, 4, 2, 5, 3, 6])
  357. assert_equal(np.ravel(x.T, order='A'), [1, 2, 3, 4, 5, 6])
  358. def test_matrix_ravel_order(self):
  359. x = matrix([[1, 2, 3], [4, 5, 6]])
  360. assert_equal(x.ravel(), [[1, 2, 3, 4, 5, 6]])
  361. assert_equal(x.ravel(order='F'), [[1, 4, 2, 5, 3, 6]])
  362. assert_equal(x.T.ravel(), [[1, 4, 2, 5, 3, 6]])
  363. assert_equal(x.T.ravel(order='A'), [[1, 2, 3, 4, 5, 6]])
  364. def test_array_memory_sharing(self):
  365. assert_(np.may_share_memory(self.a, self.a.ravel()))
  366. assert_(not np.may_share_memory(self.a, self.a.flatten()))
  367. def test_matrix_memory_sharing(self):
  368. assert_(np.may_share_memory(self.m, self.m.ravel()))
  369. assert_(not np.may_share_memory(self.m, self.m.flatten()))
  370. def test_expand_dims_matrix(self):
  371. # matrices are always 2d - so expand_dims only makes sense when the
  372. # type is changed away from matrix.
  373. a = np.arange(10).reshape((2, 5)).view(np.matrix)
  374. expanded = np.expand_dims(a, axis=1)
  375. assert_equal(expanded.ndim, 3)
  376. assert_(not isinstance(expanded, np.matrix))