From 104e249d9e750741db7219bdb3bef3fb75121761 Mon Sep 17 00:00:00 2001 From: Shanika Amarasoma Date: Wed, 7 Oct 2026 21:38:49 +0530 Subject: [PATCH] Wire the generics the docs list to their methods, drop the sixteen with nothing behind them (#142) truecell.generics declared 72 functions and 39 had only the NotImplementedError fallback, so each raised for every object. The api-map listed many as the way to do things, and docs/api/generics.md says each is the same code path as the object's own method. Twenty-three now delegate to the method, property or log that already existed, with arguments handed through untouched so a signature has no second copy to drift. command reads the command log as R's Command() does, checked against SeuratObject's source: it errors on an unknown command, reads only params for a value, and shows a command run twice once, holding its latest run. Sixteen are removed. The five create_* constructors are the top-level functions, which take their input by keyword where a dispatcher on the first positional argument cannot. Nine have no counterpart in the port. check_matrix and match_cells had internal helpers behind them that do something other than R's CheckMatrix and MatchCells. Nothing could call any of them, so no working code changes. The api-map list and the 65 module-only generics that docs/api/index.md and test_docs.py count (now 54) follow. tests/test_generics.py walks the module and fails on a generic with no implementation, and on a mismatch in either direction with the api-map's list. Eight mutants, among them a stub re-declared, mis-wired delegates and the command log's semantics, each fail their own test. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 38 ++++ docs/api/index.md | 8 +- skills/truecell/reference/api-map.md | 21 +- tests/test_docs.py | 7 +- tests/test_generics.py | 276 +++++++++++++++++++++++++++ truecell/generics.py | 127 ++++++++++-- 6 files changed, 446 insertions(+), 31 deletions(-) create mode 100644 tests/test_generics.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c627ae..3996bb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 tutorial page keeps the published vignette's image on R's side, and the PBMC 3k comparison's numbers do not change. +### Removed + +- **Sixteen names from `truecell.generics`, none of which ever did anything (#142).** + Each was declared with only the `NotImplementedError` fallback, so each raised for + every type of object and no working code changes. + - R's constructors `create_truecell_object`, `create_assay_object`, `create_fov`, + `create_centroids` and `create_segmentation`. The top-level functions of the same + names are the constructors. They take their input by keyword, which a dispatcher + on the first positional argument cannot. + - Nothing in the port is behind `as_segmentation`, `as_seurat`, `assay_class`, + `default_dim_reduc`, `default_fov`, `hvf_info`, `keys`, `list_to_s4` and + `s4_to_list`. The last two are R's S4 plumbing, and `HVFInfo()`'s table is the + per-feature columns of `assay.meta_data`. + - `check_matrix` and `match_cells` had only internal helpers behind the same names, + and those do something other than R's `CheckMatrix` and `MatchCells`. + - `docs/api/index.md` and `tests/test_docs.py` count the generics that are + module-only: 65 became 54. + ### Fixed - **The CITE-seq tutorial's ADT-weight violins read as one comparison.** Reviewer 2 @@ -65,6 +83,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `tests/test_layer_feature_alignment.py` uses the standard workflow and checks that its own fixture can tell the two lookups apart. +- **The generics the docs list now work (#142).** `truecell.generics` declared 72 + functions and 39 had only the fallback, so they raised `NotImplementedError` for every + object. `skills/truecell/reference/api-map.md` listed many as the way to do things, + and `docs/api/generics.md` says each is the same code path as the object's own + method. + - Twenty-three now delegate to what already existed: `assay_names`, `calc_n`, + `cast_assay`, `reorder_ident`, `set_ident`, `tool`, `set_tool`, `version`, + `set_layer_data`, `set_assay_data`, `set_loadings`, `set_default_assay`, + `set_default_layer`, `set_variable_features`, `set_key`, `misc`, `set_misc`, and + the spatial `as_centroids`, `crop`, `overlay`, `default_boundary`, `get_molecules`, + plus `command`. Arguments are handed through untouched, so a method's signature + has no second copy to drift. + - `command` reads the command log as R's `Command()` does: no argument gives the + names of the commands that have run, a name gives that entry, and a second + argument gives one of its parameters. An unknown command or parameter is an error, + as in R, and a command run twice appears once, holding its latest run, as in + R's named list. + - `tests/test_generics.py` fails on a generic with no implementation, and on a + mismatch in either direction between the module and the api-map's list. + ### Documentation - **The README's roadmap and `ROADMAP.md` describe 2.0.0.** Both still read as of diff --git a/docs/api/index.md b/docs/api/index.md index 14e2cc0..de68d3e 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -7,10 +7,10 @@ reading; it is not a package layout you need to know. Two pages are the exception, and on those the import path shown is the one to use. The [generics](generics.md) live on `truecell.generics` — `truecell.generics.features(obj)`, not `truecell.features(obj)`, which raises -`AttributeError`. Seven of them are re-exported at the top level as well -(`create_truecell_object`, `create_assay_object`, `create_centroids`, -`create_segmentation`, `create_fov`, `get_tissue_coordinates`, `as_graph`); the -other 65 are not. The loaders on [Loading data](io.md) likewise stay on their own +`AttributeError`. Two of them are re-exported at the top level as well +(`get_tissue_coordinates`, `as_graph`); the other 54 are not. R's constructors +(`CreateSeuratObject`, `CreateFOV`, …) are the top-level `create_*` functions, not +generics. The loaders on [Loading data](io.md) likewise stay on their own modules: `truecell.io.read_10x`, `truecell.datasets.pbmc3k`, `truecell.compat.anndata.as_anndata`. diff --git a/skills/truecell/reference/api-map.md b/skills/truecell/reference/api-map.md index 7b09be0..bf7c07e 100644 --- a/skills/truecell/reference/api-map.md +++ b/skills/truecell/reference/api-map.md @@ -337,15 +337,22 @@ BLAS runtimes loaded. Its numba checks run in child processes. `reorder_ident` · `which_cells` · `fetch_data` · `layer_data` · `set_layer_data` · `layers` · `split_layers` · `join_layers` · `get_assay_data` · `set_assay_data` · `embeddings` · `loadings` · `set_loadings` · `stdev` · `variable_features` · -`set_variable_features` · `hvf_info` · `default_assay` · `set_default_assay` · -`set_default_layer` · `key` · `set_key` · `keys` · `assay_names` · `assay_class` · -`cast_assay` · `add_meta_data` · `rename_cells` · `match_cells` · `calc_n` · +`set_variable_features` · `default_assay` · `set_default_assay` · +`set_default_layer` · `key` · `set_key` · `assay_names` · +`cast_assay` · `add_meta_data` · `rename_cells` · `calc_n` · `command` · `misc` / `set_misc` · `tool` / `set_tool` · `version` · `as_sparse` · -`as_graph` · `as_neighbor` · `as_seurat` · `check_matrix` · `is_matrix_empty` · +`as_graph` · `as_neighbor` · `is_matrix_empty` · `simplify` · `distances` · `indices` · spatial: `boundaries` · `crop` · `overlay` · `radius` · `theta` · `get_image` · -`get_molecules` · `get_tissue_coordinates` · `default_boundary` · `default_fov` · -`is_global` · `as_centroids` · `as_segmentation` · `create_fov` · `create_centroids` · -`create_segmentation` +`get_molecules` · `get_tissue_coordinates` · `default_boundary` · +`is_global` · `as_centroids` + +Each one is the object's own method, property or log reached by its R name, so +`g.set_ident(obj, cells, "x")` and `obj.set_ident(cells, "x")` are the same call. +What R has and the port does not is not stubbed here. The constructors +(`CreateSeuratObject`, `CreateFOV`, …) are the top-level `create_*` functions, which +take their input by keyword; `HVFInfo()` is the per-feature columns of +`assay.meta_data`; `Keys()`, `DefaultFOV()`, `DefaultDimReduc()`, `as.Seurat()` and +the S4 conversions have no counterpart. See [`object-model.md`](object-model.md) for what each dispatches on. diff --git a/tests/test_docs.py b/tests/test_docs.py index 9c690e6..d3411e8 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -247,11 +247,10 @@ def test_the_generics_exception_the_api_index_documents_is_real(): public = {n for n in dir(generics) if not n.startswith("_") and callable(getattr(generics, n))} - also_top_level = {"create_truecell_object", "create_assay_object", "create_centroids", - "create_segmentation", "create_fov", "get_tissue_coordinates", "as_graph"} + also_top_level = {"get_tissue_coordinates", "as_graph"} assert public & exported == also_top_level - assert len(public - exported) == 65, ( - f"{len(public - exported)} generics are module-only; docs/api/index.md says 65" + assert len(public - exported) == 54, ( + f"{len(public - exported)} generics are module-only; docs/api/index.md says 54" ) # The specific call the paragraph warns about. assert not hasattr(truecell, "features") diff --git a/tests/test_generics.py b/tests/test_generics.py new file mode 100644 index 0000000..21fd818 --- /dev/null +++ b/tests/test_generics.py @@ -0,0 +1,276 @@ +"""``truecell.generics`` declares only what something implements. + +Thirty-nine of its seventy-two generics had only the ``NotImplementedError`` +fallback registered, so each raised for every type of object, and +``skills/truecell/reference/api-map.md`` listed many of them as the way to do +things (``set_ident``, ``set_variable_features``, ``hvf_info``, …). Nothing walked +the module, and the api-map's list is prose, so no test read it either. + +A generic stays where the object has a method, a property or a log behind it, and +delegates to that, which is the "same code path" ``docs/api/generics.md`` promises. +The ones with nothing behind them, or with a different meaning from R's, are gone. +""" +import importlib +import pathlib +import pkgutil +import re + +import numpy as np +import pandas as pd +import pytest +import scipy.sparse as sp + +import truecell +from truecell import generics as g + +ROOT = pathlib.Path(__file__).resolve().parents[1] + + +def _import(name): + try: + return importlib.import_module(name) + except ImportError: # an extra that is not installed + return None + + +def _generics(): + for module in pkgutil.walk_packages(truecell.__path__, "truecell."): + _import(module.name) # so that every @register has run + return {n: f for n, f in vars(g).items() if not n.startswith("_") and hasattr(f, "registry")} + + +# --------------------------------------------------------------------------- +# What is declared is implemented, and what is documented is declared +# --------------------------------------------------------------------------- + +def test_every_generic_has_an_implementation(): + stubs = sorted(name for name, generic in _generics().items() + if all(getattr(impl, "_is_stub", False) for impl in generic.registry.values())) + assert not stubs, f"declared, but implemented for no type: {stubs}" + + +def test_the_fallback_is_what_marks_a_stub(): + """The check above reads `_is_stub`, so it must be on the fallback and only there.""" + fallback = g.cells.registry[object] + assert fallback._is_stub is True + assert not any(getattr(impl, "_is_stub", False) + for impl in g.cells.registry.values() if impl is not fallback) + + +def _backticked(text): + return set(re.findall(r"`([a-z][a-z_0-9]*)`", text)) + + +def test_the_api_maps_generics_are_all_declared(): + """The list is prose, so `test_api_map_signatures` cannot read it.""" + text = (ROOT / "skills/truecell/reference/api-map.md").read_text() + section = text.split("## Generics", 1)[1].split("\n## ", 1)[0] + listed = _backticked(section) + assert len(listed) > 40 # the section was found, not an empty one + assert not listed - set(_generics()), "listed as a generic, but not in truecell.generics" + assert not set(_generics()) - listed, "a generic the api-map does not list" + + +def test_the_generics_the_skill_names_are_declared(): + text = (ROOT / "skills/truecell/SKILL.md").read_text() + paragraph = text.split("**6. The generics are not top-level.**", 1)[1].split("```", 1)[0] + named = _backticked(paragraph) - {"truecell"} + assert len(named) > 10 + assert not named - set(_generics()) + + +@pytest.mark.parametrize("name", [ + "as_segmentation", "as_seurat", "assay_class", "check_matrix", "create_assay_object", + "create_centroids", "create_fov", "create_segmentation", "create_truecell_object", + "default_dim_reduc", "default_fov", "hvf_info", "keys", "list_to_s4", "match_cells", + "s4_to_list", +]) +def test_a_generic_with_nothing_behind_it_is_gone(name): + """Not the constructors either: `truecell.create_fov(coords=...)` takes its input by + keyword, which a dispatcher on the first positional argument cannot.""" + assert not hasattr(g, name) + + +# --------------------------------------------------------------------------- +# Each delegate is the object's own method, property or log +# --------------------------------------------------------------------------- + +@pytest.fixture +def obj(): + """The standard workflow on 60 genes and 30 cells, with an ADT assay beside RNA.""" + rng = np.random.default_rng(0) + o = truecell.create_truecell_object( + counts=sp.csc_matrix(rng.poisson(2.0, size=(60, 30)).astype(float)), + feature_names=[f"g{i}" for i in range(60)], + cell_names=[f"c{j}" for j in range(30)], + ) + truecell.normalize_data(o) + truecell.find_variable_features(o, nfeatures=20) + truecell.scale_data(o) + truecell.run_pca(o, n_pcs=5) + o.assays["ADT"] = truecell.create_assay5_object( + counts=sp.csc_matrix(rng.poisson(5.0, size=(4, 30)).astype(float)), + feature_names=list("abcd"), cell_names=o.cell_names(), key="adt_") + return o + + +def test_assay_names_and_version(obj): + assert g.assay_names(obj) == obj.assay_names() == ["RNA", "ADT"] + assert g.version(obj) == obj.version + + +def test_set_default_assay_goes_through_the_property_and_its_check(obj): + g.set_default_assay(obj, "ADT") + assert obj.default_assay == "ADT" + with pytest.raises(KeyError, match="not found"): + g.set_default_assay(obj, "nope") + reduction = obj.reductions["pca"] # reductions carry their own + g.set_default_assay(reduction, "ADT") + assert g.default_assay(reduction) == "ADT" + + +def test_set_ident_and_reorder_ident(obj): + g.set_ident(obj, ["c0", "c1"], "special") + assert list(obj.idents[:2]) == ["special", "special"] + + obj.idents = pd.Categorical(["A"] * 10 + ["B"] * 10 + ["C"] * 10) + obj.meta_data["score"] = -np.arange(30, dtype=float) # C has the lowest mean, then B + g.reorder_ident(obj, "score") + assert list(obj.idents.categories) == ["C", "B", "A"] + + +def test_tool_and_set_tool(obj): + g.set_tool(obj, "k", {"a": 1}) + assert g.tool(obj, "k") == {"a": 1} == obj.tool("k") == obj.tools["k"] + + +def test_misc_and_set_misc_on_every_container(obj): + g.set_misc(obj, 3, "n") # Misc(x, slot) <- value + assert g.misc(obj, "n") == 3 == obj.misc["n"] + g.set_misc(obj, {"z": 1}) # Misc(x) <- value replaces the list + assert g.misc(obj) is obj.misc and obj.misc == {"z": 1} + for part in (obj.get_assay(), obj.reductions["pca"]): + g.set_misc(part, "v", "slot") + assert g.misc(part, "slot") == "v" == part.misc["slot"] + + +def test_set_variable_features_for_an_object_and_for_its_assay(obj): + assay = obj.get_assay() + g.set_variable_features(obj, ["g3", "g1", "g2"]) + assert g.variable_features(obj) == assay.variable_features == ["g3", "g1", "g2"] + g.set_variable_features(assay, ["g5"]) + assert assay.variable_features == ["g5"] + g.set_variable_features(obj, ["a", "b"], assay="ADT") + assert obj.get_assay("ADT").variable_features == ["a", "b"] + assert assay.variable_features == ["g5"] # the other assay is left alone + + +def test_set_key_and_set_default_layer(obj): + assay, reduction = obj.get_assay(), obj.reductions["pca"] + g.set_key(assay, "newkey_") + g.set_key(reduction, "PCX_") + assert g.key(assay) == assay.key == "newkey_" and reduction.key == "PCX_" + g.set_default_layer(assay, "data") + assert assay.default_layer == "data" + with pytest.raises(KeyError, match="not found"): + g.set_default_layer(assay, "no_such_layer") + + +def test_layer_setters_and_calc_n(obj): + assay = obj.get_assay() + doubled = assay.layer_data("counts") * 2 + g.set_layer_data(assay, "doubled", doubled) + g.set_assay_data(assay, "also_doubled", doubled) # SetAssayData on a v5 assay is LayerData<- + for name in ("doubled", "also_doubled"): + assert (assay.layer_data(name) != doubled).nnz == 0 + pd.testing.assert_frame_equal(g.calc_n(assay), assay.calc_n()) + assert g.cast_assay(assay).layers.keys() == assay.cast_assay().layers.keys() + + +def test_set_assay_data_on_a_v3_assay(): + rng = np.random.default_rng(1) + o = truecell.create_truecell_object( + counts=sp.csc_matrix(rng.poisson(2.0, size=(10, 6)).astype(float)), + feature_names=[f"g{i}" for i in range(10)], cell_names=list("uvwxyz"), use_v5=False) + assay = o.get_assay() + new = sp.csc_matrix(np.ones((10, 6))) + g.set_assay_data(assay, "data", new) + assert (assay.get_assay_data("data") != new).nnz == 0 + pd.testing.assert_frame_equal(g.calc_n(assay), assay.calc_n()) + + +def test_set_loadings(obj): + reduction = obj.reductions["pca"] + doubled = g.loadings(reduction) * 2 + g.set_loadings(reduction, doubled) + np.testing.assert_array_equal(g.loadings(reduction), doubled) + + +# ---- the command log ---- + +def test_command_lists_what_has_run_and_reads_one_back(obj): + assert {"NormalizeData.RNA", "FindVariableFeatures.RNA", "ScaleData.RNA"} <= set(g.command(obj)) + entry = g.command(obj, "FindVariableFeatures.RNA") + assert entry is obj.commands[[c.key for c in obj.commands].index("FindVariableFeatures.RNA")] + assert g.command(obj, "FindVariableFeatures.RNA", "nfeatures") == 20 + + +def test_command_errors_as_r_does(obj): + with pytest.raises(KeyError, match="has not been run or is not a valid command"): + g.command(obj, "NoSuchCommand") + # `value` reads the parameters only: R checks `names(params)`, not the slots + with pytest.raises(KeyError, match="is not a valid parameter for FindVariableFeatures"): + g.command(obj, "FindVariableFeatures.RNA", "name") + + +def test_a_command_run_twice_keeps_one_entry_holding_the_latest(obj): + """`obj@commands` is a named list in R, so a second `FindVariableFeatures` replaces + the first in its place; `obj.commands` is a list that grows.""" + truecell.find_variable_features(obj, nfeatures=10) + keys = [c.key for c in obj.commands] + assert keys.count("FindVariableFeatures.RNA") == 2 + names = g.command(obj) + assert names.count("FindVariableFeatures.RNA") == 1 + assert names.index("FindVariableFeatures.RNA") == keys.index("FindVariableFeatures.RNA") + assert g.command(obj, "FindVariableFeatures.RNA", "nfeatures") == 10 + + +# ---- spatial ---- + +@pytest.fixture +def fov(): + rng = np.random.default_rng(7) + cells = [f"c{i}" for i in range(20)] + coords = pd.DataFrame({"x": rng.uniform(0, 100, 20), "y": rng.uniform(0, 100, 20), "cell": cells}) + molecules = pd.DataFrame({ + "x": rng.uniform(0, 100, 60), "y": rng.uniform(0, 100, 60), + "gene": [f"m{i % 3}" for i in range(60)], "cell": [cells[i % 20] for i in range(60)]}) + f = truecell.create_fov(coords, type_="centroids") + f.molecules = {"rna": truecell.create_molecules(molecules)} + return f + + +def test_fov_delegates(fov): + assert g.default_boundary(fov) == fov.default_boundary() is not None + cropped = g.crop(fov, (0, 50), (0, 50)) + assert cropped.cells() == fov.crop((0, 50), (0, 50)).cells() + assert 0 < len(cropped.cells()) < len(fov.cells()) # it cropped something + assert g.overlay(fov, cropped) == fov.overlay(cropped) + assert g.get_molecules(fov, "rna") is fov.get_molecules("rna") + assert g.get_molecules(fov) == fov.get_molecules() + + +def test_a_visium_image_is_an_fov_so_it_dispatches_the_same(): + from truecell.spatial.fov import FOV + from truecell.spatial.visium import VisiumV2 + for generic in (g.crop, g.overlay, g.default_boundary, g.get_molecules): + assert generic.dispatch(VisiumV2) is generic.dispatch(FOV) + assert not getattr(generic.dispatch(VisiumV2), "_is_stub", False) + + +def test_as_centroids_of_a_segmentation(): + rows = [{"x": float(x), "y": float(y), "cell": c} + for c in ("a", "b") for x, y in ((0, 0), (4, 0), (4, 4), (0, 4))] + segmentation = truecell.create_segmentation(pd.DataFrame(rows)) + pd.testing.assert_frame_equal(g.as_centroids(segmentation).get_tissue_coordinates(), + segmentation.as_centroids().get_tissue_coordinates()) diff --git a/truecell/generics.py b/truecell/generics.py index ae60e2e..bffe2f3 100644 --- a/truecell/generics.py +++ b/truecell/generics.py @@ -3,6 +3,14 @@ Each public function dispatches on the first argument's type. The base (object) implementation raises NotImplementedError so unregistered types get a clear message. + +A generic is declared here only where something implements it: the object's own +method, property or log, reached by its R name, which is the "same code path" +``docs/api/generics.md`` promises. R's constructors (``CreateSeuratObject``, +``CreateFOV``, …) are not here, because the top-level factories take their input +by keyword and a dispatcher cannot; nor is anything the port has no counterpart +for, such as the S4 plumbing. ``tests/test_generics.py`` fails on a generic with +no implementation. """ from __future__ import annotations @@ -14,6 +22,7 @@ def _impl(x, *args, **kwargs): raise NotImplementedError( f"{func_name}() is not implemented for {type(x).__name__}." ) + _impl._is_stub = True # type: ignore[attr-defined] return _impl @@ -49,7 +58,6 @@ def _generic(name: str): command = _generic("command") version = _generic("version") key = _generic("key") -keys = _generic("keys") # ====================================================================== # DATA ASSIGNMENT @@ -83,15 +91,12 @@ def _generic(name: str): assay_names = _generic("assay_names") default_assay = _generic("default_assay") cast_assay = _generic("cast_assay") -create_assay_object = _generic("create_assay_object") calc_n = _generic("calc_n") -assay_class = _generic("assay_class") # ====================================================================== # REDUCTION / NEIGHBOR # ====================================================================== -default_dim_reduc = _generic("default_dim_reduc") as_neighbor = _generic("as_neighbor") # ====================================================================== @@ -107,33 +112,23 @@ def _generic(name: str): # ====================================================================== variable_features = _generic("variable_features") -hvf_info = _generic("hvf_info") # ====================================================================== # OBJECT CREATION / CONVERSION # ====================================================================== -create_truecell_object = _generic("create_truecell_object") -as_seurat = _generic("as_seurat") as_graph = _generic("as_graph") as_sparse = _generic("as_sparse") -s4_to_list = _generic("s4_to_list") -list_to_s4 = _generic("list_to_s4") # ====================================================================== # SPATIAL # ====================================================================== -create_fov = _generic("create_fov") -create_segmentation = _generic("create_segmentation") -create_centroids = _generic("create_centroids") as_centroids = _generic("as_centroids") -as_segmentation = _generic("as_segmentation") crop = _generic("crop") overlay = _generic("overlay") simplify = _generic("simplify") boundaries = _generic("boundaries") -default_fov = _generic("default_fov") default_boundary = _generic("default_boundary") get_molecules = _generic("get_molecules") radius = _generic("radius") @@ -145,8 +140,6 @@ def _generic(name: str): is_global = _generic("is_global") is_matrix_empty = _generic("is_matrix_empty") -check_matrix = _generic("check_matrix") -match_cells = _generic("match_cells") rename_cells = _generic("rename_cells") # ====================================================================== @@ -392,5 +385,107 @@ def _an_g(x): return x.as_neighbor() def _asp_nd(x, fmt="csc"): return sp.csc_matrix(x) if fmt == "csc" else sp.csr_matrix(x) + # ------------------------------------------------------------------ + # Delegates: the object's own method, property or log, by its R name + # ------------------------------------------------------------------ + # `docs/api/generics.md` says each generic is the same code path as the method, + # so these hand their arguments through untouched. A signature copied here would + # be a second place to drift, which is how 39 generics came to be declared and + # never wired to anything. + + def _delegate(generic, classes, method): + def impl(x, *args, **kwargs): + return getattr(x, method)(*args, **kwargs) + for cls in classes: + generic.register(cls)(impl) + + # methods + _delegate(assay_names, (Truecell,), "assay_names") + _delegate(calc_n, (Assay, StdAssay), "calc_n") + _delegate(cast_assay, (StdAssay,), "cast_assay") + _delegate(reorder_ident, (Truecell,), "reorder_ident") + _delegate(set_ident, (Truecell,), "set_ident") + _delegate(tool, (Truecell,), "tool") + _delegate(set_tool, (Truecell,), "set_tool") + _delegate(set_layer_data, (StdAssay,), "set_layer_data") + _delegate(set_assay_data, (Assay,), "set_assay_data") + _delegate(set_loadings, (DimReduc,), "set_loadings") + _delegate(set_default_assay, (DimReduc, Graph, SpatialImage), "set_default_assay") + # spatial; VisiumV2 is an FOV + _delegate(as_centroids, (Segmentation,), "as_centroids") + _delegate(crop, (FOV,), "crop") + _delegate(overlay, (FOV,), "overlay") + _delegate(default_boundary, (FOV,), "default_boundary") + _delegate(get_molecules, (FOV,), "get_molecules") + + # properties and attributes + @set_assay_data.register(StdAssay) + def _sad_std(x, layer, new_data, **kwargs): + return x.set_layer_data(layer, new_data, **kwargs) + + @set_default_assay.register(Truecell) + def _sda_s(x, value): + x.default_assay = value + + @set_default_layer.register(StdAssay) + def _sdl_std(x, value): + x.default_layer = value + + def _set_variable_features(x, features): + x.variable_features = list(features) + + set_variable_features.register(Assay)(_set_variable_features) + set_variable_features.register(StdAssay)(_set_variable_features) + + @set_variable_features.register(Truecell) + def _svf_s(x, features, assay=None): + x.get_assay(assay).variable_features = list(features) + + def _set_key(x, value): + x.key = value + + def _misc(x, slot=None): + return x.misc if slot is None else x.misc[slot] + + def _set_misc(x, value, slot=None): + # Misc(x) <- value replaces the whole list; Misc(x, slot) <- value one entry. + if slot is None: + x.misc = dict(value) + else: + x.misc[slot] = value + + for keyed in (Assay, StdAssay, DimReduc, SpatialImage): + set_key.register(keyed)(_set_key) + for container in (Truecell, Assay, StdAssay, DimReduc, SpatialImage): + misc.register(container)(_misc) + set_misc.register(container)(_set_misc) + + @version.register(Truecell) + def _ver_s(x): + return x.version + + # the command log + @command.register(Truecell) + def _command_s(x, command=None, value=None): + """R's ``Command()``: the commands that have run, one of them, or one parameter. + + ``obj@commands`` is a named list in R, so a command run twice keeps one entry, + in the place of the first run and holding the latest. ``x.commands`` is a + list that grows with every run, so the same view is taken here. As in R, an + unknown command or parameter is an error, and ``value`` reads ``params`` + only, not the name or the time stamp. + """ + latest = {entry.key: entry for entry in x.commands} + if command is None: + return list(latest) + if command not in latest: + raise KeyError(f"{command} has not been run or is not a valid command.") + entry = latest[command] + if value is None: + return entry + if value not in entry.params: + raise KeyError(f"{value} is not a valid parameter for {entry.name}.") + return entry.params[value] + _register_all()