test_interaction.py 12 KB

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