File size: 20,754 Bytes
7885a28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
import contextlib
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_equal

from scipy.sparse import csr_array, dok_array, SparseEfficiencyWarning
from .test_arithmetic1d import toarray


formats_for_index1d = [csr_array, dok_array]


@contextlib.contextmanager
def check_remains_sorted(X):
    """Checks that sorted indices property is retained through an operation"""
    yield
    if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices:
        return
    indices = X.indices.copy()
    X.has_sorted_indices = False
    X.sort_indices()
    assert_equal(indices, X.indices, 'Expected sorted indices, found unsorted')


@pytest.mark.parametrize("spcreator", formats_for_index1d)
class TestGetSet1D:
    def test_None_index(self, spcreator):
        D = np.array([4, 3, 0])
        A = spcreator(D)

        N = D.shape[0]
        for j in range(-N, N):
            assert_equal(A[j, None].toarray(), D[j, None])
            assert_equal(A[None, j].toarray(), D[None, j])
            assert_equal(A[None, None, j].toarray(), D[None, None, j])

    def test_getitem_shape(self, spcreator):
        A = spcreator(np.arange(3 * 4).reshape(3, 4))
        assert A[1, 2].ndim == 0
        assert A[1, 2:3].shape == (1,)
        assert A[None, 1, 2:3].shape == (1, 1)
        assert A[None, 1, 2].shape == (1,)
        assert A[None, 1, 2, None].shape == (1, 1)

        # see gh-22458
        assert A[None, 1].shape == (1, 4)
        assert A[1, None].shape == (1, 4)
        assert A[None, 1, :].shape == (1, 4)
        assert A[1, None, :].shape == (1, 4)
        assert A[1, :, None].shape == (4, 1)

        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
            A[None, 2, 1, None, None]
        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
            A[None, 0:2, None, 1]
        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
            A[0:1, 1:, None]
        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
            A[1:, 1, None, None]

    def test_getelement(self, spcreator):
        D = np.array([4, 3, 0])
        A = spcreator(D)

        N = D.shape[0]
        for j in range(-N, N):
            assert_equal(A[j], D[j])

        for ij in [3, -4]:
            with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'):
                A.__getitem__(ij)

        # single element tuples unwrapped
        assert A[(0,)] == 4

        with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'):
            A.__getitem__((4,))

    def test_setelement(self, spcreator):
        dtype = np.float64
        A = spcreator((12,), dtype=dtype)
        with np.testing.suppress_warnings() as sup:
            sup.filter(
                SparseEfficiencyWarning,
                "Changing the sparsity structure of .* is expensive",
            )
            A[0] = dtype(0)
            A[1] = dtype(3)
            A[8] = dtype(9.0)
            A[-2] = dtype(7)
            A[5] = 9

            A[-9,] = dtype(8)
            A[1,] = dtype(5)  # overwrite using 1-tuple index

            for ij in [13, -14, (13,), (14,)]:
                with pytest.raises(IndexError, match='out of (range|bounds)'):
                    A.__setitem__(ij, 123.0)


