diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index e6f7dc4..524bc84 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -948,7 +948,14 @@ is the first suspect. requested display settings intact. A second pass over `xenium.zarr` (whose `obsm` holds only `spatial`) runs an embedding recipe and asserts the checkpoint comes back with the embedding canvas the read could not have built, and no duplicate spatial one; it prints - a `[skip]` line when that fixture is absent. + a `[skip]` line when that fixture is absent. A third pass needs no fixture: it writes a + SpatialData `.zarr.zip` shaped like an instrument export (two wells placed in a shared + `global` system, region-local coordinates stored as an `X`/`Y` data frame, a points + element, several tables with the cell table not first, the store one folder down in + the archive) and reads it as the workflow's `spatialdata` type does, asserting the + points are left out, the session and the sidecar open on the chosen table, and the + wells are stitched into `obsm['spatial_global']` (and that world coordinates already + in `obsm['spatial']` are not stitched again). - `cd backend && PYTHONPATH=. python test_compression.py` — dataset-free unit test for `SelectiveGZipMiddleware`: which content types compress, round-trip/passthrough correctness, and the regression guard that gzip runs off the event loop (a @@ -962,7 +969,8 @@ is the first suspect. `data_types.json` against its schema, checks every recipe it names exists, verifies each common parameter's `applies_to` really is the set of types whose recipes declare it, checks each type's display default colours by a parameter that applies to it, - checks the params agree across `nextflow.config` and `nextflow_schema.json`, checks every + checks the params agree across `nextflow.config` and `nextflow_schema.json`, checks each + `reader_params_from` entry names a real param, checks every `companion_files` rule matches a file the fixture lays down (a rule whose suffix has a typo never fires and reports nothing, which reads as "no problem found"), and runs discovery over a synthetic tree of every catalogued type, asserting both the diff --git a/backend/app/persistence/store.py b/backend/app/persistence/store.py index bea8240..fa7eddf 100644 --- a/backend/app/persistence/store.py +++ b/backend/app/persistence/store.py @@ -243,7 +243,7 @@ def version_stack(path: str) -> sds_layers.Stack | None: return stack -def read_spatialdata_archive(path: str, progress=None): +def read_spatialdata_archive(path: str, progress=None, selection: tuple[str, ...] | None = None): """Read a SpatialData zarr store from a bare `.zarr` directory, a `.zarr.zip`, a `.zarr.tar.gz` archive, or a saved version's folder (`version_stack`). Returns (sdata, extract_dir, hash_check); `extract_dir` is the temp directory an archive was @@ -252,8 +252,15 @@ def read_spatialdata_archive(path: str, progress=None): `hash_check` is the embedded-content-hash verification result (`_hash_result`), or None when the name carries no hash to verify. Shared by the checkpoint load path and the SpatialData-zarr import reader. `progress(message, pct)` (optional) reports - extraction/read progress; see `create_from_load`.""" + extraction/read progress; see `create_from_load`. + + `selection` names the element groups to read (spatialdata's own `read_zarr` + selection: images, labels, points, shapes, tables); None reads them all. A `.zarr.zip` + without an embedded hash is also extracted without the groups left out, which is + what makes a store whose points dwarf everything else openable at all: an instrument + export can carry tens of GB of transcript points that nothing here draws.""" report = progress or (lambda *a, **k: None) + sel = tuple(selection) if selection else None if (stack := version_stack(path)) is not None: with _extraction_dir() as extract_dir: report("Assembling the version…") @@ -270,21 +277,21 @@ def read_spatialdata_archive(path: str, progress=None): # extracted anyway. sds_layers.flatten(stack, Path(extract_dir), link=False) report("Reading data tables…") - return sd.read_zarr(extract_dir), extract_dir, None + return _read_store(extract_dir, sel), extract_dir, None if path.endswith((".zarr.tar.gz", ".zarr.tgz")): with _extraction_dir() as extract_dir: report("Extracting checkpoint…") with tarfile.open(path, "r:gz") as tf: tf.extractall(extract_dir, filter="data") report("Reading data tables…") - return sd.read_zarr(_zarr_root(extract_dir)), extract_dir, None + return _read_store(_zarr_root(extract_dir), sel), extract_dir, None if path.endswith(".zarr.zip") or (os.path.isfile(path) and zipfile.is_zipfile(path)): with _extraction_dir() as extract_dir: expected = _expected_content_hash(path) if expected is None: report("Extracting checkpoint…") with zipfile.ZipFile(path) as zf: - zf.extractall(extract_dir) + zf.extractall(extract_dir, members=_selected_members(zf.namelist(), sel)) hash_check = None else: # Auto-named checkpoint: recompute the embedded content hash while @@ -292,9 +299,52 @@ def read_spatialdata_archive(path: str, progress=None): # verification costs no extra read pass over the archive. hash_check = _extract_zip_verifying(path, extract_dir, expected, report) report("Reading data tables…") - return sd.read_zarr(_zarr_root(extract_dir)), extract_dir, hash_check + return _read_store(_zarr_root(extract_dir), sel), extract_dir, hash_check report("Reading data tables…") - return sd.read_zarr(path), None, None + return _read_store(path, sel), None, None + + +_ELEMENT_GROUPS = ("images", "labels", "points", "shapes", "tables") + + +def _read_store(root: str, selection: tuple[str, ...] | None): + """`sd.read_zarr`, with the table this app saved first put first again. + + spatialdata reads tables back sorted by name, while the session, the saved displays + and the viewer all go by the first table, and the viewer takes it from the sidecar's + `table_keys`, which keeps the order they were saved in. Without this a checkpoint + whose open table does not sort first opens on that table in the viewer but on + another one in the Studio.""" + from ..registry.reader_fixes import table_first + + sdata = sd.read_zarr(root, selection=selection) + try: + saved = zarr.open_group(root, mode="r", use_consolidated=False)[VIEWER_GROUP].attrs.get("table_keys") + except KeyError: + return sdata + if saved and saved[0] in sdata.tables: + table_first(sdata, saved[0]) + return sdata + + +def _selected_members(names: list[str], selection: tuple[str, ...] | None) -> list[str] | None: + """The archive members to extract when only `selection`'s element groups are read: + everything except the members of an element group left out. None (extract all) when + nothing is left out. + + The store may sit at the archive root or one folder down (`_zarr_root` reads either), + so a member's element group is its first path part below that root.""" + if selection is None: + return None + skipped = set(_ELEMENT_GROUPS) - set(selection) + if not skipped: + return None + tops = {n.split("/", 1)[0] for n in names} + nested = (len(tops) == 1 and not any(n in ("zarr.json", ".zgroup") for n in names) + and all("/" in n for n in names)) + depth = 1 if nested else 0 + return [n for n in names + if len(parts := n.split("/")) <= depth or parts[depth] not in skipped] def _extract_zip_verifying(path: str, extract_dir: str, expected: str, diff --git a/backend/app/registry/custom/README.md b/backend/app/registry/custom/README.md index 6de9ba9..83a7b88 100644 --- a/backend/app/registry/custom/README.md +++ b/backend/app/registry/custom/README.md @@ -181,6 +181,18 @@ plots and the rest of the `app_state` in the object are not reloaded (raw import not a checkpoint reload), but a compute history recorded by this app is carried into the new session so the provenance of the data stays visible in History. +Two optional parameters suit a store written by an instrument or another program. +**selection** names the element groups to read (images, labels, points, shapes, +tables): leaving out points skips unpacking them, which can be most of an export's +size, and nothing draws them. **table** names the table to open on, for a store +holding several; otherwise it is the first by name. A store from elsewhere is also +brought into the shape the viewer reads. Cell coordinates stored as a data frame of +`X`/`Y` columns in `obsm['spatial']` become an array. A table spanning several regions +(a plate's wells, a slide's fields of view) whose coordinates are relative to each +region gets the stitched world coordinates as `obsm['spatial_']`, so the +regions are laid out side by side instead of drawn on one origin; this happens only +when the coordinates fit their regions as local ones and not as world ones. + **Citation:** SpatialData (Marconato et al., Nat Methods 22, 58-62 (2025)); `.zarr.zip` / `.zarr.tar.gz` archive extraction and saved-version reading original to this repository. diff --git a/backend/app/registry/custom/read_spatialdata.py b/backend/app/registry/custom/read_spatialdata.py index 9e4aa75..7e2f353 100644 --- a/backend/app/registry/custom/read_spatialdata.py +++ b/backend/app/registry/custom/read_spatialdata.py @@ -7,6 +7,7 @@ path.""" from __future__ import annotations +import shutil import traceback from ..base import CallResult, Function, ParamSpec, capture_log, short_error @@ -17,6 +18,16 @@ tooltip=("Path to a SpatialData store: a .zarr directory, a .zarr.zip / .zarr.tar.gz " "archive, or the folder of a version saved in the Cirro app"), path_kind="either") +_SELECTION_PARAM = ParamSpec( + "selection", {"type": "array", "items": {"type": "string", + "enum": ["images", "labels", "points", "shapes", "tables"]}}, + "multitext", None, required=False, + tooltip=("Element groups to read (images, labels, points, shapes, tables); empty reads " + "them all. Leaving out points skips unpacking them, which is most of an " + "instrument export's size and is never drawn")) +_TABLE_PARAM = ParamSpec.text( + "table", default=None, + tooltip="Table to open the session on, for a store holding several; empty keeps the store's first") class ReadSpatialDataZarr(Function): @@ -53,19 +64,46 @@ class ReadSpatialDataZarr(Function): store Path to the SpatialData store (a `.zarr` directory, a `.zarr.zip` / `.zarr.tar.gz` archive, or a saved version's folder) under the data directory. +selection + The element groups to read; empty reads them all. Leaving out `points` is how a + store carrying tens of GB of transcript points opens at all: the viewer never + draws them, and they are not unpacked. +table + The table to open the session on, moved to the front of the store's tables (the + session and a saved checkpoint both open on the first). Empty keeps the store's + own order. + +A store written by other software is also brought into the shape the viewer reads: +a table's `obsm['spatial']` stored as a data frame of coordinate columns becomes an +array, and a table spanning several regions whose coordinates are region-local gains +the stitched ones (see `sessions/transform.stitch_world_coordinates`). """ - params = [_STORE_PARAM] + params = [_STORE_PARAM, _SELECTION_PARAM, _TABLE_PARAM] def execute(self, params: dict, session) -> CallResult: from ...persistence.store import read_spatialdata_archive + from ...sessions.transform import stitch_world_coordinates + from .. import reader_fixes store = params.get("store") if not store: return CallResult(status="failed", error="a store path is required") + extract_dir = None with capture_log() as buf: try: - sdata, extract_dir, _ = read_spatialdata_archive(store) + sdata, extract_dir, _ = read_spatialdata_archive( + store, selection=params.get("selection") or None) + if params.get("table"): + sdata = reader_fixes.table_first(sdata, params["table"]) + reader_fixes.spatial_coordinates_as_array(sdata) + for name, table in sdata.tables.items(): + if (key := stitch_world_coordinates(sdata, table)) is not None: + print(f"table {name!r}: region-local obsm['spatial'] stitched into obsm[{key!r}]") except Exception as e: + # The archive reader cleans up a failed unpack itself; a correction that + # fails after it leaves an extract dir no session will ever adopt. + if extract_dir is not None: + shutil.rmtree(extract_dir, ignore_errors=True) return CallResult(status="failed", log=buf.getvalue() + "\n" + traceback.format_exc(), error=short_error(e)) log = buf.getvalue() diff --git a/backend/app/registry/reader_fixes.py b/backend/app/registry/reader_fixes.py index e87bfa6..996fd80 100644 --- a/backend/app/registry/reader_fixes.py +++ b/backend/app/registry/reader_fixes.py @@ -1,5 +1,7 @@ -"""Corrections to what a reflected spatialdata-io reader returns, applied in the read -call's child process before the session adopts the object (registry/kernel.py).""" +"""Corrections to what a reader returns, applied before the session adopts the object: +in the read call's child process for a reflected spatialdata-io reader +(registry/kernel.py), and by the SpatialData-zarr importer for a store another program +wrote (registry/custom/read_spatialdata.py).""" def name_steinbock_channels(sdata): @@ -22,3 +24,44 @@ def name_steinbock_channels(sdata): f"has {len(markers)} markers, so its channels can't be named") sdata.images[name] = set_channel_names(image, markers) return sdata + + +def table_first(sdata, name: str): + """Move table `name` to the front of `sdata.tables`. + + The session opens on the first table (`Session._default_table_key`) and so does a + saved checkpoint in the viewer, so a store holding several tables opens on whichever + its writer happened to list first, which is not necessarily the cell table. Only + the in-memory order changes; nothing is deleted from the backing store.""" + if name not in sdata.tables: + raise ValueError(f"no table {name!r} in this store; its tables are " + f"{', '.join(sdata.tables) or 'none'}") + tables = dict(sdata.tables) + for key in tables: + del sdata.tables[key] + for key in [name, *(k for k in tables if k != name)]: + sdata.tables[key] = tables[key] + return sdata + + +def spatial_coordinates_as_array(sdata) -> None: + """Store each table's `obsm['spatial']` as a float array when it arrived as a data + frame of coordinate columns. + + AnnData allows an obsm entry to be a data frame, and some writers store the cell + coordinates that way (a group of `X`/`Y` columns on disk). The viewer reads + `obsm['spatial']` as an n x d array and cannot open a store whose coordinates are a + group; every consumer here takes `np.asarray` of it anyway, so the column order of + the frame is the axis order it already meant.""" + import numpy as np + import pandas as pd + + for name, table in sdata.tables.items(): + coords = table.obsm.get("spatial") + if not isinstance(coords, pd.DataFrame): + continue + non_numeric = [c for c in coords.columns if not pd.api.types.is_numeric_dtype(coords[c])] + if non_numeric: + raise ValueError(f"table {name!r}: obsm['spatial'] is a data frame with non-numeric " + f"column(s) {non_numeric}, so it cannot be read as coordinates") + table.obsm["spatial"] = coords.to_numpy(dtype=np.float64) diff --git a/backend/app/sessions/transform.py b/backend/app/sessions/transform.py index 1a86f60..bcb6c79 100644 --- a/backend/app/sessions/transform.py +++ b/backend/app/sessions/transform.py @@ -191,6 +191,73 @@ def world_space(sdata, table) -> tuple[str, str | None]: return "spatial", None +def _intrinsic_box(elem) -> list[float] | None: + """A region element's extent in its own intrinsic space, [x0, y0, x1, y1]: the + level-0 pixel grid of a labels element, the geometry bounds of a shapes element. + None for points, whose extent would mean computing every point.""" + import geopandas as gpd + from .. import imaging + + if isinstance(elem, gpd.GeoDataFrame): + x0, y0, x1, y1 = elem.total_bounds + return [float(x0), float(y0), float(x1), float(y1)] + if hasattr(elem, "dims") or hasattr(elem, "children"): + arr = imaging.level_array(elem, 0) + return [0.0, 0.0, float(arr.shape[-1]), float(arr.shape[-2])] + return None + + +def _inside(xy: np.ndarray, box) -> np.ndarray: + x0, y0, x1, y1 = box + return (xy[:, 0] >= x0) & (xy[:, 0] <= x1) & (xy[:, 1] >= y0) & (xy[:, 1] <= y1) + + +def stitch_world_coordinates(sdata, table) -> str | None: + """Give a multi-region table whose `obsm['spatial']` is region-local the stitched + world coordinates it lacks, as `obsm['spatial_']`; returns that key, or None + when nothing was added. + + `world_space` can only find stitched coordinates a reader already wrote (CosMx's + `obsm['global']`); a store that carries just the region-local ones falls back to + drawing every region on one origin. This writes them, so `world_space` then finds + them like any other key. + + Whether `obsm['spatial']` is region-local is decided from the data rather than + assumed, because some writers put world coordinates there: the rows must lie inside + their own region element's intrinsic extent, and fewer of them inside that extent + mapped into the shared system. A region placed at the origin fits both readings, so + it is the other regions that tell them apart; when every region fits both equally + the two readings agree and nothing needs stitching. Otherwise the coordinates are + left as they are.""" + from .. import imaging + + if world_space(sdata, table)[1] is not None: + return None + elements = _multiregion_regions(sdata, table) + system = _multiregion_system(sdata, table) if elements is not None else None + if system is None: + return None + key = f"spatial_{system}" + if key in table.obsm: + return None + region_key = table.uns["spatialdata_attrs"]["region_key"] + xy = np.asarray(table.obsm["spatial"])[:, :2].astype(float) + rows = np.asarray(table.obs[region_key].astype(str)) + local_fit = world_fit = 0 + for name, elem in elements.items(): + box = _intrinsic_box(elem) + a = imaging.affine_xy(elem, system) + if box is None or a is None: + return None + mask = rows == name + local_fit += int(_inside(xy[mask], box).sum()) + world_fit += int(_inside(xy[mask], imaging.bbox_aabb(a, box)).sum()) + if len(xy) == 0 or local_fit < 0.99 * len(xy) or world_fit >= local_fit: + return None + table.obsm[key] = _multiregion_world_xy(sdata, table, system) + return key + + def world_key(sdata, table) -> str: """The `obsm` key holding the coordinates the canvas draws (see `world_space`).""" return world_space(sdata, table)[0] diff --git a/backend/cli.py b/backend/cli.py index 3a5dd3e..808823c 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -107,8 +107,12 @@ def _read_entries(registry): def _resolve_reader(registry, parser): - """Map --parser to a (namespace, function) reader, or raise SystemExit listing - the valid choices. Sentinels are handled by the caller before this is reached.""" + """Map --parser to a (namespace, function, primary path param) reader, or raise + SystemExit listing the valid choices. Sentinels are handled by the caller before + this is reached. The path param is the reader's own name for its input — `path` + for the reflected readers, `store` for the SpatialData-zarr importer.""" + from app.registry.reader_paths import primary_path_param + readers = _read_entries(registry) if "." in parser: matches = [k for k in readers if k == parser] @@ -116,7 +120,7 @@ def _resolve_reader(registry, parser): matches = [k for k in readers if k.split(".", 1)[1] == parser] if len(matches) == 1: fn = registry.get(matches[0]) - return fn.namespace, fn.function + return fn.namespace, fn.function, primary_path_param(p.name for p in fn.params) or "path" choices = ", ".join(readers + list(ZARR_PARSERS)) raise SystemExit(f"unknown or ambiguous --parser {parser!r}; choose one of: {choices}") @@ -189,8 +193,8 @@ def _open_session(manager, args, reader): log, _ = sess.get_log(load_id) raise SystemExit(f"load of {resolved_input} failed:\n{log}") return sess - namespace, function = reader - params = {"path": resolved_input} + namespace, function, path_param = reader + params = {path_param: resolved_input} if args.reader_params: params.update(json.loads(args.reader_params)) sess = manager.create_from_read({"namespace": namespace, "function": function, "params": params}) diff --git a/backend/test_cli.py b/backend/test_cli.py index 996c3b5..04734ce 100644 --- a/backend/test_cli.py +++ b/backend/test_cli.py @@ -95,6 +95,133 @@ def check_embedding_display(cli) -> int: return 0 +# Where each well of the synthetic store below sits in its shared 'global' system. +WELL_OFFSETS = {"w1": (0.0, 0.0), "w2": (1000.0, 500.0)} +WELL_SHAPE = (100, 120) # (y, x) of each well's label image + + +def write_foreign_store(tmp: str) -> str: + """A SpatialData `.zarr.zip` shaped the way instrument exports are and this app's own + checkpoints are not: one labels region per well placed in a shared 'global' system, + a table annotating both with well-local coordinates stored as an `X`/`Y` data frame, + a points element, several tables with the cell table not first (and one with no rows + or region at all), and the store one folder down inside the archive. Returns the + archive's path.""" + import zipfile + + import anndata as ad + import numpy as np + import pandas as pd + import spatialdata as sd + from spatialdata.models import Labels2DModel, PointsModel, TableModel + from spatialdata.transformations import Translation + + rng = np.random.default_rng(0) + labels, rows = {}, [] + for well, (dx, dy) in WELL_OFFSETS.items(): + to_global = {"global": Translation([dx, dy], axes=("x", "y"))} + labels[f"{well}-labels-Cell"] = Labels2DModel.parse( + np.zeros(WELL_SHAPE, dtype=np.uint32), dims=("y", "x"), transformations=to_global) + for i in range(10): + rows.append({"region_key": f"{well}-labels-Cell", "cell_id": len(rows) + 1, + "X": float(rng.uniform(5, WELL_SHAPE[1] - 5)), + "Y": float(rng.uniform(5, WELL_SHAPE[0] - 5))}) + obs = pd.DataFrame(rows) + obs.index = obs.index.astype(str) + cells = ad.AnnData(X=rng.poisson(3, (len(obs), 5)).astype(np.float32), + obs=obs[["region_key", "cell_id"]].assign( + region_key=lambda o: o["region_key"].astype("category"))) + cells.obsm["spatial"] = obs[["X", "Y"]] + region = list(labels) + tables = { + "a-guides": TableModel.parse(cells[:, :2].copy(), region=region, + region_key="region_key", instance_key="cell_id"), + "cells": TableModel.parse(cells, region=region, region_key="region_key", + instance_key="cell_id"), + "metadata": TableModel.parse(ad.AnnData()), + } + points = {"w1-points": PointsModel.parse( + pd.DataFrame({"x": rng.uniform(0, 120, 50), "y": rng.uniform(0, 100, 50)}), + transformations={"global": Translation([0.0, 0.0], axes=("x", "y"))})} + store = os.path.join(tmp, "src", "run.zarr") + sd.SpatialData(labels=labels, points=points, tables=tables).write(store) + + archive = os.path.join(tmp, "data", "run.zarr.zip") + os.makedirs(os.path.dirname(archive)) + with zipfile.ZipFile(archive, "w", zipfile.ZIP_STORED) as zf: + for dirpath, _dirs, files in os.walk(store): + for name in files: + full = os.path.join(dirpath, name) + zf.write(full, os.path.join("run.zarr", os.path.relpath(full, store))) + return archive + + +def check_foreign_store(cli) -> int: + """The SpatialData-store path the workflow's `spatialdata` type takes: the importer + with the catalog's reader params. Dataset-free, so it always runs. The store is + written under test-data/ because the data root the reader is held to is fixed by the + first run in the process, which is the Visium one's parent when main() runs.""" + import zipfile + + import numpy as np + + data_root = os.path.dirname(DATA) + os.makedirs(data_root, exist_ok=True) + with tempfile.TemporaryDirectory(dir=data_root) as tmp: + archive = write_foreign_store(tmp) + out_dir = os.path.join(tmp, "out") + reader_params = {"selection": ["images", "labels", "shapes", "tables"], "table": "cells"} + rc = cli.main(["--parser", "io.read_zarr", "--input", archive, "--name", "store_result", + "--reader-params", json.dumps(reader_params), "--output", out_dir]) + assert rc == 0, f"cli returned {rc}" + out_zip = written_checkpoint(out_dir, "store_result") + + from app.persistence.store import _selected_members, load_spatialdata + + names = ["run.zarr/", "run.zarr/zarr.json", "run.zarr/points/p/zarr.json", + "run.zarr/tables/t/zarr.json"] + assert _selected_members(names, ("tables",)) == ["run.zarr/", "run.zarr/zarr.json", + "run.zarr/tables/t/zarr.json"] + assert _selected_members(["zarr.json", "points/p/zarr.json"], + ("labels", "tables")) == ["zarr.json"] + print("[ok] archive members of a left-out element group are not extracted, at the " + "root or one folder down") + + sdata, app_state, _newer, _extract, _hash = load_spatialdata(out_zip) + assert not sdata.points, f"points were not dropped: {list(sdata.points)}" + assert list(sdata.tables)[0] == "cells", list(sdata.tables) + table = sdata.tables["cells"] + assert isinstance(table.obsm["spatial"], np.ndarray), type(table.obsm["spatial"]) + print(f"[ok] points left out, opened on 'cells' (tables: {list(sdata.tables)}), " + f"obsm['spatial'] an array") + + local = np.asarray(table.obsm["spatial"]) + wells = table.obs["region_key"].astype(str).str.split("-").str[0].to_numpy() + offsets = np.array([WELL_OFFSETS[w] for w in wells]) + np.testing.assert_allclose(table.obsm["spatial_global"], local + offsets) + canvas = next(d for d in app_state["displays"] if d["type"] == "spatial_canvas") + assert canvas["encoding"]["coords"] == "obsm:spatial_global", canvas["encoding"] + print("[ok] region-local coordinates stitched into obsm['spatial_global'], " + "and the canvas draws those") + + # A writer that already put world coordinates in obsm['spatial'] is left alone. + from app.sessions.transform import stitch_world_coordinates + table.obsm["spatial"] = np.asarray(table.obsm.pop("spatial_global")) + assert stitch_world_coordinates(sdata, table) is None + assert "spatial_global" not in table.obsm + print("[ok] coordinates already in world space are not stitched again") + + with zipfile.ZipFile(out_zip) as zf: + assert "zarr.json" in zf.namelist(), "checkpoint is not at the archive root" + sidecar = json.loads(zf.read("viewer/zarr.json"))["attributes"] + # What the browser viewer opens on: the sidecar's first table and its world key. + assert sidecar["table_keys"][0] == "cells", sidecar["table_keys"] + assert sidecar["world_key"]["cells"] == "spatial_global", sidecar["world_key"] + print("[ok] checkpoint written with the store at the archive root; its sidecar opens " + "the viewer on 'cells' drawn from obsm['spatial_global']") + return 0 + + def written_checkpoint(out_dir: str, base: str) -> str: """The checkpoint cli.py wrote under `base`. Its name embeds a hash of its own contents, so the exact filename is only known once the bytes are.""" @@ -185,6 +312,7 @@ def main() -> int: f"({len(log)} chars): {log.splitlines()[-1][:80]}") check_embedding_display(cli) + check_foreign_store(cli) print("\nCLI E2E CHECKS PASSED") return 0 diff --git a/cirro-studio/src/data/discover.test.ts b/cirro-studio/src/data/discover.test.ts index 2b1aa19..569f2f7 100644 --- a/cirro-studio/src/data/discover.test.ts +++ b/cirro-studio/src/data/discover.test.ts @@ -38,6 +38,10 @@ describe('findRuns', () => { expect(runs.map((r) => [r.path, r.type.id])).toEqual([['', 'visium']]); }); + it('does not take an ordinary folder for a store type recognised by name', () => { + expect(findRuns(files('notes/readme.txt', 'run1.zarr.zip'))).toEqual([]); + }); + it('treats glob characters literally except * and ?', () => { expect(findRuns(files('x/experimentXxenium', 'x/cell_feature_matrix.h5'))).toEqual([]); }); diff --git a/cirro-studio/src/data/discover.ts b/cirro-studio/src/data/discover.ts index c85ec62..a420c1b 100644 --- a/cirro-studio/src/data/discover.ts +++ b/cirro-studio/src/data/discover.ts @@ -19,6 +19,7 @@ export interface ListedFile { } interface Detect { + name?: string[]; all_of?: string[]; any_of?: string[][]; none_of?: string[]; @@ -102,13 +103,18 @@ function patternPresent(tree: Map>, dir: string, pattern: st return [...(tree.get(target) ?? [])].some((name) => leaf.test(name)); } +// A type recognised by `name` matches only a folder so named, as in discovery.nf's +// nameMatches. The one such type (`spatialdata`) names stores, which `findStores` lists; +// without this check its empty content rules would match every folder. function detectMatches(tree: Map>, dir: string, detect: Detect): boolean { - return (detect.all_of ?? []).every((p) => patternPresent(tree, dir, p)) + const base = dir.split('/').pop() ?? ''; + return (detect.name ?? ['*']).some((glob) => globToRegex(glob).test(base)) + && (detect.all_of ?? []).every((p) => patternPresent(tree, dir, p)) && (detect.any_of ?? []).every((group) => group.some((p) => patternPresent(tree, dir, p))) && !(detect.none_of ?? []).some((p) => patternPresent(tree, dir, p)); } -const detectScore = (d: Detect) => (d.all_of ?? []).length + (d.any_of ?? []).length; +const detectScore = (d: Detect) => (d.all_of ?? []).length + (d.any_of ?? []).length + (d.name ? 1 : 0); function runTypeOf(tree: Map>, dir: string): RunType | null { const matched = RUN_TYPES.filter((t) => detectMatches(tree, dir, t.detect)); diff --git a/docs/guide/link-a-dataset.md b/docs/guide/link-a-dataset.md index 03959e8..11b66b8 100644 --- a/docs/guide/link-a-dataset.md +++ b/docs/guide/link-a-dataset.md @@ -104,10 +104,13 @@ The file is a [SpatialData](https://spatialdata.scverse.org/) The repository's [workflow](../../nextflow/README.md) does the work for you: 1. It finds the datasets in a folder of instrument output: Xenium, Visium, Visium HD, - MERSCOPE, CosMx, Curio, Steinbock or MCMICRO. -2. It reads each one with spatialdata-io. + MERSCOPE, CosMx, Curio, Steinbock or MCMICRO. It also takes SpatialData stores that + another program wrote, such as an instrument's own `.zarr.zip` export. +2. It reads each one with spatialdata-io. A SpatialData store is read without its + points, which the app doesn't draw, and is put in the shape the app reads (see the + workflow's README). 3. It runs that data type's analysis: quality filtering, clustering, a UMAP and cellular - neighborhoods. + neighborhoods. A SpatialData store is published without analysis. 4. It writes each dataset as a `.sdata.zarr.zip`. ```bash diff --git a/nextflow/README.md b/nextflow/README.md index 2978764..106c51b 100644 --- a/nextflow/README.md +++ b/nextflow/README.md @@ -1,9 +1,10 @@ # Spatial data workflow (Nextflow) Point it at a folder. It finds the spatial datasets inside — Xenium, Visium, Visium HD, -MERSCOPE, CosMx, Curio, Steinbock, MCMICRO — loads each with the right reader, runs that -data type's preprocessing recipes, and publishes the results in a tree mirroring where -they were found, plus a MultiQC report over the whole run and a browsable viewer. +MERSCOPE, CosMx, Curio, Steinbock, MCMICRO, or a SpatialData store some other program +wrote — loads each with the right reader, runs that data type's preprocessing recipes, +and publishes the results in a tree mirroring where they were found, plus a MultiQC +report over the whole run and a browsable viewer. This is the repo's only workflow entrypoint. @@ -29,6 +30,7 @@ edit to that one file. | Curio Seeker | `anndata.h5ad` + `Metrics.csv`/`cluster_assignment.txt` | as Visium (whole transcriptome) | | Steinbock | `cells.h5ad` + `ome/` + a masks folder | z-score → PCA → neighbors → Leiden → UMAP, then neighborhoods | | MCMICRO | `quantification/` + `markers.csv` + `registration/`/`dearray/` | as Steinbock | +| SpatialData store | a `*.zarr.zip` file or `*.zarr` folder, by name | none: read and published as is | ### How each result opens in the viewer @@ -45,7 +47,8 @@ the tissue: Rename either column and the display follows it — the catalog names the parameter, not the column. With `--preprocess false` the boundaries still come on but the colouring is -left as read, since neither column exists without the recipes that write them. +left as read, since neither column exists without the recipes that write them. A +SpatialData store, which has no recipes, is always coloured as read. The **Embeddings** view is configured too, on the UMAP the recipes compute (the obsm picker in its controls switches to the 3D UMAP or the PCA, and the 3D toggle turns the @@ -53,6 +56,28 @@ view into an orbit). It has to be written into the checkpoint here: no embedding exists when the dataset is first read, and a viewer opening a checkpoint that lacks the view can only rebuild it by hand, for that browser session only. +A **SpatialData store** is one some other program already wrote: an instrument's own +export, spatialdata-io, or a previous run of this workflow. It has no recipes, because a +store says nothing about the assay that made it; the checkpoint is published as read, +for analysis in the app. Reading it brings it into the shape the viewer opens: + +- **Points are not read.** Nothing draws them, and an instrument export can carry tens of + GB of transcript points, more than the rest of the store together; they are not even + unpacked. The Xenium, MERSCOPE and CosMx readers leave transcripts out for the same + reason. +- **`--table` picks the table to open on**, for a store holding several. Otherwise it is + the store's first, by name, which is not necessarily the table of cells. +- **Cell coordinates stored as a data frame** (`X`/`Y` columns in `obsm['spatial']`) + become the array the viewer reads. +- **Coordinates local to each region are stitched.** A table spanning several regions + (the wells of a plate, the fields of view of a slide) may hold each cell's position + relative to its own region. When the positions fit their regions that way and not as + world coordinates, the world ones are written beside them as `obsm['spatial_']` + and drawn instead, so the regions are laid out rather than stacked on one origin. + +The published checkpoint is rewritten whole, with the store at the archive root, so a +store that arrived nested one folder down inside its zip opens directly. + Steinbock and MCMICRO measure **protein intensity**, not transcript counts, so they take a path with no `normalize_total`/`log1p` and no highly-variable-gene selection — those assume counts. See `backend/app/recipes/25_cluster_protein_intensities.json`. @@ -70,6 +95,13 @@ is not descended into, so a format that nests its own sub-outputs yields one dat rather than several. When two types match the same folder the more specific one wins, so a Visium HD run does not also register as the Visium-shaped matrix it contains. +A type recognised by name alone (`detect.name` in the catalog) can match a file as well +as a folder: each `*.zarr.zip` is a SpatialData store of its own, published under its +name less the suffix (`run1.zarr.zip` → `run1/`). A Xenium bundle's own `.zarr.zip` +outputs are not picked up, since the bundle folder is recognised first and not +descended into. A store that turns out not to be SpatialData (a bare OME-Zarr image) +fails to read like any other unreadable dataset. + With `--recurse false` each input root is expected to be a dataset itself. ### Files that only work in pairs @@ -205,17 +237,18 @@ per-gene cell floor. A parameter is simply ignored by a type that does not use i | `--recurse` | `true` | Walk into subfolders. | | `--preprocess` | `true` | Run each type's recipes. Off loads and publishes unanalysed. | | `--fail_on_dataset_error` | `false` | Fail the run if any dataset produces no checkpoint. Off, only a run where none did fails. | +| `--table` | the store's first | The table each checkpoint opens on, for a store holding several. A dataset without it fails to read. (SpatialData store) | | `--lowres_max_image_mb` | `10` | Image budget for the low-res copy. | | `--min_reads_per_cell` | `10` | (Xenium, MERSCOPE, CosMx, Visium, Visium HD, Curio) | | `--max_reads_per_cell` | `35000` | (Visium, Visium HD, Curio) | | `--min_cells_per_gene` | `5` | (Xenium, MERSCOPE, CosMx) | | `--n_top_genes` | `2000` | (Visium, Visium HD, Curio) | -| `--cluster_key` | `leiden` | (all) | +| `--cluster_key` | `leiden` | (all but SpatialData store) | | `--resolution` | `1.0` | (Xenium, MERSCOPE, CosMx, Steinbock, MCMICRO) | | `--marker_method` | `wilcoxon` | (Xenium, MERSCOPE, CosMx, Visium, Visium HD, Curio) | | `--n_marker_genes` | `5` | (Xenium, MERSCOPE, CosMx) | -| `--neighborhood_resolution` | `0.1` | (all) | -| `--neighborhood_key` | `cellular_neighborhood` | (all) | +| `--neighborhood_resolution` | `0.1` | (all but SpatialData store) | +| `--neighborhood_key` | `cellular_neighborhood` | (all but SpatialData store) | Profiles: `docker` enables Docker (each process declares its own image); `test` points `--input` at the bundled raw Xenium bundle that `scripts/prepare_xenium_data.py` diff --git a/nextflow/data_types.json b/nextflow/data_types.json index a39eca2..a134967 100644 --- a/nextflow/data_types.json +++ b/nextflow/data_types.json @@ -450,6 +450,25 @@ }, "validated": false, "notes": "Protein intensities per cell, as Steinbock. markers.csv plus quantification/ is what distinguishes an MCMICRO output directory." + }, + { + "id": "spatialdata", + "label": "SpatialData store", + "reader": "io.read_zarr", + "reader_params": {"selection": ["images", "labels", "shapes", "tables"]}, + "reader_params_from": {"table": "table"}, + "detect": { + "name": [ + "*.zarr.zip", + "*.zarr" + ] + }, + "recipes": [], + "display": { + "render_mode": "points+shapes" + }, + "validated": false, + "notes": "An existing SpatialData store, from any writer (an instrument's own export, spatialdata-io, a previous run of this workflow). Recognised by name, so a .zarr.zip file is a dataset on its own; a vendor folder that carries .zarr.zip outputs is claimed by its own type first and never descended into. Points are not read: nothing draws them, and an instrument export can hold tens of GB of them, as the Xenium, MERSCOPE and CosMx readers' transcripts=false also reflects. No recipes, because a store says nothing about its modality: the checkpoint is published as read, for analysis in the app. A store that is not SpatialData (a bare OME-Zarr image) fails to read, which is reported and does not stop the run." } ] } diff --git a/nextflow/data_types.schema.json b/nextflow/data_types.schema.json index fc477b0..6536486 100644 --- a/nextflow/data_types.schema.json +++ b/nextflow/data_types.schema.json @@ -71,6 +71,11 @@ "type": "object", "description": "Extra kwargs merged into the reader call (cli.py --reader-params)." }, + "reader_params_from": { + "type": "object", + "additionalProperties": { "type": "string", "minLength": 1 }, + "description": "Reader kwargs filled from a workflow parameter, as reader kwarg -> parameter name: a choice that differs run to run (which of a store's tables to open on) rather than one fixed for the type. Passed only when the parameter is set, over any reader_params value of the same name. Each parameter must exist in nextflow.config and nextflow_schema.json (tests/check_catalog.py)." + }, "detect": { "$ref": "#/definitions/detect" }, "companion_files": { "type": "array", @@ -153,8 +158,14 @@ "detect": { "type": "object", "additionalProperties": false, - "description": "How a folder of this type is recognised. Patterns are shell globs matched against paths relative to the candidate folder; a pattern containing '/' is matched against that subfolder's listing, so nesting stays explicit and discovery never walks a whole tree to test one folder. A folder matches when every all_of pattern matches, every any_of group has at least one match, and no none_of pattern matches.", + "description": "How a folder of this type is recognised. Patterns are shell globs matched against paths relative to the candidate folder; a pattern containing '/' is matched against that subfolder's listing, so nesting stays explicit and discovery never walks a whole tree to test one folder. A folder matches when every all_of pattern matches, every any_of group has at least one match, and no none_of pattern matches. A type with `name` and nothing else is recognised by name alone, and then a file can be a dataset too: a store archive such as a `.zarr.zip`.", "properties": { + "name": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "minLength": 1 }, + "description": "Globs the candidate's own name must match (any one of them). Counts as one pattern when ranking competing matches. A `*` glob also sets the name the dataset is published under: its own name less that suffix." + }, "all_of": { "type": "array", "items": { "type": "string", "minLength": 1 }, diff --git a/nextflow/main.nf b/nextflow/main.nf index 8bb8f0d..55cf000 100644 --- a/nextflow/main.nf +++ b/nextflow/main.nf @@ -285,6 +285,16 @@ def recipeParamsFor(Map catalog, String typeId) { return values } +/** The reader kwargs for one data type: its fixed `reader_params`, with each + * `reader_params_from` entry filled from its workflow parameter when that is set. */ +def readerParamsFor(Map type) { + def values = [:] + (type.reader_params ?: [:]) + (type.reader_params_from ?: [:]).each { kwarg, name -> + if( params[name] ) values[kwarg] = params[name] + } + return values +} + /** Stop the run when it published too little to call a success. * * ANALYSE turns a dataset that cannot be read into a published log and a `failed` row in @@ -337,6 +347,7 @@ workflow { def work = candidates.collect { prefix, typeId, dir -> def type = catalog.data_types.find { t -> t.id == typeId } def at = prefix ?: dir.name // a bare root that is itself the dataset + def reader_params = readerParamsFor(type) tuple(at, [ id : typeId, label : type.label, @@ -350,8 +361,7 @@ workflow { ? "obs:${params[type.display.color_by_param]}".toString() : null, display_render_mode: type.display?.render_mode, recipe_params_json : groovy.json.JsonOutput.toJson(recipeParamsFor(catalog, typeId)), - reader_params_json : type.reader_params - ? groovy.json.JsonOutput.toJson(type.reader_params) : null, + reader_params_json : reader_params ? groovy.json.JsonOutput.toJson(reader_params) : null, // Files the reader will read without what it needs to interpret them (an // aligned image with no alignment matrix). Resolved here, where the folder // is still in hand — the store the reader goes on to build carries no trace diff --git a/nextflow/modules/discovery.nf b/nextflow/modules/discovery.nf index 1507601..a721fbe 100644 --- a/nextflow/modules/discovery.nf +++ b/nextflow/modules/discovery.nf @@ -44,6 +44,19 @@ def patternPresent(dir, String pattern, Map listings) { return listings[key].any { name -> name ==~ regex } } +// Whether `name` is one a data type's `detect.name` globs allow. A type that declares +// none accepts any name, which is every type that is recognised by what its folder holds. +def nameMatches(String name, Map detect) { + def globs = (detect.name ?: []) as List + return !globs || globs.any { glob -> name ==~ globToRegex(glob) } +} + +// Whether a type is recognised by name alone: a file has no listing, so it can only be +// a dataset of a type whose `detect` asks for nothing inside it. +def detectsByNameOnly(Map detect) { + return detect.name && !detect.all_of && !detect.any_of && !detect.none_of +} + // Whether `dir` satisfies a data type's `detect` block: every all_of present, every // any_of group represented, no none_of present. def detectMatches(dir, Map detect, Map listings) { @@ -60,13 +73,19 @@ def detectMatches(dir, Map detect, Map listings) { // How much a `detect` block asserts. Used only to rank competing matches, so a format // that is a superset of another (Visium HD over Visium) wins without a special case. def detectScore(Map detect) { - return ((detect.all_of ?: []).size() + (detect.any_of ?: []).size()) as int + return ((detect.all_of ?: []).size() + (detect.any_of ?: []).size() + (detect.name ? 1 : 0)) as int } // The data type `dir` holds, or null. When several match, the most specific wins. A -// genuine tie is a catalog bug rather than a data problem, so it stops the run. -def classify(dir, List types, Map listings) { - def matched = types.findAll { type -> detectMatches(dir, type.detect, listings) } +// genuine tie is a catalog bug rather than a data problem, so it stops the run. A file +// is tested by name only, against the types that are recognised that way, which keeps +// the walk to one listing per folder however many files the tree holds. +def classify(dir, List types, Map listings, boolean isFile) { + def name = dir.name.toString() + def matched = types.findAll { type -> + nameMatches(name, type.detect) && + (isFile ? detectsByNameOnly(type.detect) : detectMatches(dir, type.detect, listings)) + } if( !matched ) return null def best = matched.max { type -> detectScore(type.detect) } def tied = matched.findAll { type -> detectScore(type.detect) == detectScore(best.detect) } @@ -76,22 +95,39 @@ def classify(dir, List types, Map listings) { return best } +// The name a dataset is published under: its own name, less the suffix of the +// `detect.name` glob that recognised it, so `run1.zarr.zip` publishes as `run1`. Only a +// glob of the form `*` names a suffix; anything else leaves the name whole. +def datasetName(String name, Map detect) { + def suffix = ((detect.name ?: []) as List) + .findAll { glob -> glob.startsWith('*') && !glob.substring(1).contains('*') && !glob.contains('?') } + .collect { glob -> glob.substring(1) } + .findAll { s -> name.endsWith(s) && name.length() > s.length() } + .max { s -> s.length() } + return suffix ? name.substring(0, name.length() - suffix.length()) : name +} + // Depth-first walk. Greedy: a folder that classifies is a candidate and is not // descended into, so a format that nests its own sub-outputs yields one result rather -// than several. Written as recursion because the workflow language has no loops. +// than several. A file is a candidate only for a type recognised by name (a store +// archive), and is never descended into. Written as recursion because the workflow +// language has no loops. def collectFrom(dir, String at, List types, boolean recurse, Map listings) { - def type = classify(dir, types, listings) - if( type ) return [[at, type.id, dir]] - if( !recurse ) return [] + def isFile = !dir.isDirectory() + def type = classify(dir, types, listings, isFile) + if( type ) { + def parent = at.contains('/') ? at.substring(0, at.lastIndexOf('/') + 1) : '' + def leaf = at.contains('/') ? at.substring(at.lastIndexOf('/') + 1) : at + return [[leaf ? parent + datasetName(leaf, type.detect) : at, type.id, dir]] + } + if( isFile || !recurse ) return [] return childNames(dir).sort().collectMany { name -> - def child = dir.resolve(name) - return child.isDirectory() - ? collectFrom(child, at ? "${at}/${name}".toString() : name, types, recurse, listings) - : [] + collectFrom(dir.resolve(name), at ? "${at}/${name}".toString() : name, types, recurse, listings) } } -/** Data folders under `root`, each as `[prefix, data_type_id, path]`. +/** Datasets under `root` (data folders, or store files such as a `.zarr.zip`), each as + * `[prefix, data_type_id, path]`. * * `prefix` is where the result is published: the caller's prefix for the root itself, * extended by the candidate's path relative to the root. diff --git a/nextflow/nextflow.config b/nextflow/nextflow.config index 6e16258..e7fcc72 100644 --- a/nextflow/nextflow.config +++ b/nextflow/nextflow.config @@ -8,6 +8,7 @@ params { recurse = true // walk into subfolders looking for datasets preprocess = true // run each data type's preprocessing recipes after loading fail_on_dataset_error = false // fail the run if any dataset produces no checkpoint (none always does) + table = null // SpatialData stores: the table each checkpoint opens on (default: the store's first) // --- output ------------------------------------------------------------ outdir = 'results' diff --git a/nextflow/nextflow_schema.json b/nextflow/nextflow_schema.json index 0b9e34c..eb7721b 100644 --- a/nextflow/nextflow_schema.json +++ b/nextflow/nextflow_schema.json @@ -36,7 +36,7 @@ "properties": { "data_types": { "type": "string", - "description": "Comma-separated data-type ids to look for. Default is every type in the catalog: xenium, visium_hd, visium, merscope, cosmx, curio, steinbock, mcmicro." + "description": "Comma-separated data-type ids to look for. Default is every type in the catalog: xenium, visium_hd, visium, merscope, cosmx, curio, steinbock, mcmicro, spatialdata." }, "recurse": { "type": "boolean", @@ -52,6 +52,10 @@ "type": "boolean", "default": false, "description": "Fail the run if any dataset produces no checkpoint. Off, a dataset that cannot be read is published as its log and reported as failed while the others carry on, and the run fails only if no dataset produced one." + }, + "table": { + "type": "string", + "description": "The table each checkpoint opens on, for a store holding several: the viewer and the analysis use one table at a time, and otherwise take the store's first. A dataset without a table of this name fails to read. (SpatialData store)" } } }, diff --git a/nextflow/tests/check_catalog.py b/nextflow/tests/check_catalog.py index 5a86906..67bc4d4 100644 --- a/nextflow/tests/check_catalog.py +++ b/nextflow/tests/check_catalog.py @@ -115,6 +115,19 @@ def check_display(catalog: dict) -> None: print(f"[ok] {with_display} display default(s) name a param their own recipes fill") +def check_reader_params_from(catalog: dict) -> None: + """A `reader_params_from` entry names a workflow parameter; one that does not exist + would never be set, and the reader would silently keep its default.""" + config = config_defaults() + count = 0 + for data_type in catalog["data_types"]: + for kwarg, name in data_type.get("reader_params_from", {}).items(): + count += 1 + check(name in config, f"{data_type['id']}: reader_params_from {kwarg!r} names " + f"{name!r}, which is not a param in nextflow.config") + print(f"[ok] {count} reader_params_from entr(ies) name a workflow param") + + def config_defaults() -> dict[str, str]: """`name = value` pairs from the params block of nextflow.config.""" text = (NF / "nextflow.config").read_text() @@ -164,7 +177,9 @@ def check_params_exposed(catalog: dict) -> None: # folder that is nothing. Values are paths to create relative to the dataset folder; # a trailing '/' makes a directory. FIXTURE = { - "a/xen1": ["experiment.xenium", "cell_feature_matrix.h5"], + # A vendor folder that also carries a `.zarr.zip` output: the folder is the dataset, + # and the archive inside it must not become a second one. + "a/xen1": ["experiment.xenium", "cell_feature_matrix.h5", "cells.zarr.zip"], # An added-image pair that is complete (H&E) beside one that is not (IF), which is # exactly how the 10x pancreas bundle arrived: the reader places the first and # silently leaves the second at identity. @@ -183,11 +198,16 @@ def check_params_exposed(catalog: dict) -> None: "st1": ["cells.h5ad", "ome/", "masks_deepcell/"], "mc1": ["markers.csv", "quantification/", "registration/"], "junk": ["notes.txt", "readme/"], + # SpatialData stores are recognised by name, so the datasets are the archive and the + # store folder themselves, published without their suffix; the folder holding them is + # not one. + "stores": ["run1.zarr.zip", "run2.zarr/zarr.json", "notes.txt"], } EXPECTED = { "a/xen1": "xenium", "aligned/xen2": "xenium", "a/b/vis1": "visium", "hd1": "visium_hd", "deep/x/y/mer1": "merscope", "cos1": "cosmx", "cur1": "curio", "st1": "steinbock", "mc1": "mcmicro", + "stores/run1": "spatialdata", "stores/run2": "spatialdata", } # The `companion_files` pairs FIXTURE leaves unsatisfied, as (folder, file, companion). # `S_he_image.ome.tif` is deliberately absent: its companion is there, so a satisfied @@ -205,7 +225,7 @@ def check_companions(catalog: dict) -> None: rules = 0 for data_type in catalog["data_types"]: folders = [f for f, tid in EXPECTED.items() if tid == data_type["id"]] - names = {name for f in folders for name in FIXTURE[f]} + names = {name for f in folders for name in FIXTURE.get(f, [])} for rule in data_type.get("companion_files", []): rules += 1 check(any(name.endswith(rule["suffix"]) for name in names), @@ -263,6 +283,7 @@ def main() -> int: check_applies_to(catalog) check_display(catalog) check_params_exposed(catalog) + check_reader_params_from(catalog) check_companions(catalog) check_discovery(catalog)