test_twodim_base.py 18 KB

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