pydata / pydata/sparse

Support boolean indexing with a COO sparse matrix

Open
#304 9 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Python
Stars
668
Forks
141
Avg merge
2d 8h
Merged PRs (30d)
4

Description

While investigating https://github.com/theislab/scanpy/issues/921 I ran into the following limitation when using a boolean array as an index.

This is the expected behaviour for regular NumPy:

>>> import numpy as np
x = np.array([1, 2, 3, 4])
>>> x[x % 2 == 0]
array([2, 4])

But the same thing fails for sparse:

>>> import sparse
>>> s = sparse.COO.from_numpy(x)
>>> s
<COO: shape=(4,), dtype=int64, nnz=4, fill_value=0>
>>> [s % 2 == 0]
[<COO: shape=(4,), dtype=bool, nnz=2, fill_value=True>]
>>> s[s % 2 == 0]
<class 'sparse._coo.core.COO'>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/tom/workspace/scanpy/venv/lib/python3.7/site-packages/sparse/_coo/indexing.py", line 60, in getitem
    index = normalize_index(index, x.shape)
  File "/Users/tom/workspace/scanpy/venv/lib/python3.7/site-packages/sparse/_slicing.py", line 58, in normalize_index
    check_index(i, d)
  File "/Users/tom/workspace/scanpy/venv/lib/python3.7/site-packages/sparse/_slicing.py", line 123, in check_index
    raise IndexError("only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and "
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

It would be good to fix it for GCXS if that's a problem too. I couldn't reproduce it there since from sparse import GCXS fails.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in sparse/_coo/indexing.py and sparse/_slicing.py, where the traceback shows boolean index normalization failing for a COO array. Trace how boolean arrays are validated and indexed, then check whether the same behavior applies to GCXS. Done means the shown boolean-indexing example works for COO and, if applicable, GCXS without breaking existing index forms.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
data
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.