Skip to content

Commit 86fed09

Browse files
committed
basic support for AnnData accessors
this should keep scanpy plotting working with MuData objects
1 parent 61f35d2 commit 86fed09

3 files changed

Lines changed: 33 additions & 1 deletion

File tree

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ dev = [
4848
"pre-commit",
4949
"twine>=4.0.2",
5050
]
51-
test = [ "coverage>=7.10", "mudata[io]", "pytest" ]
51+
test = [ "coverage>=7.10", "mudata[io]", "packaging", "pytest" ]
5252
doc = [
5353
"docutils>=0.8,!=0.18.*,!=0.19.*",
5454
"ipykernel",

src/mudata/_core/mudata.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,25 @@ def strings_to_categoricals(self, df: pd.DataFrame | None = None) -> pd.DataFram
513513
def __getitem__(self, index) -> AnnData | MuData:
514514
if isinstance(index, str):
515515
return self._mod[index]
516+
elif type(index).__module__.startswith("anndata.acc") and type(index).__name__ == "AdRef":
517+
try:
518+
return index.acc.get(self, index.idx)
519+
except KeyError as e:
520+
if index.acc.dim in ("obs", "var"):
521+
for modname, mod in self._mod.items():
522+
try:
523+
index.acc.get(mod, index.idx)
524+
except KeyError:
525+
pass
526+
else:
527+
raise KeyError(
528+
f"There is no key {index.idx} in MuData .{index.acc.dim} but there is one in {modname} .{index.acc.dim}. Consider running `pull_{index.acc.dim}()` to update global .{index.acc.dim}."
529+
) from e
530+
raise KeyError(
531+
f"There is no key {index.idx} in MuData .{index.acc.dim} or in .{index.acc.dim} of any modalities."
532+
) from e
533+
else:
534+
raise
516535
else:
517536
return MuData(self, as_view=True, index=index)
518537

tests/test_obs_var.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
from pathlib import Path
22

3+
import anndata as ad
34
import numpy as np
45
import pandas as pd
56
import pytest
7+
from packaging.version import Version
68

79
import mudata as md
810

@@ -145,3 +147,14 @@ def test_names_make_unique(mdata: md.MuData):
145147

146148
with pytest.raises(TypeError, match="axis="):
147149
getattr(mdata, f"{attr}_names_make_unique")()
150+
151+
152+
@pytest.mark.skipif(
153+
Version(ad.__version__) < Version("0.13dev0"), reason="anndata version too old, no accessor support"
154+
)
155+
def test_accessors(mdata: md.MuData):
156+
assert (mdata[ad.acc.A.obs["arange"]] == mdata.obs["arange"]).all()
157+
with pytest.raises(KeyError, match="any modalities"):
158+
mdata[ad.acc.A.var["test"]]
159+
with pytest.raises(KeyError, match="there is one in"):
160+
mdata[ad.acc.A.var["assert-bool"]]

0 commit comments

Comments
 (0)