test_shape_base.py 26 KB

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