Skip to content

Commit

Permalink
Backport PR #1746 on branch 0.11.x ((fix): raise error on non-integer…
Browse files Browse the repository at this point in the history
… floating types in iterables) (#1799)

Co-authored-by: Ilan Gold <[email protected]>
  • Loading branch information
meeseeksmachine and ilan-gold authored Dec 10, 2024
1 parent 6bf0d1d commit ba06d2a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
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`
6 changes: 6 additions & 0 deletions src/anndata/_core/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ def name_idx(i):
indexer = np.array(indexer)
if len(indexer) == 0:
indexer = indexer.astype(int)
if isinstance(indexer, np.ndarray) and np.issubdtype(
indexer.dtype, np.floating
):
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
16 changes: 16 additions & 0 deletions tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,22 @@ 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([1.2, 3.4], id="list"),
*(
pytest.param(np.array([1.2, 2.3], dtype=dtype), id=f"ndarray-{dtype}")
for dtype in [np.float32, np.float64]
),
],
)
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

0 comments on commit ba06d2a

Please sign in to comment.