test_indexing1d.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. import contextlib
  2. import warnings
  3. import pytest
  4. import numpy as np
  5. from numpy.testing import assert_allclose, assert_equal
  6. from scipy.sparse import csr_array, dok_array, SparseEfficiencyWarning
  7. from .test_arithmetic1d import toarray
  8. formats_for_index1d = [csr_array, dok_array]
  9. @contextlib.contextmanager
  10. def check_remains_sorted(X):
  11. """Checks that sorted indices property is retained through an operation"""
  12. yield
  13. if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices:
  14. return
  15. indices = X.indices.copy()
  16. X.has_sorted_indices = False
  17. X.sort_indices()
  18. assert_equal(indices, X.indices, 'Expected sorted indices, found unsorted')
  19. @pytest.mark.parametrize("spcreator", formats_for_index1d)
  20. class TestGetSet1D:
  21. def test_None_index(self, spcreator):
  22. D = np.array([4, 3, 0])
  23. A = spcreator(D)
  24. N = D.shape[0]
  25. for j in range(-N, N):
  26. assert_equal(A[j, None].toarray(), D[j, None])
  27. assert_equal(A[None, j].toarray(), D[None, j])
  28. assert_equal(A[None, None, j].toarray(), D[None, None, j])
  29. def test_getitem_shape(self, spcreator):
  30. A = spcreator(np.arange(3 * 4).reshape(3, 4))
  31. assert A[1, 2].ndim == 0
  32. assert A[1, 2:3].shape == (1,)
  33. assert A[None, 1, 2:3].shape == (1, 1)
  34. assert A[None, 1, 2].shape == (1,)
  35. assert A[None, 1, 2, None].shape == (1, 1)
  36. # see gh-22458
  37. assert A[None, 1].shape == (1, 4)
  38. assert A[1, None].shape == (1, 4)
  39. assert A[None, 1, :].shape == (1, 4)
  40. assert A[1, None, :].shape == (1, 4)
  41. assert A[1, :, None].shape == (4, 1)
  42. # output is >2D
  43. if A.format == "coo":
  44. assert A[None, 2, 1, None, None].shape == (1, 1, 1)
  45. assert A[None, 0:2, None, 1].shape == (1,2,1)
  46. assert A[0:1, 1:, None].shape == (1,3,1)
  47. assert A[1:, 1, None, None].shape == (3,1,1)
  48. def test_getelement(self, spcreator):
  49. D = np.array([4, 3, 0])
  50. A = spcreator(D)
  51. N = D.shape[0]
  52. for j in range(-N, N):
  53. assert_equal(A[j], D[j])
  54. for ij in [3, -4]:
  55. with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'):
  56. A.__getitem__(ij)
  57. # single element tuples unwrapped
  58. assert A[(0,)] == 4
  59. with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'):
  60. A.__getitem__((4,))
  61. @pytest.mark.parametrize(
  62. "scalar_container",
  63. [lambda x: csr_array(np.array([[x]])), np.array, lambda x: x],
  64. ids=["sparse", "dense", "scalar"]
  65. )
  66. def test_setelement(self, spcreator, scalar_container):
  67. dtype = np.float64
  68. A = spcreator((12,), dtype=dtype)
  69. with warnings.catch_warnings():
  70. warnings.filterwarnings(
  71. "ignore",
  72. "Changing the sparsity structure of .* is expensive",
  73. SparseEfficiencyWarning,
  74. )
  75. A[0] = scalar_container(dtype(0))
  76. A[1] = scalar_container(dtype(3))
  77. A[8] = scalar_container(dtype(9.0))
  78. A[-2] = scalar_container(dtype(7))
  79. A[5] = scalar_container(9)
  80. A[-9,] = scalar_container(dtype(8))
  81. A[1,] = scalar_container(dtype(5)) # overwrite using 1-tuple index
  82. for ij in [13, -14, (13,), (14,)]:
  83. with pytest.raises(IndexError, match='out of (range|bounds)'):
  84. A.__setitem__(ij, 123.0)
  85. @pytest.mark.parametrize("spcreator", formats_for_index1d)
  86. class TestSlicingAndFancy1D:
  87. #######################
  88. # Int-like Array Index
  89. #######################
  90. def test_get_array_index(self, spcreator):
  91. D = np.array([4, 3, 0])
  92. A = spcreator(D)
  93. assert_equal(A[()].toarray(), D[()])
  94. for ij in [(0, 3), (3,)]:
  95. with pytest.raises(IndexError, match='out of (range|bounds)|many indices'):
  96. A.__getitem__(ij)
  97. def test_set_array_index(self, spcreator):
  98. dtype = np.float64
  99. A = spcreator((12,), dtype=dtype)
  100. with warnings.catch_warnings():
  101. warnings.filterwarnings(
  102. "ignore",
  103. "Changing the sparsity structure of .* is expensive",
  104. SparseEfficiencyWarning,
  105. )
  106. A[np.array(6)] = dtype(4.0) # scalar index
  107. A[np.array(6)] = dtype(2.0) # overwrite with scalar index
  108. assert_equal(A.toarray(), [0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0])
  109. for ij in [(13,), (-14,)]:
  110. with pytest.raises(IndexError, match='index .* out of (range|bounds)'):
  111. A.__setitem__(ij, 123.0)
  112. for v in [(), (0, 3), [1, 2, 3], np.array([1, 2, 3])]:
  113. msg = 'Trying to assign a sequence to an item'
  114. with pytest.raises(ValueError, match=msg):
  115. A.__setitem__(0, v)
  116. ####################
  117. # 1d Slice as index
  118. ####################
  119. def test_dtype_preservation(self, spcreator):
  120. assert_equal(spcreator((10,), dtype=np.int16)[1:5].dtype, np.int16)
  121. assert_equal(spcreator((6,), dtype=np.int32)[0:0:2].dtype, np.int32)
  122. assert_equal(spcreator((6,), dtype=np.int64)[:].dtype, np.int64)
  123. def test_get_1d_slice(self, spcreator):
  124. B = np.arange(50.)
  125. A = spcreator(B)
  126. assert_equal(B[:], A[:].toarray())
  127. assert_equal(B[2:5], A[2:5].toarray())
  128. C = np.array([4, 0, 6, 0, 0, 0, 0, 0, 1])
  129. D = spcreator(C)
  130. assert_equal(C[1:3], D[1:3].toarray())
  131. # Now test slicing when a row contains only zeros
  132. E = np.array([0, 0, 0, 0, 0])
  133. F = spcreator(E)
  134. assert_equal(E[1:3], F[1:3].toarray())
  135. assert_equal(E[-2:], F[-2:].toarray())
  136. assert_equal(E[:], F[:].toarray())
  137. assert_equal(E[slice(None)], F[slice(None)].toarray())
  138. def test_slicing_idx_slice(self, spcreator):
  139. B = np.arange(50)
  140. A = spcreator(B)
  141. # [i]
  142. assert_equal(A[2], B[2])
  143. assert_equal(A[-1], B[-1])
  144. assert_equal(A[np.array(-2)], B[-2])
  145. # [1:2]
  146. assert_equal(A[:].toarray(), B[:])
  147. assert_equal(A[5:-2].toarray(), B[5:-2])
  148. assert_equal(A[5:12:3].toarray(), B[5:12:3])
  149. # int8 slice
  150. s = slice(np.int8(2), np.int8(4), None)
  151. assert_equal(A[s].toarray(), B[2:4])
  152. # np.s_
  153. s_ = np.s_
  154. slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
  155. s_[15:20], s_[3:2],
  156. s_[8:3:-1], s_[4::-2], s_[:5:-1],
  157. 0, 1, s_[:], s_[1:5], -1, -2, -5,
  158. np.array(-1), np.int8(-3)]
  159. for j, a in enumerate(slices):
  160. x = A[a]
  161. y = B[a]
  162. if y.shape == ():
  163. assert_equal(x, y, repr(a))
  164. else:
  165. if x.size == 0 and y.size == 0:
  166. pass
  167. else:
  168. assert_equal(x.toarray(), y, repr(a))
  169. def test_ellipsis_1d_slicing(self, spcreator):
  170. B = np.arange(50)
  171. A = spcreator(B)
  172. assert_equal(A[...].toarray(), B[...])
  173. assert_equal(A[...,].toarray(), B[...,])
  174. ##########################
  175. # Assignment with Slicing
  176. ##########################
  177. def test_slice_scalar_assign(self, spcreator):
  178. A = spcreator((5,))
  179. B = np.zeros((5,))
  180. with warnings.catch_warnings():
  181. warnings.filterwarnings(
  182. "ignore",
  183. "Changing the sparsity structure of .* is expensive",
  184. SparseEfficiencyWarning,
  185. )
  186. for C in [A, B]:
  187. C[0:1] = 1
  188. C[2:0] = 4
  189. C[2:3] = 9
  190. C[3:] = 1
  191. C[3::-1] = 9
  192. assert_equal(A.toarray(), B)
  193. def test_slice_assign_2(self, spcreator):
  194. shape = (10,)
  195. for idx in [slice(3), slice(None, 10, 4), slice(5, -2)]:
  196. A = spcreator(shape)
  197. with warnings.catch_warnings():
  198. warnings.filterwarnings(
  199. "ignore",
  200. "Changing the sparsity structure of .* is expensive",
  201. SparseEfficiencyWarning,
  202. )
  203. A[idx] = 1
  204. B = np.zeros(shape)
  205. B[idx] = 1
  206. msg = f"idx={idx!r}"
  207. assert_allclose(A.toarray(), B, err_msg=msg)
  208. def test_self_self_assignment(self, spcreator):
  209. # Tests whether a row of one lil_matrix can be assigned to another.
  210. B = spcreator((5,))
  211. with warnings.catch_warnings():
  212. warnings.filterwarnings(
  213. "ignore",
  214. "Changing the sparsity structure of .* is expensive",
  215. SparseEfficiencyWarning,
  216. )
  217. B[0] = 2
  218. B[1] = 0
  219. B[2] = 3
  220. B[3] = 10
  221. A = B / 10
  222. B[:] = A[:]
  223. assert_equal(A[:].toarray(), B[:].toarray())
  224. A = B / 10
  225. B[:] = A[:1]
  226. assert_equal(np.zeros((5,)) + A[0], B.toarray())
  227. A = B / 10
  228. B[:-1] = A[1:]
  229. assert_equal(A[1:].toarray(), B[:-1].toarray())
  230. def test_slice_assignment(self, spcreator):
  231. B = spcreator((4,))
  232. expected = np.array([10, 0, 14, 0])
  233. block = [2, 1]
  234. with warnings.catch_warnings():
  235. warnings.filterwarnings(
  236. "ignore",
  237. "Changing the sparsity structure of .* is expensive",
  238. SparseEfficiencyWarning,
  239. )
  240. B[0] = 5
  241. B[2] = 7
  242. B[:] = B + B
  243. assert_equal(B.toarray(), expected)
  244. B[:2] = csr_array(block)
  245. assert_equal(B.toarray()[:2], block)
  246. def test_set_slice(self, spcreator):
  247. A = spcreator((5,))
  248. B = np.zeros(5, float)
  249. s_ = np.s_
  250. slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
  251. s_[8:3:-1], s_[4::-2], s_[:5:-1],
  252. 0, 1, s_[:], s_[1:5], -1, -2, -5,
  253. np.array(-1), np.int8(-3)]
  254. with warnings.catch_warnings():
  255. warnings.filterwarnings(
  256. "ignore",
  257. "Changing the sparsity structure of .* is expensive",
  258. SparseEfficiencyWarning,
  259. )
  260. for j, a in enumerate(slices):
  261. A[a] = j
  262. B[a] = j
  263. assert_equal(A.toarray(), B, repr(a))
  264. A[1:10:2] = range(1, 5, 2)
  265. B[1:10:2] = range(1, 5, 2)
  266. assert_equal(A.toarray(), B)
  267. # The next commands should raise exceptions
  268. toobig = list(range(100))
  269. with pytest.raises(ValueError, match='Trying to assign a sequence to an item'):
  270. A.__setitem__(0, toobig)
  271. with pytest.raises(ValueError, match='could not be broadcast together'):
  272. A.__setitem__(slice(None), toobig)
  273. def test_assign_empty(self, spcreator):
  274. A = spcreator(np.ones(3))
  275. B = spcreator((2,))
  276. A[:2] = B
  277. assert_equal(A.toarray(), [0, 0, 1])
  278. ####################
  279. # 1d Fancy Indexing
  280. ####################
  281. def test_dtype_preservation_empty_index(self, spcreator):
  282. A = spcreator((2,), dtype=np.int16)
  283. assert_equal(A[[False, False]].dtype, np.int16)
  284. assert_equal(A[[]].dtype, np.int16)
  285. def test_bad_index(self, spcreator):
  286. A = spcreator(np.zeros(5))
  287. with pytest.raises(IndexError, match='Index dimension must be 1 or 2'):
  288. A.__getitem__("foo")
  289. with pytest.raises(IndexError, match='tuple index out of range'):
  290. A.__getitem__((2, "foo"))
  291. def test_fancy_indexing_2darray(self, spcreator):
  292. B = np.arange(50).reshape((5, 10))
  293. A = spcreator(B)
  294. # [i]
  295. assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
  296. # [i,[1,2]]
  297. assert_equal(A[3, [1, 3]].toarray(), B[3, [1, 3]])
  298. assert_equal(A[-1, [2, -5]].toarray(), B[-1, [2, -5]])
  299. assert_equal(A[np.array(-1), [2, -5]].toarray(), B[-1, [2, -5]])
  300. assert_equal(A[-1, np.array([2, -5])].toarray(), B[-1, [2, -5]])
  301. assert_equal(A[np.array(-1), np.array([2, -5])].toarray(), B[-1, [2, -5]])
  302. # [1:2,[1,2]]
  303. assert_equal(A[:, [2, 8, 3, -1]].toarray(), B[:, [2, 8, 3, -1]])
  304. assert_equal(A[3:4, [9]].toarray(), B[3:4, [9]])
  305. assert_equal(A[1:4, [-1, -5]].toarray(), B[1:4, [-1, -5]])
  306. assert_equal(A[1:4, np.array([-1, -5])].toarray(), B[1:4, [-1, -5]])
  307. # [[1,2],j]
  308. assert_equal(A[[1, 3], 3].toarray(), B[[1, 3], 3])
  309. assert_equal(A[[2, -5], -4].toarray(), B[[2, -5], -4])
  310. assert_equal(A[np.array([2, -5]), -4].toarray(), B[[2, -5], -4])
  311. assert_equal(A[[2, -5], np.array(-4)].toarray(), B[[2, -5], -4])
  312. assert_equal(A[np.array([2, -5]), np.array(-4)].toarray(), B[[2, -5], -4])
  313. # [[1,2],1:2]
  314. assert_equal(A[[1, 3], :].toarray(), B[[1, 3], :])
  315. assert_equal(A[[2, -5], 8:-1].toarray(), B[[2, -5], 8:-1])
  316. assert_equal(A[np.array([2, -5]), 8:-1].toarray(), B[[2, -5], 8:-1])
  317. # [[1,2],[1,2]]
  318. assert_equal(toarray(A[[1, 3], [2, 4]]), B[[1, 3], [2, 4]])
  319. assert_equal(toarray(A[[-1, -3], [2, -4]]), B[[-1, -3], [2, -4]])
  320. assert_equal(
  321. toarray(A[np.array([-1, -3]), [2, -4]]), B[[-1, -3], [2, -4]]
  322. )
  323. assert_equal(
  324. toarray(A[[-1, -3], np.array([2, -4])]), B[[-1, -3], [2, -4]]
  325. )
  326. assert_equal(
  327. toarray(A[np.array([-1, -3]), np.array([2, -4])]), B[[-1, -3], [2, -4]]
  328. )
  329. # [[[1],[2]],[1,2]]
  330. assert_equal(A[[[1], [3]], [2, 4]].toarray(), B[[[1], [3]], [2, 4]])
  331. assert_equal(
  332. A[[[-1], [-3], [-2]], [2, -4]].toarray(),
  333. B[[[-1], [-3], [-2]], [2, -4]]
  334. )
  335. assert_equal(
  336. A[np.array([[-1], [-3], [-2]]), [2, -4]].toarray(),
  337. B[[[-1], [-3], [-2]], [2, -4]]
  338. )
  339. assert_equal(
  340. A[[[-1], [-3], [-2]], np.array([2, -4])].toarray(),
  341. B[[[-1], [-3], [-2]], [2, -4]]
  342. )
  343. assert_equal(
  344. A[np.array([[-1], [-3], [-2]]), np.array([2, -4])].toarray(),
  345. B[[[-1], [-3], [-2]], [2, -4]]
  346. )
  347. # [[1,2]]
  348. assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
  349. assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
  350. assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]])
  351. # [[1,2],:][:,[1,2]]
  352. assert_equal(
  353. A[[1, 3], :][:, [2, 4]].toarray(), B[[1, 3], :][:, [2, 4]]
  354. )
  355. assert_equal(
  356. A[[-1, -3], :][:, [2, -4]].toarray(), B[[-1, -3], :][:, [2, -4]]
  357. )
  358. assert_equal(
  359. A[np.array([-1, -3]), :][:, np.array([2, -4])].toarray(),
  360. B[[-1, -3], :][:, [2, -4]]
  361. )
  362. # [:,[1,2]][[1,2],:]
  363. assert_equal(
  364. A[:, [1, 3]][[2, 4], :].toarray(), B[:, [1, 3]][[2, 4], :]
  365. )
  366. assert_equal(
  367. A[:, [-1, -3]][[2, -4], :].toarray(), B[:, [-1, -3]][[2, -4], :]
  368. )
  369. assert_equal(
  370. A[:, np.array([-1, -3])][np.array([2, -4]), :].toarray(),
  371. B[:, [-1, -3]][[2, -4], :]
  372. )
  373. def test_fancy_indexing(self, spcreator):
  374. B = np.arange(50)
  375. A = spcreator(B)
  376. # [i]
  377. assert_equal(A[[3]].toarray(), B[[3]])
  378. # [np.array]
  379. assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
  380. assert_equal(A[[2, -5]].toarray(), B[[2, -5]])
  381. assert_equal(A[np.array(-1)], B[-1])
  382. assert_equal(A[np.array([-1, 2])].toarray(), B[[-1, 2]])
  383. assert_equal(A[np.array(5)], B[np.array(5)])
  384. # [[[1],[2]]]
  385. ind = np.array([[1], [3]])
  386. assert_equal(A[ind].toarray(), B[ind])
  387. ind = np.array([[-1], [-3], [-2]])
  388. assert_equal(A[ind].toarray(), B[ind])
  389. # [[1, 2]]
  390. assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
  391. assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
  392. assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]])
  393. # [[1, 2]][[1, 2]]
  394. assert_equal(A[[1, 5, 2, 8]][[1, 3]].toarray(),
  395. B[[1, 5, 2, 8]][[1, 3]])
  396. assert_equal(A[[-1, -5, 2, 8]][[1, -4]].toarray(),
  397. B[[-1, -5, 2, 8]][[1, -4]])
  398. def test_fancy_indexing_boolean(self, spcreator):
  399. np.random.seed(1234) # make runs repeatable
  400. B = np.arange(50)
  401. A = spcreator(B)
  402. I = np.array(np.random.randint(0, 2, size=50), dtype=bool)
  403. assert_equal(toarray(A[I]), B[I])
  404. assert_equal(toarray(A[B > 9]), B[B > 9])
  405. Z1 = np.zeros(51, dtype=bool)
  406. Z2 = np.zeros(51, dtype=bool)
  407. Z2[-1] = True
  408. Z3 = np.zeros(51, dtype=bool)
  409. Z3[0] = True
  410. msg = 'bool index .* has shape|boolean index did not match'
  411. with pytest.raises(IndexError, match=msg):
  412. A.__getitem__(Z1)
  413. with pytest.raises(IndexError, match=msg):
  414. A.__getitem__(Z2)
  415. with pytest.raises(IndexError, match=msg):
  416. A.__getitem__(Z3)
  417. def test_fancy_indexing_sparse_boolean(self, spcreator):
  418. np.random.seed(1234) # make runs repeatable
  419. B = np.arange(20)
  420. A = spcreator(B)
  421. X = np.array(np.random.randint(0, 2, size=20), dtype=bool)
  422. Xsp = csr_array(X)
  423. assert_equal(toarray(A[Xsp]), B[X])
  424. assert_equal(toarray(A[A > 9]), B[B > 9])
  425. Y = np.array(np.random.randint(0, 2, size=60), dtype=bool)
  426. Ysp = csr_array(Y)
  427. with pytest.raises(IndexError, match='bool index .* has shape|only integers'):
  428. A.__getitem__(Ysp)
  429. with pytest.raises(IndexError, match='tuple index out of range|only integers'):
  430. A.__getitem__((Xsp, 1))
  431. def test_fancy_indexing_seq_assign(self, spcreator):
  432. mat = spcreator(np.array([1, 0]))
  433. with pytest.raises(ValueError, match='Trying to assign a sequence to an item'):
  434. mat.__setitem__(0, np.array([1, 2]))
  435. def test_fancy_indexing_empty(self, spcreator):
  436. B = np.arange(50)
  437. B[3:9] = 0
  438. B[30] = 0
  439. A = spcreator(B)
  440. K = np.array([False] * 50)
  441. assert_equal(toarray(A[K]), B[K])
  442. K = np.array([], dtype=int)
  443. assert_equal(toarray(A[K]), B[K])
  444. J = np.array([0, 1, 2, 3, 4], dtype=int)
  445. assert_equal(toarray(A[J]), B[J])
  446. ############################
  447. # 1d Fancy Index Assignment
  448. ############################
  449. def test_bad_index_assign(self, spcreator):
  450. A = spcreator(np.zeros(5))
  451. msg = 'Index dimension must be 1 or 2|only integers'
  452. with pytest.raises((IndexError, ValueError, TypeError), match=msg):
  453. A.__setitem__("foo", 2)
  454. def test_fancy_indexing_set(self, spcreator):
  455. M = (5,)
  456. # [1:2]
  457. for j in [[2, 3, 4], slice(None, 10, 4), np.arange(3),
  458. slice(5, -2), slice(2, 5)]:
  459. A = spcreator(M)
  460. B = np.zeros(M)
  461. with warnings.catch_warnings():
  462. warnings.filterwarnings(
  463. "ignore",
  464. "Changing the sparsity structure of .* is expensive",
  465. SparseEfficiencyWarning,
  466. )
  467. B[j] = 1
  468. with check_remains_sorted(A):
  469. A[j] = 1
  470. assert_allclose(A.toarray(), B)
  471. def test_sequence_assignment(self, spcreator):
  472. A = spcreator((4,))
  473. B = spcreator((3,))
  474. i0 = [0, 1, 2]
  475. i1 = (0, 1, 2)
  476. i2 = np.array(i0)
  477. with warnings.catch_warnings():
  478. warnings.filterwarnings(
  479. "ignore",
  480. "Changing the sparsity structure of .* is expensive",
  481. SparseEfficiencyWarning,
  482. )
  483. with check_remains_sorted(A):
  484. A[i0] = B[i0]
  485. msg = "Too many indices for array|tuple index out of range"
  486. with pytest.raises(IndexError, match=msg):
  487. B.__getitem__(i1)
  488. A[i2] = B[i2]
  489. assert_equal(A[:3].toarray(), B.toarray())
  490. assert A.shape == (4,)
  491. # slice
  492. A = spcreator((4,))
  493. with check_remains_sorted(A):
  494. A[1:3] = [10, 20]
  495. assert_equal(A.toarray(), [0, 10, 20, 0])
  496. # array
  497. A = spcreator((4,))
  498. B = np.zeros(4)
  499. with check_remains_sorted(A):
  500. for C in [A, B]:
  501. C[[0, 1, 2]] = [4, 5, 6]
  502. assert_equal(A.toarray(), B)
  503. def test_fancy_assign_empty(self, spcreator):
  504. B = np.arange(50)
  505. B[2] = 0
  506. B[[3, 6]] = 0
  507. A = spcreator(B)
  508. K = np.array([False] * 50)
  509. A[K] = 42
  510. assert_equal(A.toarray(), B)
  511. K = np.array([], dtype=int)
  512. A[K] = 42
  513. assert_equal(A.toarray(), B)