test_twodim_base.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. """Test functions for matrix module
  2. """
  3. from numpy.testing import (
  4. assert_equal, assert_array_equal, assert_array_max_ulp,
  5. assert_array_almost_equal, assert_raises, assert_
  6. )
  7. from numpy import (
  8. arange, add, fliplr, flipud, zeros, ones, eye, array, diag, histogram2d,
  9. tri, mask_indices, triu_indices, triu_indices_from, tril_indices,
  10. tril_indices_from, vander,
  11. )
  12. import numpy as np
  13. from numpy.core.tests.test_overrides import requires_array_function
  14. import pytest
  15. def get_mat(n):
  16. data = arange(n)
  17. data = add.outer(data, data)
  18. return data
  19. class TestEye:
  20. def test_basic(self):
  21. assert_equal(eye(4),
  22. array([[1, 0, 0, 0],
  23. [0, 1, 0, 0],
  24. [0, 0, 1, 0],
  25. [0, 0, 0, 1]]))
  26. assert_equal(eye(4, dtype='f'),
  27. array([[1, 0, 0, 0],
  28. [0, 1, 0, 0],
  29. [0, 0, 1, 0],
  30. [0, 0, 0, 1]], 'f'))
  31. assert_equal(eye(3) == 1,
  32. eye(3, dtype=bool))
  33. def test_uint64(self):
  34. # Regression test for gh-9982
  35. assert_equal(eye(np.uint64(2), dtype=int), array([[1, 0], [0, 1]]))
  36. assert_equal(eye(np.uint64(2), M=np.uint64(4), k=np.uint64(1)),
  37. array([[0, 1, 0, 0], [0, 0, 1, 0]]))
  38. def test_diag(self):
  39. assert_equal(eye(4, k=1),
  40. array([[0, 1, 0, 0],
  41. [0, 0, 1, 0],
  42. [0, 0, 0, 1],
  43. [0, 0, 0, 0]]))
  44. assert_equal(eye(4, k=-1),
  45. array([[0, 0, 0, 0],
  46. [1, 0, 0, 0],
  47. [0, 1, 0, 0],
  48. [0, 0, 1, 0]]))
  49. def test_2d(self):
  50. assert_equal(eye(4, 3),
  51. array([[1, 0, 0],
  52. [0, 1, 0],
  53. [0, 0, 1],
  54. [0, 0, 0]]))
  55. assert_equal(eye(3, 4),
  56. array([[1, 0, 0, 0],
  57. [0, 1, 0, 0],
  58. [0, 0, 1, 0]]))
  59. def test_diag2d(self):
  60. assert_equal(eye(3, 4, k=2),
  61. array([[0, 0, 1, 0],
  62. [0, 0, 0, 1],
  63. [0, 0, 0, 0]]))
  64. assert_equal(eye(4, 3, k=-2),
  65. array([[0, 0, 0],
  66. [0, 0, 0],
  67. [1, 0, 0],
  68. [0, 1, 0]]))
  69. def test_eye_bounds(self):
  70. assert_equal(eye(2, 2, 1), [[0, 1], [0, 0]])
  71. assert_equal(eye(2, 2, -1), [[0, 0], [1, 0]])
  72. assert_equal(eye(2, 2, 2), [[0, 0], [0, 0]])
  73. assert_equal(eye(2, 2, -2), [[0, 0], [0, 0]])
  74. assert_equal(eye(3, 2, 2), [[0, 0], [0, 0], [0, 0]])
  75. assert_equal(eye(3, 2, 1), [[0, 1], [0, 0], [0, 0]])
  76. assert_equal(eye(3, 2, -1), [[0, 0], [1, 0], [0, 1]])
  77. assert_equal(eye(3, 2, -2), [[0, 0], [0, 0], [1, 0]])
  78. assert_equal(eye(3, 2, -3), [[0, 0], [0, 0], [0, 0]])
  79. def test_strings(self):
  80. assert_equal(eye(2, 2, dtype='S3'),
  81. [[b'1', b''], [b'', b'1']])
  82. def test_bool(self):
  83. assert_equal(eye(2, 2, dtype=bool), [[True, False], [False, True]])
  84. def test_order(self):
  85. mat_c = eye(4, 3, k=-1)
  86. mat_f = eye(4, 3, k=-1, order='F')
  87. assert_equal(mat_c, mat_f)
  88. assert mat_c.flags.c_contiguous
  89. assert not mat_c.flags.f_contiguous
  90. assert not mat_f.flags.c_contiguous
  91. assert mat_f.flags.f_contiguous
  92. class TestDiag:
  93. def test_vector(self):
  94. vals = (100 * arange(5)).astype('l')
  95. b = zeros((5, 5))
  96. for k in range(5):
  97. b[k, k] = vals[k]
  98. assert_equal(diag(vals), b)
  99. b = zeros((7, 7))
  100. c = b.copy()
  101. for k in range(5):
  102. b[k, k + 2] = vals[k]
  103. c[k + 2, k] = vals[k]
  104. assert_equal(diag(vals, k=2), b)
  105. assert_equal(diag(vals, k=-2), c)
  106. def test_matrix(self, vals=None):
  107. if vals is None:
  108. vals = (100 * get_mat(5) + 1).astype('l')
  109. b = zeros((5,))
  110. for k in range(5):
  111. b[k] = vals[k, k]
  112. assert_equal(diag(vals), b)
  113. b = b * 0
  114. for k in range(3):
  115. b[k] = vals[k, k + 2]
  116. assert_equal(diag(vals, 2), b[:3])
  117. for k in range(3):
  118. b[k] = vals[k + 2, k]
  119. assert_equal(diag(vals, -2), b[:3])
  120. def test_fortran_order(self):
  121. vals = array((100 * get_mat(5) + 1), order='F', dtype='l')
  122. self.test_matrix(vals)
  123. def test_diag_bounds(self):
  124. A = [[1, 2], [3, 4], [5, 6]]
  125. assert_equal(diag(A, k=2), [])
  126. assert_equal(diag(A, k=1), [2])
  127. assert_equal(diag(A, k=0), [1, 4])
  128. assert_equal(diag(A, k=-1), [3, 6])
  129. assert_equal(diag(A, k=-2), [5])
  130. assert_equal(diag(A, k=-3), [])
  131. def test_failure(self):
  132. assert_raises(ValueError, diag, [[[1]]])
  133. class TestFliplr:
  134. def test_basic(self):
  135. assert_raises(ValueError, fliplr, ones(4))
  136. a = get_mat(4)
  137. b = a[:, ::-1]
  138. assert_equal(fliplr(a), b)
  139. a = [[0, 1, 2],
  140. [3, 4, 5]]
  141. b = [[2, 1, 0],
  142. [5, 4, 3]]
  143. assert_equal(fliplr(a), b)
  144. class TestFlipud:
  145. def test_basic(self):
  146. a = get_mat(4)
  147. b = a[::-1, :]
  148. assert_equal(flipud(a), b)
  149. a = [[0, 1, 2],
  150. [3, 4, 5]]
  151. b = [[3, 4, 5],
  152. [0, 1, 2]]
  153. assert_equal(flipud(a), b)
  154. class TestHistogram2d:
  155. def test_simple(self):
  156. x = array(
  157. [0.41702200, 0.72032449, 1.1437481e-4, 0.302332573, 0.146755891])
  158. y = array(
  159. [0.09233859, 0.18626021, 0.34556073, 0.39676747, 0.53881673])
  160. xedges = np.linspace(0, 1, 10)
  161. yedges = np.linspace(0, 1, 10)
  162. H = histogram2d(x, y, (xedges, yedges))[0]
  163. answer = array(
  164. [[0, 0, 0, 1, 0, 0, 0, 0, 0],
  165. [0, 0, 0, 0, 0, 0, 1, 0, 0],
  166. [0, 0, 0, 0, 0, 0, 0, 0, 0],
  167. [1, 0, 1, 0, 0, 0, 0, 0, 0],
  168. [0, 1, 0, 0, 0, 0, 0, 0, 0],
  169. [0, 0, 0, 0, 0, 0, 0, 0, 0],
  170. [0, 0, 0, 0, 0, 0, 0, 0, 0],
  171. [0, 0, 0, 0, 0, 0, 0, 0, 0],
  172. [0, 0, 0, 0, 0, 0, 0, 0, 0]])
  173. assert_array_equal(H.T, answer)
  174. H = histogram2d(x, y, xedges)[0]
  175. assert_array_equal(H.T, answer)
  176. H, xedges, yedges = histogram2d(list(range(10)), list(range(10)))
  177. assert_array_equal(H, eye(10, 10))
  178. assert_array_equal(xedges, np.linspace(0, 9, 11))
  179. assert_array_equal(yedges, np.linspace(0, 9, 11))
  180. def test_asym(self):
  181. x = array([1, 1, 2, 3, 4, 4, 4, 5])
  182. y = array([1, 3, 2, 0, 1, 2, 3, 4])
  183. H, xed, yed = histogram2d(
  184. x, y, (6, 5), range=[[0, 6], [0, 5]], density=True)
  185. answer = array(
  186. [[0., 0, 0, 0, 0],
  187. [0, 1, 0, 1, 0],
  188. [0, 0, 1, 0, 0],
  189. [1, 0, 0, 0, 0],
  190. [0, 1, 1, 1, 0],
  191. [0, 0, 0, 0, 1]])
  192. assert_array_almost_equal(H, answer/8., 3)
  193. assert_array_equal(xed, np.linspace(0, 6, 7))
  194. assert_array_equal(yed, np.linspace(0, 5, 6))
  195. def test_density(self):
  196. x = array([1, 2, 3, 1, 2, 3, 1, 2, 3])
  197. y = array([1, 1, 1, 2, 2, 2, 3, 3, 3])
  198. H, xed, yed = histogram2d(
  199. x, y, [[1, 2, 3, 5], [1, 2, 3, 5]], density=True)
  200. answer = array([[1, 1, .5],
  201. [1, 1, .5],
  202. [.5, .5, .25]])/9.
  203. assert_array_almost_equal(H, answer, 3)
  204. def test_all_outliers(self):
  205. r = np.random.rand(100) + 1. + 1e6 # histogramdd rounds by decimal=6
  206. H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1]))
  207. assert_array_equal(H, 0)
  208. def test_empty(self):
  209. a, edge1, edge2 = histogram2d([], [], bins=([0, 1], [0, 1]))
  210. assert_array_max_ulp(a, array([[0.]]))
  211. a, edge1, edge2 = histogram2d([], [], bins=4)
  212. assert_array_max_ulp(a, np.zeros((4, 4)))
  213. def test_binparameter_combination(self):
  214. x = array(
  215. [0, 0.09207008, 0.64575234, 0.12875982, 0.47390599,
  216. 0.59944483, 1])
  217. y = array(
  218. [0, 0.14344267, 0.48988575, 0.30558665, 0.44700682,
  219. 0.15886423, 1])
  220. edges = (0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)
  221. H, xe, ye = histogram2d(x, y, (edges, 4))
  222. answer = array(
  223. [[2., 0., 0., 0.],
  224. [0., 1., 0., 0.],
  225. [0., 0., 0., 0.],
  226. [0., 0., 0., 0.],
  227. [0., 1., 0., 0.],
  228. [1., 0., 0., 0.],
  229. [0., 1., 0., 0.],
  230. [0., 0., 0., 0.],
  231. [0., 0., 0., 0.],
  232. [0., 0., 0., 1.]])
  233. assert_array_equal(H, answer)
  234. assert_array_equal(ye, array([0., 0.25, 0.5, 0.75, 1]))
  235. H, xe, ye = histogram2d(x, y, (4, edges))
  236. answer = array(
  237. [[1., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
  238. [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
  239. [0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],
  240. [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
  241. assert_array_equal(H, answer)
  242. assert_array_equal(xe, array([0., 0.25, 0.5, 0.75, 1]))
  243. @requires_array_function
  244. def test_dispatch(self):
  245. class ShouldDispatch:
  246. def __array_function__(self, function, types, args, kwargs):
  247. return types, args, kwargs
  248. xy = [1, 2]
  249. s_d = ShouldDispatch()
  250. r = histogram2d(s_d, xy)
  251. # Cannot use assert_equal since that dispatches...
  252. assert_(r == ((ShouldDispatch,), (s_d, xy), {}))
  253. r = histogram2d(xy, s_d)
  254. assert_(r == ((ShouldDispatch,), (xy, s_d), {}))
  255. r = histogram2d(xy, xy, bins=s_d)
  256. assert_(r, ((ShouldDispatch,), (xy, xy), dict(bins=s_d)))
  257. r = histogram2d(xy, xy, bins=[s_d, 5])
  258. assert_(r, ((ShouldDispatch,), (xy, xy), dict(bins=[s_d, 5])))
  259. assert_raises(Exception, histogram2d, xy, xy, bins=[s_d])
  260. r = histogram2d(xy, xy, weights=s_d)
  261. assert_(r, ((ShouldDispatch,), (xy, xy), dict(weights=s_d)))
  262. @pytest.mark.parametrize(("x_len", "y_len"), [(10, 11), (20, 19)])
  263. def test_bad_length(self, x_len, y_len):
  264. x, y = np.ones(x_len), np.ones(y_len)
  265. with pytest.raises(ValueError,
  266. match='x and y must have the same length.'):
  267. histogram2d(x, y)
  268. class TestTri:
  269. def test_dtype(self):
  270. out = array([[1, 0, 0],
  271. [1, 1, 0],
  272. [1, 1, 1]])
  273. assert_array_equal(tri(3), out)
  274. assert_array_equal(tri(3, dtype=bool), out.astype(bool))
  275. def test_tril_triu_ndim2():
  276. for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
  277. a = np.ones((2, 2), dtype=dtype)
  278. b = np.tril(a)
  279. c = np.triu(a)
  280. assert_array_equal(b, [[1, 0], [1, 1]])
  281. assert_array_equal(c, b.T)
  282. # should return the same dtype as the original array
  283. assert_equal(b.dtype, a.dtype)
  284. assert_equal(c.dtype, a.dtype)
  285. def test_tril_triu_ndim3():
  286. for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
  287. a = np.array([
  288. [[1, 1], [1, 1]],
  289. [[1, 1], [1, 0]],
  290. [[1, 1], [0, 0]],
  291. ], dtype=dtype)
  292. a_tril_desired = np.array([
  293. [[1, 0], [1, 1]],
  294. [[1, 0], [1, 0]],
  295. [[1, 0], [0, 0]],
  296. ], dtype=dtype)
  297. a_triu_desired = np.array([
  298. [[1, 1], [0, 1]],
  299. [[1, 1], [0, 0]],
  300. [[1, 1], [0, 0]],
  301. ], dtype=dtype)
  302. a_triu_observed = np.triu(a)
  303. a_tril_observed = np.tril(a)
  304. assert_array_equal(a_triu_observed, a_triu_desired)
  305. assert_array_equal(a_tril_observed, a_tril_desired)
  306. assert_equal(a_triu_observed.dtype, a.dtype)
  307. assert_equal(a_tril_observed.dtype, a.dtype)
  308. def test_tril_triu_with_inf():
  309. # Issue 4859
  310. arr = np.array([[1, 1, np.inf],
  311. [1, 1, 1],
  312. [np.inf, 1, 1]])
  313. out_tril = np.array([[1, 0, 0],
  314. [1, 1, 0],
  315. [np.inf, 1, 1]])
  316. out_triu = out_tril.T
  317. assert_array_equal(np.triu(arr), out_triu)
  318. assert_array_equal(np.tril(arr), out_tril)
  319. def test_tril_triu_dtype():
  320. # Issue 4916
  321. # tril and triu should return the same dtype as input
  322. for c in np.typecodes['All']:
  323. if c == 'V':
  324. continue
  325. arr = np.zeros((3, 3), dtype=c)
  326. assert_equal(np.triu(arr).dtype, arr.dtype)
  327. assert_equal(np.tril(arr).dtype, arr.dtype)
  328. # check special cases
  329. arr = np.array([['2001-01-01T12:00', '2002-02-03T13:56'],
  330. ['2004-01-01T12:00', '2003-01-03T13:45']],
  331. dtype='datetime64')
  332. assert_equal(np.triu(arr).dtype, arr.dtype)
  333. assert_equal(np.tril(arr).dtype, arr.dtype)
  334. arr = np.zeros((3, 3), dtype='f4,f4')
  335. assert_equal(np.triu(arr).dtype, arr.dtype)
  336. assert_equal(np.tril(arr).dtype, arr.dtype)
  337. def test_mask_indices():
  338. # simple test without offset
  339. iu = mask_indices(3, np.triu)
  340. a = np.arange(9).reshape(3, 3)
  341. assert_array_equal(a[iu], array([0, 1, 2, 4, 5, 8]))
  342. # Now with an offset
  343. iu1 = mask_indices(3, np.triu, 1)
  344. assert_array_equal(a[iu1], array([1, 2, 5]))
  345. def test_tril_indices():
  346. # indices without and with offset
  347. il1 = tril_indices(4)
  348. il2 = tril_indices(4, k=2)
  349. il3 = tril_indices(4, m=5)
  350. il4 = tril_indices(4, k=2, m=5)
  351. a = np.array([[1, 2, 3, 4],
  352. [5, 6, 7, 8],
  353. [9, 10, 11, 12],
  354. [13, 14, 15, 16]])
  355. b = np.arange(1, 21).reshape(4, 5)
  356. # indexing:
  357. assert_array_equal(a[il1],
  358. array([1, 5, 6, 9, 10, 11, 13, 14, 15, 16]))
  359. assert_array_equal(b[il3],
  360. array([1, 6, 7, 11, 12, 13, 16, 17, 18, 19]))
  361. # And for assigning values:
  362. a[il1] = -1
  363. assert_array_equal(a,
  364. array([[-1, 2, 3, 4],
  365. [-1, -1, 7, 8],
  366. [-1, -1, -1, 12],
  367. [-1, -1, -1, -1]]))
  368. b[il3] = -1
  369. assert_array_equal(b,
  370. array([[-1, 2, 3, 4, 5],
  371. [-1, -1, 8, 9, 10],
  372. [-1, -1, -1, 14, 15],
  373. [-1, -1, -1, -1, 20]]))
  374. # These cover almost the whole array (two diagonals right of the main one):
  375. a[il2] = -10
  376. assert_array_equal(a,
  377. array([[-10, -10, -10, 4],
  378. [-10, -10, -10, -10],
  379. [-10, -10, -10, -10],
  380. [-10, -10, -10, -10]]))
  381. b[il4] = -10
  382. assert_array_equal(b,
  383. array([[-10, -10, -10, 4, 5],
  384. [-10, -10, -10, -10, 10],
  385. [-10, -10, -10, -10, -10],
  386. [-10, -10, -10, -10, -10]]))
  387. class TestTriuIndices:
  388. def test_triu_indices(self):
  389. iu1 = triu_indices(4)
  390. iu2 = triu_indices(4, k=2)
  391. iu3 = triu_indices(4, m=5)
  392. iu4 = triu_indices(4, k=2, m=5)
  393. a = np.array([[1, 2, 3, 4],
  394. [5, 6, 7, 8],
  395. [9, 10, 11, 12],
  396. [13, 14, 15, 16]])
  397. b = np.arange(1, 21).reshape(4, 5)
  398. # Both for indexing:
  399. assert_array_equal(a[iu1],
  400. array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16]))
  401. assert_array_equal(b[iu3],
  402. array([1, 2, 3, 4, 5, 7, 8, 9,
  403. 10, 13, 14, 15, 19, 20]))
  404. # And for assigning values:
  405. a[iu1] = -1
  406. assert_array_equal(a,
  407. array([[-1, -1, -1, -1],
  408. [5, -1, -1, -1],
  409. [9, 10, -1, -1],
  410. [13, 14, 15, -1]]))
  411. b[iu3] = -1
  412. assert_array_equal(b,
  413. array([[-1, -1, -1, -1, -1],
  414. [6, -1, -1, -1, -1],
  415. [11, 12, -1, -1, -1],
  416. [16, 17, 18, -1, -1]]))
  417. # These cover almost the whole array (two diagonals right of the
  418. # main one):
  419. a[iu2] = -10
  420. assert_array_equal(a,
  421. array([[-1, -1, -10, -10],
  422. [5, -1, -1, -10],
  423. [9, 10, -1, -1],
  424. [13, 14, 15, -1]]))
  425. b[iu4] = -10
  426. assert_array_equal(b,
  427. array([[-1, -1, -10, -10, -10],
  428. [6, -1, -1, -10, -10],
  429. [11, 12, -1, -1, -10],
  430. [16, 17, 18, -1, -1]]))
  431. class TestTrilIndicesFrom:
  432. def test_exceptions(self):
  433. assert_raises(ValueError, tril_indices_from, np.ones((2,)))
  434. assert_raises(ValueError, tril_indices_from, np.ones((2, 2, 2)))
  435. # assert_raises(ValueError, tril_indices_from, np.ones((2, 3)))
  436. class TestTriuIndicesFrom:
  437. def test_exceptions(self):
  438. assert_raises(ValueError, triu_indices_from, np.ones((2,)))
  439. assert_raises(ValueError, triu_indices_from, np.ones((2, 2, 2)))
  440. # assert_raises(ValueError, triu_indices_from, np.ones((2, 3)))
  441. class TestVander:
  442. def test_basic(self):
  443. c = np.array([0, 1, -2, 3])
  444. v = vander(c)
  445. powers = np.array([[0, 0, 0, 0, 1],
  446. [1, 1, 1, 1, 1],
  447. [16, -8, 4, -2, 1],
  448. [81, 27, 9, 3, 1]])
  449. # Check default value of N:
  450. assert_array_equal(v, powers[:, 1:])
  451. # Check a range of N values, including 0 and 5 (greater than default)
  452. m = powers.shape[1]
  453. for n in range(6):
  454. v = vander(c, N=n)
  455. assert_array_equal(v, powers[:, m-n:m])
  456. def test_dtypes(self):
  457. c = array([11, -12, 13], dtype=np.int8)
  458. v = vander(c)
  459. expected = np.array([[121, 11, 1],
  460. [144, -12, 1],
  461. [169, 13, 1]])
  462. assert_array_equal(v, expected)
  463. c = array([1.0+1j, 1.0-1j])
  464. v = vander(c, N=3)
  465. expected = np.array([[2j, 1+1j, 1],
  466. [-2j, 1-1j, 1]])
  467. # The data is floating point, but the values are small integers,
  468. # so assert_array_equal *should* be safe here (rather than, say,
  469. # assert_array_almost_equal).
  470. assert_array_equal(v, expected)