test_interaction.py 12 KB

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