demo / scripts /make_xsmall.py
ckmah's picture
Organize into small/ and xsmall/ datasets
7984785 verified
Raw History Blame Contribute Delete
4.99 kB
# /// script
# requires-python = ">=3.11"
# dependencies = ["numpy", "pandas", "pyarrow", "zarr>=3"]
# ///
"""Crop ``small/`` to a 100 um cube and write the result to ``xsmall/``.
Cells are selected by centroid (``cell_metadata_v1.csv``) inside the cube and
kept whole: all of their segmentation polygons and all of their assigned
transcripts are included, so ``cell_by_gene_v1.csv`` stays consistent with
``cell_assigned_gene_v1.csv``. Unassigned transcripts are kept only when they
fall inside the cube. The DAPI mosaic is cropped to the cube at every
pyramid level, with the OME-NGFF translations updated accordingly.
Usage (from the repository root):
uv run scripts/make_xsmall.py
"""
from __future__ import annotations
import math
import shutil
import zipfile
from pathlib import Path
import pandas as pd
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
import zarr
ROOT = Path(__file__).resolve().parent.parent
SRC = ROOT / "small"
DST = ROOT / "xsmall"
# 100 um cube (in um, global coordinates), placed over a cell-dense region
X_RANGE = (900.0, 1000.0)
Y_RANGE = (-5140.0, -5040.0)
Z_RANGE = (20.0, 120.0)
UNASSIGNED_SUFFIX = "_-1"
MOSAIC_NAME = "mosaic_3d.ome.zarr"
def _in_cube(df: pd.DataFrame) -> pd.Series:
return (
df["X_um"].between(*X_RANGE, inclusive="left")
& df["Y_um"].between(*Y_RANGE, inclusive="left")
& df["Z_um"].between(*Z_RANGE, inclusive="left")
)
def crop_tables() -> list[str]:
metadata = pd.read_csv(SRC / "cell_metadata_v1.csv")
metadata = metadata[_in_cube(metadata)]
cell_ids = metadata["cell_id"].tolist()
metadata.to_csv(DST / "cell_metadata_v1.csv", index=False)
by_gene = pd.read_csv(SRC / "cell_by_gene_v1.csv")
by_gene[by_gene["cell_id"].isin(cell_ids)].to_csv(DST / "cell_by_gene_v1.csv", index=False)
transcripts = pd.read_csv(SRC / "cell_assigned_gene_v1.csv")
unassigned = transcripts["cell_id"].str.endswith(UNASSIGNED_SUFFIX)
keep = transcripts["cell_id"].isin(cell_ids) | (unassigned & _in_cube(transcripts))
transcripts[keep].to_csv(DST / "cell_assigned_gene_v1.csv", index=False)
geometries = pq.read_table(SRC / "segmentation_geometries_v1.parquet")
geometries = geometries.filter(pc.is_in(geometries["cell_id"], value_set=pa.array(cell_ids, type=pa.string())))
pq.write_table(geometries, DST / "segmentation_geometries_v1.parquet", compression="zstd")
print(f"cells: {len(cell_ids)}, transcripts: {int(keep.sum())} ({int((keep & unassigned).sum())} unassigned)")
return cell_ids
def crop_mosaic() -> None:
src_store = zarr.storage.ZipStore(SRC / f"{MOSAIC_NAME}.zip", mode="r")
src = zarr.open_group(store=src_store, mode="r", path=MOSAIC_NAME)
ome = src.attrs.asdict()["ome"]
multiscale = ome["multiscales"][0]
axes = [a["name"] for a in multiscale["axes"]]
ranges = {"z": Z_RANGE, "y": Y_RANGE, "x": X_RANGE}
tmp_dir = DST / MOSAIC_NAME
if tmp_dir.exists():
shutil.rmtree(tmp_dir)
dst = zarr.open_group(store=tmp_dir, mode="w")
for dataset in multiscale["datasets"]:
transforms = {ct["type"]: ct for ct in dataset["coordinateTransformations"]}
scale = transforms["scale"]["scale"]
translation = transforms["translation"]["translation"]
array = src[dataset["path"]]
# NGFF translation is the physical position of the centre of pixel 0
slices = []
for i, ax in enumerate(axes):
if ax not in ranges:
slices.append(slice(None))
continue
lo, hi = ranges[ax]
start = max(0, math.ceil((lo - translation[i]) / scale[i]))
stop = min(array.shape[i], math.ceil((hi - translation[i]) / scale[i]))
slices.append(slice(start, stop))
translation[i] = translation[i] + start * scale[i]
data = array[tuple(slices)]
chunks = tuple(min(c, s) for c, s in zip(array.chunks, data.shape, strict=True))
out = dst.create_array(
dataset["path"],
shape=data.shape,
dtype=data.dtype,
chunks=chunks,
compressors=zarr.codecs.ZstdCodec(level=19),
dimension_names=axes,
)
out[:] = data
dst.require_group(dataset["path"].split("/")[0]).attrs["_ARRAY_DIMENSIONS"] = axes
print(f"{dataset['path']}: {array.shape} -> {data.shape}")
dst.attrs["ome"] = ome
src_store.close()
zip_path = DST / f"{MOSAIC_NAME}.zip"
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_STORED) as zf:
for f in sorted(tmp_dir.rglob("*")):
if f.is_file():
zf.write(f, f.relative_to(DST).as_posix())
shutil.rmtree(tmp_dir)
def main() -> None:
DST.mkdir(exist_ok=True)
crop_tables()
crop_mosaic()
for f in sorted(DST.iterdir()):
print(f" {f.name}: {f.stat().st_size / 1024:.1f} KB")
if __name__ == "__main__":
main()