Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
64 changes: 57 additions & 7 deletions backend/app/persistence/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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…")
Expand All @@ -270,31 +277,74 @@ 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
# unzipping (same sorted-arcname + bytes scheme as `_zip_dir`), so the
# 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,
Expand Down
12 changes: 12 additions & 0 deletions backend/app/registry/custom/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<system>']`, 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.
42 changes: 40 additions & 2 deletions backend/app/registry/custom/read_spatialdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
path."""
from __future__ import annotations

import shutil
import traceback

from ..base import CallResult, Function, ParamSpec, capture_log, short_error
Expand All @@ -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):
Expand Down Expand Up @@ -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()
Expand Down
47 changes: 45 additions & 2 deletions backend/app/registry/reader_fixes.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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)
67 changes: 67 additions & 0 deletions backend/app/sessions/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_<system>']`; 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]
Expand Down
Loading
Loading