Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ dev = [
"pre-commit",
"twine>=4.0.2",
]
test = [ "coverage>=7.10", "mudata[io]", "pytest" ]
test = [ "coverage>=7.10", "mudata[io]", "packaging", "pytest" ]
doc = [
"docutils>=0.8,!=0.18.*,!=0.19.*",
"ipykernel",
Expand Down
28 changes: 26 additions & 2 deletions src/mudata/_core/mudata.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,8 +533,32 @@ def strings_to_categoricals(self, df: pd.DataFrame | None = None) -> pd.DataFram
def __getitem__(self, index) -> AnnData | MuData:
if isinstance(index, str):
return self._mod[index]
else:
return MuData(self, as_view=True, index=index)

with suppress(ImportError):
from anndata.acc import AdRef

if isinstance(index, AdRef):
try:
return index.acc.get(self, index.idx)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

So this relies on the fact that MuData carries an obs, var etc. but does not follow the type?

https://anndata.readthedocs.io/en/latest/generated/anndata.acc.RefAcc.html#anndata.acc.RefAcc.get

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe we should use a protocol?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

So this relies on the fact that MuData carries an obs, var etc. but does not follow the type?

Exactly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

There may be a cleaner way to this aside from violating types.

You're violating types every time you pass a MuData to scanpy, everything there is typed as AnnData. Perhaps a protocol would indeed make sense.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You're violating types every time you pass a MuData to scanpy, everything there is typed as AnnData. Perhaps a protocol would indeed make sense.

But maybe there's a way we can stop doing this now that scanpy is being redesigned - perhaps with a view to MuData.

except KeyError as e:
if index.acc.dim in ("obs", "var"):
for modname, mod in self._mod.items():
if index in mod:
raise KeyError(
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}."
) from e
raise
return MuData(self, as_view=True, index=index)

def __contains__(self, key) -> bool:
if isinstance(key, str):
return key in self._mod
with suppress(ImportError):
from anndata.acc import AdRef, MapAcc, RefAcc

if isinstance(key, AdRef | RefAcc | MapAcc):
return AnnData.__contains__(self, key)
raise TypeError(f"Unexpected key {key!r}.")

@property
def mod(self) -> Mapping[str, AnnData | MuData]:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_obs_var.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from pathlib import Path

import anndata as ad
import numpy as np
import pandas as pd
import pytest
from packaging.version import Version

import mudata as md

Expand Down Expand Up @@ -145,3 +147,15 @@ def test_names_make_unique(mdata: md.MuData):

with pytest.raises(TypeError, match="axis="):
getattr(mdata, f"{attr}_names_make_unique")()


@pytest.mark.skipif(
Version(ad.__version__) < Version("0.13dev0"), reason="anndata version too old, no accessor support"
)
def test_accessors(mdata: md.MuData):
assert ad.acc.A.obs["arange"] in mdata
assert (mdata[ad.acc.A.obs["arange"]] == mdata.obs["arange"]).all()
with pytest.raises(KeyError, match="test"):
mdata[ad.acc.A.var["test"]]
with pytest.raises(KeyError, match="there is one in"):
mdata[ad.acc.A.var["assert-bool"]]
3 changes: 3 additions & 0 deletions tests/test_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ def test_update_simple(mdata: MuData, axis: Axis):
for mod in mdata.mod.keys():
assert mdata.obsmap[mod].dtype.kind == "u"
assert mdata.varmap[mod].dtype.kind == "u"
assert mod in mdata
with pytest.raises(TypeError):
1 in mdata # noqa: B015

# names along non-axis are concatenated
assert mdata.shape[1 - axis] == sum(mod.shape[1 - axis] for mod in mdata.mod.values())
Expand Down
Loading