Skip to content
Draft
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
417 changes: 417 additions & 0 deletions experiments/histogram_storage_study/README.md

Large diffs are not rendered by default.

6,088 changes: 6,088 additions & 0 deletions experiments/histogram_storage_study/accuracy.json

Large diffs are not rendered by default.

374 changes: 374 additions & 0 deletions experiments/histogram_storage_study/accuracy.py

Large diffs are not rendered by default.

198 changes: 198 additions & 0 deletions experiments/histogram_storage_study/bench_io.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""Write and read times, peak memory and sizes of every format (not for merge).

bench_io.py OUT.json [REPEATS] [DATASET ...]

For every dataset, histogram variant and format, each operation runs in a fresh Python process
(``--op``), one at a time:

``write`` all records to one file (the final table)
``read`` that file back to ``PlaneRecord`` objects (every PlaneHistogram invariant checked)
``write_sh1`` / ``read_sh1`` one file per image (preprocessing's staging shards), serially
``write_sh4`` / ``read_sh4`` the same with 4 threads (image workers share one process)

In the child, the input records (or the written file) are ready and the format's modules are
imported before anything is measured. After one untimed warm-up call (lazy library loads), the
peak RSS is reset (``/proc/self/clear_refs``) and one call measures peak memory: the rise of
the peak RSS (``VmHWM``) over the RSS just before it, which includes pyarrow's and zarr's own
allocators. Then REPEATS timed calls (default 5); the median, minimum and
maximum are reported. The bytes, the file count and the per-channel-plane bytes come from the
written file.
"""

from __future__ import annotations

import gc
import json
import os
import pickle
import shutil
import statistics
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

HERE = Path(__file__).resolve().parent
OPS = ("write", "read", "write_sh1", "read_sh1", "write_sh4", "read_sh4")


def _status(field: str) -> int:
"""VmRSS or VmHWM of this process, in bytes (Linux)."""
with open("/proc/self/status") as fh:
for line in fh:
if line.startswith(field + ":"):
return int(line.split()[1]) * 1024
raise KeyError(field)


def _reset_peak() -> None:
"""Reset the peak RSS (VmHWM) to the current RSS (Linux >= 4.0)."""
with open("/proc/self/clear_refs", "w") as fh:
fh.write("5")


def _shards(records):
by_image = {}
for r in records:
by_image.setdefault(r.source_relative_path, []).append(r)
return list(by_image.values())


def child(records_pkl: str, fmt: str, op: str, folder: str, repeats: int) -> None:
from common import channel_ids
from formats import READERS, SUFFIX, WRITERS

if fmt == "parquet_long":
import pyarrow.parquet # noqa: F401
if fmt == "zarr_trimmed":
import zarr # noqa: F401
with open(records_pkl, "rb") as fh:
records = pickle.load(fh)
ids = channel_ids(records)
folder = Path(folder)
one = folder / f"table{SUFFIX[fmt]}"
shards = _shards(records)
shard_paths = [folder / f"shard{k:03d}{SUFFIX[fmt]}" for k in range(len(shards))]
write, read = WRITERS[fmt], READERS[fmt]
if op.startswith("read"):
if op == "read":
write(records, one, ids)
else:
for s, p in zip(shards, shard_paths, strict=True):
write(s, p, ids)
del records, shards
workers = 4 if op.endswith("sh4") else 1

def run():
if op == "write":
write(records, one, ids)
elif op == "read":
return read(one)
elif op.startswith("write_sh"):
with ThreadPoolExecutor(workers) as pool:
list(pool.map(lambda a: write(a[0], a[1], ids), zip(shards, shard_paths)))
else:
with ThreadPoolExecutor(workers) as pool:
return list(pool.map(read, shard_paths))

def clear():
if op.startswith("write"):
for p in [one, *shard_paths]:
if p.is_dir():
shutil.rmtree(p)
elif p.exists():
p.unlink()

run() # warm-up: lazy library loads and allocator arenas are not the operation's
clear()
gc.collect()
_reset_peak()
before = _status("VmRSS")
out = run()
peak = _status("VmHWM") - before
del out
times = []
for _ in range(repeats):
clear()
gc.collect()
t0 = time.perf_counter()
out = run()
times.append(time.perf_counter() - t0)
del out
print(json.dumps({"times": times, "peak_rss_rise": max(peak, 0)}))


def main() -> None:
from common import WORK, channel_ids
from formats import FORMATS, SUFFIX, WRITERS, size_of

out_json = Path(sys.argv[1])
repeats = int(sys.argv[2]) if len(sys.argv) > 2 else 5
datasets = sys.argv[3:] or ["study", "cmu1", "hpmec", "jump"]
results = json.loads(out_json.read_text()) if out_json.exists() else []
done = {(r["dataset"], r["variant"], r["format"], r["op"]) for r in results}
for dataset in datasets:
with open(WORK / dataset / "prepared.pkl", "rb") as fh:
prepared = pickle.load(fh)
for variant, data in prepared["variants"].items():
records = data["records"]
pkl = WORK / dataset / f"records_{variant}.pkl"
with open(pkl, "wb") as fh:
pickle.dump(records, fh, protocol=pickle.HIGHEST_PROTOCOL)
planes = sum(len(r.channels) for r in records)
ids = channel_ids(records)
for fmt in FORMATS:
folder = WORK / "io" / f"{dataset}_{variant}_{fmt}"
shutil.rmtree(folder, ignore_errors=True)
folder.mkdir(parents=True)
path = folder / f"size{SUFFIX[fmt]}"
WRITERS[fmt](records, path, ids)
nbytes, nfiles = size_of(path)
shard_bytes = 0
for k, shard in enumerate(_shards(records)):
p = folder / f"sizeshard{k}{SUFFIX[fmt]}"
WRITERS[fmt](shard, p, ids)
shard_bytes += size_of(p)[0]
shutil.rmtree(folder)
for op in OPS:
key = (dataset, variant, fmt, op)
if key in done:
continue
folder.mkdir(parents=True)
proc = subprocess.run(
[sys.executable, __file__, "--op", str(pkl), fmt, op, str(folder),
str(repeats if not op.endswith(("sh1", "sh4")) else 3)],
capture_output=True, text=True, check=False,
env={**os.environ, "PYTHONPATH": str(HERE)},
)
shutil.rmtree(folder)
if proc.returncode:
print(proc.stderr, file=sys.stderr)
raise SystemExit(f"child failed: {key}")
child_out = json.loads(proc.stdout.strip().splitlines()[-1])
t = child_out["times"]
row = {
"dataset": dataset, "variant": variant, "format": fmt, "op": op,
"planes": planes, "records": len(records), "bytes": nbytes,
"files": nfiles, "shard_bytes": shard_bytes,
"median_s": statistics.median(t), "min_s": min(t), "max_s": max(t),
"times": t, "peak_rss_rise": child_out["peak_rss_rise"],
"load": os.getloadavg()[0],
}
results.append(row)
out_json.write_text(json.dumps(results, indent=1))
print(
f"{dataset:6s} {variant:7s} {fmt:13s} {op:10s} {nbytes:>10d} B "
f"{row['median_s']:.4f} s ({row['min_s']:.4f}-{row['max_s']:.4f}) "
f"peak +{row['peak_rss_rise'] / 2**20:.1f} MiB load {row['load']:.1f}",
flush=True,
)
pkl.unlink()


if __name__ == "__main__":
if sys.argv[1] == "--op":
child(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], int(sys.argv[6]))
else:
main()
178 changes: 178 additions & 0 deletions experiments/histogram_storage_study/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
"""Datasets, plane records and histogram variants of the storage study (not for merge).

Every histogram is computed with this repository's own code
(``compute_plane_histogram`` / ``histogram_with_range_check``); nothing here bins a pixel.

Datasets (folder layout made by the commands in README.md, under ``DATA``):

``study`` preprocessing's ``tools/benchmark_run_workers.py`` data at scale 1 (PR #318): 14 seeded
uint16 images (TCYX, 2 channels), 76 channel planes, values 0..3499.
``cmu1`` OpenSlide test data CMU-1 (Aperio, CC0): 8 level-0 crops of 2048 x 2048 with the most
tissue, and CMU-1-Small-Region (2967 x 2220); uint8 RGB.
``hpmec`` MorphoRelate ``data/hpmec_perfusion``: 2 fields, 4 channels, 2048 x 2048, uint16.
``jump`` JUMP cpg0016 source_4 (CC0), the plates of MorphoRelate ``data/jump_target2``: 3 plates
(biological repeats) x wells E08 (DMSO) and D19 (FK-866) x sites 1-3, 5 channels,
1080 x 1080 uint16 (checked against MorphoRelate's ``sources.csv`` SHA-256).
"""

from __future__ import annotations

import os
import re
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path

import numpy as np

from morphobricks_normalization import (
HistogramSettings,
PlaneRecord,
compute_plane_histogram,
histogram_with_range_check,
)

DATA = Path(os.environ.get("D9_DATA", "data"))
WORK = Path(os.environ.get("D9_WORK", "work"))

# Histogram variants: name -> (bin_count or None for the default, histogram_range)
VARIANTS = {
"exact": (None, "minmax"),
"d4096": (4096, "minmax"),
"d4096r": (4096, "robust"),
"d1024": (1024, "minmax"),
"d1024r": (1024, "robust"),
}
JUMP_CHANNELS = {"ch5": "DNA", "ch4": "ER", "ch3": "RNA", "ch2": "AGP", "ch1": "Mito"}
JUMP_WELLS = {"r05c08": ("DMSO", "E08"), "r04c19": ("FK-866", "D19")}


@dataclass(frozen=True)
class Image:
"""One source image: its labels and how to read it as T, C, Y, X."""

rel: str
condition: str
repeat: str
techrep: str
position_id: str
channels: tuple[str, ...]
files: tuple[Path, ...] # one file (all channels) or one file per channel
kind: str # tiff_tcyx | zarr_tcyx | tiff_cyx | tiff_yx_per_channel | tiff_rgb | svs_rgb

def read(self) -> np.ndarray:
"""Return the pixels as (T, C, Y, X)."""
import tifffile

if self.kind == "tiff_tcyx":
return tifffile.imread(self.files[0])
if self.kind == "zarr_tcyx":
import zarr

return np.asarray(zarr.open_array(str(self.files[0] / "0"), mode="r")[...])
if self.kind == "tiff_cyx":
return tifffile.imread(self.files[0])[None]
if self.kind == "tiff_yx_per_channel":
return np.stack([tifffile.imread(f) for f in self.files])[None]
if self.kind in ("tiff_rgb", "svs_rgb"):
with tifffile.TiffFile(self.files[0]) as tif:
rgb = tif.pages[0].asarray()
return np.moveaxis(rgb, -1, 0)[None]
raise ValueError(self.kind)


def images(dataset: str) -> list[Image]:
"""The images of a dataset, in a fixed order."""
root = DATA / dataset
out = []
if dataset == "study":
for path in sorted((root / "experiment").glob("*/rep1/*")):
condition = path.parts[-3]
kind = "zarr_tcyx" if path.name.endswith(".zarr") else "tiff_tcyx"
stem = path.name.split(".")[0]
rel = f"{condition}/rep1/{path.name}"
out.append(
Image(rel, condition, "rep1", "single", stem, ("ch1", "ch2"), (path,), kind)
)
elif dataset == "cmu1":
files = sorted((root / "crops").glob("*.tif")) + [root / "CMU-1-Small-Region.svs"]
for path in files:
kind = "svs_rgb" if path.suffix == ".svs" else "tiff_rgb"
rel = f"slide/single/{path.name}"
out.append(
Image(rel, "slide", "single", "single", path.stem, ("R", "G", "B"), (path,), kind)
)
elif dataset == "hpmec":
for name, condition in (("Position_1", "HPMEC_ctrl"), ("Position_2", "HPMEC_cond2")):
path = root / f"{name}.tif"
rel = f"{condition}/single/{name}.tif"
chans = ("ch0", "ch1", "ch2", "ch3")
out.append(Image(rel, condition, "single", "single", name, chans, (path,), "tiff_cyx"))
elif dataset == "jump":
pattern = re.compile(r"(\d{4}_\d\d_\d\d)_Batch\d+__(r\d\dc\d\d)(f\d\d)p01-ch(\d)")
fields: dict[tuple[str, str, str], dict[str, Path]] = {}
for path in sorted(root.glob("*.tiff")):
date, well, site, ch = pattern.match(path.name).groups()
fields.setdefault((date, well, site), {})[f"ch{ch}"] = path
for (date, well, site), by_ch in sorted(fields.items()):
condition, well_name = JUMP_WELLS[well]
files = tuple(by_ch[ch] for ch in JUMP_CHANNELS)
chans = tuple(JUMP_CHANNELS.values())
pos = f"{date}_{well_name}_{site}"
rel = f"{condition}/{date}/{well_name}/{pos}.tiff"
kind = "tiff_yx_per_channel"
out.append(Image(rel, condition, date, well_name, pos, chans, files, kind))
else:
raise ValueError(dataset)
return out


def image_type(dataset: str) -> str:
return "rgb" if dataset == "cmu1" else "fluorescence"


def plane_histogram(pixels: np.ndarray, variant: str):
"""The histogram of one channel plane under a variant, and its range check (or None)."""
bins, histogram_range = VARIANTS[variant]
if variant == "exact":
return compute_plane_histogram(pixels), None
top = int(np.iinfo(pixels.dtype).max) + 1 if pixels.dtype.kind in "ui" else bins
bins = min(bins, top) # uint8 allows at most 256 bins: 1,024 and 4,096 do not apply
settings = HistogramSettings(histogram_range=histogram_range)
return histogram_with_range_check(
lambda: (pixels,), pixels.dtype, bins, settings=settings
)


def records_of(image: Image, data: np.ndarray, variant: str) -> tuple[list[PlaneRecord], list]:
"""One record per T plane of an image (Z is 1 in every dataset here), and range checks."""
records, checks = [], []
for t in range(data.shape[0]):
hists = []
for c, channel in enumerate(image.channels):
hist, check = plane_histogram(np.ascontiguousarray(data[t, c]), variant)
hists.append(hist)
checks.append((f"{image.rel}::t={t}", channel, check))
records.append(
PlaneRecord(
source_relative_path=image.rel,
condition=image.condition,
biological_repeat=image.repeat,
technical_repeat=image.techrep,
histograms=hists,
z=0,
t=t,
position_id=image.position_id,
channels=image.channels,
)
)
return records, checks


def iter_images(dataset: str) -> Iterator[tuple[Image, np.ndarray]]:
for image in images(dataset):
yield image, image.read()


def channel_ids(records: list[PlaneRecord]) -> tuple[str, ...]:
return tuple(sorted({c for r in records for c in r.channels}))
Loading
Loading