"""Cohort, folds and per-case data access. A data root holds one folder per case plus a cohort table: /cases.csv //geometry.json scanner and detector geometry //views.npz angle_rad (V,), z_mm (V,) [, source_isocenter_mm (V,)] //proj_full.npy (V, rows, cols) line integrals, routine dose //proj_low.npy optional, same shape: reduced-dose scan of the same acquisition //image.json reconstruction grid: z_mm, pixel_spacing_mm, origin_mm, thickness_mm //image_full.npy (S, H, W) HU, routine-dose reconstruction (teacher input) //image_low.npy optional, scanner reconstruction of proj_low (same slices) See README.md for every field. """ import json import os from dataclasses import dataclass from functools import cached_property from pathlib import Path import numpy as np import pandas as pd import torch import torch.nn.functional as F from sklearn.model_selection import StratifiedKFold HALF = 18.0 # slab half-length along the table, mm (a slab is 36 mm) STEP = 12.0 # spacing of evaluation slabs, mm SLAB_SHAPE = (24, 256, 256) # encoder input (slices, rows, columns) HU_RANGE = (-1024.0, 2048.0) # intensity window of the encoder input def to_input(x): """HU volume (S, H, W) -> encoder input (1, 24, 256, 256), values in [0, 1].""" lo, hi = HU_RANGE x = (x.clamp(lo, hi) - lo) / (hi - lo) return F.interpolate(x[None, None], SLAB_SHAPE, mode="trilinear", align_corners=False)[0] def slab_rows(z, z0): keep = np.flatnonzero(np.abs(z - z0) <= HALF) if len(keep) == 0: raise ValueError(f"no slices within {HALF} mm of z0={z0:.1f}") return slice(keep[0], keep[-1] + 1), z[keep[0]] > z[keep[-1]] class Case: """Lazy access to one case folder.""" def __init__(self, root, case_id, row=None): self.id, self.dir = case_id, Path(root) / case_id self.row = row or {} @cached_property def geometry(self): return json.loads((self.dir / "geometry.json").read_text()) @cached_property def image_meta(self): return json.loads((self.dir / "image.json").read_text()) @cached_property def views(self): with np.load(self.dir / "views.npz") as v: return {k: v[k] for k in v.files} def _field(self, name): """Value from cases.csv, falling back to geometry.json when the cell is empty.""" v = self.row.get(name) if v is None or (isinstance(v, float) and np.isnan(v)) or str(v).strip() in ("", "nan"): v = self.geometry.get(name) return v @property def manufacturer(self): return str(self._field("manufacturer")).strip() @property def region(self): return str(self.row.get("region", "unknown")) @property def low_dose_fraction(self): f = self._field("low_dose_fraction") if f is None: return None f = float(f) if not 0 < f < 1: raise ValueError(f"{self.id}: low_dose_fraction must be between 0 and 1, got {f}") return f def has(self, name): return (self.dir / f"{name}.npy").exists() def array(self, name): """proj_full, proj_low, image_full, image_low as read-only memory maps.""" return np.load(self.dir / f"{name}.npy", mmap_mode="r") @cached_property def image_z(self): return np.asarray(self.image_meta["z_mm"], dtype=np.float64) @cached_property def slab_range(self): """Slab centres with full image coverage and measurements around them.""" vz = self.views["z_mm"] lo = max(self.image_z.min(), vz.min()) + HALF hi = min(self.image_z.max(), vz.max()) - HALF return lo, hi def image_slab(self, z0, mirror=False, dose="full"): """Scanner image slab in the encoder input convention (1, 24, 256, 256).""" rows, flip = slab_rows(self.image_z, z0) x = torch.from_numpy(np.array(self.array(f"image_{dose}")[rows], dtype=np.float32)) x = to_input(x.flip(0) if flip else x) return x.flip(-1) if mirror else x def grid(self): lo, hi = self.slab_range return np.arange(lo, hi + 1e-6, STEP) def usable(self, image=True): """Covers at least one 36 mm slab (and has a routine-dose image when image=True).""" lo, hi = self.slab_range return hi >= lo and (self.has("image_full") or not image) @dataclass class Cohort: root: Path table: pd.DataFrame # one row per case: case_id, region, manufacturer, fold, ... def case(self, case_id): return Case(self.root, case_id, self.table.set_index("case_id").loc[case_id].to_dict()) def split(self, fold): """(training case ids, held-out case ids) for a cross-validation fold.""" t = self.table return t.case_id[t.fold != fold].tolist(), t.case_id[t.fold == fold].tolist() def ids(self): return self.table.case_id.tolist() def cases(self, ids, image=True): """Case objects for ids, skipping (with a message) cases too short or without images.""" out = [] for c in map(self.case, ids): if c.usable(image): out.append(c) else: print(f"skipping {c.id}: shorter than one slab" + (" or no image_full.npy" if image else ""), flush=True) return out def load_cohort(data_root, folds=5, seed=1234, strata=("region", "manufacturer"), work_dir=None): """Read cases.csv; draw stratified folds if the table has no `fold` column. Cases with `exclude` set are dropped after the folds are drawn, so excluding a case never moves another case to a different fold. Drawn folds are written to /folds.csv so later steps and reruns use the same split. """ root = Path(data_root) t = pd.read_csv(root / "cases.csv", dtype={"case_id": str}) if "manufacturer" not in t: t["manufacturer"] = None t["manufacturer"] = [Case(root, c, {"manufacturer": m}).manufacturer for c, m in zip(t.case_id, t.manufacturer)] if "region" not in t: t["region"] = "unknown" saved = Path(work_dir) / "folds.csv" if work_dir else None if "fold" not in t: if saved and saved.exists(): t = t.merge(pd.read_csv(saved, dtype={"case_id": str}), on="case_id", how="left") if t.fold.isna().any(): raise ValueError(f"{saved} does not cover every case in cases.csv; delete it to redraw folds") else: key = t[list(strata)].astype(str).agg("|".join, axis=1) small = key.map(key.value_counts()) < folds # rare strata are pooled key[small] = "other" t["fold"] = -1 for f, (_, te) in enumerate(StratifiedKFold(folds, shuffle=True, random_state=seed).split(t, key)): t.loc[t.index[te], "fold"] = f if saved: # atomic: concurrent ranks write identical content saved.parent.mkdir(parents=True, exist_ok=True) tmp = saved.with_suffix(f".{os.getpid()}.tmp") t[["case_id", "fold"]].to_csv(tmp, index=False) os.replace(tmp, saved) t["fold"] = t.fold.astype(int) if "exclude" in t: t = t[~t.exclude.fillna(0).astype(bool)] return Cohort(root, t.reset_index(drop=True)) def group_of(case, no_thin): """True if the case belongs to a REGION:MANUFACTURER group listed in no_thin.""" for g in no_thin: region, _, maker = g.partition(":") if (region in ("*", case.region)) and case.manufacturer.upper().startswith(maker.upper()): return True return False