test_indexing.py 52 KB

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