Skip to content

AnnData subclass modalities (e.g. TreeData) lose their extra elements and type on write_h5mu/write_zarr + read #210

Open

Description

@pedrocr83

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 False

The 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 attribute mudata-modality-class = "module:qualname".
  • On read, if that attribute is present, mudata imports the class and returns cls._read_mudata_extras(group, adata), where adata is 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_elem still 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

  1. ilia-kats commented on Oct 12, 2026

    @ilia-kats
    Collaborator

    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 write encoding-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 inside read_elem / write_elem. @ilan-gold what do you think?

  2. colganwi commented on Oct 12, 2026

    @colganwi
    Contributor

    I agree this probably belong in AnnData. Extending AnnData's read_elm/write_elm to 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.

  3. ilan-gold commented on Oct 12, 2026

    @ilan-gold
    Contributor

    Can treedata export its own read/write function for mudata? It seems like less work for identical cost - you need treedata installed in your env to read treedata anyway and will likely need some degree of type checking for obst and vart.

    I would be more interested in getting TreeData away from subclassing, just like MuData no longer does. The private classes MuData uses

    from anndata._core.aligned_mapping import AlignedView, AxisArrays, AxisArraysBase, PairwiseArrays

    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 MuData does.

    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,

  4. ilan-gold commented on Oct 12, 2026

    @ilan-gold
    Contributor

    Or maybe even consider making trees a full part of the next anndata disk format, optionally perhaps in some form scverse/anndata#2060,

    I am actually very open to this...

  5. ilia-kats commented on Oct 12, 2026

    @ilia-kats
    Collaborator

    Can treedata export its own read/write function for mudata? It seems like less work for identical cost - you need treedata installed in your env to read treedata anyway and will likely need some degree of type checking for obst and vart.

    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_elem method.

    And if we really need subclassing, I'd rather discuss a contract

    What do you mean by that?

    I would be more interested in getting TreeData away from subclassing, just like MuData no longer does.

    MuData was never a subclass of AnnData, it always relied on duck typing.

  6. ilan-gold commented on Oct 12, 2026

    @ilan-gold
    Contributor

    MuData was never a subclass of AnnData, it always relied on duck typing.

    Ok I misremembered this - there used to be more unneeded private imports then.

    What do you mean by that?

    I guess a Protocol, mixin, rules about not overriding private methods (which TreeData does).

    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_elem method.

    I'm not fully opposed to this, but don't really see what it buys over "the user is aware that the MuData object contains a TreeData object and uses treedata functions."

    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 treedata installed which automatically (or user-directly) edits the registry somewhere in the code that is not visible to the caller of read_elem.

  7. colganwi commented on Oct 13, 2026

    @colganwi
    Contributor

    Given @ilan-gold's concern about handling this within AnnData it seems like there are three possible alternatives:

    1. MuData does some minimal type checking and then calls read/write exported by TreeData. This could be implemented without making TreeData a new dependency:
    # write, inside the per-modality loop, after the AnnData elements
    td = sys.modules.get("treedata")            # only if the user already imported treedata
    if td is not None and isinstance(adata, td.TreeData):
        td.write_tree_elems(group, adata, dataset_kwargs=kwargs)
    
    # read, per modality
    if "obst" in group or "vart" in group:      # marker: tree elements present
        try:
            import treedata as td
        except ImportError:
            warn("...tree data present but treedata is not installed; reading as AnnData")
    
    1. Anndata exposes its IO registry, and treedata registers its reader and writer.

    2. 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.

  8. colganwi commented on Oct 13, 2026

    @colganwi
    Contributor

    I would be more interested in getting TreeData away from subclassing, just like MuData no longer does.

    @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 if isinstance(tdata, AnnData) returned false. To move away from subclassing we'd need either a Protocol/ABC those checks accept or relaxed duck typing.

  9. ilia-kats commented on Oct 13, 2026

    @ilia-kats
    Collaborator

    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.

    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?

  10. colganwi commented on Oct 13, 2026

    @colganwi
    Contributor

    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?

    If AnnData natively supported obst/vart TreeData could be deprecated, but I don't think this is what @ilan-gold is suggesting. Integrating obst/vart in 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 through obsg/varg or similar.

    And obst/vart behavior 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.

  11. ilia-kats commented on Oct 13, 2026

    @ilia-kats
    Collaborator

    @ilan-gold

    don't really see what it buys over "the user is aware that the MuData object contains a TreeData object and uses treedata functions."

    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.write or mudata.write_h5mu or mudata.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.

  12. ilan-gold commented on Oct 14, 2026

    @ilan-gold
    Contributor

    I don't see how the user can use treedata functions to write a MuData object to disk.

    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.

  13. ilan-gold commented on Oct 14, 2026

    @ilan-gold
    Contributor

    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.

    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.

  14. ilia-kats commented on Oct 15, 2026

    @ilia-kats
    Collaborator

    I'm in favor of extension points / subclass hooks. That's sort of what @colganwi proposed in this PR.

  15. colganwi commented on Oct 15, 2026

    @colganwi
    Contributor

    I opened #216 implementing option 1 as a short-term fix. It follows the discussion above and replaces the hook approach in #211.

    • Write: if treedata is already imported and a modality is a TreeData, mudata calls treedata.write_tree_elems and sets encoding-subtype = "treedata" on the group. encoding-type stays anndata, so older readers still load it as plain AnnData.
    • Read: the subtype selects treedata.read_tree_elems. If treedata is missing or the subtype is unknown, it warns and returns the AnnData.
    • Registry: subtypes live in a small private registry (name → module, class, writer, reader). It isn't a public hook, so mudata decides what it calls. All of it sits in two helpers, so it can be swapped out if the extension points in the next anndata spec land. I'm happy to help with that spec.

    @ilia-kats @ilan-gold, does this look like an acceptable stopgap?

  16. colganwi commented on Oct 15, 2026

    @colganwi
    Contributor

    I'm in favor of extension points / subclass hooks. That's sort of what @colganwi proposed in this PR.

    I agree, extension points seem like a good long term fix

  17. ilia-kats commented on Oct 15, 2026

    @ilia-kats
    Collaborator

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions