File size: 4,991 Bytes
7984785 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | # /// 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()
|