Repository navigation
Description
Report
A modality that is an AnnData subclass is written as plain AnnData and read back as AnnData, so the elements the subclass adds are lost on write_h5mu/write_zarr/write_h5ad + read. Example with treedata.TreeData (an AnnData subclass with obst/vart trees):
import mudata as md
import networkx as nx
import numpy as np
import pandas as pd
import treedata as td
tree = nx.DiGraph([("root", "a"), ("root", "b")])
obs = pd.DataFrame(index=["a", "b"])
tdata = td.TreeData(np.ones((2, 2)), obs=obs, obst={"t": tree}, label="clade", allow_overlap=False)
mdata = md.MuData({"tree": tdata})
print(type(mdata["tree"]).__name__, list(mdata["tree"].obst)) # TreeData ['t']
md.write_h5mu("test.h5mu", mdata)
mdata2 = md.read_h5mu("test.h5mu")
print(type(mdata2["tree"]).__name__, hasattr(mdata2["tree"], "obst")) # AnnData FalseThe same happens with write_zarr/read_zarr and write_h5ad/read_h5ad. It is present in mudata 0.4.1 and on main (26ddfd7).
Cause. The writers write a fixed list of AnnData elements per modality (X, raw, obs, var, obsm, varm, obsp, varp, layers, uns), and the readers always build an AnnData (read_elem / read_dispatched). A subclass cannot plug in through anndata either: the IO registry dispatches on exact types and has no public registration API.
Proposal. A small duck-typed, opt-in hook, with no dependency on any particular subclass:
- After writing a modality's AnnData elements, if the object has
_write_mudata_extras(group, *, dataset_kwargs), mudata calls it (the subclass writes its extra elements into the modality group) and records the class in the group attributemudata-modality-class = "module:qualname". - On read, if that attribute is present, mudata imports the class and returns
cls._read_mudata_extras(group, adata), whereadatais the AnnData it read as today. If the class cannot be imported, it warns and returns the AnnData. - Modalities without the hook are written and read exactly as before. The group stays a valid AnnData group, so older mudata versions and
anndata.io.read_elemstill read it (as AnnData).
Open points for you to decide: (1) the read side imports a module named in the file; it only imports installed modules and checks that the result is an AnnData subclass with the hook, but an entry-point registry would avoid importing by name; (2) the hook and attribute names; (3) whether this belongs in anndata instead.
Implementation: #211. Companion treedata PR implementing the two hooks: YosefLab/treedata#103 (treedata issue: YosefLab/treedata#102). Found while building biotapy, a microbiome toolkit on TreeData/MuData.
Versions
mudata 0.4.1 (also main @ 26ddfd7)
treedata 0.3.1
anndata 0.13.4
h5py 3.16.0
zarr 3.4.1
Python 3.13.2, Linux
Activity
ilia-kats commentedon Oct 12, 2026
Since this concerns AnnData subclasses, IMHO this should be handled in AnnData. I also noticed that treedata writes
encoding-type=treedata. Perhaps it would make sense to have some unified standard for AnnData subclasses, where they writeencoding-type=anndata, but then have an addtional attribute similar to what you suggested, e.g.encoding-subtype=module:qualname. That way, if the respective package is not installed, at least the AnnData part of it can still be read with a warning to the user. Ideally, this should all be handled insideread_elem/write_elem. @ilan-gold what do you think?colganwi commentedon Oct 12, 2026
I agree this probably belong in AnnData. Extending AnnData's
read_elm/write_elmto handle subclasses would also add TreeData support to SpatialData. @ilan-gold would you be open to this? If so, I'm happy to help with a spec, and implement the treedata side.@ilia-kats we would still need to make minor changes to MuData to deal with backed mode.
ilan-gold commentedon Oct 12, 2026
Can
treedataexport its own read/write function for mudata? It seems like less work for identical cost - you needtreedatainstalled in your env to readtreedataanyway and will likely need some degree of type checking forobstandvart.I would be more interested in getting
TreeDataaway from subclassing, just likeMuDatano longer does. The private classesMuDatausesmudata/src/mudata/_core/mudata.py
Line 20 in 2ce2c18
should probably be public anyway for type-checking reasons. And with accessors coming in scanpy (and even with the current state of things), there are ways to keep interop without subclassing, just as
MuDatadoes.And if we really need subclassing, I'd rather discuss a contract than make our I/o mechanism even more porous without that. Or maybe even consider making trees a full part of the next anndata disk format, optionally perhaps in some form scverse/anndata#2060,
ilan-gold commentedon Oct 12, 2026
I am actually very open to this...
ilia-kats commentedon Oct 12, 2026
I think this is more a question of how to handle it generally. Using treedata functions directly would mean that mudata has on write to check if the modality is a treedata object and call the corresponding function, similarly on read. If more AnnData subclasses come along this really doesn't scale. One alternative would be to make AnnDatas IO registry public, so packages can register their own readers/writers, along with an entry point mechanism in AnnData that takes care of this so that the user doesn't need to import all the required packages himself. Then treedata can just register a
read_elem/write_elemmethod.What do you mean by that?
MuData was never a subclass of AnnData, it always relied on duck typing.
ilan-gold commentedon Oct 12, 2026
Ok I misremembered this - there used to be more unneeded private imports then.
I guess a
Protocol, mixin, rules about not overriding private methods (whichTreeDatadoes).I'm not fully opposed to this, but don't really see what it buys over "the user is aware that the
MuDataobject contains aTreeDataobject and usestreedatafunctions."If the export of the registry were done cleanly enough, I could see that being ok. That might make extensions of our on-disk format in the next iteration (I intend for it to be relatively open) actually easier so this seems reasonable notwithstanding my general objection to subclassing/silently hooking i.e., you have
treedatainstalled which automatically (or user-directly) edits the registry somewhere in the code that is not visible to the caller ofread_elem.colganwi commentedon Oct 13, 2026
Given @ilan-gold's concern about handling this within AnnData it seems like there are three possible alternatives:
read/writeexported by TreeData. This could be implemented without making TreeData a new dependency:Anndata exposes its IO registry, and treedata registers its reader and writer.
Trees are added to the AnnData disk format.
I'm happy to modify TreeData to support any of these. 1 seems like a decent short term solution that could be rolled back if 2 or 3 are ever implemented. @ilia-kats, I hear your point about scalability but currently this is an N=1 problem. For 2 we could add a
ad.io.registered_subtypes()function so the user could check the registry and see how it has been modified by loading treedata. For 3 I'd recommend a more flexible graph representation in AnnData so users can store directed/undirected graphs (lineage trees, GRNs, etc). If we go with this option MuData would still need some type checking to return a TreeData object if a tree is present.colganwi commentedon Oct 13, 2026
@ilan-gold I'm open to moving away from subclassing, and you're right that TreeData currently overrides private methods, so a contract would help either way. I'd like to avoid reimplementing AnnData's view and subsetting logic, so it would be great if those pieces were made public.
The biggest blocker for this is type checking in scanpy and and other scverse packages. Users should be able to call
sc.pp.pca(tdata)which would break ifisinstance(tdata, AnnData)returned false. To move away from subclassing we'd need either a Protocol/ABC those checks accept or relaxed duck typing.ilia-kats commentedon Oct 13, 2026
I'm not super familiar with TreeData, but if AnnData natively supports
obst/vart, couldn't all the other TreeData functionality be moved to an extension namespace?colganwi commentedon Oct 13, 2026
If AnnData natively supported
obst/vartTreeData could be deprecated, but I don't think this is what @ilan-gold is suggesting. Integratingobst/vartin their current form would require adding lineage tracing specific subsetting behavior (see alignment). I think this specific use case is better handled by a separate package. It makes more sense to add a general purpose graph representation to the AnnData on-disk format and potentially the API throughobsg/vargor similar.And
obst/vartbehavior cannot be be recreated through a namespace alone. The main thing TreeData provides is keeping trees aligned with obs/var through slicing and concat operations (e.g. subsetting prunes the trees), which only works if obst/vart are aligned mappings in AnnData.ilia-kats commentedon Oct 13, 2026
@ilan-gold
I don't see how the user can use treedata functions to write a MuData object to disk. Treedata itself is not aware of MuData, it can only write itself. To write out a MuData object (any MuData object, regardless of whether it contains TreeData or not), the user has to use
mdata.writeormudata.write_h5muormudata.write_zarr, which means that these functions have to be aware of TreeData or other AnnData subclasses.@colganwi OK, good to know. I'd be fine with the short-term solution proposed as point 1 as long as we agree on a more general long-term plan.
ilan-gold commentedon Oct 14, 2026
This is part of my hesitancy around exposing our io mechanisms - technically, a treedata object isn't an anndata object either (so a mudata with treedata in it is not a mudata object). The only reason any of this "works" is because TreeData subclasses.
ilan-gold commentedon Oct 14, 2026
My long term proposal would be to formalize either trees or "extension points" into the next anndata spec (the later may make more sense than the former). Other things would fall out from that like whether or not we need to expose the internals of our reader to support this behavior (I'm not sure we will need to do that TBH), whether there can be a subclass hook of some kind etc.
ilia-kats commentedon Oct 15, 2026
I'm in favor of extension points / subclass hooks. That's sort of what @colganwi proposed in this PR.
colganwi commentedon Oct 15, 2026
I opened #216 implementing option 1 as a short-term fix. It follows the discussion above and replaces the hook approach in #211.
treedata.write_tree_elemsand setsencoding-subtype = "treedata"on the group. encoding-type stays anndata, so older readers still load it as plain AnnData.treedata.read_tree_elems. If treedata is missing or the subtype is unknown, it warns and returns the AnnData.@ilia-kats @ilan-gold, does this look like an acceptable stopgap?
colganwi commentedon Oct 15, 2026
I agree, extension points seem like a good long term fix
ilia-kats commentedon Oct 15, 2026
I'm also just realizing that #83 is probably because people want to store EHRData objects inside MuData. Since EHRData now also has its own read/write implementation, that will also require handling in MuData or an extension point / subclass hook.