Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(fix): raise error on non-integer floating types in iterables #1746

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/release-notes/1746.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Error out on floating point indices that are not actually integers {user}`ilan-gold`
4 changes: 4 additions & 0 deletions src/anndata/_core/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ def name_idx(i):
indexer = np.array(indexer)
if len(indexer) == 0:
indexer = indexer.astype(int)
if isinstance(indexer, np.ndarray) and indexer.dtype == float:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please fix the comparison so it doesn’t only work with float64:

>>> np.dtype(np.float64) == float
True
>>> np.dtype(np.float32) == float
False

(and parametrize the tests please)

indexer_int = indexer.astype(int)
if np.all((indexer - indexer_int) != 0):
raise IndexError(f"Indexer {indexer!r} has floating point values.")
if issubclass(indexer.dtype.type, np.integer | np.floating):
return indexer # Might not work for range indexes
elif issubclass(indexer.dtype.type, np.bool_):
Expand Down
13 changes: 13 additions & 0 deletions tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,19 @@ def test_index_3d_errors(index: tuple[int | EllipsisType, ...], expected_error:
gen_adata((10, 10))[index]


@pytest.mark.parametrize(
"index",
[
pytest.param(sparse.csr_matrix(np.random.random((1, 10))), id="sparse"),
pytest.param(np.array([1.2, 2.3]), id="ndarray"),
pytest.param([1.2, 3.4], id="list"),
],
)
def test_index_float_sequence_raises_error(index):
with pytest.raises(IndexError, match=r"has floating point values"):
gen_adata((10, 10))[index]


# @pytest.mark.parametrize("dim", ["obs", "var"])
# @pytest.mark.parametrize(
# ("idx", "pat"),
Expand Down
Loading