test_shape_base.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. import numpy as np
  2. import functools
  3. import sys
  4. import pytest
  5. from numpy import (
  6. apply_along_axis, apply_over_axes, array_split, split, hsplit, dsplit,
  7. vsplit, dstack, column_stack, kron, tile, expand_dims, take_along_axis,
  8. put_along_axis
  9. )
  10. from numpy.exceptions import AxisError
  11. from numpy.testing import (
  12. assert_, assert_equal, assert_array_equal, assert_raises, assert_warns
  13. )
  14. IS_64BIT = sys.maxsize > 2**32
  15. def _add_keepdims(func):
  16. """ hack in keepdims behavior into a function taking an axis """
  17. @functools.wraps(func)
  18. def wrapped(a, axis, **kwargs):
  19. res = func(a, axis=axis, **kwargs)
  20. if axis is None:
  21. axis = 0 # res is now a scalar, so we can insert this anywhere
  22. return np.expand_dims(res, axis=axis)
  23. return wrapped
  24. class TestTakeAlongAxis:
  25. def test_argequivalent(self):
  26. """ Test it translates from arg<func> to <func> """
  27. from numpy.random import rand
  28. a = rand(3, 4, 5)
  29. funcs = [
  30. (np.sort, np.argsort, dict()),
  31. (_add_keepdims(np.min), _add_keepdims(np.argmin), dict()),
  32. (_add_keepdims(np.max), _add_keepdims(np.argmax), dict()),
  33. #(np.partition, np.argpartition, dict(kth=2)),
  34. ]
  35. for func, argfunc, kwargs in funcs:
  36. for axis in list(range(a.ndim)) + [None]:
  37. a_func = func(a, axis=axis, **kwargs)
  38. ai_func = argfunc(a, axis=axis, **kwargs)
  39. assert_equal(a_func, take_along_axis(a, ai_func, axis=axis))
  40. def test_invalid(self):
  41. """ Test it errors when indices has too few dimensions """
  42. a = np.ones((10, 10))
  43. ai = np.ones((10, 2), dtype=np.intp)
  44. # sanity check
  45. take_along_axis(a, ai, axis=1)
  46. # not enough indices
  47. assert_raises(ValueError, take_along_axis, a, np.array(1), axis=1)
  48. # bool arrays not allowed
  49. assert_raises(IndexError, take_along_axis, a, ai.astype(bool), axis=1)
  50. # float arrays not allowed
  51. assert_raises(IndexError, take_along_axis, a, ai.astype(float), axis=1)
  52. # invalid axis
  53. assert_raises(AxisError, take_along_axis, a, ai, axis=10)
  54. # invalid indices
  55. assert_raises(ValueError, take_along_axis, a, ai, axis=None)
  56. def test_empty(self):
  57. """ Test everything is ok with empty results, even with inserted dims """
  58. a = np.ones((3, 4, 5))
  59. ai = np.ones((3, 0, 5), dtype=np.intp)
  60. actual = take_along_axis(a, ai, axis=1)
  61. assert_equal(actual.shape, ai.shape)
  62. def test_broadcast(self):
  63. """ Test that non-indexing dimensions are broadcast in both directions """
  64. a = np.ones((3, 4, 1))
  65. ai = np.ones((1, 2, 5), dtype=np.intp)
  66. actual = take_along_axis(a, ai, axis=1)
  67. assert_equal(actual.shape, (3, 2, 5))
  68. class TestPutAlongAxis:
  69. def test_replace_max(self):
  70. a_base = np.array([[10, 30, 20], [60, 40, 50]])
  71. for axis in list(range(a_base.ndim)) + [None]:
  72. # we mutate this in the loop
  73. a = a_base.copy()
  74. # replace the max with a small value
  75. i_max = _add_keepdims(np.argmax)(a, axis=axis)
  76. put_along_axis(a, i_max, -99, axis=axis)
  77. # find the new minimum, which should max
  78. i_min = _add_keepdims(np.argmin)(a, axis=axis)
  79. assert_equal(i_min, i_max)
  80. def test_broadcast(self):
  81. """ Test that non-indexing dimensions are broadcast in both directions """
  82. a = np.ones((3, 4, 1))
  83. ai = np.arange(10, dtype=np.intp).reshape((1, 2, 5)) % 4
  84. put_along_axis(a, ai, 20, axis=1)
  85. assert_equal(take_along_axis(a, ai, axis=1), 20)
  86. def test_invalid(self):
  87. """ Test invalid inputs """
  88. a_base = np.array([[10, 30, 20], [60, 40, 50]])
  89. indices = np.array([[0], [1]])
  90. values = np.array([[2], [1]])
  91. # sanity check
  92. a = a_base.copy()
  93. put_along_axis(a, indices, values, axis=0)
  94. assert np.all(a == [[2, 2, 2], [1, 1, 1]])
  95. # invalid indices
  96. a = a_base.copy()
  97. with assert_raises(ValueError) as exc:
  98. put_along_axis(a, indices, values, axis=None)
  99. assert "single dimension" in str(exc.exception)
  100. class TestApplyAlongAxis:
  101. def test_simple(self):
  102. a = np.ones((20, 10), 'd')
  103. assert_array_equal(
  104. apply_along_axis(len, 0, a), len(a)*np.ones(a.shape[1]))
  105. def test_simple101(self):
  106. a = np.ones((10, 101), 'd')
  107. assert_array_equal(
  108. apply_along_axis(len, 0, a), len(a)*np.ones(a.shape[1]))
  109. def test_3d(self):
  110. a = np.arange(27).reshape((3, 3, 3))
  111. assert_array_equal(apply_along_axis(np.sum, 0, a),
  112. [[27, 30, 33], [36, 39, 42], [45, 48, 51]])
  113. def test_preserve_subclass(self):
  114. def double(row):
  115. return row * 2
  116. class MyNDArray(np.ndarray):
  117. pass
  118. m = np.array([[0, 1], [2, 3]]).view(MyNDArray)
  119. expected = np.array([[0, 2], [4, 6]]).view(MyNDArray)
  120. result = apply_along_axis(double, 0, m)
  121. assert_(isinstance(result, MyNDArray))
  122. assert_array_equal(result, expected)
  123. result = apply_along_axis(double, 1, m)
  124. assert_(isinstance(result, MyNDArray))
  125. assert_array_equal(result, expected)
  126. def test_subclass(self):
  127. class MinimalSubclass(np.ndarray):
  128. data = 1
  129. def minimal_function(array):
  130. return array.data
  131. a = np.zeros((6, 3)).view(MinimalSubclass)
  132. assert_array_equal(
  133. apply_along_axis(minimal_function, 0, a), np.array([1, 1, 1])
  134. )
  135. def test_scalar_array(self, cls=np.ndarray):
  136. a = np.ones((6, 3)).view(cls)
  137. res = apply_along_axis(np.sum, 0, a)
  138. assert_(isinstance(res, cls))
  139. assert_array_equal(res, np.array([6, 6, 6]).view(cls))
  140. def test_0d_array(self, cls=np.ndarray):
  141. def sum_to_0d(x):
  142. """ Sum x, returning a 0d array of the same class """
  143. assert_equal(x.ndim, 1)
  144. return np.squeeze(np.sum(x, keepdims=True))
  145. a = np.ones((6, 3)).view(cls)
  146. res = apply_along_axis(sum_to_0d, 0, a)
  147. assert_(isinstance(res, cls))
  148. assert_array_equal(res, np.array([6, 6, 6]).view(cls))
  149. res = apply_along_axis(sum_to_0d, 1, a)
  150. assert_(isinstance(res, cls))
  151. assert_array_equal(res, np.array([3, 3, 3, 3, 3, 3]).view(cls))
  152. def test_axis_insertion(self, cls=np.ndarray):
  153. def f1to2(x):
  154. """produces an asymmetric non-square matrix from x"""
  155. assert_equal(x.ndim, 1)
  156. return (x[::-1] * x[1:,None]).view(cls)
  157. a2d = np.arange(6*3).reshape((6, 3))
  158. # 2d insertion along first axis
  159. actual = apply_along_axis(f1to2, 0, a2d)
  160. expected = np.stack([
  161. f1to2(a2d[:,i]) for i in range(a2d.shape[1])
  162. ], axis=-1).view(cls)
  163. assert_equal(type(actual), type(expected))
  164. assert_equal(actual, expected)
  165. # 2d insertion along last axis
  166. actual = apply_along_axis(f1to2, 1, a2d)
  167. expected = np.stack([
  168. f1to2(a2d[i,:]) for i in range(a2d.shape[0])
  169. ], axis=0).view(cls)
  170. assert_equal(type(actual), type(expected))
  171. assert_equal(actual, expected)
  172. # 3d insertion along middle axis
  173. a3d = np.arange(6*5*3).reshape((6, 5, 3))
  174. actual = apply_along_axis(f1to2, 1, a3d)
  175. expected = np.stack([
  176. np.stack([
  177. f1to2(a3d[i,:,j]) for i in range(a3d.shape[0])
  178. ], axis=0)
  179. for j in range(a3d.shape[2])
  180. ], axis=-1).view(cls)
  181. assert_equal(type(actual), type(expected))
  182. assert_equal(actual, expected)
  183. def test_subclass_preservation(self):
  184. class MinimalSubclass(np.ndarray):
  185. pass
  186. self.test_scalar_array(MinimalSubclass)
  187. self.test_0d_array(MinimalSubclass)
  188. self.test_axis_insertion(MinimalSubclass)
  189. def test_axis_insertion_ma(self):
  190. def f1to2(x):
  191. """produces an asymmetric non-square matrix from x"""
  192. assert_equal(x.ndim, 1)
  193. res = x[::-1] * x[1:,None]
  194. return np.ma.masked_where(res%5==0, res)
  195. a = np.arange(6*3).reshape((6, 3))
  196. res = apply_along_axis(f1to2, 0, a)
  197. assert_(isinstance(res, np.ma.masked_array))
  198. assert_equal(res.ndim, 3)
  199. assert_array_equal(res[:,:,0].mask, f1to2(a[:,0]).mask)
  200. assert_array_equal(res[:,:,1].mask, f1to2(a[:,1]).mask)
  201. assert_array_equal(res[:,:,2].mask, f1to2(a[:,2]).mask)
  202. def test_tuple_func1d(self):
  203. def sample_1d(x):
  204. return x[1], x[0]
  205. res = np.apply_along_axis(sample_1d, 1, np.array([[1, 2], [3, 4]]))
  206. assert_array_equal(res, np.array([[2, 1], [4, 3]]))
  207. def test_empty(self):
  208. # can't apply_along_axis when there's no chance to call the function
  209. def never_call(x):
  210. assert_(False) # should never be reached
  211. a = np.empty((0, 0))
  212. assert_raises(ValueError, np.apply_along_axis, never_call, 0, a)
  213. assert_raises(ValueError, np.apply_along_axis, never_call, 1, a)
  214. # but it's sometimes ok with some non-zero dimensions
  215. def empty_to_1(x):
  216. assert_(len(x) == 0)
  217. return 1
  218. a = np.empty((10, 0))
  219. actual = np.apply_along_axis(empty_to_1, 1, a)
  220. assert_equal(actual, np.ones(10))
  221. assert_raises(ValueError, np.apply_along_axis, empty_to_1, 0, a)
  222. def test_with_iterable_object(self):
  223. # from issue 5248
  224. d = np.array([
  225. [{1, 11}, {2, 22}, {3, 33}],
  226. [{4, 44}, {5, 55}, {6, 66}]
  227. ])
  228. actual = np.apply_along_axis(lambda a: set.union(*a), 0, d)
  229. expected = np.array([{1, 11, 4, 44}, {2, 22, 5, 55}, {3, 33, 6, 66}])
  230. assert_equal(actual, expected)
  231. # issue 8642 - assert_equal doesn't detect this!
  232. for i in np.ndindex(actual.shape):
  233. assert_equal(type(actual[i]), type(expected[i]))
  234. class TestApplyOverAxes:
  235. def test_simple(self):
  236. a = np.arange(24).reshape(2, 3, 4)
  237. aoa_a = apply_over_axes(np.sum, a, [0, 2])
  238. assert_array_equal(aoa_a, np.array([[[60], [92], [124]]]))
  239. class TestExpandDims:
  240. def test_functionality(self):
  241. s = (2, 3, 4, 5)
  242. a = np.empty(s)
  243. for axis in range(-5, 4):
  244. b = expand_dims(a, axis)
  245. assert_(b.shape[axis] == 1)
  246. assert_(np.squeeze(b).shape == s)
  247. def test_axis_tuple(self):
  248. a = np.empty((3, 3, 3))
  249. assert np.expand_dims(a, axis=(0, 1, 2)).shape == (1, 1, 1, 3, 3, 3)
  250. assert np.expand_dims(a, axis=(0, -1, -2)).shape == (1, 3, 3, 3, 1, 1)
  251. assert np.expand_dims(a, axis=(0, 3, 5)).shape == (1, 3, 3, 1, 3, 1)
  252. assert np.expand_dims(a, axis=(0, -3, -5)).shape == (1, 1, 3, 1, 3, 3)
  253. def test_axis_out_of_range(self):
  254. s = (2, 3, 4, 5)
  255. a = np.empty(s)
  256. assert_raises(AxisError, expand_dims, a, -6)
  257. assert_raises(AxisError, expand_dims, a, 5)
  258. a = np.empty((3, 3, 3))
  259. assert_raises(AxisError, expand_dims, a, (0, -6))
  260. assert_raises(AxisError, expand_dims, a, (0, 5))
  261. def test_repeated_axis(self):
  262. a = np.empty((3, 3, 3))
  263. assert_raises(ValueError, expand_dims, a, axis=(1, 1))
  264. def test_subclasses(self):
  265. a = np.arange(10).reshape((2, 5))
  266. a = np.ma.array(a, mask=a%3 == 0)
  267. expanded = np.expand_dims(a, axis=1)
  268. assert_(isinstance(expanded, np.ma.MaskedArray))
  269. assert_equal(expanded.shape, (2, 1, 5))
  270. assert_equal(expanded.mask.shape, (2, 1, 5))
  271. class TestArraySplit:
  272. def test_integer_0_split(self):
  273. a = np.arange(10)
  274. assert_raises(ValueError, array_split, a, 0)
  275. def test_integer_split(self):
  276. a = np.arange(10)
  277. res = array_split(a, 1)
  278. desired = [np.arange(10)]
  279. compare_results(res, desired)
  280. res = array_split(a, 2)
  281. desired = [np.arange(5), np.arange(5, 10)]
  282. compare_results(res, desired)
  283. res = array_split(a, 3)
  284. desired = [np.arange(4), np.arange(4, 7), np.arange(7, 10)]
  285. compare_results(res, desired)
  286. res = array_split(a, 4)
  287. desired = [np.arange(3), np.arange(3, 6), np.arange(6, 8),
  288. np.arange(8, 10)]
  289. compare_results(res, desired)
  290. res = array_split(a, 5)
  291. desired = [np.arange(2), np.arange(2, 4), np.arange(4, 6),
  292. np.arange(6, 8), np.arange(8, 10)]
  293. compare_results(res, desired)
  294. res = array_split(a, 6)
  295. desired = [np.arange(2), np.arange(2, 4), np.arange(4, 6),
  296. np.arange(6, 8), np.arange(8, 9), np.arange(9, 10)]
  297. compare_results(res, desired)
  298. res = array_split(a, 7)
  299. desired = [np.arange(2), np.arange(2, 4), np.arange(4, 6),
  300. np.arange(6, 7), np.arange(7, 8), np.arange(8, 9),
  301. np.arange(9, 10)]
  302. compare_results(res, desired)
  303. res = array_split(a, 8)
  304. desired = [np.arange(2), np.arange(2, 4), np.arange(4, 5),
  305. np.arange(5, 6), np.arange(6, 7), np.arange(7, 8),
  306. np.arange(8, 9), np.arange(9, 10)]
  307. compare_results(res, desired)
  308. res = array_split(a, 9)
  309. desired = [np.arange(2), np.arange(2, 3), np.arange(3, 4),
  310. np.arange(4, 5), np.arange(5, 6), np.arange(6, 7),
  311. np.arange(7, 8), np.arange(8, 9), np.arange(9, 10)]
  312. compare_results(res, desired)
  313. res = array_split(a, 10)
  314. desired = [np.arange(1), np.arange(1, 2), np.arange(2, 3),
  315. np.arange(3, 4), np.arange(4, 5), np.arange(5, 6),
  316. np.arange(6, 7), np.arange(7, 8), np.arange(8, 9),
  317. np.arange(9, 10)]
  318. compare_results(res, desired)
  319. res = array_split(a, 11)
  320. desired = [np.arange(1), np.arange(1, 2), np.arange(2, 3),
  321. np.arange(3, 4), np.arange(4, 5), np.arange(5, 6),
  322. np.arange(6, 7), np.arange(7, 8), np.arange(8, 9),
  323. np.arange(9, 10), np.array([])]
  324. compare_results(res, desired)
  325. def test_integer_split_2D_rows(self):
  326. a = np.array([np.arange(10), np.arange(10)])
  327. res = array_split(a, 3, axis=0)
  328. tgt = [np.array([np.arange(10)]), np.array([np.arange(10)]),
  329. np.zeros((0, 10))]
  330. compare_results(res, tgt)
  331. assert_(a.dtype.type is res[-1].dtype.type)
  332. # Same thing for manual splits:
  333. res = array_split(a, [0, 1], axis=0)
  334. tgt = [np.zeros((0, 10)), np.array([np.arange(10)]),
  335. np.array([np.arange(10)])]
  336. compare_results(res, tgt)
  337. assert_(a.dtype.type is res[-1].dtype.type)
  338. def test_integer_split_2D_cols(self):
  339. a = np.array([np.arange(10), np.arange(10)])
  340. res = array_split(a, 3, axis=-1)
  341. desired = [np.array([np.arange(4), np.arange(4)]),
  342. np.array([np.arange(4, 7), np.arange(4, 7)]),
  343. np.array([np.arange(7, 10), np.arange(7, 10)])]
  344. compare_results(res, desired)
  345. def test_integer_split_2D_default(self):
  346. """ This will fail if we change default axis
  347. """
  348. a = np.array([np.arange(10), np.arange(10)])
  349. res = array_split(a, 3)
  350. tgt = [np.array([np.arange(10)]), np.array([np.arange(10)]),
  351. np.zeros((0, 10))]
  352. compare_results(res, tgt)
  353. assert_(a.dtype.type is res[-1].dtype.type)
  354. # perhaps should check higher dimensions
  355. @pytest.mark.skipif(not IS_64BIT, reason="Needs 64bit platform")
  356. def test_integer_split_2D_rows_greater_max_int32(self):
  357. a = np.broadcast_to([0], (1 << 32, 2))
  358. res = array_split(a, 4)
  359. chunk = np.broadcast_to([0], (1 << 30, 2))
  360. tgt = [chunk] * 4
  361. for i in range(len(tgt)):
  362. assert_equal(res[i].shape, tgt[i].shape)
  363. def test_index_split_simple(self):
  364. a = np.arange(10)
  365. indices = [1, 5, 7]
  366. res = array_split(a, indices, axis=-1)
  367. desired = [np.arange(0, 1), np.arange(1, 5), np.arange(5, 7),
  368. np.arange(7, 10)]
  369. compare_results(res, desired)
  370. def test_index_split_low_bound(self):
  371. a = np.arange(10)
  372. indices = [0, 5, 7]
  373. res = array_split(a, indices, axis=-1)
  374. desired = [np.array([]), np.arange(0, 5), np.arange(5, 7),
  375. np.arange(7, 10)]
  376. compare_results(res, desired)
  377. def test_index_split_high_bound(self):
  378. a = np.arange(10)
  379. indices = [0, 5, 7, 10, 12]
  380. res = array_split(a, indices, axis=-1)
  381. desired = [np.array([]), np.arange(0, 5), np.arange(5, 7),
  382. np.arange(7, 10), np.array([]), np.array([])]
  383. compare_results(res, desired)
  384. class TestSplit:
  385. # The split function is essentially the same as array_split,
  386. # except that it test if splitting will result in an
  387. # equal split. Only test for this case.
  388. def test_equal_split(self):
  389. a = np.arange(10)
  390. res = split(a, 2)
  391. desired = [np.arange(5), np.arange(5, 10)]
  392. compare_results(res, desired)
  393. def test_unequal_split(self):
  394. a = np.arange(10)
  395. assert_raises(ValueError, split, a, 3)
  396. class TestColumnStack:
  397. def test_non_iterable(self):
  398. assert_raises(TypeError, column_stack, 1)
  399. def test_1D_arrays(self):
  400. # example from docstring
  401. a = np.array((1, 2, 3))
  402. b = np.array((2, 3, 4))
  403. expected = np.array([[1, 2],
  404. [2, 3],
  405. [3, 4]])
  406. actual = np.column_stack((a, b))
  407. assert_equal(actual, expected)
  408. def test_2D_arrays(self):
  409. # same as hstack 2D docstring example
  410. a = np.array([[1], [2], [3]])
  411. b = np.array([[2], [3], [4]])
  412. expected = np.array([[1, 2],
  413. [2, 3],
  414. [3, 4]])
  415. actual = np.column_stack((a, b))
  416. assert_equal(actual, expected)
  417. def test_generator(self):
  418. with pytest.raises(TypeError, match="arrays to stack must be"):
  419. column_stack(np.arange(3) for _ in range(2))
  420. class TestDstack:
  421. def test_non_iterable(self):
  422. assert_raises(TypeError, dstack, 1)
  423. def test_0D_array(self):
  424. a = np.array(1)
  425. b = np.array(2)
  426. res = dstack([a, b])
  427. desired = np.array([[[1, 2]]])
  428. assert_array_equal(res, desired)
  429. def test_1D_array(self):
  430. a = np.array([1])
  431. b = np.array([2])
  432. res = dstack([a, b])
  433. desired = np.array([[[1, 2]]])
  434. assert_array_equal(res, desired)
  435. def test_2D_array(self):
  436. a = np.array([[1], [2]])
  437. b = np.array([[1], [2]])
  438. res = dstack([a, b])
  439. desired = np.array([[[1, 1]], [[2, 2, ]]])
  440. assert_array_equal(res, desired)
  441. def test_2D_array2(self):
  442. a = np.array([1, 2])
  443. b = np.array([1, 2])
  444. res = dstack([a, b])
  445. desired = np.array([[[1, 1], [2, 2]]])
  446. assert_array_equal(res, desired)
  447. def test_generator(self):
  448. with pytest.raises(TypeError, match="arrays to stack must be"):
  449. dstack(np.arange(3) for _ in range(2))
  450. # array_split has more comprehensive test of splitting.
  451. # only do simple test on hsplit, vsplit, and dsplit
  452. class TestHsplit:
  453. """Only testing for integer splits.
  454. """
  455. def test_non_iterable(self):
  456. assert_raises(ValueError, hsplit, 1, 1)
  457. def test_0D_array(self):
  458. a = np.array(1)
  459. try:
  460. hsplit(a, 2)
  461. assert_(0)
  462. except ValueError:
  463. pass
  464. def test_1D_array(self):
  465. a = np.array([1, 2, 3, 4])
  466. res = hsplit(a, 2)
  467. desired = [np.array([1, 2]), np.array([3, 4])]
  468. compare_results(res, desired)
  469. def test_2D_array(self):
  470. a = np.array([[1, 2, 3, 4],
  471. [1, 2, 3, 4]])
  472. res = hsplit(a, 2)
  473. desired = [np.array([[1, 2], [1, 2]]), np.array([[3, 4], [3, 4]])]
  474. compare_results(res, desired)
  475. class TestVsplit:
  476. """Only testing for integer splits.
  477. """
  478. def test_non_iterable(self):
  479. assert_raises(ValueError, vsplit, 1, 1)
  480. def test_0D_array(self):
  481. a = np.array(1)
  482. assert_raises(ValueError, vsplit, a, 2)
  483. def test_1D_array(self):
  484. a = np.array([1, 2, 3, 4])
  485. try:
  486. vsplit(a, 2)
  487. assert_(0)
  488. except ValueError:
  489. pass
  490. def test_2D_array(self):
  491. a = np.array([[1, 2, 3, 4],
  492. [1, 2, 3, 4]])
  493. res = vsplit(a, 2)
  494. desired = [np.array([[1, 2, 3, 4]]), np.array([[1, 2, 3, 4]])]
  495. compare_results(res, desired)
  496. class TestDsplit:
  497. # Only testing for integer splits.
  498. def test_non_iterable(self):
  499. assert_raises(ValueError, dsplit, 1, 1)
  500. def test_0D_array(self):
  501. a = np.array(1)
  502. assert_raises(ValueError, dsplit, a, 2)
  503. def test_1D_array(self):
  504. a = np.array([1, 2, 3, 4])
  505. assert_raises(ValueError, dsplit, a, 2)
  506. def test_2D_array(self):
  507. a = np.array([[1, 2, 3, 4],
  508. [1, 2, 3, 4]])
  509. try:
  510. dsplit(a, 2)
  511. assert_(0)
  512. except ValueError:
  513. pass
  514. def test_3D_array(self):
  515. a = np.array([[[1, 2, 3, 4],
  516. [1, 2, 3, 4]],
  517. [[1, 2, 3, 4],
  518. [1, 2, 3, 4]]])
  519. res = dsplit(a, 2)
  520. desired = [np.array([[[1, 2], [1, 2]], [[1, 2], [1, 2]]]),
  521. np.array([[[3, 4], [3, 4]], [[3, 4], [3, 4]]])]
  522. compare_results(res, desired)
  523. class TestSqueeze:
  524. def test_basic(self):
  525. from numpy.random import rand
  526. a = rand(20, 10, 10, 1, 1)
  527. b = rand(20, 1, 10, 1, 20)
  528. c = rand(1, 1, 20, 10)
  529. assert_array_equal(np.squeeze(a), np.reshape(a, (20, 10, 10)))
  530. assert_array_equal(np.squeeze(b), np.reshape(b, (20, 10, 20)))
  531. assert_array_equal(np.squeeze(c), np.reshape(c, (20, 10)))
  532. # Squeezing to 0-dim should still give an ndarray
  533. a = [[[1.5]]]
  534. res = np.squeeze(a)
  535. assert_equal(res, 1.5)
  536. assert_equal(res.ndim, 0)
  537. assert_equal(type(res), np.ndarray)
  538. class TestKron:
  539. def test_basic(self):
  540. # Using 0-dimensional ndarray
  541. a = np.array(1)
  542. b = np.array([[1, 2], [3, 4]])
  543. k = np.array([[1, 2], [3, 4]])
  544. assert_array_equal(np.kron(a, b), k)
  545. a = np.array([[1, 2], [3, 4]])
  546. b = np.array(1)
  547. assert_array_equal(np.kron(a, b), k)
  548. # Using 1-dimensional ndarray
  549. a = np.array([3])
  550. b = np.array([[1, 2], [3, 4]])
  551. k = np.array([[3, 6], [9, 12]])
  552. assert_array_equal(np.kron(a, b), k)
  553. a = np.array([[1, 2], [3, 4]])
  554. b = np.array([3])
  555. assert_array_equal(np.kron(a, b), k)
  556. # Using 3-dimensional ndarray
  557. a = np.array([[[1]], [[2]]])
  558. b = np.array([[1, 2], [3, 4]])
  559. k = np.array([[[1, 2], [3, 4]], [[2, 4], [6, 8]]])
  560. assert_array_equal(np.kron(a, b), k)
  561. a = np.array([[1, 2], [3, 4]])
  562. b = np.array([[[1]], [[2]]])
  563. k = np.array([[[1, 2], [3, 4]], [[2, 4], [6, 8]]])
  564. assert_array_equal(np.kron(a, b), k)
  565. def test_return_type(self):
  566. class myarray(np.ndarray):
  567. __array_priority__ = 1.0
  568. a = np.ones([2, 2])
  569. ma = myarray(a.shape, a.dtype, a.data)
  570. assert_equal(type(kron(a, a)), np.ndarray)
  571. assert_equal(type(kron(ma, ma)), myarray)
  572. assert_equal(type(kron(a, ma)), myarray)
  573. assert_equal(type(kron(ma, a)), myarray)
  574. @pytest.mark.parametrize(
  575. "array_class", [np.asarray, np.asmatrix]
  576. )
  577. def test_kron_smoke(self, array_class):
  578. a = array_class(np.ones([3, 3]))
  579. b = array_class(np.ones([3, 3]))
  580. k = array_class(np.ones([9, 9]))
  581. assert_array_equal(np.kron(a, b), k)
  582. def test_kron_ma(self):
  583. x = np.ma.array([[1, 2], [3, 4]], mask=[[0, 1], [1, 0]])
  584. k = np.ma.array(np.diag([1, 4, 4, 16]),
  585. mask=~np.array(np.identity(4), dtype=bool))
  586. assert_array_equal(k, np.kron(x, x))
  587. @pytest.mark.parametrize(
  588. "shape_a,shape_b", [
  589. ((1, 1), (1, 1)),
  590. ((1, 2, 3), (4, 5, 6)),
  591. ((2, 2), (2, 2, 2)),
  592. ((1, 0), (1, 1)),
  593. ((2, 0, 2), (2, 2)),
  594. ((2, 0, 0, 2), (2, 0, 2)),
  595. ])
  596. def test_kron_shape(self, shape_a, shape_b):
  597. a = np.ones(shape_a)
  598. b = np.ones(shape_b)
  599. normalised_shape_a = (1,) * max(0, len(shape_b)-len(shape_a)) + shape_a
  600. normalised_shape_b = (1,) * max(0, len(shape_a)-len(shape_b)) + shape_b
  601. expected_shape = np.multiply(normalised_shape_a, normalised_shape_b)
  602. k = np.kron(a, b)
  603. assert np.array_equal(
  604. k.shape, expected_shape), "Unexpected shape from kron"
  605. class TestTile:
  606. def test_basic(self):
  607. a = np.array([0, 1, 2])
  608. b = [[1, 2], [3, 4]]
  609. assert_equal(tile(a, 2), [0, 1, 2, 0, 1, 2])
  610. assert_equal(tile(a, (2, 2)), [[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2]])
  611. assert_equal(tile(a, (1, 2)), [[0, 1, 2, 0, 1, 2]])
  612. assert_equal(tile(b, 2), [[1, 2, 1, 2], [3, 4, 3, 4]])
  613. assert_equal(tile(b, (2, 1)), [[1, 2], [3, 4], [1, 2], [3, 4]])
  614. assert_equal(tile(b, (2, 2)), [[1, 2, 1, 2], [3, 4, 3, 4],
  615. [1, 2, 1, 2], [3, 4, 3, 4]])
  616. def test_tile_one_repetition_on_array_gh4679(self):
  617. a = np.arange(5)
  618. b = tile(a, 1)
  619. b += 2
  620. assert_equal(a, np.arange(5))
  621. def test_empty(self):
  622. a = np.array([[[]]])
  623. b = np.array([[], []])
  624. c = tile(b, 2).shape
  625. d = tile(a, (3, 2, 5)).shape
  626. assert_equal(c, (2, 0))
  627. assert_equal(d, (3, 2, 0))
  628. def test_kroncompare(self):
  629. from numpy.random import randint
  630. reps = [(2,), (1, 2), (2, 1), (2, 2), (2, 3, 2), (3, 2)]
  631. shape = [(3,), (2, 3), (3, 4, 3), (3, 2, 3), (4, 3, 2, 4), (2, 2)]
  632. for s in shape:
  633. b = randint(0, 10, size=s)
  634. for r in reps:
  635. a = np.ones(r, b.dtype)
  636. large = tile(b, r)
  637. klarge = kron(a, b)
  638. assert_equal(large, klarge)
  639. class TestMayShareMemory:
  640. def test_basic(self):
  641. d = np.ones((50, 60))
  642. d2 = np.ones((30, 60, 6))
  643. assert_(np.may_share_memory(d, d))
  644. assert_(np.may_share_memory(d, d[::-1]))
  645. assert_(np.may_share_memory(d, d[::2]))
  646. assert_(np.may_share_memory(d, d[1:, ::-1]))
  647. assert_(not np.may_share_memory(d[::-1], d2))
  648. assert_(not np.may_share_memory(d[::2], d2))
  649. assert_(not np.may_share_memory(d[1:, ::-1], d2))
  650. assert_(np.may_share_memory(d2[1:, ::-1], d2))
  651. # Utility
  652. def compare_results(res, desired):
  653. """Compare lists of arrays."""
  654. if len(res) != len(desired):
  655. raise ValueError("Iterables have different lengths")
  656. # See also PEP 618 for Python 3.10
  657. for x, y in zip(res, desired):
  658. assert_array_equal(x, y)