test_twodim_base.py 18 KB

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