test_interaction.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. """Tests of interaction of matrix with other parts of numpy.
  2. Note that tests with MaskedArray and linalg are done in separate files.
  3. """
  4. import textwrap
  5. import warnings
  6. import pytest
  7. import numpy as np
  8. from numpy.testing import (
  9. assert_,
  10. assert_almost_equal,
  11. assert_array_almost_equal,
  12. assert_array_equal,
  13. assert_equal,
  14. assert_raises,
  15. assert_raises_regex,
  16. )
  17. def test_fancy_indexing():
  18. # The matrix class messes with the shape. While this is always
  19. # weird (getitem is not used, it does not have setitem nor knows
  20. # about fancy indexing), this tests gh-3110
  21. # 2018-04-29: moved here from core.tests.test_index.
  22. m = np.matrix([[1, 2], [3, 4]])
  23. assert_(isinstance(m[[0, 1, 0], :], np.matrix))
  24. # gh-3110. Note the transpose currently because matrices do *not*
  25. # support dimension fixing for fancy indexing correctly.
  26. x = np.asmatrix(np.arange(50).reshape(5, 10))
  27. assert_equal(x[:2, np.array(-1)], x[:2, -1].T)
  28. def test_polynomial_mapdomain():
  29. # test that polynomial preserved matrix subtype.
  30. # 2018-04-29: moved here from polynomial.tests.polyutils.
  31. dom1 = [0, 4]
  32. dom2 = [1, 3]
  33. x = np.matrix([dom1, dom1])
  34. res = np.polynomial.polyutils.mapdomain(x, dom1, dom2)
  35. assert_(isinstance(res, np.matrix))
  36. def test_sort_matrix_none():
  37. # 2018-04-29: moved here from core.tests.test_multiarray
  38. a = np.matrix([[2, 1, 0]])
  39. actual = np.sort(a, axis=None)
  40. expected = np.matrix([[0, 1, 2]])
  41. assert_equal(actual, expected)
  42. assert_(type(expected) is np.matrix)
  43. def test_partition_matrix_none():
  44. # gh-4301
  45. # 2018-04-29: moved here from core.tests.test_multiarray
  46. a = np.matrix([[2, 1, 0]])
  47. actual = np.partition(a, 1, axis=None)
  48. expected = np.matrix([[0, 1, 2]])
  49. assert_equal(actual, expected)
  50. assert_(type(expected) is np.matrix)
  51. def test_dot_scalar_and_matrix_of_objects():
  52. # Ticket #2469
  53. # 2018-04-29: moved here from core.tests.test_multiarray
  54. arr = np.matrix([1, 2], dtype=object)
  55. desired = np.matrix([[3, 6]], dtype=object)
  56. assert_equal(np.dot(arr, 3), desired)
  57. assert_equal(np.dot(3, arr), desired)
  58. def test_inner_scalar_and_matrix():
  59. # 2018-04-29: moved here from core.tests.test_multiarray
  60. for dt in np.typecodes['AllInteger'] + np.typecodes['AllFloat'] + '?':
  61. sca = np.array(3, dtype=dt)[()]
  62. arr = np.matrix([[1, 2], [3, 4]], dtype=dt)
  63. desired = np.matrix([[3, 6], [9, 12]], dtype=dt)
  64. assert_equal(np.inner(arr, sca), desired)
  65. assert_equal(np.inner(sca, arr), desired)
  66. def test_inner_scalar_and_matrix_of_objects():
  67. # Ticket #4482
  68. # 2018-04-29: moved here from core.tests.test_multiarray
  69. arr = np.matrix([1, 2], dtype=object)
  70. desired = np.matrix([[3, 6]], dtype=object)
  71. assert_equal(np.inner(arr, 3), desired)
  72. assert_equal(np.inner(3, arr), desired)
  73. def test_iter_allocate_output_subtype():
  74. # Make sure that the subtype with priority wins
  75. # 2018-04-29: moved here from core.tests.test_nditer, given the
  76. # matrix specific shape test.
  77. # matrix vs ndarray
  78. a = np.matrix([[1, 2], [3, 4]])
  79. b = np.arange(4).reshape(2, 2).T
  80. i = np.nditer([a, b, None], [],
  81. [['readonly'], ['readonly'], ['writeonly', 'allocate']])
  82. assert_(type(i.operands[2]) is np.matrix)
  83. assert_(type(i.operands[2]) is not np.ndarray)
  84. assert_equal(i.operands[2].shape, (2, 2))
  85. # matrix always wants things to be 2D
  86. b = np.arange(4).reshape(1, 2, 2)
  87. assert_raises(RuntimeError, np.nditer, [a, b, None], [],
  88. [['readonly'], ['readonly'], ['writeonly', 'allocate']])
  89. # but if subtypes are disabled, the result can still work
  90. i = np.nditer([a, b, None], [],
  91. [['readonly'], ['readonly'],
  92. ['writeonly', 'allocate', 'no_subtype']])
  93. assert_(type(i.operands[2]) is np.ndarray)
  94. assert_(type(i.operands[2]) is not np.matrix)
  95. assert_equal(i.operands[2].shape, (1, 2, 2))
  96. def like_function():
  97. # 2018-04-29: moved here from core.tests.test_numeric
  98. a = np.matrix([[1, 2], [3, 4]])
  99. for like_function in np.zeros_like, np.ones_like, np.empty_like:
  100. b = like_function(a)
  101. assert_(type(b) is np.matrix)
  102. c = like_function(a, subok=False)
  103. assert_(type(c) is not np.matrix)
  104. def test_array_astype():
  105. # 2018-04-29: copied here from core.tests.test_api
  106. # subok=True passes through a matrix
  107. a = np.matrix([[0, 1, 2], [3, 4, 5]], dtype='f4')
  108. b = a.astype('f4', subok=True, copy=False)
  109. assert_(a is b)
  110. # subok=True is default, and creates a subtype on a cast
  111. b = a.astype('i4', copy=False)
  112. assert_equal(a, b)
  113. assert_equal(type(b), np.matrix)
  114. # subok=False never returns a matrix
  115. b = a.astype('f4', subok=False, copy=False)
  116. assert_equal(a, b)
  117. assert_(not (a is b))
  118. assert_(type(b) is not np.matrix)
  119. def test_stack():
  120. # 2018-04-29: copied here from core.tests.test_shape_base
  121. # check np.matrix cannot be stacked
  122. m = np.matrix([[1, 2], [3, 4]])
  123. assert_raises_regex(ValueError, 'shape too large to be a matrix',
  124. np.stack, [m, m])
  125. def test_object_scalar_multiply():
  126. # Tickets #2469 and #4482
  127. # 2018-04-29: moved here from core.tests.test_ufunc
  128. arr = np.matrix([1, 2], dtype=object)
  129. desired = np.matrix([[3, 6]], dtype=object)
  130. assert_equal(np.multiply(arr, 3), desired)
  131. assert_equal(np.multiply(3, arr), desired)
  132. def test_nanfunctions_matrices():
  133. # Check that it works and that type and
  134. # shape are preserved
  135. # 2018-04-29: moved here from core.tests.test_nanfunctions
  136. mat = np.matrix(np.eye(3))
  137. for f in [np.nanmin, np.nanmax]:
  138. res = f(mat, axis=0)
  139. assert_(isinstance(res, np.matrix))
  140. assert_(res.shape == (1, 3))
  141. res = f(mat, axis=1)
  142. assert_(isinstance(res, np.matrix))
  143. assert_(res.shape == (3, 1))
  144. res = f(mat)
  145. assert_(np.isscalar(res))
  146. # check that rows of nan are dealt with for subclasses (#4628)
  147. mat[1] = np.nan
  148. for f in [np.nanmin, np.nanmax]:
  149. with warnings.catch_warnings(record=True) as w:
  150. warnings.simplefilter('always')
  151. res = f(mat, axis=0)
  152. assert_(isinstance(res, np.matrix))
  153. assert_(not np.any(np.isnan(res)))
  154. assert_(len(w) == 0)
  155. with warnings.catch_warnings(record=True) as w:
  156. warnings.simplefilter('always')
  157. res = f(mat, axis=1)
  158. assert_(isinstance(res, np.matrix))
  159. assert_(np.isnan(res[1, 0]) and not np.isnan(res[0, 0])
  160. and not np.isnan(res[2, 0]))
  161. assert_(len(w) == 1, 'no warning raised')
  162. assert_(issubclass(w[0].category, RuntimeWarning))
  163. with warnings.catch_warnings(record=True) as w:
  164. warnings.simplefilter('always')
  165. res = f(mat)
  166. assert_(np.isscalar(res))
  167. assert_(res != np.nan)
  168. assert_(len(w) == 0)
  169. def test_nanfunctions_matrices_general():
  170. # Check that it works and that type and
  171. # shape are preserved
  172. # 2018-04-29: moved here from core.tests.test_nanfunctions
  173. mat = np.matrix(np.eye(3))
  174. for f in (np.nanargmin, np.nanargmax, np.nansum, np.nanprod,
  175. np.nanmean, np.nanvar, np.nanstd):
  176. res = f(mat, axis=0)
  177. assert_(isinstance(res, np.matrix))
  178. assert_(res.shape == (1, 3))
  179. res = f(mat, axis=1)
  180. assert_(isinstance(res, np.matrix))
  181. assert_(res.shape == (3, 1))
  182. res = f(mat)
  183. assert_(np.isscalar(res))
  184. for f in np.nancumsum, np.nancumprod:
  185. res = f(mat, axis=0)
  186. assert_(isinstance(res, np.matrix))
  187. assert_(res.shape == (3, 3))
  188. res = f(mat, axis=1)
  189. assert_(isinstance(res, np.matrix))
  190. assert_(res.shape == (3, 3))
  191. res = f(mat)
  192. assert_(isinstance(res, np.matrix))
  193. assert_(res.shape == (1, 3 * 3))
  194. def test_average_matrix():
  195. # 2018-04-29: moved here from core.tests.test_function_base.
  196. y = np.matrix(np.random.rand(5, 5))
  197. assert_array_equal(y.mean(0), np.average(y, 0))
  198. a = np.matrix([[1, 2], [3, 4]])
  199. w = np.matrix([[1, 2], [3, 4]])
  200. r = np.average(a, axis=0, weights=w)
  201. assert_equal(type(r), np.matrix)
  202. assert_equal(r, [[2.5, 10.0 / 3]])
  203. def test_dot_matrix():
  204. # Test to make sure matrices give the same answer as ndarrays
  205. # 2018-04-29: moved here from core.tests.test_function_base.
  206. x = np.linspace(0, 5)
  207. y = np.linspace(-5, 0)
  208. mx = np.matrix(x)
  209. my = np.matrix(y)
  210. r = np.dot(x, y)
  211. mr = np.dot(mx, my.T)
  212. assert_almost_equal(mr, r)
  213. def test_ediff1d_matrix():
  214. # 2018-04-29: moved here from core.tests.test_arraysetops.
  215. assert isinstance(np.ediff1d(np.matrix(1)), np.matrix)
  216. assert isinstance(np.ediff1d(np.matrix(1), to_begin=1), np.matrix)
  217. def test_apply_along_axis_matrix():
  218. # this test is particularly malicious because matrix
  219. # refuses to become 1d
  220. # 2018-04-29: moved here from core.tests.test_shape_base.
  221. def double(row):
  222. return row * 2
  223. m = np.matrix([[0, 1], [2, 3]])
  224. expected = np.matrix([[0, 2], [4, 6]])
  225. result = np.apply_along_axis(double, 0, m)
  226. assert_(isinstance(result, np.matrix))
  227. assert_array_equal(result, expected)
  228. result = np.apply_along_axis(double, 1, m)
  229. assert_(isinstance(result, np.matrix))
  230. assert_array_equal(result, expected)
  231. def test_kron_matrix():
  232. # 2018-04-29: moved here from core.tests.test_shape_base.
  233. a = np.ones([2, 2])
  234. m = np.asmatrix(a)
  235. assert_equal(type(np.kron(a, a)), np.ndarray)
  236. assert_equal(type(np.kron(m, m)), np.matrix)
  237. assert_equal(type(np.kron(a, m)), np.matrix)
  238. assert_equal(type(np.kron(m, a)), np.matrix)
  239. class TestConcatenatorMatrix:
  240. # 2018-04-29: moved here from core.tests.test_index_tricks.
  241. def test_matrix(self):
  242. a = [1, 2]
  243. b = [3, 4]
  244. ab_r = np.r_['r', a, b]
  245. ab_c = np.r_['c', a, b]
  246. assert_equal(type(ab_r), np.matrix)
  247. assert_equal(type(ab_c), np.matrix)
  248. assert_equal(np.array(ab_r), [[1, 2, 3, 4]])
  249. assert_equal(np.array(ab_c), [[1], [2], [3], [4]])
  250. assert_raises(ValueError, lambda: np.r_['rc', a, b])
  251. def test_matrix_scalar(self):
  252. r = np.r_['r', [1, 2], 3]
  253. assert_equal(type(r), np.matrix)
  254. assert_equal(np.array(r), [[1, 2, 3]])
  255. def test_matrix_builder(self):
  256. a = np.array([1])
  257. b = np.array([2])
  258. c = np.array([3])
  259. d = np.array([4])
  260. actual = np.r_['a, b; c, d']
  261. expected = np.bmat([[a, b], [c, d]])
  262. assert_equal(actual, expected)
  263. assert_equal(type(actual), type(expected))
  264. def test_array_equal_error_message_matrix():
  265. # 2018-04-29: moved here from testing.tests.test_utils.
  266. with pytest.raises(AssertionError) as exc_info:
  267. assert_equal(np.array([1, 2]), np.matrix([1, 2]))
  268. msg = str(exc_info.value)
  269. msg_reference = textwrap.dedent("""\
  270. Arrays are not equal
  271. (shapes (2,), (1, 2) mismatch)
  272. ACTUAL: array([1, 2])
  273. DESIRED: matrix([[1, 2]])""")
  274. assert_equal(msg, msg_reference)
  275. def test_array_almost_equal_matrix():
  276. # Matrix slicing keeps things 2-D, while array does not necessarily.
  277. # See gh-8452.
  278. # 2018-04-29: moved here from testing.tests.test_utils.
  279. m1 = np.matrix([[1., 2.]])
  280. m2 = np.matrix([[1., np.nan]])
  281. m3 = np.matrix([[1., -np.inf]])
  282. m4 = np.matrix([[np.nan, np.inf]])
  283. m5 = np.matrix([[1., 2.], [np.nan, np.inf]])
  284. for assert_func in assert_array_almost_equal, assert_almost_equal:
  285. for m in m1, m2, m3, m4, m5:
  286. assert_func(m, m)
  287. a = np.array(m)
  288. assert_func(a, m)
  289. assert_func(m, a)