test_indexing.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  1. import sys
  2. import warnings
  3. import functools
  4. import operator
  5. import numpy as np
  6. from numpy.core._multiarray_tests import array_indexing
  7. from itertools import product
  8. from numpy.testing import (
  9. assert_, assert_equal, assert_raises, assert_array_equal, assert_warns,
  10. HAS_REFCOUNT,
  11. )
  12. class TestIndexing:
  13. def test_index_no_floats(self):
  14. a = np.array([[[5]]])
  15. assert_raises(IndexError, lambda: a[0.0])
  16. assert_raises(IndexError, lambda: a[0, 0.0])
  17. assert_raises(IndexError, lambda: a[0.0, 0])
  18. assert_raises(IndexError, lambda: a[0.0,:])
  19. assert_raises(IndexError, lambda: a[:, 0.0])
  20. assert_raises(IndexError, lambda: a[:, 0.0,:])
  21. assert_raises(IndexError, lambda: a[0.0,:,:])
  22. assert_raises(IndexError, lambda: a[0, 0, 0.0])
  23. assert_raises(IndexError, lambda: a[0.0, 0, 0])
  24. assert_raises(IndexError, lambda: a[0, 0.0, 0])
  25. assert_raises(IndexError, lambda: a[-1.4])
  26. assert_raises(IndexError, lambda: a[0, -1.4])
  27. assert_raises(IndexError, lambda: a[-1.4, 0])
  28. assert_raises(IndexError, lambda: a[-1.4,:])
  29. assert_raises(IndexError, lambda: a[:, -1.4])
  30. assert_raises(IndexError, lambda: a[:, -1.4,:])
  31. assert_raises(IndexError, lambda: a[-1.4,:,:])
  32. assert_raises(IndexError, lambda: a[0, 0, -1.4])
  33. assert_raises(IndexError, lambda: a[-1.4, 0, 0])
  34. assert_raises(IndexError, lambda: a[0, -1.4, 0])
  35. assert_raises(IndexError, lambda: a[0.0:, 0.0])
  36. assert_raises(IndexError, lambda: a[0.0:, 0.0,:])
  37. def test_slicing_no_floats(self):
  38. a = np.array([[5]])
  39. # start as float.
  40. assert_raises(TypeError, lambda: a[0.0:])
  41. assert_raises(TypeError, lambda: a[0:, 0.0:2])
  42. assert_raises(TypeError, lambda: a[0.0::2, :0])
  43. assert_raises(TypeError, lambda: a[0.0:1:2,:])
  44. assert_raises(TypeError, lambda: a[:, 0.0:])
  45. # stop as float.
  46. assert_raises(TypeError, lambda: a[:0.0])
  47. assert_raises(TypeError, lambda: a[:0, 1:2.0])
  48. assert_raises(TypeError, lambda: a[:0.0:2, :0])
  49. assert_raises(TypeError, lambda: a[:0.0,:])
  50. assert_raises(TypeError, lambda: a[:, 0:4.0:2])
  51. # step as float.
  52. assert_raises(TypeError, lambda: a[::1.0])
  53. assert_raises(TypeError, lambda: a[0:, :2:2.0])
  54. assert_raises(TypeError, lambda: a[1::4.0, :0])
  55. assert_raises(TypeError, lambda: a[::5.0,:])
  56. assert_raises(TypeError, lambda: a[:, 0:4:2.0])
  57. # mixed.
  58. assert_raises(TypeError, lambda: a[1.0:2:2.0])
  59. assert_raises(TypeError, lambda: a[1.0::2.0])
  60. assert_raises(TypeError, lambda: a[0:, :2.0:2.0])
  61. assert_raises(TypeError, lambda: a[1.0:1:4.0, :0])
  62. assert_raises(TypeError, lambda: a[1.0:5.0:5.0,:])
  63. assert_raises(TypeError, lambda: a[:, 0.4:4.0:2.0])
  64. # should still get the DeprecationWarning if step = 0.
  65. assert_raises(TypeError, lambda: a[::0.0])
  66. def test_index_no_array_to_index(self):
  67. # No non-scalar arrays.
  68. a = np.array([[[1]]])
  69. assert_raises(TypeError, lambda: a[a:a:a])
  70. def test_none_index(self):
  71. # `None` index adds newaxis
  72. a = np.array([1, 2, 3])
  73. assert_equal(a[None], a[np.newaxis])
  74. assert_equal(a[None].ndim, a.ndim + 1)
  75. def test_empty_tuple_index(self):
  76. # Empty tuple index creates a view
  77. a = np.array([1, 2, 3])
  78. assert_equal(a[()], a)
  79. assert_(a[()].base is a)
  80. a = np.array(0)
  81. assert_(isinstance(a[()], np.int_))
  82. def test_void_scalar_empty_tuple(self):
  83. s = np.zeros((), dtype='V4')
  84. assert_equal(s[()].dtype, s.dtype)
  85. assert_equal(s[()], s)
  86. assert_equal(type(s[...]), np.ndarray)
  87. def test_same_kind_index_casting(self):
  88. # Indexes should be cast with same-kind and not safe, even if that
  89. # is somewhat unsafe. So test various different code paths.
  90. index = np.arange(5)
  91. u_index = index.astype(np.uintp)
  92. arr = np.arange(10)
  93. assert_array_equal(arr[index], arr[u_index])
  94. arr[u_index] = np.arange(5)
  95. assert_array_equal(arr, np.arange(10))
  96. arr = np.arange(10).reshape(5, 2)
  97. assert_array_equal(arr[index], arr[u_index])
  98. arr[u_index] = np.arange(5)[:,None]
  99. assert_array_equal(arr, np.arange(5)[:,None].repeat(2, axis=1))
  100. arr = np.arange(25).reshape(5, 5)
  101. assert_array_equal(arr[u_index, u_index], arr[index, index])
  102. def test_empty_fancy_index(self):
  103. # Empty list index creates an empty array
  104. # with the same dtype (but with weird shape)
  105. a = np.array([1, 2, 3])
  106. assert_equal(a[[]], [])
  107. assert_equal(a[[]].dtype, a.dtype)
  108. b = np.array([], dtype=np.intp)
  109. assert_equal(a[[]], [])
  110. assert_equal(a[[]].dtype, a.dtype)
  111. b = np.array([])
  112. assert_raises(IndexError, a.__getitem__, b)
  113. def test_ellipsis_index(self):
  114. a = np.array([[1, 2, 3],
  115. [4, 5, 6],
  116. [7, 8, 9]])
  117. assert_(a[...] is not a)
  118. assert_equal(a[...], a)
  119. # `a[...]` was `a` in numpy <1.9.
  120. assert_(a[...].base is a)
  121. # Slicing with ellipsis can skip an
  122. # arbitrary number of dimensions
  123. assert_equal(a[0, ...], a[0])
  124. assert_equal(a[0, ...], a[0,:])
  125. assert_equal(a[..., 0], a[:, 0])
  126. # Slicing with ellipsis always results
  127. # in an array, not a scalar
  128. assert_equal(a[0, ..., 1], np.array(2))
  129. # Assignment with `(Ellipsis,)` on 0-d arrays
  130. b = np.array(1)
  131. b[(Ellipsis,)] = 2
  132. assert_equal(b, 2)
  133. def test_single_int_index(self):
  134. # Single integer index selects one row
  135. a = np.array([[1, 2, 3],
  136. [4, 5, 6],
  137. [7, 8, 9]])
  138. assert_equal(a[0], [1, 2, 3])
  139. assert_equal(a[-1], [7, 8, 9])
  140. # Index out of bounds produces IndexError
  141. assert_raises(IndexError, a.__getitem__, 1 << 30)
  142. # Index overflow produces IndexError
  143. assert_raises(IndexError, a.__getitem__, 1 << 64)
  144. def test_single_bool_index(self):
  145. # Single boolean index
  146. a = np.array([[1, 2, 3],
  147. [4, 5, 6],
  148. [7, 8, 9]])
  149. assert_equal(a[np.array(True)], a[None])
  150. assert_equal(a[np.array(False)], a[None][0:0])
  151. def test_boolean_shape_mismatch(self):
  152. arr = np.ones((5, 4, 3))
  153. index = np.array([True])
  154. assert_raises(IndexError, arr.__getitem__, index)
  155. index = np.array([False] * 6)
  156. assert_raises(IndexError, arr.__getitem__, index)
  157. index = np.zeros((4, 4), dtype=bool)
  158. assert_raises(IndexError, arr.__getitem__, index)
  159. assert_raises(IndexError, arr.__getitem__, (slice(None), index))
  160. def test_boolean_indexing_onedim(self):
  161. # Indexing a 2-dimensional array with
  162. # boolean array of length one
  163. a = np.array([[ 0., 0., 0.]])
  164. b = np.array([ True], dtype=bool)
  165. assert_equal(a[b], a)
  166. # boolean assignment
  167. a[b] = 1.
  168. assert_equal(a, [[1., 1., 1.]])
  169. def test_boolean_assignment_value_mismatch(self):
  170. # A boolean assignment should fail when the shape of the values
  171. # cannot be broadcast to the subscription. (see also gh-3458)
  172. a = np.arange(4)
  173. def f(a, v):
  174. a[a > -1] = v
  175. assert_raises(ValueError, f, a, [])
  176. assert_raises(ValueError, f, a, [1, 2, 3])
  177. assert_raises(ValueError, f, a[:1], [1, 2, 3])
  178. def test_boolean_assignment_needs_api(self):
  179. # See also gh-7666
  180. # This caused a segfault on Python 2 due to the GIL not being
  181. # held when the iterator does not need it, but the transfer function
  182. # does
  183. arr = np.zeros(1000)
  184. indx = np.zeros(1000, dtype=bool)
  185. indx[:100] = True
  186. arr[indx] = np.ones(100, dtype=object)
  187. expected = np.zeros(1000)
  188. expected[:100] = 1
  189. assert_array_equal(arr, expected)
  190. def test_boolean_indexing_twodim(self):
  191. # Indexing a 2-dimensional array with
  192. # 2-dimensional boolean array
  193. a = np.array([[1, 2, 3],
  194. [4, 5, 6],
  195. [7, 8, 9]])
  196. b = np.array([[ True, False, True],
  197. [False, True, False],
  198. [ True, False, True]])
  199. assert_equal(a[b], [1, 3, 5, 7, 9])
  200. assert_equal(a[b[1]], [[4, 5, 6]])
  201. assert_equal(a[b[0]], a[b[2]])
  202. # boolean assignment
  203. a[b] = 0
  204. assert_equal(a, [[0, 2, 0],
  205. [4, 0, 6],
  206. [0, 8, 0]])
  207. def test_boolean_indexing_list(self):
  208. # Regression test for #13715. It's a use-after-free bug which the
  209. # test won't directly catch, but it will show up in valgrind.
  210. a = np.array([1, 2, 3])
  211. b = [True, False, True]
  212. # Two variants of the test because the first takes a fast path
  213. assert_equal(a[b], [1, 3])
  214. assert_equal(a[None, b], [[1, 3]])
  215. def test_reverse_strides_and_subspace_bufferinit(self):
  216. # This tests that the strides are not reversed for simple and
  217. # subspace fancy indexing.
  218. a = np.ones(5)
  219. b = np.zeros(5, dtype=np.intp)[::-1]
  220. c = np.arange(5)[::-1]
  221. a[b] = c
  222. # If the strides are not reversed, the 0 in the arange comes last.
  223. assert_equal(a[0], 0)
  224. # This also tests that the subspace buffer is initialized:
  225. a = np.ones((5, 2))
  226. c = np.arange(10).reshape(5, 2)[::-1]
  227. a[b, :] = c
  228. assert_equal(a[0], [0, 1])
  229. def test_reversed_strides_result_allocation(self):
  230. # Test a bug when calculating the output strides for a result array
  231. # when the subspace size was 1 (and test other cases as well)
  232. a = np.arange(10)[:, None]
  233. i = np.arange(10)[::-1]
  234. assert_array_equal(a[i], a[i.copy('C')])
  235. a = np.arange(20).reshape(-1, 2)
  236. def test_uncontiguous_subspace_assignment(self):
  237. # During development there was a bug activating a skip logic
  238. # based on ndim instead of size.
  239. a = np.full((3, 4, 2), -1)
  240. b = np.full((3, 4, 2), -1)
  241. a[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T
  242. b[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T.copy()
  243. assert_equal(a, b)
  244. def test_too_many_fancy_indices_special_case(self):
  245. # Just documents behaviour, this is a small limitation.
  246. a = np.ones((1,) * 32) # 32 is NPY_MAXDIMS
  247. assert_raises(IndexError, a.__getitem__, (np.array([0]),) * 32)
  248. def test_scalar_array_bool(self):
  249. # NumPy bools can be used as boolean index (python ones as of yet not)
  250. a = np.array(1)
  251. assert_equal(a[np.bool_(True)], a[np.array(True)])
  252. assert_equal(a[np.bool_(False)], a[np.array(False)])
  253. # After deprecating bools as integers:
  254. #a = np.array([0,1,2])
  255. #assert_equal(a[True, :], a[None, :])
  256. #assert_equal(a[:, True], a[:, None])
  257. #
  258. #assert_(not np.may_share_memory(a, a[True, :]))
  259. def test_everything_returns_views(self):
  260. # Before `...` would return a itself.
  261. a = np.arange(5)
  262. assert_(a is not a[()])
  263. assert_(a is not a[...])
  264. assert_(a is not a[:])
  265. def test_broaderrors_indexing(self):
  266. a = np.zeros((5, 5))
  267. assert_raises(IndexError, a.__getitem__, ([0, 1], [0, 1, 2]))
  268. assert_raises(IndexError, a.__setitem__, ([0, 1], [0, 1, 2]), 0)
  269. def test_trivial_fancy_out_of_bounds(self):
  270. a = np.zeros(5)
  271. ind = np.ones(20, dtype=np.intp)
  272. ind[-1] = 10
  273. assert_raises(IndexError, a.__getitem__, ind)
  274. assert_raises(IndexError, a.__setitem__, ind, 0)
  275. ind = np.ones(20, dtype=np.intp)
  276. ind[0] = 11
  277. assert_raises(IndexError, a.__getitem__, ind)
  278. assert_raises(IndexError, a.__setitem__, ind, 0)
  279. def test_trivial_fancy_not_possible(self):
  280. # Test that the fast path for trivial assignment is not incorrectly
  281. # used when the index is not contiguous or 1D, see also gh-11467.
  282. a = np.arange(6)
  283. idx = np.arange(6, dtype=np.intp).reshape(2, 1, 3)[:, :, 0]
  284. assert_array_equal(a[idx], idx)
  285. # this case must not go into the fast path, note that idx is
  286. # a non-contiuguous none 1D array here.
  287. a[idx] = -1
  288. res = np.arange(6)
  289. res[0] = -1
  290. res[3] = -1
  291. assert_array_equal(a, res)
  292. def test_nonbaseclass_values(self):
  293. class SubClass(np.ndarray):
  294. def __array_finalize__(self, old):
  295. # Have array finalize do funny things
  296. self.fill(99)
  297. a = np.zeros((5, 5))
  298. s = a.copy().view(type=SubClass)
  299. s.fill(1)
  300. a[[0, 1, 2, 3, 4], :] = s
  301. assert_((a == 1).all())
  302. # Subspace is last, so transposing might want to finalize
  303. a[:, [0, 1, 2, 3, 4]] = s
  304. assert_((a == 1).all())
  305. a.fill(0)
  306. a[...] = s
  307. assert_((a == 1).all())
  308. def test_subclass_writeable(self):
  309. d = np.rec.array([('NGC1001', 11), ('NGC1002', 1.), ('NGC1003', 1.)],
  310. dtype=[('target', 'S20'), ('V_mag', '>f4')])
  311. ind = np.array([False, True, True], dtype=bool)
  312. assert_(d[ind].flags.writeable)
  313. ind = np.array([0, 1])
  314. assert_(d[ind].flags.writeable)
  315. assert_(d[...].flags.writeable)
  316. assert_(d[0].flags.writeable)
  317. def test_memory_order(self):
  318. # This is not necessary to preserve. Memory layouts for
  319. # more complex indices are not as simple.
  320. a = np.arange(10)
  321. b = np.arange(10).reshape(5,2).T
  322. assert_(a[b].flags.f_contiguous)
  323. # Takes a different implementation branch:
  324. a = a.reshape(-1, 1)
  325. assert_(a[b, 0].flags.f_contiguous)
  326. def test_scalar_return_type(self):
  327. # Full scalar indices should return scalars and object
  328. # arrays should not call PyArray_Return on their items
  329. class Zero:
  330. # The most basic valid indexing
  331. def __index__(self):
  332. return 0
  333. z = Zero()
  334. class ArrayLike:
  335. # Simple array, should behave like the array
  336. def __array__(self):
  337. return np.array(0)
  338. a = np.zeros(())
  339. assert_(isinstance(a[()], np.float_))
  340. a = np.zeros(1)
  341. assert_(isinstance(a[z], np.float_))
  342. a = np.zeros((1, 1))
  343. assert_(isinstance(a[z, np.array(0)], np.float_))
  344. assert_(isinstance(a[z, ArrayLike()], np.float_))
  345. # And object arrays do not call it too often:
  346. b = np.array(0)
  347. a = np.array(0, dtype=object)
  348. a[()] = b
  349. assert_(isinstance(a[()], np.ndarray))
  350. a = np.array([b, None])
  351. assert_(isinstance(a[z], np.ndarray))
  352. a = np.array([[b, None]])
  353. assert_(isinstance(a[z, np.array(0)], np.ndarray))
  354. assert_(isinstance(a[z, ArrayLike()], np.ndarray))
  355. def test_small_regressions(self):
  356. # Reference count of intp for index checks
  357. a = np.array([0])
  358. if HAS_REFCOUNT:
  359. refcount = sys.getrefcount(np.dtype(np.intp))
  360. # item setting always checks indices in separate function:
  361. a[np.array([0], dtype=np.intp)] = 1
  362. a[np.array([0], dtype=np.uint8)] = 1
  363. assert_raises(IndexError, a.__setitem__,
  364. np.array([1], dtype=np.intp), 1)
  365. assert_raises(IndexError, a.__setitem__,
  366. np.array([1], dtype=np.uint8), 1)
  367. if HAS_REFCOUNT:
  368. assert_equal(sys.getrefcount(np.dtype(np.intp)), refcount)
  369. def test_unaligned(self):
  370. v = (np.zeros(64, dtype=np.int8) + ord('a'))[1:-7]
  371. d = v.view(np.dtype("S8"))
  372. # unaligned source
  373. x = (np.zeros(16, dtype=np.int8) + ord('a'))[1:-7]
  374. x = x.view(np.dtype("S8"))
  375. x[...] = np.array("b" * 8, dtype="S")
  376. b = np.arange(d.size)
  377. #trivial
  378. assert_equal(d[b], d)
  379. d[b] = x
  380. # nontrivial
  381. # unaligned index array
  382. b = np.zeros(d.size + 1).view(np.int8)[1:-(np.intp(0).itemsize - 1)]
  383. b = b.view(np.intp)[:d.size]
  384. b[...] = np.arange(d.size)
  385. assert_equal(d[b.astype(np.int16)], d)
  386. d[b.astype(np.int16)] = x
  387. # boolean
  388. d[b % 2 == 0]
  389. d[b % 2 == 0] = x[::2]
  390. def test_tuple_subclass(self):
  391. arr = np.ones((5, 5))
  392. # A tuple subclass should also be an nd-index
  393. class TupleSubclass(tuple):
  394. pass
  395. index = ([1], [1])
  396. index = TupleSubclass(index)
  397. assert_(arr[index].shape == (1,))
  398. # Unlike the non nd-index:
  399. assert_(arr[index,].shape != (1,))
  400. def test_broken_sequence_not_nd_index(self):
  401. # See gh-5063:
  402. # If we have an object which claims to be a sequence, but fails
  403. # on item getting, this should not be converted to an nd-index (tuple)
  404. # If this object happens to be a valid index otherwise, it should work
  405. # This object here is very dubious and probably bad though:
  406. class SequenceLike:
  407. def __index__(self):
  408. return 0
  409. def __len__(self):
  410. return 1
  411. def __getitem__(self, item):
  412. raise IndexError('Not possible')
  413. arr = np.arange(10)
  414. assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])
  415. # also test that field indexing does not segfault
  416. # for a similar reason, by indexing a structured array
  417. arr = np.zeros((1,), dtype=[('f1', 'i8'), ('f2', 'i8')])
  418. assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])
  419. def test_indexing_array_weird_strides(self):
  420. # See also gh-6221
  421. # the shapes used here come from the issue and create the correct
  422. # size for the iterator buffering size.
  423. x = np.ones(10)
  424. x2 = np.ones((10, 2))
  425. ind = np.arange(10)[:, None, None, None]
  426. ind = np.broadcast_to(ind, (10, 55, 4, 4))
  427. # single advanced index case
  428. assert_array_equal(x[ind], x[ind.copy()])
  429. # higher dimensional advanced index
  430. zind = np.zeros(4, dtype=np.intp)
  431. assert_array_equal(x2[ind, zind], x2[ind.copy(), zind])
  432. def test_indexing_array_negative_strides(self):
  433. # From gh-8264,
  434. # core dumps if negative strides are used in iteration
  435. arro = np.zeros((4, 4))
  436. arr = arro[::-1, ::-1]
  437. slices = (slice(None), [0, 1, 2, 3])
  438. arr[slices] = 10
  439. assert_array_equal(arr, 10.)
  440. class TestFieldIndexing:
  441. def test_scalar_return_type(self):
  442. # Field access on an array should return an array, even if it
  443. # is 0-d.
  444. a = np.zeros((), [('a','f8')])
  445. assert_(isinstance(a['a'], np.ndarray))
  446. assert_(isinstance(a[['a']], np.ndarray))
  447. class TestBroadcastedAssignments:
  448. def assign(self, a, ind, val):
  449. a[ind] = val
  450. return a
  451. def test_prepending_ones(self):
  452. a = np.zeros((3, 2))
  453. a[...] = np.ones((1, 3, 2))
  454. # Fancy with subspace with and without transpose
  455. a[[0, 1, 2], :] = np.ones((1, 3, 2))
  456. a[:, [0, 1]] = np.ones((1, 3, 2))
  457. # Fancy without subspace (with broadcasting)
  458. a[[[0], [1], [2]], [0, 1]] = np.ones((1, 3, 2))
  459. def test_prepend_not_one(self):
  460. assign = self.assign
  461. s_ = np.s_
  462. a = np.zeros(5)
  463. # Too large and not only ones.
  464. assert_raises(ValueError, assign, a, s_[...], np.ones((2, 1)))
  465. assert_raises(ValueError, assign, a, s_[[1, 2, 3],], np.ones((2, 1)))
  466. assert_raises(ValueError, assign, a, s_[[[1], [2]],], np.ones((2,2,1)))
  467. def test_simple_broadcasting_errors(self):
  468. assign = self.assign
  469. s_ = np.s_
  470. a = np.zeros((5, 1))
  471. assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 2)))
  472. assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 0)))
  473. assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 2)))
  474. assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 0)))
  475. assert_raises(ValueError, assign, a, s_[[0], :], np.zeros((2, 1)))
  476. def test_index_is_larger(self):
  477. # Simple case of fancy index broadcasting of the index.
  478. a = np.zeros((5, 5))
  479. a[[[0], [1], [2]], [0, 1, 2]] = [2, 3, 4]
  480. assert_((a[:3, :3] == [2, 3, 4]).all())
  481. def test_broadcast_subspace(self):
  482. a = np.zeros((100, 100))
  483. v = np.arange(100)[:,None]
  484. b = np.arange(100)[::-1]
  485. a[b] = v
  486. assert_((a[::-1] == v).all())
  487. class TestSubclasses:
  488. def test_basic(self):
  489. # Test that indexing in various ways produces SubClass instances,
  490. # and that the base is set up correctly: the original subclass
  491. # instance for views, and a new ndarray for advanced/boolean indexing
  492. # where a copy was made (latter a regression test for gh-11983).
  493. class SubClass(np.ndarray):
  494. pass
  495. a = np.arange(5)
  496. s = a.view(SubClass)
  497. s_slice = s[:3]
  498. assert_(type(s_slice) is SubClass)
  499. assert_(s_slice.base is s)
  500. assert_array_equal(s_slice, a[:3])
  501. s_fancy = s[[0, 1, 2]]
  502. assert_(type(s_fancy) is SubClass)
  503. assert_(s_fancy.base is not s)
  504. assert_(type(s_fancy.base) is np.ndarray)
  505. assert_array_equal(s_fancy, a[[0, 1, 2]])
  506. assert_array_equal(s_fancy.base, a[[0, 1, 2]])
  507. s_bool = s[s > 0]
  508. assert_(type(s_bool) is SubClass)
  509. assert_(s_bool.base is not s)
  510. assert_(type(s_bool.base) is np.ndarray)
  511. assert_array_equal(s_bool, a[a > 0])
  512. assert_array_equal(s_bool.base, a[a > 0])
  513. def test_fancy_on_read_only(self):
  514. # Test that fancy indexing on read-only SubClass does not make a
  515. # read-only copy (gh-14132)
  516. class SubClass(np.ndarray):
  517. pass
  518. a = np.arange(5)
  519. s = a.view(SubClass)
  520. s.flags.writeable = False
  521. s_fancy = s[[0, 1, 2]]
  522. assert_(s_fancy.flags.writeable)
  523. def test_finalize_gets_full_info(self):
  524. # Array finalize should be called on the filled array.
  525. class SubClass(np.ndarray):
  526. def __array_finalize__(self, old):
  527. self.finalize_status = np.array(self)
  528. self.old = old
  529. s = np.arange(10).view(SubClass)
  530. new_s = s[:3]
  531. assert_array_equal(new_s.finalize_status, new_s)
  532. assert_array_equal(new_s.old, s)
  533. new_s = s[[0,1,2,3]]
  534. assert_array_equal(new_s.finalize_status, new_s)
  535. assert_array_equal(new_s.old, s)
  536. new_s = s[s > 0]
  537. assert_array_equal(new_s.finalize_status, new_s)
  538. assert_array_equal(new_s.old, s)
  539. class TestFancyIndexingCast:
  540. def test_boolean_index_cast_assign(self):
  541. # Setup the boolean index and float arrays.
  542. shape = (8, 63)
  543. bool_index = np.zeros(shape).astype(bool)
  544. bool_index[0, 1] = True
  545. zero_array = np.zeros(shape)
  546. # Assigning float is fine.
  547. zero_array[bool_index] = np.array([1])
  548. assert_equal(zero_array[0, 1], 1)
  549. # Fancy indexing works, although we get a cast warning.
  550. assert_warns(np.ComplexWarning,
  551. zero_array.__setitem__, ([0], [1]), np.array([2 + 1j]))
  552. assert_equal(zero_array[0, 1], 2) # No complex part
  553. # Cast complex to float, throwing away the imaginary portion.
  554. assert_warns(np.ComplexWarning,
  555. zero_array.__setitem__, bool_index, np.array([1j]))
  556. assert_equal(zero_array[0, 1], 0)
  557. class TestFancyIndexingEquivalence:
  558. def test_object_assign(self):
  559. # Check that the field and object special case using copyto is active.
  560. # The right hand side cannot be converted to an array here.
  561. a = np.arange(5, dtype=object)
  562. b = a.copy()
  563. a[:3] = [1, (1,2), 3]
  564. b[[0, 1, 2]] = [1, (1,2), 3]
  565. assert_array_equal(a, b)
  566. # test same for subspace fancy indexing
  567. b = np.arange(5, dtype=object)[None, :]
  568. b[[0], :3] = [[1, (1,2), 3]]
  569. assert_array_equal(a, b[0])
  570. # Check that swapping of axes works.
  571. # There was a bug that made the later assignment throw a ValueError
  572. # do to an incorrectly transposed temporary right hand side (gh-5714)
  573. b = b.T
  574. b[:3, [0]] = [[1], [(1,2)], [3]]
  575. assert_array_equal(a, b[:, 0])
  576. # Another test for the memory order of the subspace
  577. arr = np.ones((3, 4, 5), dtype=object)
  578. # Equivalent slicing assignment for comparison
  579. cmp_arr = arr.copy()
  580. cmp_arr[:1, ...] = [[[1], [2], [3], [4]]]
  581. arr[[0], ...] = [[[1], [2], [3], [4]]]
  582. assert_array_equal(arr, cmp_arr)
  583. arr = arr.copy('F')
  584. arr[[0], ...] = [[[1], [2], [3], [4]]]
  585. assert_array_equal(arr, cmp_arr)
  586. def test_cast_equivalence(self):
  587. # Yes, normal slicing uses unsafe casting.
  588. a = np.arange(5)
  589. b = a.copy()
  590. a[:3] = np.array(['2', '-3', '-1'])
  591. b[[0, 2, 1]] = np.array(['2', '-1', '-3'])
  592. assert_array_equal(a, b)
  593. # test the same for subspace fancy indexing
  594. b = np.arange(5)[None, :]
  595. b[[0], :3] = np.array([['2', '-3', '-1']])
  596. assert_array_equal(a, b[0])
  597. class TestMultiIndexingAutomated:
  598. """
  599. These tests use code to mimic the C-Code indexing for selection.
  600. NOTE:
  601. * This still lacks tests for complex item setting.
  602. * If you change behavior of indexing, you might want to modify
  603. these tests to try more combinations.
  604. * Behavior was written to match numpy version 1.8. (though a
  605. first version matched 1.7.)
  606. * Only tuple indices are supported by the mimicking code.
  607. (and tested as of writing this)
  608. * Error types should match most of the time as long as there
  609. is only one error. For multiple errors, what gets raised
  610. will usually not be the same one. They are *not* tested.
  611. Update 2016-11-30: It is probably not worth maintaining this test
  612. indefinitely and it can be dropped if maintenance becomes a burden.
  613. """
  614. def setup(self):
  615. self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6)
  616. self.b = np.empty((3, 0, 5, 6))
  617. self.complex_indices = ['skip', Ellipsis,
  618. 0,
  619. # Boolean indices, up to 3-d for some special cases of eating up
  620. # dimensions, also need to test all False
  621. np.array([True, False, False]),
  622. np.array([[True, False], [False, True]]),
  623. np.array([[[False, False], [False, False]]]),
  624. # Some slices:
  625. slice(-5, 5, 2),
  626. slice(1, 1, 100),
  627. slice(4, -1, -2),
  628. slice(None, None, -3),
  629. # Some Fancy indexes:
  630. np.empty((0, 1, 1), dtype=np.intp), # empty and can be broadcast
  631. np.array([0, 1, -2]),
  632. np.array([[2], [0], [1]]),
  633. np.array([[0, -1], [0, 1]], dtype=np.dtype('intp').newbyteorder()),
  634. np.array([2, -1], dtype=np.int8),
  635. np.zeros([1]*31, dtype=int), # trigger too large array.
  636. np.array([0., 1.])] # invalid datatype
  637. # Some simpler indices that still cover a bit more
  638. self.simple_indices = [Ellipsis, None, -1, [1], np.array([True]),
  639. 'skip']
  640. # Very simple ones to fill the rest:
  641. self.fill_indices = [slice(None, None), 0]
  642. def _get_multi_index(self, arr, indices):
  643. """Mimic multi dimensional indexing.
  644. Parameters
  645. ----------
  646. arr : ndarray
  647. Array to be indexed.
  648. indices : tuple of index objects
  649. Returns
  650. -------
  651. out : ndarray
  652. An array equivalent to the indexing operation (but always a copy).
  653. `arr[indices]` should be identical.
  654. no_copy : bool
  655. Whether the indexing operation requires a copy. If this is `True`,
  656. `np.may_share_memory(arr, arr[indices])` should be `True` (with
  657. some exceptions for scalars and possibly 0-d arrays).
  658. Notes
  659. -----
  660. While the function may mostly match the errors of normal indexing this
  661. is generally not the case.
  662. """
  663. in_indices = list(indices)
  664. indices = []
  665. # if False, this is a fancy or boolean index
  666. no_copy = True
  667. # number of fancy/scalar indexes that are not consecutive
  668. num_fancy = 0
  669. # number of dimensions indexed by a "fancy" index
  670. fancy_dim = 0
  671. # NOTE: This is a funny twist (and probably OK to change).
  672. # The boolean array has illegal indexes, but this is
  673. # allowed if the broadcast fancy-indices are 0-sized.
  674. # This variable is to catch that case.
  675. error_unless_broadcast_to_empty = False
  676. # We need to handle Ellipsis and make arrays from indices, also
  677. # check if this is fancy indexing (set no_copy).
  678. ndim = 0
  679. ellipsis_pos = None # define here mostly to replace all but first.
  680. for i, indx in enumerate(in_indices):
  681. if indx is None:
  682. continue
  683. if isinstance(indx, np.ndarray) and indx.dtype == bool:
  684. no_copy = False
  685. if indx.ndim == 0:
  686. raise IndexError
  687. # boolean indices can have higher dimensions
  688. ndim += indx.ndim
  689. fancy_dim += indx.ndim
  690. continue
  691. if indx is Ellipsis:
  692. if ellipsis_pos is None:
  693. ellipsis_pos = i
  694. continue # do not increment ndim counter
  695. raise IndexError
  696. if isinstance(indx, slice):
  697. ndim += 1
  698. continue
  699. if not isinstance(indx, np.ndarray):
  700. # This could be open for changes in numpy.
  701. # numpy should maybe raise an error if casting to intp
  702. # is not safe. It rejects np.array([1., 2.]) but not
  703. # [1., 2.] as index (same for ie. np.take).
  704. # (Note the importance of empty lists if changing this here)
  705. try:
  706. indx = np.array(indx, dtype=np.intp)
  707. except ValueError:
  708. raise IndexError
  709. in_indices[i] = indx
  710. elif indx.dtype.kind != 'b' and indx.dtype.kind != 'i':
  711. raise IndexError('arrays used as indices must be of '
  712. 'integer (or boolean) type')
  713. if indx.ndim != 0:
  714. no_copy = False
  715. ndim += 1
  716. fancy_dim += 1
  717. if arr.ndim - ndim < 0:
  718. # we can't take more dimensions then we have, not even for 0-d
  719. # arrays. since a[()] makes sense, but not a[(),]. We will
  720. # raise an error later on, unless a broadcasting error occurs
  721. # first.
  722. raise IndexError
  723. if ndim == 0 and None not in in_indices:
  724. # Well we have no indexes or one Ellipsis. This is legal.
  725. return arr.copy(), no_copy
  726. if ellipsis_pos is not None:
  727. in_indices[ellipsis_pos:ellipsis_pos+1] = ([slice(None, None)] *
  728. (arr.ndim - ndim))
  729. for ax, indx in enumerate(in_indices):
  730. if isinstance(indx, slice):
  731. # convert to an index array
  732. indx = np.arange(*indx.indices(arr.shape[ax]))
  733. indices.append(['s', indx])
  734. continue
  735. elif indx is None:
  736. # this is like taking a slice with one element from a new axis:
  737. indices.append(['n', np.array([0], dtype=np.intp)])
  738. arr = arr.reshape((arr.shape[:ax] + (1,) + arr.shape[ax:]))
  739. continue
  740. if isinstance(indx, np.ndarray) and indx.dtype == bool:
  741. if indx.shape != arr.shape[ax:ax+indx.ndim]:
  742. raise IndexError
  743. try:
  744. flat_indx = np.ravel_multi_index(np.nonzero(indx),
  745. arr.shape[ax:ax+indx.ndim], mode='raise')
  746. except Exception:
  747. error_unless_broadcast_to_empty = True
  748. # fill with 0s instead, and raise error later
  749. flat_indx = np.array([0]*indx.sum(), dtype=np.intp)
  750. # concatenate axis into a single one:
  751. if indx.ndim != 0:
  752. arr = arr.reshape((arr.shape[:ax]
  753. + (np.prod(arr.shape[ax:ax+indx.ndim]),)
  754. + arr.shape[ax+indx.ndim:]))
  755. indx = flat_indx
  756. else:
  757. # This could be changed, a 0-d boolean index can
  758. # make sense (even outside the 0-d indexed array case)
  759. # Note that originally this is could be interpreted as
  760. # integer in the full integer special case.
  761. raise IndexError
  762. else:
  763. # If the index is a singleton, the bounds check is done
  764. # before the broadcasting. This used to be different in <1.9
  765. if indx.ndim == 0:
  766. if indx >= arr.shape[ax] or indx < -arr.shape[ax]:
  767. raise IndexError
  768. if indx.ndim == 0:
  769. # The index is a scalar. This used to be two fold, but if
  770. # fancy indexing was active, the check was done later,
  771. # possibly after broadcasting it away (1.7. or earlier).
  772. # Now it is always done.
  773. if indx >= arr.shape[ax] or indx < - arr.shape[ax]:
  774. raise IndexError
  775. if (len(indices) > 0 and
  776. indices[-1][0] == 'f' and
  777. ax != ellipsis_pos):
  778. # NOTE: There could still have been a 0-sized Ellipsis
  779. # between them. Checked that with ellipsis_pos.
  780. indices[-1].append(indx)
  781. else:
  782. # We have a fancy index that is not after an existing one.
  783. # NOTE: A 0-d array triggers this as well, while one may
  784. # expect it to not trigger it, since a scalar would not be
  785. # considered fancy indexing.
  786. num_fancy += 1
  787. indices.append(['f', indx])
  788. if num_fancy > 1 and not no_copy:
  789. # We have to flush the fancy indexes left
  790. new_indices = indices[:]
  791. axes = list(range(arr.ndim))
  792. fancy_axes = []
  793. new_indices.insert(0, ['f'])
  794. ni = 0
  795. ai = 0
  796. for indx in indices:
  797. ni += 1
  798. if indx[0] == 'f':
  799. new_indices[0].extend(indx[1:])
  800. del new_indices[ni]
  801. ni -= 1
  802. for ax in range(ai, ai + len(indx[1:])):
  803. fancy_axes.append(ax)
  804. axes.remove(ax)
  805. ai += len(indx) - 1 # axis we are at
  806. indices = new_indices
  807. # and now we need to transpose arr:
  808. arr = arr.transpose(*(fancy_axes + axes))
  809. # We only have one 'f' index now and arr is transposed accordingly.
  810. # Now handle newaxis by reshaping...
  811. ax = 0
  812. for indx in indices:
  813. if indx[0] == 'f':
  814. if len(indx) == 1:
  815. continue
  816. # First of all, reshape arr to combine fancy axes into one:
  817. orig_shape = arr.shape
  818. orig_slice = orig_shape[ax:ax + len(indx[1:])]
  819. arr = arr.reshape((arr.shape[:ax]
  820. + (np.prod(orig_slice).astype(int),)
  821. + arr.shape[ax + len(indx[1:]):]))
  822. # Check if broadcasting works
  823. res = np.broadcast(*indx[1:])
  824. # unfortunately the indices might be out of bounds. So check
  825. # that first, and use mode='wrap' then. However only if
  826. # there are any indices...
  827. if res.size != 0:
  828. if error_unless_broadcast_to_empty:
  829. raise IndexError
  830. for _indx, _size in zip(indx[1:], orig_slice):
  831. if _indx.size == 0:
  832. continue
  833. if np.any(_indx >= _size) or np.any(_indx < -_size):
  834. raise IndexError
  835. if len(indx[1:]) == len(orig_slice):
  836. if np.product(orig_slice) == 0:
  837. # Work around for a crash or IndexError with 'wrap'
  838. # in some 0-sized cases.
  839. try:
  840. mi = np.ravel_multi_index(indx[1:], orig_slice,
  841. mode='raise')
  842. except Exception:
  843. # This happens with 0-sized orig_slice (sometimes?)
  844. # here it is a ValueError, but indexing gives a:
  845. raise IndexError('invalid index into 0-sized')
  846. else:
  847. mi = np.ravel_multi_index(indx[1:], orig_slice,
  848. mode='wrap')
  849. else:
  850. # Maybe never happens...
  851. raise ValueError
  852. arr = arr.take(mi.ravel(), axis=ax)
  853. try:
  854. arr = arr.reshape((arr.shape[:ax]
  855. + mi.shape
  856. + arr.shape[ax+1:]))
  857. except ValueError:
  858. # too many dimensions, probably
  859. raise IndexError
  860. ax += mi.ndim
  861. continue
  862. # If we are here, we have a 1D array for take:
  863. arr = arr.take(indx[1], axis=ax)
  864. ax += 1
  865. return arr, no_copy
  866. def _check_multi_index(self, arr, index):
  867. """Check a multi index item getting and simple setting.
  868. Parameters
  869. ----------
  870. arr : ndarray
  871. Array to be indexed, must be a reshaped arange.
  872. index : tuple of indexing objects
  873. Index being tested.
  874. """
  875. # Test item getting
  876. try:
  877. mimic_get, no_copy = self._get_multi_index(arr, index)
  878. except Exception as e:
  879. if HAS_REFCOUNT:
  880. prev_refcount = sys.getrefcount(arr)
  881. assert_raises(type(e), arr.__getitem__, index)
  882. assert_raises(type(e), arr.__setitem__, index, 0)
  883. if HAS_REFCOUNT:
  884. assert_equal(prev_refcount, sys.getrefcount(arr))
  885. return
  886. self._compare_index_result(arr, index, mimic_get, no_copy)
  887. def _check_single_index(self, arr, index):
  888. """Check a single index item getting and simple setting.
  889. Parameters
  890. ----------
  891. arr : ndarray
  892. Array to be indexed, must be an arange.
  893. index : indexing object
  894. Index being tested. Must be a single index and not a tuple
  895. of indexing objects (see also `_check_multi_index`).
  896. """
  897. try:
  898. mimic_get, no_copy = self._get_multi_index(arr, (index,))
  899. except Exception as e:
  900. if HAS_REFCOUNT:
  901. prev_refcount = sys.getrefcount(arr)
  902. assert_raises(type(e), arr.__getitem__, index)
  903. assert_raises(type(e), arr.__setitem__, index, 0)
  904. if HAS_REFCOUNT:
  905. assert_equal(prev_refcount, sys.getrefcount(arr))
  906. return
  907. self._compare_index_result(arr, index, mimic_get, no_copy)
  908. def _compare_index_result(self, arr, index, mimic_get, no_copy):
  909. """Compare mimicked result to indexing result.
  910. """
  911. arr = arr.copy()
  912. indexed_arr = arr[index]
  913. assert_array_equal(indexed_arr, mimic_get)
  914. # Check if we got a view, unless its a 0-sized or 0-d array.
  915. # (then its not a view, and that does not matter)
  916. if indexed_arr.size != 0 and indexed_arr.ndim != 0:
  917. assert_(np.may_share_memory(indexed_arr, arr) == no_copy)
  918. # Check reference count of the original array
  919. if HAS_REFCOUNT:
  920. if no_copy:
  921. # refcount increases by one:
  922. assert_equal(sys.getrefcount(arr), 3)
  923. else:
  924. assert_equal(sys.getrefcount(arr), 2)
  925. # Test non-broadcast setitem:
  926. b = arr.copy()
  927. b[index] = mimic_get + 1000
  928. if b.size == 0:
  929. return # nothing to compare here...
  930. if no_copy and indexed_arr.ndim != 0:
  931. # change indexed_arr in-place to manipulate original:
  932. indexed_arr += 1000
  933. assert_array_equal(arr, b)
  934. return
  935. # Use the fact that the array is originally an arange:
  936. arr.flat[indexed_arr.ravel()] += 1000
  937. assert_array_equal(arr, b)
  938. def test_boolean(self):
  939. a = np.array(5)
  940. assert_equal(a[np.array(True)], 5)
  941. a[np.array(True)] = 1
  942. assert_equal(a, 1)
  943. # NOTE: This is different from normal broadcasting, as
  944. # arr[boolean_array] works like in a multi index. Which means
  945. # it is aligned to the left. This is probably correct for
  946. # consistency with arr[boolean_array,] also no broadcasting
  947. # is done at all
  948. self._check_multi_index(
  949. self.a, (np.zeros_like(self.a, dtype=bool),))
  950. self._check_multi_index(
  951. self.a, (np.zeros_like(self.a, dtype=bool)[..., 0],))
  952. self._check_multi_index(
  953. self.a, (np.zeros_like(self.a, dtype=bool)[None, ...],))
  954. def test_multidim(self):
  955. # Automatically test combinations with complex indexes on 2nd (or 1st)
  956. # spot and the simple ones in one other spot.
  957. with warnings.catch_warnings():
  958. # This is so that np.array(True) is not accepted in a full integer
  959. # index, when running the file separately.
  960. warnings.filterwarnings('error', '', DeprecationWarning)
  961. warnings.filterwarnings('error', '', np.VisibleDeprecationWarning)
  962. def isskip(idx):
  963. return isinstance(idx, str) and idx == "skip"
  964. for simple_pos in [0, 2, 3]:
  965. tocheck = [self.fill_indices, self.complex_indices,
  966. self.fill_indices, self.fill_indices]
  967. tocheck[simple_pos] = self.simple_indices
  968. for index in product(*tocheck):
  969. index = tuple(i for i in index if not isskip(i))
  970. self._check_multi_index(self.a, index)
  971. self._check_multi_index(self.b, index)
  972. # Check very simple item getting:
  973. self._check_multi_index(self.a, (0, 0, 0, 0))
  974. self._check_multi_index(self.b, (0, 0, 0, 0))
  975. # Also check (simple cases of) too many indices:
  976. assert_raises(IndexError, self.a.__getitem__, (0, 0, 0, 0, 0))
  977. assert_raises(IndexError, self.a.__setitem__, (0, 0, 0, 0, 0), 0)
  978. assert_raises(IndexError, self.a.__getitem__, (0, 0, [1], 0, 0))
  979. assert_raises(IndexError, self.a.__setitem__, (0, 0, [1], 0, 0), 0)
  980. def test_1d(self):
  981. a = np.arange(10)
  982. for index in self.complex_indices:
  983. self._check_single_index(a, index)
  984. class TestFloatNonIntegerArgument:
  985. """
  986. These test that ``TypeError`` is raised when you try to use
  987. non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]``
  988. and ``a[0.5]``, or other functions like ``array.reshape(1., -1)``.
  989. """
  990. def test_valid_indexing(self):
  991. # These should raise no errors.
  992. a = np.array([[[5]]])
  993. a[np.array([0])]
  994. a[[0, 0]]
  995. a[:, [0, 0]]
  996. a[:, 0,:]
  997. a[:,:,:]
  998. def test_valid_slicing(self):
  999. # These should raise no errors.
  1000. a = np.array([[[5]]])
  1001. a[::]
  1002. a[0:]
  1003. a[:2]
  1004. a[0:2]
  1005. a[::2]
  1006. a[1::2]
  1007. a[:2:2]
  1008. a[1:2:2]
  1009. def test_non_integer_argument_errors(self):
  1010. a = np.array([[5]])
  1011. assert_raises(TypeError, np.reshape, a, (1., 1., -1))
  1012. assert_raises(TypeError, np.reshape, a, (np.array(1.), -1))
  1013. assert_raises(TypeError, np.take, a, [0], 1.)
  1014. assert_raises(TypeError, np.take, a, [0], np.float64(1.))
  1015. def test_non_integer_sequence_multiplication(self):
  1016. # NumPy scalar sequence multiply should not work with non-integers
  1017. def mult(a, b):
  1018. return a * b
  1019. assert_raises(TypeError, mult, [1], np.float_(3))
  1020. # following should be OK
  1021. mult([1], np.int_(3))
  1022. def test_reduce_axis_float_index(self):
  1023. d = np.zeros((3,3,3))
  1024. assert_raises(TypeError, np.min, d, 0.5)
  1025. assert_raises(TypeError, np.min, d, (0.5, 1))
  1026. assert_raises(TypeError, np.min, d, (1, 2.2))
  1027. assert_raises(TypeError, np.min, d, (.2, 1.2))
  1028. class TestBooleanIndexing:
  1029. # Using a boolean as integer argument/indexing is an error.
  1030. def test_bool_as_int_argument_errors(self):
  1031. a = np.array([[[1]]])
  1032. assert_raises(TypeError, np.reshape, a, (True, -1))
  1033. assert_raises(TypeError, np.reshape, a, (np.bool_(True), -1))
  1034. # Note that operator.index(np.array(True)) does not work, a boolean
  1035. # array is thus also deprecated, but not with the same message:
  1036. assert_raises(TypeError, operator.index, np.array(True))
  1037. assert_warns(DeprecationWarning, operator.index, np.True_)
  1038. assert_raises(TypeError, np.take, args=(a, [0], False))
  1039. def test_boolean_indexing_weirdness(self):
  1040. # Weird boolean indexing things
  1041. a = np.ones((2, 3, 4))
  1042. a[False, True, ...].shape == (0, 2, 3, 4)
  1043. a[True, [0, 1], True, True, [1], [[2]]] == (1, 2)
  1044. assert_raises(IndexError, lambda: a[False, [0, 1], ...])
  1045. class TestArrayToIndexDeprecation:
  1046. """Creating an an index from array not 0-D is an error.
  1047. """
  1048. def test_array_to_index_error(self):
  1049. # so no exception is expected. The raising is effectively tested above.
  1050. a = np.array([[[1]]])
  1051. assert_raises(TypeError, operator.index, np.array([1]))
  1052. assert_raises(TypeError, np.reshape, a, (a, -1))
  1053. assert_raises(TypeError, np.take, a, [0], a)
  1054. class TestNonIntegerArrayLike:
  1055. """Tests that array_likes only valid if can safely cast to integer.
  1056. For instance, lists give IndexError when they cannot be safely cast to
  1057. an integer.
  1058. """
  1059. def test_basic(self):
  1060. a = np.arange(10)
  1061. assert_raises(IndexError, a.__getitem__, [0.5, 1.5])
  1062. assert_raises(IndexError, a.__getitem__, (['1', '2'],))
  1063. # The following is valid
  1064. a.__getitem__([])
  1065. class TestMultipleEllipsisError:
  1066. """An index can only have a single ellipsis.
  1067. """
  1068. def test_basic(self):
  1069. a = np.arange(10)
  1070. assert_raises(IndexError, lambda: a[..., ...])
  1071. assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 2,))
  1072. assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 3,))
  1073. class TestCApiAccess:
  1074. def test_getitem(self):
  1075. subscript = functools.partial(array_indexing, 0)
  1076. # 0-d arrays don't work:
  1077. assert_raises(IndexError, subscript, np.ones(()), 0)
  1078. # Out of bound values:
  1079. assert_raises(IndexError, subscript, np.ones(10), 11)
  1080. assert_raises(IndexError, subscript, np.ones(10), -11)
  1081. assert_raises(IndexError, subscript, np.ones((10, 10)), 11)
  1082. assert_raises(IndexError, subscript, np.ones((10, 10)), -11)
  1083. a = np.arange(10)
  1084. assert_array_equal(a[4], subscript(a, 4))
  1085. a = a.reshape(5, 2)
  1086. assert_array_equal(a[-4], subscript(a, -4))
  1087. def test_setitem(self):
  1088. assign = functools.partial(array_indexing, 1)
  1089. # Deletion is impossible:
  1090. assert_raises(ValueError, assign, np.ones(10), 0)
  1091. # 0-d arrays don't work:
  1092. assert_raises(IndexError, assign, np.ones(()), 0, 0)
  1093. # Out of bound values:
  1094. assert_raises(IndexError, assign, np.ones(10), 11, 0)
  1095. assert_raises(IndexError, assign, np.ones(10), -11, 0)
  1096. assert_raises(IndexError, assign, np.ones((10, 10)), 11, 0)
  1097. assert_raises(IndexError, assign, np.ones((10, 10)), -11, 0)
  1098. a = np.arange(10)
  1099. assign(a, 4, 10)
  1100. assert_(a[4] == 10)
  1101. a = a.reshape(5, 2)
  1102. assign(a, 4, 10)
  1103. assert_array_equal(a[-1], [10, 10])