test_stride_tricks.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. from __future__ import division, absolute_import, print_function
  2. import numpy as np
  3. from numpy.core._rational_tests import rational
  4. from numpy.testing import (
  5. assert_equal, assert_array_equal, assert_raises, assert_,
  6. assert_raises_regex
  7. )
  8. from numpy.lib.stride_tricks import (
  9. as_strided, broadcast_arrays, _broadcast_shape, broadcast_to
  10. )
  11. def assert_shapes_correct(input_shapes, expected_shape):
  12. # Broadcast a list of arrays with the given input shapes and check the
  13. # common output shape.
  14. inarrays = [np.zeros(s) for s in input_shapes]
  15. outarrays = broadcast_arrays(*inarrays)
  16. outshapes = [a.shape for a in outarrays]
  17. expected = [expected_shape] * len(inarrays)
  18. assert_equal(outshapes, expected)
  19. def assert_incompatible_shapes_raise(input_shapes):
  20. # Broadcast a list of arrays with the given (incompatible) input shapes
  21. # and check that they raise a ValueError.
  22. inarrays = [np.zeros(s) for s in input_shapes]
  23. assert_raises(ValueError, broadcast_arrays, *inarrays)
  24. def assert_same_as_ufunc(shape0, shape1, transposed=False, flipped=False):
  25. # Broadcast two shapes against each other and check that the data layout
  26. # is the same as if a ufunc did the broadcasting.
  27. x0 = np.zeros(shape0, dtype=int)
  28. # Note that multiply.reduce's identity element is 1.0, so when shape1==(),
  29. # this gives the desired n==1.
  30. n = int(np.multiply.reduce(shape1))
  31. x1 = np.arange(n).reshape(shape1)
  32. if transposed:
  33. x0 = x0.T
  34. x1 = x1.T
  35. if flipped:
  36. x0 = x0[::-1]
  37. x1 = x1[::-1]
  38. # Use the add ufunc to do the broadcasting. Since we're adding 0s to x1, the
  39. # result should be exactly the same as the broadcasted view of x1.
  40. y = x0 + x1
  41. b0, b1 = broadcast_arrays(x0, x1)
  42. assert_array_equal(y, b1)
  43. def test_same():
  44. x = np.arange(10)
  45. y = np.arange(10)
  46. bx, by = broadcast_arrays(x, y)
  47. assert_array_equal(x, bx)
  48. assert_array_equal(y, by)
  49. def test_broadcast_kwargs():
  50. # ensure that a TypeError is appropriately raised when
  51. # np.broadcast_arrays() is called with any keyword
  52. # argument other than 'subok'
  53. x = np.arange(10)
  54. y = np.arange(10)
  55. with assert_raises_regex(TypeError,
  56. r'broadcast_arrays\(\) got an unexpected keyword*'):
  57. broadcast_arrays(x, y, dtype='float64')
  58. def test_one_off():
  59. x = np.array([[1, 2, 3]])
  60. y = np.array([[1], [2], [3]])
  61. bx, by = broadcast_arrays(x, y)
  62. bx0 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
  63. by0 = bx0.T
  64. assert_array_equal(bx0, bx)
  65. assert_array_equal(by0, by)
  66. def test_same_input_shapes():
  67. # Check that the final shape is just the input shape.
  68. data = [
  69. (),
  70. (1,),
  71. (3,),
  72. (0, 1),
  73. (0, 3),
  74. (1, 0),
  75. (3, 0),
  76. (1, 3),
  77. (3, 1),
  78. (3, 3),
  79. ]
  80. for shape in data:
  81. input_shapes = [shape]
  82. # Single input.
  83. assert_shapes_correct(input_shapes, shape)
  84. # Double input.
  85. input_shapes2 = [shape, shape]
  86. assert_shapes_correct(input_shapes2, shape)
  87. # Triple input.
  88. input_shapes3 = [shape, shape, shape]
  89. assert_shapes_correct(input_shapes3, shape)
  90. def test_two_compatible_by_ones_input_shapes():
  91. # Check that two different input shapes of the same length, but some have
  92. # ones, broadcast to the correct shape.
  93. data = [
  94. [[(1,), (3,)], (3,)],
  95. [[(1, 3), (3, 3)], (3, 3)],
  96. [[(3, 1), (3, 3)], (3, 3)],
  97. [[(1, 3), (3, 1)], (3, 3)],
  98. [[(1, 1), (3, 3)], (3, 3)],
  99. [[(1, 1), (1, 3)], (1, 3)],
  100. [[(1, 1), (3, 1)], (3, 1)],
  101. [[(1, 0), (0, 0)], (0, 0)],
  102. [[(0, 1), (0, 0)], (0, 0)],
  103. [[(1, 0), (0, 1)], (0, 0)],
  104. [[(1, 1), (0, 0)], (0, 0)],
  105. [[(1, 1), (1, 0)], (1, 0)],
  106. [[(1, 1), (0, 1)], (0, 1)],
  107. ]
  108. for input_shapes, expected_shape in data:
  109. assert_shapes_correct(input_shapes, expected_shape)
  110. # Reverse the input shapes since broadcasting should be symmetric.
  111. assert_shapes_correct(input_shapes[::-1], expected_shape)
  112. def test_two_compatible_by_prepending_ones_input_shapes():
  113. # Check that two different input shapes (of different lengths) broadcast
  114. # to the correct shape.
  115. data = [
  116. [[(), (3,)], (3,)],
  117. [[(3,), (3, 3)], (3, 3)],
  118. [[(3,), (3, 1)], (3, 3)],
  119. [[(1,), (3, 3)], (3, 3)],
  120. [[(), (3, 3)], (3, 3)],
  121. [[(1, 1), (3,)], (1, 3)],
  122. [[(1,), (3, 1)], (3, 1)],
  123. [[(1,), (1, 3)], (1, 3)],
  124. [[(), (1, 3)], (1, 3)],
  125. [[(), (3, 1)], (3, 1)],
  126. [[(), (0,)], (0,)],
  127. [[(0,), (0, 0)], (0, 0)],
  128. [[(0,), (0, 1)], (0, 0)],
  129. [[(1,), (0, 0)], (0, 0)],
  130. [[(), (0, 0)], (0, 0)],
  131. [[(1, 1), (0,)], (1, 0)],
  132. [[(1,), (0, 1)], (0, 1)],
  133. [[(1,), (1, 0)], (1, 0)],
  134. [[(), (1, 0)], (1, 0)],
  135. [[(), (0, 1)], (0, 1)],
  136. ]
  137. for input_shapes, expected_shape in data:
  138. assert_shapes_correct(input_shapes, expected_shape)
  139. # Reverse the input shapes since broadcasting should be symmetric.
  140. assert_shapes_correct(input_shapes[::-1], expected_shape)
  141. def test_incompatible_shapes_raise_valueerror():
  142. # Check that a ValueError is raised for incompatible shapes.
  143. data = [
  144. [(3,), (4,)],
  145. [(2, 3), (2,)],
  146. [(3,), (3,), (4,)],
  147. [(1, 3, 4), (2, 3, 3)],
  148. ]
  149. for input_shapes in data:
  150. assert_incompatible_shapes_raise(input_shapes)
  151. # Reverse the input shapes since broadcasting should be symmetric.
  152. assert_incompatible_shapes_raise(input_shapes[::-1])
  153. def test_same_as_ufunc():
  154. # Check that the data layout is the same as if a ufunc did the operation.
  155. data = [
  156. [[(1,), (3,)], (3,)],
  157. [[(1, 3), (3, 3)], (3, 3)],
  158. [[(3, 1), (3, 3)], (3, 3)],
  159. [[(1, 3), (3, 1)], (3, 3)],
  160. [[(1, 1), (3, 3)], (3, 3)],
  161. [[(1, 1), (1, 3)], (1, 3)],
  162. [[(1, 1), (3, 1)], (3, 1)],
  163. [[(1, 0), (0, 0)], (0, 0)],
  164. [[(0, 1), (0, 0)], (0, 0)],
  165. [[(1, 0), (0, 1)], (0, 0)],
  166. [[(1, 1), (0, 0)], (0, 0)],
  167. [[(1, 1), (1, 0)], (1, 0)],
  168. [[(1, 1), (0, 1)], (0, 1)],
  169. [[(), (3,)], (3,)],
  170. [[(3,), (3, 3)], (3, 3)],
  171. [[(3,), (3, 1)], (3, 3)],
  172. [[(1,), (3, 3)], (3, 3)],
  173. [[(), (3, 3)], (3, 3)],
  174. [[(1, 1), (3,)], (1, 3)],
  175. [[(1,), (3, 1)], (3, 1)],
  176. [[(1,), (1, 3)], (1, 3)],
  177. [[(), (1, 3)], (1, 3)],
  178. [[(), (3, 1)], (3, 1)],
  179. [[(), (0,)], (0,)],
  180. [[(0,), (0, 0)], (0, 0)],
  181. [[(0,), (0, 1)], (0, 0)],
  182. [[(1,), (0, 0)], (0, 0)],
  183. [[(), (0, 0)], (0, 0)],
  184. [[(1, 1), (0,)], (1, 0)],
  185. [[(1,), (0, 1)], (0, 1)],
  186. [[(1,), (1, 0)], (1, 0)],
  187. [[(), (1, 0)], (1, 0)],
  188. [[(), (0, 1)], (0, 1)],
  189. ]
  190. for input_shapes, expected_shape in data:
  191. assert_same_as_ufunc(input_shapes[0], input_shapes[1],
  192. "Shapes: %s %s" % (input_shapes[0], input_shapes[1]))
  193. # Reverse the input shapes since broadcasting should be symmetric.
  194. assert_same_as_ufunc(input_shapes[1], input_shapes[0])
  195. # Try them transposed, too.
  196. assert_same_as_ufunc(input_shapes[0], input_shapes[1], True)
  197. # ... and flipped for non-rank-0 inputs in order to test negative
  198. # strides.
  199. if () not in input_shapes:
  200. assert_same_as_ufunc(input_shapes[0], input_shapes[1], False, True)
  201. assert_same_as_ufunc(input_shapes[0], input_shapes[1], True, True)
  202. def test_broadcast_to_succeeds():
  203. data = [
  204. [np.array(0), (0,), np.array(0)],
  205. [np.array(0), (1,), np.zeros(1)],
  206. [np.array(0), (3,), np.zeros(3)],
  207. [np.ones(1), (1,), np.ones(1)],
  208. [np.ones(1), (2,), np.ones(2)],
  209. [np.ones(1), (1, 2, 3), np.ones((1, 2, 3))],
  210. [np.arange(3), (3,), np.arange(3)],
  211. [np.arange(3), (1, 3), np.arange(3).reshape(1, -1)],
  212. [np.arange(3), (2, 3), np.array([[0, 1, 2], [0, 1, 2]])],
  213. # test if shape is not a tuple
  214. [np.ones(0), 0, np.ones(0)],
  215. [np.ones(1), 1, np.ones(1)],
  216. [np.ones(1), 2, np.ones(2)],
  217. # these cases with size 0 are strange, but they reproduce the behavior
  218. # of broadcasting with ufuncs (see test_same_as_ufunc above)
  219. [np.ones(1), (0,), np.ones(0)],
  220. [np.ones((1, 2)), (0, 2), np.ones((0, 2))],
  221. [np.ones((2, 1)), (2, 0), np.ones((2, 0))],
  222. ]
  223. for input_array, shape, expected in data:
  224. actual = broadcast_to(input_array, shape)
  225. assert_array_equal(expected, actual)
  226. def test_broadcast_to_raises():
  227. data = [
  228. [(0,), ()],
  229. [(1,), ()],
  230. [(3,), ()],
  231. [(3,), (1,)],
  232. [(3,), (2,)],
  233. [(3,), (4,)],
  234. [(1, 2), (2, 1)],
  235. [(1, 1), (1,)],
  236. [(1,), -1],
  237. [(1,), (-1,)],
  238. [(1, 2), (-1, 2)],
  239. ]
  240. for orig_shape, target_shape in data:
  241. arr = np.zeros(orig_shape)
  242. assert_raises(ValueError, lambda: broadcast_to(arr, target_shape))
  243. def test_broadcast_shape():
  244. # broadcast_shape is already exercized indirectly by broadcast_arrays
  245. assert_equal(_broadcast_shape(), ())
  246. assert_equal(_broadcast_shape([1, 2]), (2,))
  247. assert_equal(_broadcast_shape(np.ones((1, 1))), (1, 1))
  248. assert_equal(_broadcast_shape(np.ones((1, 1)), np.ones((3, 4))), (3, 4))
  249. assert_equal(_broadcast_shape(*([np.ones((1, 2))] * 32)), (1, 2))
  250. assert_equal(_broadcast_shape(*([np.ones((1, 2))] * 100)), (1, 2))
  251. # regression tests for gh-5862
  252. assert_equal(_broadcast_shape(*([np.ones(2)] * 32 + [1])), (2,))
  253. bad_args = [np.ones(2)] * 32 + [np.ones(3)] * 32
  254. assert_raises(ValueError, lambda: _broadcast_shape(*bad_args))
  255. def test_as_strided():
  256. a = np.array([None])
  257. a_view = as_strided(a)
  258. expected = np.array([None])
  259. assert_array_equal(a_view, np.array([None]))
  260. a = np.array([1, 2, 3, 4])
  261. a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,))
  262. expected = np.array([1, 3])
  263. assert_array_equal(a_view, expected)
  264. a = np.array([1, 2, 3, 4])
  265. a_view = as_strided(a, shape=(3, 4), strides=(0, 1 * a.itemsize))
  266. expected = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
  267. assert_array_equal(a_view, expected)
  268. # Regression test for gh-5081
  269. dt = np.dtype([('num', 'i4'), ('obj', 'O')])
  270. a = np.empty((4,), dtype=dt)
  271. a['num'] = np.arange(1, 5)
  272. a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
  273. expected_num = [[1, 2, 3, 4]] * 3
  274. expected_obj = [[None]*4]*3
  275. assert_equal(a_view.dtype, dt)
  276. assert_array_equal(expected_num, a_view['num'])
  277. assert_array_equal(expected_obj, a_view['obj'])
  278. # Make sure that void types without fields are kept unchanged
  279. a = np.empty((4,), dtype='V4')
  280. a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
  281. assert_equal(a.dtype, a_view.dtype)
  282. # Make sure that the only type that could fail is properly handled
  283. dt = np.dtype({'names': [''], 'formats': ['V4']})
  284. a = np.empty((4,), dtype=dt)
  285. a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
  286. assert_equal(a.dtype, a_view.dtype)
  287. # Custom dtypes should not be lost (gh-9161)
  288. r = [rational(i) for i in range(4)]
  289. a = np.array(r, dtype=rational)
  290. a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
  291. assert_equal(a.dtype, a_view.dtype)
  292. assert_array_equal([r] * 3, a_view)
  293. def as_strided_writeable():
  294. arr = np.ones(10)
  295. view = as_strided(arr, writeable=False)
  296. assert_(not view.flags.writeable)
  297. # Check that writeable also is fine:
  298. view = as_strided(arr, writeable=True)
  299. assert_(view.flags.writeable)
  300. view[...] = 3
  301. assert_array_equal(arr, np.full_like(arr, 3))
  302. # Test that things do not break down for readonly:
  303. arr.flags.writeable = False
  304. view = as_strided(arr, writeable=False)
  305. view = as_strided(arr, writeable=True)
  306. assert_(not view.flags.writeable)
  307. class VerySimpleSubClass(np.ndarray):
  308. def __new__(cls, *args, **kwargs):
  309. kwargs['subok'] = True
  310. return np.array(*args, **kwargs).view(cls)
  311. class SimpleSubClass(VerySimpleSubClass):
  312. def __new__(cls, *args, **kwargs):
  313. kwargs['subok'] = True
  314. self = np.array(*args, **kwargs).view(cls)
  315. self.info = 'simple'
  316. return self
  317. def __array_finalize__(self, obj):
  318. self.info = getattr(obj, 'info', '') + ' finalized'
  319. def test_subclasses():
  320. # test that subclass is preserved only if subok=True
  321. a = VerySimpleSubClass([1, 2, 3, 4])
  322. assert_(type(a) is VerySimpleSubClass)
  323. a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,))
  324. assert_(type(a_view) is np.ndarray)
  325. a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,), subok=True)
  326. assert_(type(a_view) is VerySimpleSubClass)
  327. # test that if a subclass has __array_finalize__, it is used
  328. a = SimpleSubClass([1, 2, 3, 4])
  329. a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,), subok=True)
  330. assert_(type(a_view) is SimpleSubClass)
  331. assert_(a_view.info == 'simple finalized')
  332. # similar tests for broadcast_arrays
  333. b = np.arange(len(a)).reshape(-1, 1)
  334. a_view, b_view = broadcast_arrays(a, b)
  335. assert_(type(a_view) is np.ndarray)
  336. assert_(type(b_view) is np.ndarray)
  337. assert_(a_view.shape == b_view.shape)
  338. a_view, b_view = broadcast_arrays(a, b, subok=True)
  339. assert_(type(a_view) is SimpleSubClass)
  340. assert_(a_view.info == 'simple finalized')
  341. assert_(type(b_view) is np.ndarray)
  342. assert_(a_view.shape == b_view.shape)
  343. # and for broadcast_to
  344. shape = (2, 4)
  345. a_view = broadcast_to(a, shape)
  346. assert_(type(a_view) is np.ndarray)
  347. assert_(a_view.shape == shape)
  348. a_view = broadcast_to(a, shape, subok=True)
  349. assert_(type(a_view) is SimpleSubClass)
  350. assert_(a_view.info == 'simple finalized')
  351. assert_(a_view.shape == shape)
  352. def test_writeable():
  353. # broadcast_to should return a readonly array
  354. original = np.array([1, 2, 3])
  355. result = broadcast_to(original, (2, 3))
  356. assert_equal(result.flags.writeable, False)
  357. assert_raises(ValueError, result.__setitem__, slice(None), 0)
  358. # but the result of broadcast_arrays needs to be writeable (for now), to
  359. # preserve backwards compatibility
  360. for results in [broadcast_arrays(original),
  361. broadcast_arrays(0, original)]:
  362. for result in results:
  363. assert_equal(result.flags.writeable, True)
  364. # keep readonly input readonly
  365. original.flags.writeable = False
  366. _, result = broadcast_arrays(0, original)
  367. assert_equal(result.flags.writeable, False)
  368. # regression test for GH6491
  369. shape = (2,)
  370. strides = [0]
  371. tricky_array = as_strided(np.array(0), shape, strides)
  372. other = np.zeros((1,))
  373. first, second = broadcast_arrays(tricky_array, other)
  374. assert_(first.shape == second.shape)
  375. def test_reference_types():
  376. input_array = np.array('a', dtype=object)
  377. expected = np.array(['a'] * 3, dtype=object)
  378. actual = broadcast_to(input_array, (3,))
  379. assert_array_equal(expected, actual)
  380. actual, _ = broadcast_arrays(input_array, np.ones(3))
  381. assert_array_equal(expected, actual)