@pytest.mark.parametrize("spcreator", formats_for_index1d)
class TestSlicingAndFancy1D:
    #######################
    #  Int-like Array Index
    #######################
    def test_get_array_index(self, spcreator):
        D = np.array([4, 3, 0])
        A = spcreator(D)

        assert_equal(A[()].toarray(), D[()])
        for ij in [(0, 3), (3,)]:
            with pytest.raises(IndexError, match='out of (range|bounds)|many indices'):
                A.__getitem__(ij)

    def test_set_array_index(self, spcreator):
        dtype = np.float64
        A = spcreator((12,), dtype=dtype)
        with np.testing.suppress_warnings() as sup:
            sup.filter(
                SparseEfficiencyWarning,
                "Changing the sparsity structure of .* is expensive",
            )
            A[np.array(6)] = dtype(4.0)  # scalar index
            A[np.array(6)] = dtype(2.0)  # overwrite with scalar index
            assert_equal(A.toarray(), [0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0])

            for ij in [(13,), (-14,)]:
                with pytest.raises(IndexError, match='index .* out of (range|bounds)'):
                    A.__setitem__(ij, 123.0)

            for v in [(), (0, 3), [1, 2, 3], np.array([1, 2, 3])]:
                msg = 'Trying to assign a sequence to an item'
                with pytest.raises(ValueError, match=msg):
                    A.__setitem__(0, v)

    ####################
    #  1d Slice as index
    ####################
    def test_dtype_preservation(self, spcreator):
        assert_equal(spcreator((10,), dtype=np.int16)[1:5].dtype, np.int16)
        assert_equal(spcreator((6,), dtype=np.int32)[0:0:2].dtype, np.int32)
        assert_equal(spcreator((6,), dtype=np.int64)[:].dtype, np.int64)

    def test_get_1d_slice(self, spcreator):
        B = np.arange(50.)
        A = spcreator(B)
        assert_equal(B[:], A[:].toarray())
        assert_equal(B[2:5], A[2:5].toarray())

        C = np.array([4, 0, 6, 0, 0, 0, 0, 0, 1])
        D = spcreator(C)
        assert_equal(C[1:3], D[1:3].toarray())

        # Now test slicing when a row contains only zeros
        E = np.array([0, 0, 0, 0, 0])
        F = spcreator(E)
        assert_equal(E[1:3], F[1:3].toarray())
        assert_equal(E[-2:], F[-2:].toarray())
        assert_equal(E[:], F[:].toarray())
        assert_equal(E[slice(None)], F[slice(None)].toarray())

    def test_slicing_idx_slice(self, spcreator):
        B = np.arange(50)
        A = spcreator(B)

        # [i]
        assert_equal(A[2], B[2])
        assert_equal(A[-1], B[-1])
        assert_equal(A[np.array(-2)], B[-2])

        # [1:2]
        assert_equal(A[:].toarray(), B[:])
        assert_equal(A[5:-2].toarray(), B[5:-2])
        assert_equal(A[5:12:3].toarray(), B[5:12:3])

        # int8 slice
        s = slice(np.int8(2), np.int8(4), None)
        assert_equal(A[s].toarray(), B[2:4])

        # np.s_
        s_ = np.s_
        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
                  s_[15:20], s_[3:2],
                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
                  0, 1, s_[:], s_[1:5], -1, -2, -5,
                  np.array(-1), np.int8(-3)]

        for j, a in enumerate(slices):
            x = A[a]
            y = B[a]
            if y.shape == ():
                assert_equal(x, y, repr(a))
            else:
                if x.size == 0 and y.size == 0:
                    pass
                else:
                    assert_equal(x.toarray(), y, repr(a))

    def test_ellipsis_1d_slicing(self, spcreator):
        B = np.arange(50)
        A = spcreator(B)
        assert_equal(A[...].toarray(), B[...])
        assert_equal(A[...,].toarray(), B[...,])

    ##########################
    #  Assignment with Slicing
    ##########################
    def test_slice_scalar_assign(self, spcreator):
        A = spcreator((5,))
        B = np.zeros((5,))
        with np.testing.suppress_warnings() as sup:
            sup.filter(
                SparseEfficiencyWarning,
                "Changing the sparsity structure of .* is expensive",
            )
            for C in [A, B]:
                C[0:1] = 1
                C[2:0] = 4
                C[2:3] = 9
                C[3:] = 1
                C[3::-1] = 9
        assert_equal(A.toarray(), B)

    def test_slice_assign_2(self, spcreator):
        shape = (10,)

        for idx in [slice(3), slice(None, 10, 4), slice(5, -2)]:
            A = spcreator(shape)
            with np.testing.suppress_warnings() as sup:
                sup.filter(
                    SparseEfficiencyWarning,
                    "Changing the sparsity structure of .* is expensive",
                )
                A[idx] = 1
            B = np.zeros(shape)
            B[idx] = 1
            msg = f"idx={idx!r}"
            assert_allclose(A.toarray(), B, err_msg=msg)

    def test_self_self_assignment(self, spcreator):
        # Tests whether a row of one lil_matrix can be assigned to another.
        B = spcreator((5,))
        with np.testing.suppress_warnings() as sup:
            sup.filter(
                SparseEfficiencyWarning,
                "Changing the sparsity structure of .* is expensive",
            )
            B[0] = 2
            B[1] = 0
            B[2] = 3
            B[3] = 10

            A = B / 10
            B[:] = A[:]
            assert_equal(A[:].toarray(), B[:].toarray())

            A = B / 10
            B[:] = A[:1]
            assert_equal(np.zeros((5,)) + A[0], B.toarray())

            A = B / 10
            B[:-1] = A[1:]
            assert_equal(A[1:].toarray(), B[:-1].toarray())

    def test_slice_assignment(self, spcreator):
        B = spcreator((4,))
        expected = np.array([10, 0, 14, 0])
        block = [2, 1]

        with np.testing.suppress_warnings() as sup:
            sup.filter(
                SparseEfficiencyWarning,
                "Changing the sparsity structure of .* is expensive",
            )
            B[0] = 5
            B[2] = 7
            B[:] = B + B
            assert_equal(B.toarray(), expected)

            B[:2] = csr_array(block)
            assert_equal(B.toarray()[:2], block)

    def test_set_slice(self, spcreator):
        A = spcreator((5,))
        B = np.zeros(5, float)
        s_ = np.s_
        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
                  0, 1, s_[:], s_[1:5], -1, -2, -5,
                  np.array(-1), np.int8(-3)]

        with np.testing.suppress_warnings() as sup:
            sup.filter(
                SparseEfficiencyWarning,
                "Changing the sparsity structure of .* is expensive",
            )
            for j, a in enumerate(slices):
                A[a] = j
                B[a] = j
                assert_equal(A.toarray(), B, repr(a))

            A[1:10:2] = range(1, 5, 2)
            B[1:10:2] = range(1, 5, 2)
            assert_equal(A.toarray(), B)

        # The next commands should raise exceptions
        toobig = list(range(100))
        with pytest.raises(ValueError, match='Trying to assign a sequence to an item'):
            A.__setitem__(0, toobig)
        with pytest.raises(ValueError, match='could not be broadcast together'):
            A.__setitem__(slice(None), toobig)

    def test_assign_empty(self, spcreator):
        A = spcreator(np.ones(3))
        B = spcreator((2,))
        A[:2] = B
        assert_equal(A.toarray(), [0, 0, 1])

    ####################
    #  1d Fancy Indexing
    ####################
    def test_dtype_preservation_empty_index(self, spcreator):
        A = spcreator((2,), dtype=np.int16)
        assert_equal(A[[False, False]].dtype, np.int16)
        assert_equal(A[[]].dtype, np.int16)

    def test_bad_index(self, spcreator):
        A = spcreator(np.zeros(5))
        with pytest.raises(
            (IndexError, ValueError, TypeError),
            match='Index dimension must be 1 or 2|only integers',
        ):
            A.__getitem__("foo")
        with pytest.raises(
            (IndexError, ValueError, TypeError),
            match='tuple index out of range|only integers',
        ):
            A.__getitem__((2, "foo"))

    def test_fancy_indexing_2darray(self, spcreator):
        B = np.arange(50).reshape((5, 10))
        A = spcreator(B)

        # [i]
        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])

        # [i,[1,2]]
        assert_equal(A[3, [1, 3]].toarray(), B[3, [1, 3]])
        assert_equal(A[-1, [2, -5]].toarray(), B[-1, [2, -5]])
        assert_equal(A[np.array(-1), [2, -5]].toarray(), B[-1, [2, -5]])
        assert_equal(A[-1, np.array([2, -5])].toarray(), B[-1, [2, -5]])
        assert_equal(A[np.array(-1), np.array([2, -5])].toarray(), B[-1, [2, -5]])

        # [1:2,[1,2]]
        assert_equal(A[:, [2, 8, 3, -1]].toarray(), B[:, [2, 8, 3, -1]])
        assert_equal(A[3:4, [9]].toarray(), B[3:4, [9]])
        assert_equal(A[1:4, [-1, -5]].toarray(), B[1:4, [-1, -5]])
        assert_equal(A[1:4, np.array([-1, -5])].toarray(), B[1:4, [-1, -5]])

        # [[1,2],j]
        assert_equal(A[[1, 3], 3].toarray(), B[[1, 3], 3])
        assert_equal(A[[2, -5], -4].toarray(), B[[2, -5], -4])
        assert_equal(A[np.array([2, -5]), -4].toarray(), B[[2, -5], -4])
        assert_equal(A[[2, -5], np.array(-4)].toarray(), B[[2, -5], -4])
        assert_equal(A[np.array([2, -5]), np.array(-4)].toarray(), B[[2, -5], -4])

        # [[1,2],1:2]
        assert_equal(A[[1, 3], :].toarray(), B[[1, 3], :])
        assert_equal(A[[2, -5], 8:-1].toarray(), B[[2, -5], 8:-1])
        assert_equal(A[np.array([2, -5]), 8:-1].toarray(), B[[2, -5], 8:-1])

        # [[1,2],[1,2]]
        assert_equal(toarray(A[[1, 3], [2, 4]]), B[[1, 3], [2, 4]])
        assert_equal(toarray(A[[-1, -3], [2, -4]]), B[[-1, -3], [2, -4]])
        assert_equal(
            toarray(A[np.array([-1, -3]), [2, -4]]), B[[-1, -3], [2, -4]]
        )
        assert_equal(
            toarray(A[[-1, -3], np.array([2, -4])]), B[[-1, -3], [2, -4]]
        )
        assert_equal(
            toarray(A[np.array([-1, -3]), np.array([2, -4])]), B[[-1, -3], [2, -4]]
        )

        # [[[1],[2]],[1,2]]
        assert_equal(A[[[1], [3]], [2, 4]].toarray(), B[[[1], [3]], [2, 4]])
        assert_equal(
            A[[[-1], [-3], [-2]], [2, -4]].toarray(),
            B[[[-1], [-3], [-2]], [2, -4]]
        )
        assert_equal(
            A[np.array([[-1], [-3], [-2]]), [2, -4]].toarray(),
            B[[[-1], [-3], [-2]], [2, -4]]
        )
        assert_equal(
            A[[[-1], [-3], [-2]], np.array([2, -4])].toarray(),
            B[[[-1], [-3], [-2]], [2, -4]]
        )
        assert_equal(
            A[np.array([[-1], [-3], [-2]]), np.array([2, -4])].toarray(),
            B[[[-1], [-3], [-2]], [2, -4]]
        )

        # [[1,2]]
        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
        assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
        assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]])

        # [[1,2],:][:,[1,2]]
        assert_equal(
            A[[1, 3], :][:, [2, 4]].toarray(), B[[1, 3], :][:, [2, 4]]
        )
        assert_equal(
            A[[-1, -3], :][:, [2, -4]].toarray(), B[[-1, -3], :][:, [2, -4]]
        )
        assert_equal(
            A[np.array([-1, -3]), :][:, np.array([2, -4])].toarray(),
            B[[-1, -3], :][:, [2, -4]]
        )

        # [:,[1,2]][[1,2],:]
        assert_equal(
            A[:, [1, 3]][[2, 4], :].toarray(), B[:, [1, 3]][[2, 4], :]
        )
        assert_equal(
            A[:, [-1, -3]][[2, -4], :].toarray(), B[:, [-1, -3]][[2, -4], :]
        )
        assert_equal(
            A[:, np.array([-1, -3])][np.array([2, -4]), :].toarray(),
            B[:, [-1, -3]][[2, -4], :]
        )

    def test_fancy_indexing(self, spcreator):
        B = np.arange(50)
        A = spcreator(B)

        # [i]
        assert_equal(A[[3]].toarray(), B[[3]])

        # [np.array]
        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
        assert_equal(A[[2, -5]].toarray(), B[[2, -5]])
        assert_equal(A[np.array(-1)], B[-1])
        assert_equal(A[np.array([-1, 2])].toarray(), B[[-1, 2]])
        assert_equal(A[np.array(5)], B[np.array(5)])

        # [[[1],[2]]]
        ind = np.array([[1], [3]])
        assert_equal(A[ind].toarray(), B[ind])
        ind = np.array([[-1], [-3], [-2]])
        assert_equal(A[ind].toarray(), B[ind])

        # [[1, 2]]
        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
        assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
        assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]])

        # [[1, 2]][[1, 2]]
        assert_equal(A[[1, 5, 2, 8]][[1, 3]].toarray(),
                     B[[1, 5, 2, 8]][[1, 3]])
        assert_equal(A[[-1, -5, 2, 8]][[1, -4]].toarray(),
                     B[[-1, -5, 2, 8]][[1, -4]])

    def test_fancy_indexing_boolean(self, spcreator):
        np.random.seed(1234)  # make runs repeatable

        B = np.arange(50)
        A = spcreator(B)

        I = np.array(np.random.randint(0, 2, size=50), dtype=bool)

        assert_equal(toarray(A[I]), B[I])
        assert_equal(toarray(A[B > 9]), B[B > 9])

        Z1 = np.zeros(51, dtype=bool)
        Z2 = np.zeros(51, dtype=bool)
        Z2[-1] = True
        Z3 = np.zeros(51, dtype=bool)
        Z3[0] = True

        msg = 'bool index .* has shape|boolean index did not match'
        with pytest.raises(IndexError, match=msg):
            A.__getitem__(Z1)
        with pytest.raises(IndexError, match=msg):
            A.__getitem__(Z2)
        with pytest.raises(IndexError, match=msg):
            A.__getitem__(Z3)

    def test_fancy_indexing_sparse_boolean(self, spcreator):
        np.random.seed(1234)  # make runs repeatable

        B = np.arange(20)
        A = spcreator(B)

        X = np.array(np.random.randint(0, 2, size=20), dtype=bool)
        Xsp = csr_array(X)

        assert_equal(toarray(A[Xsp]), B[X])
        assert_equal(toarray(A[A > 9]), B[B > 9])

        Y = np.array(np.random.randint(0, 2, size=60), dtype=bool)

        Ysp = csr_array(Y)

        with pytest.raises(IndexError, match='bool index .* has shape|only integers'):
            A.__getitem__(Ysp)
        with pytest.raises(IndexError, match='tuple index out of range|only integers'):
            A.__getitem__((Xsp, 1))

    def test_fancy_indexing_seq_assign(self, spcreator):
        mat = spcreator(np.array([1, 0]))
        with pytest.raises(ValueError, match='Trying to assign a sequence to an item'):
            mat.__setitem__(0, np.array([1, 2]))

    def test_fancy_indexing_empty(self, spcreator):
        B = np.arange(50)
        B[3:9] = 0
        B[30] = 0
        A = spcreator(B)

        K = np.array([False] * 50)
        assert_equal(toarray(A[K]), B[K])
        K = np.array([], dtype=int)
        assert_equal(toarray(A[K]), B[K])
        J = np.array([0, 1, 2, 3, 4], dtype=int)
        assert_equal(toarray(A[J]), B[J])

    ############################
    #  1d Fancy Index Assignment
    ############################
    def test_bad_index_assign(self, spcreator):
        A = spcreator(np.zeros(5))
        msg = 'Index dimension must be 1 or 2|only integers'
        with pytest.raises((IndexError, ValueError, TypeError), match=msg):
            A.__setitem__("foo", 2)

    def test_fancy_indexing_set(self, spcreator):
        M = (5,)

        # [1:2]
        for j in [[2, 3, 4], slice(None, 10, 4), np.arange(3),
                     slice(5, -2), slice(2, 5)]:
            A = spcreator(M)
            B = np.zeros(M)
            with np.testing.suppress_warnings() as sup:
                sup.filter(
                    SparseEfficiencyWarning,
                    "Changing the sparsity structure of .* is expensive",
                )
                B[j] = 1
                with check_remains_sorted(A):
                    A[j] = 1
            assert_allclose(A.toarray(), B)

    def test_sequence_assignment(self, spcreator):
        A = spcreator((4,))
        B = spcreator((3,))

        i0 = [0, 1, 2]
        i1 = (0, 1, 2)
        i2 = np.array(i0)

        with np.testing.suppress_warnings() as sup:
            sup.filter(
                SparseEfficiencyWarning,
                "Changing the sparsity structure of .* is expensive",
            )
            with check_remains_sorted(A):
                A[i0] = B[i0]
                msg = "too many indices for array|tuple index out of range"
                with pytest.raises(IndexError, match=msg):
                    B.__getitem__(i1)
                A[i2] = B[i2]
            assert_equal(A[:3].toarray(), B.toarray())
            assert A.shape == (4,)

            # slice
            A = spcreator((4,))
            with check_remains_sorted(A):
                A[1:3] = [10, 20]
            assert_equal(A.toarray(), [0, 10, 20, 0])

            # array
            A = spcreator((4,))
            B = np.zeros(4)
            with check_remains_sorted(A):
                for C in [A, B]:
                    C[[0, 1, 2]] = [4, 5, 6]
            assert_equal(A.toarray(), B)

    def test_fancy_assign_empty(self, spcreator):
        B = np.arange(50)
        B[2] = 0
        B[[3, 6]] = 0
        A = spcreator(B)

        K = np.array([False] * 50)
        A[K] = 42
        assert_equal(A.toarray(), B)

        K = np.array([], dtype=int)
        A[K] = 42
        assert_equal(A.toarray(), B)