Skip to content

Commit

Permalink
(chore): disallow AnnData(...) with non-csr{r,c} matrices/arrays (#…
Browse files Browse the repository at this point in the history
…1829)

* (chore): disallow `AnnData(...)` with non-csr{r,c} matrices/arrays

* (chore): release note

* (chore): clean up boolean check
  • Loading branch information
ilan-gold authored Jan 16, 2025
1 parent 9120c4d commit faec0f8
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 13 deletions.
1 change: 1 addition & 0 deletions docs/release-notes/1829.breaking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Disallow declaration of {class}`~anndata.AnnData` with non-`cs{r,c}` sparse data-structures {user}`ilan-gold`
20 changes: 12 additions & 8 deletions src/anndata/_core/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import pandas as pd
from scipy import sparse

from anndata.compat import SpArray

from .._warnings import ImplicitModificationWarning
from ..utils import (
ensure_df_homogeneous,
Expand Down Expand Up @@ -39,14 +41,16 @@ def coerce_array(
warnings.warn(msg, ImplicitModificationWarning)
value = value.A
return value
elif isinstance(value, sparse.spmatrix):
msg = (
f"AnnData previously had undefined behavior around matrices of type {type(value)}."
"In 0.12, passing in this type will throw an error. Please convert to a supported type."
"Continue using for this minor version at your own risk."
)
warnings.warn(msg, FutureWarning)
return value
is_non_csc_r_array_or_matrix = (
(isinstance(value, base) and not isinstance(value, csr_c_format))
for base, csr_c_format in [
(sparse.spmatrix, sparse.csr_matrix | sparse.csc_matrix),
(SpArray, sparse.csr_array | sparse.csc_array),
]
)
if any(is_non_csc_r_array_or_matrix):
msg = f"Only CSR and CSC {'matrices' if isinstance(value, sparse.spmatrix) else 'arrays'} are supported."
raise ValueError(msg)
if isinstance(value, pd.DataFrame):
if allow_df:
raise_value_error_if_multiindex_columns(value, name)
Expand Down
10 changes: 5 additions & 5 deletions tests/test_x.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,10 @@ def test_set_dense_x_view_from_sparse():
assert_equal(orig.X[30:], x[30:]) # change propagates through


def test_warn_on_non_csr_csc_matrix():
X = sparse.eye(100)
with pytest.warns(
FutureWarning,
match=rf"AnnData previously had undefined behavior around matrices of type {type(X)}.*",
def test_fail_on_non_csr_csc_matrix():
X = sparse.eye(100, format="coo")
with pytest.raises(
ValueError,
match=r"Only CSR and CSC.*",
):
ad.AnnData(X=X)

0 comments on commit faec0f8

Please sign in to comment.