| |
| """Create training-ready NPZ caches from preprocessed liver manifests. |
| |
| Outputs: |
| data/processed_training/waw_tace_npz/*.npz |
| data/processed_training/msd_liver_npz/*.npz |
| manifests/waw_tace_training_manifest.csv |
| manifests/msd_liver_training_manifest.csv |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| from pathlib import Path |
| from typing import Iterable |
|
|
| import numpy as np |
| import pandas as pd |
| import SimpleITK as sitk |
|
|
|
|
| PHASES = ["native", "arterial", "portal", "delayed"] |
| PHASE_PRIORITY = ["arterial", "portal", "native", "delayed"] |
| HU_MIN = -150.0 |
| HU_MAX = 400.0 |
|
|
|
|
| def rel(path: Path, root: Path) -> str: |
| path = path if path.is_absolute() else path.absolute() |
| root = root if root.is_absolute() else root.absolute() |
| try: |
| return str(path.relative_to(root)) |
| except ValueError: |
| return str(path) |
|
|
|
|
| def parse_spacing(value: str) -> tuple[float, float, float]: |
| parts = [float(x) for x in value.split(",")] |
| if len(parts) == 1: |
| return (parts[0], parts[0], parts[0]) |
| if len(parts) != 3: |
| raise ValueError("--spacing must be a single value or three comma-separated values") |
| return tuple(parts) |
|
|
|
|
| def nonempty(value: object) -> bool: |
| if value is None or pd.isna(value): |
| return False |
| return str(value).strip() != "" |
|
|
|
|
| def read_image(path: Path) -> sitk.Image: |
| return sitk.ReadImage(str(path)) |
|
|
|
|
| def make_reference_grid(image: sitk.Image, spacing_xyz: tuple[float, float, float]) -> sitk.Image: |
| original_spacing = image.GetSpacing() |
| original_size = image.GetSize() |
| size = [ |
| max(1, int(round(original_size[i] * original_spacing[i] / spacing_xyz[i]))) |
| for i in range(3) |
| ] |
| ref = sitk.Image(size, sitk.sitkFloat32) |
| ref.SetOrigin(image.GetOrigin()) |
| ref.SetSpacing(spacing_xyz) |
| ref.SetDirection(image.GetDirection()) |
| return ref |
|
|
|
|
| def resample_to_ref( |
| image: sitk.Image, |
| ref: sitk.Image, |
| *, |
| interpolator: int, |
| default_value: float = 0.0, |
| pixel_type: int | None = None, |
| ) -> sitk.Image: |
| if pixel_type is None: |
| pixel_type = image.GetPixelID() |
| return sitk.Resample( |
| image, |
| ref, |
| sitk.Transform(), |
| interpolator, |
| default_value, |
| pixel_type, |
| ) |
|
|
|
|
| def sitk_to_array(image: sitk.Image) -> np.ndarray: |
| return sitk.GetArrayFromImage(image) |
|
|
|
|
| def normalize_ct(array: np.ndarray) -> np.ndarray: |
| array = np.clip(array.astype(np.float32), HU_MIN, HU_MAX) |
| array = (array - HU_MIN) / (HU_MAX - HU_MIN) |
| return array.astype(np.float16) |
|
|
|
|
| def bbox_from_mask(mask: np.ndarray, margin_vox: tuple[int, int, int]) -> tuple[slice, slice, slice]: |
| coords = np.argwhere(mask > 0) |
| if coords.size == 0: |
| return tuple(slice(0, s) for s in mask.shape) |
| lo = coords.min(axis=0) |
| hi = coords.max(axis=0) + 1 |
| for axis in range(3): |
| lo[axis] = max(0, lo[axis] - margin_vox[axis]) |
| hi[axis] = min(mask.shape[axis], hi[axis] + margin_vox[axis]) |
| return slice(lo[0], hi[0]), slice(lo[1], hi[1]), slice(lo[2], hi[2]) |
|
|
|
|
| def choose_reference_phase(row: pd.Series) -> str | None: |
| |
| |
| for phase in PHASES: |
| if int(row.get(f"phase_available_{phase}", 0)) == 1 and nonempty(row.get(f"tumor_mask_{phase}_path")): |
| return phase |
| for phase in PHASE_PRIORITY: |
| if int(row.get(f"phase_available_{phase}", 0)) == 1 and nonempty(row.get(f"ct_{phase}_path")): |
| return phase |
| return None |
|
|
|
|
| def save_npz(path: Path, compressed: bool, **arrays: np.ndarray) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| if compressed: |
| np.savez_compressed(path, **arrays) |
| else: |
| np.savez(path, **arrays) |
|
|
|
|
| def process_waw_case( |
| row: pd.Series, |
| root: Path, |
| out_dir: Path, |
| spacing_xyz: tuple[float, float, float], |
| margin_mm: float, |
| overwrite: bool, |
| compressed: bool, |
| ) -> dict[str, object] | None: |
| patient_id = str(row["patient_id"]) |
| out_path = out_dir / f"{patient_id}.npz" |
| if out_path.exists() and not overwrite: |
| return { |
| "dataset": "waw_tace", |
| "patient_id": patient_id, |
| "case_id": patient_id, |
| "npz_path": rel(out_path, root), |
| "skipped_existing": 1, |
| } |
|
|
| ref_phase = choose_reference_phase(row) |
| if ref_phase is None: |
| return None |
| ref_ct_path = root / str(row[f"ct_{ref_phase}_path"]) |
| ref_grid = make_reference_grid(read_image(ref_ct_path), spacing_xyz) |
| margin_vox = tuple(max(1, int(round(margin_mm / s))) for s in spacing_xyz[::-1]) |
|
|
| image_channels = [] |
| phase_available = [] |
| liver_union = np.zeros(ref_grid.GetSize()[::-1], dtype=bool) |
| tumor_union = np.zeros(ref_grid.GetSize()[::-1], dtype=bool) |
|
|
| for phase in PHASES: |
| ct_path_value = row.get(f"ct_{phase}_path") |
| if nonempty(ct_path_value): |
| ct = read_image(root / str(ct_path_value)) |
| ct_resampled = resample_to_ref( |
| ct, |
| ref_grid, |
| interpolator=sitk.sitkLinear, |
| default_value=HU_MIN, |
| pixel_type=sitk.sitkFloat32, |
| ) |
| image_channels.append(normalize_ct(sitk_to_array(ct_resampled))) |
| phase_available.append(1) |
| else: |
| image_channels.append(np.zeros(ref_grid.GetSize()[::-1], dtype=np.float16)) |
| phase_available.append(0) |
|
|
| liver_path_value = row.get(f"liver_mask_{phase}_path") |
| if nonempty(liver_path_value): |
| liver = read_image(root / str(liver_path_value)) |
| liver_resampled = resample_to_ref( |
| liver, |
| ref_grid, |
| interpolator=sitk.sitkNearestNeighbor, |
| default_value=0, |
| pixel_type=sitk.sitkUInt8, |
| ) |
| liver_union |= sitk_to_array(liver_resampled) > 0 |
|
|
| tumor_path_value = row.get(f"tumor_mask_{phase}_path") |
| if nonempty(tumor_path_value): |
| tumor = read_image(root / str(tumor_path_value)) |
| tumor_resampled = resample_to_ref( |
| tumor, |
| ref_grid, |
| interpolator=sitk.sitkNearestNeighbor, |
| default_value=0, |
| pixel_type=sitk.sitkUInt8, |
| ) |
| tumor_union |= sitk_to_array(tumor_resampled) > 0 |
|
|
| crop_source = liver_union | tumor_union |
| crop = bbox_from_mask(crop_source, margin_vox) |
| image = np.stack([channel[crop] for channel in image_channels], axis=0).astype(np.float16) |
| liver_mask = liver_union[crop].astype(np.uint8) |
| tumor_mask = tumor_union[crop].astype(np.uint8) |
|
|
| clinical_cols = [ |
| c for c in row.index |
| if not c.endswith("_missing") |
| and c not in set(["dataset", "patient_id", "case_id"]) |
| and not c.endswith("_path") |
| and not c.startswith("ct_") |
| and not c.startswith("organ_mask_") |
| and not c.startswith("liver_mask_") |
| and not c.startswith("tumor_mask_") |
| ] |
| numeric = pd.to_numeric(row[clinical_cols], errors="coerce") |
| clinical_values = numeric.to_numpy(dtype=np.float32) |
| clinical_missing = np.isnan(clinical_values).astype(np.uint8) |
| clinical_values = np.nan_to_num(clinical_values, nan=0.0) |
|
|
| save_npz( |
| out_path, |
| compressed, |
| image=image, |
| liver_mask=liver_mask, |
| tumor_mask=tumor_mask, |
| phase_available=np.asarray(phase_available, dtype=np.uint8), |
| clinical_values=clinical_values, |
| clinical_missing=clinical_missing, |
| spacing=np.asarray(spacing_xyz, dtype=np.float32), |
| crop_start=np.asarray([crop[0].start, crop[1].start, crop[2].start], dtype=np.int32), |
| crop_stop=np.asarray([crop[0].stop, crop[1].stop, crop[2].stop], dtype=np.int32), |
| label_response=np.asarray([row.get("label_response", np.nan)], dtype=np.float32), |
| label_progression=np.asarray([row.get("label_progression", np.nan)], dtype=np.float32), |
| time_pfs=np.asarray([row.get("time_pfs", np.nan)], dtype=np.float32), |
| event_pfs=np.asarray([row.get("event_pfs", np.nan)], dtype=np.float32), |
| time_os=np.asarray([row.get("time_os", np.nan)], dtype=np.float32), |
| event_os=np.asarray([row.get("event_os", np.nan)], dtype=np.float32), |
| time_ttp=np.asarray([row.get("time_ttp", np.nan)], dtype=np.float32), |
| event_ttp=np.asarray([row.get("event_ttp", np.nan)], dtype=np.float32), |
| ) |
|
|
| return { |
| "dataset": "waw_tace", |
| "patient_id": patient_id, |
| "case_id": patient_id, |
| "npz_path": rel(out_path, root), |
| "reference_phase": ref_phase, |
| "spacing_x": spacing_xyz[0], |
| "spacing_y": spacing_xyz[1], |
| "spacing_z": spacing_xyz[2], |
| "shape_c": image.shape[0], |
| "shape_z": image.shape[1], |
| "shape_y": image.shape[2], |
| "shape_x": image.shape[3], |
| "phase_available_native": phase_available[0], |
| "phase_available_arterial": phase_available[1], |
| "phase_available_portal": phase_available[2], |
| "phase_available_delayed": phase_available[3], |
| "has_liver_mask": int(liver_mask.any()), |
| "has_tumor_mask": int(tumor_mask.any()), |
| "label_response": row.get("label_response", np.nan), |
| "label_progression": row.get("label_progression", np.nan), |
| "time_pfs": row.get("time_pfs", np.nan), |
| "event_pfs": row.get("event_pfs", np.nan), |
| "time_os": row.get("time_os", np.nan), |
| "event_os": row.get("event_os", np.nan), |
| "time_ttp": row.get("time_ttp", np.nan), |
| "event_ttp": row.get("event_ttp", np.nan), |
| "skipped_existing": 0, |
| } |
|
|
|
|
| def build_waw_cache(args: argparse.Namespace, root: Path) -> pd.DataFrame: |
| manifest = pd.read_csv(root / "manifests" / "waw_tace_manifest.csv") |
| out_dir = root / "data" / "processed_training" / "waw_tace_npz" |
| rows = [] |
| spacing_xyz = parse_spacing(args.spacing) |
| iterable: Iterable[tuple[int, pd.Series]] = manifest.iterrows() |
| for i, row in iterable: |
| if args.limit and len(rows) >= args.limit: |
| break |
| result = process_waw_case( |
| row, |
| root, |
| out_dir, |
| spacing_xyz, |
| args.margin_mm, |
| args.overwrite, |
| args.compressed, |
| ) |
| if result is not None: |
| rows.append(result) |
| if len(rows) % args.progress_every == 0: |
| print(f"WAW cached {len(rows)}/{len(manifest)}") |
| df = pd.DataFrame(rows) |
| path = root / "manifests" / "waw_tace_training_manifest.csv" |
| path.parent.mkdir(parents=True, exist_ok=True) |
| df.to_csv(path, index=False) |
| print(f"Wrote {path} ({len(df)} rows)") |
| return df |
|
|
|
|
| def process_msd_case( |
| row: pd.Series, |
| root: Path, |
| out_dir: Path, |
| spacing_xyz: tuple[float, float, float], |
| margin_mm: float, |
| overwrite: bool, |
| compressed: bool, |
| ) -> dict[str, object]: |
| case_id = str(row["case_id"]) |
| out_path = out_dir / f"{case_id}.npz" |
| if out_path.exists() and not overwrite: |
| with np.load(out_path) as data: |
| shape = data["image"].shape |
| return { |
| "dataset": "msd_liver", |
| "patient_id": case_id, |
| "case_id": case_id, |
| "npz_path": rel(out_path, root), |
| "shape_c": shape[0], |
| "shape_z": shape[1], |
| "shape_y": shape[2], |
| "shape_x": shape[3], |
| "skipped_existing": 1, |
| } |
|
|
| image_src = root / str(row["ct_path"]) |
| label_src = root / str(row["label_path"]) |
| image = read_image(image_src) |
| label = read_image(label_src) |
| ref_grid = make_reference_grid(image, spacing_xyz) |
| image_resampled = resample_to_ref( |
| image, |
| ref_grid, |
| interpolator=sitk.sitkLinear, |
| default_value=HU_MIN, |
| pixel_type=sitk.sitkFloat32, |
| ) |
| label_resampled = resample_to_ref( |
| label, |
| ref_grid, |
| interpolator=sitk.sitkNearestNeighbor, |
| default_value=0, |
| pixel_type=sitk.sitkUInt8, |
| ) |
| image_arr = normalize_ct(sitk_to_array(image_resampled)) |
| label_arr = sitk_to_array(label_resampled).astype(np.uint8) |
| margin_vox = tuple(max(1, int(round(margin_mm / s))) for s in spacing_xyz[::-1]) |
| crop = bbox_from_mask(label_arr > 0, margin_vox) |
| image_arr = image_arr[crop][None, ...].astype(np.float16) |
| label_arr = label_arr[crop].astype(np.uint8) |
| save_npz( |
| out_path, |
| compressed, |
| image=image_arr, |
| label=label_arr, |
| spacing=np.asarray(spacing_xyz, dtype=np.float32), |
| crop_start=np.asarray([crop[0].start, crop[1].start, crop[2].start], dtype=np.int32), |
| crop_stop=np.asarray([crop[0].stop, crop[1].stop, crop[2].stop], dtype=np.int32), |
| ) |
| return { |
| "dataset": "msd_liver", |
| "patient_id": case_id, |
| "case_id": case_id, |
| "npz_path": rel(out_path, root), |
| "spacing_x": spacing_xyz[0], |
| "spacing_y": spacing_xyz[1], |
| "spacing_z": spacing_xyz[2], |
| "shape_c": image_arr.shape[0], |
| "shape_z": image_arr.shape[1], |
| "shape_y": image_arr.shape[2], |
| "shape_x": image_arr.shape[3], |
| "has_liver_mask": int((label_arr == 1).any()), |
| "has_tumor_mask": int((label_arr == 2).any()), |
| "skipped_existing": 0, |
| } |
|
|
|
|
| def build_msd_cache(args: argparse.Namespace, root: Path) -> pd.DataFrame: |
| manifest = pd.read_csv(root / "manifests" / "msd_liver_manifest.csv") |
| out_dir = root / "data" / "processed_training" / "msd_liver_npz" |
| rows = [] |
| spacing_xyz = parse_spacing(args.spacing) |
| for _, row in manifest.iterrows(): |
| if args.limit and len(rows) >= args.limit: |
| break |
| rows.append( |
| process_msd_case( |
| row, |
| root, |
| out_dir, |
| spacing_xyz, |
| args.margin_mm, |
| args.overwrite, |
| args.compressed, |
| ) |
| ) |
| if len(rows) % args.progress_every == 0: |
| print(f"MSD cached {len(rows)}/{len(manifest)}") |
| df = pd.DataFrame(rows) |
| path = root / "manifests" / "msd_liver_training_manifest.csv" |
| path.parent.mkdir(parents=True, exist_ok=True) |
| df.to_csv(path, index=False) |
| print(f"Wrote {path} ({len(df)} rows)") |
| return df |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("--project-root", type=Path, default=Path(__file__).resolve().parents[1]) |
| parser.add_argument("--dataset", choices=["waw", "msd", "all"], default="all") |
| parser.add_argument("--spacing", default="2.0", help="Target spacing in xyz order, e.g. 2.0 or 2.0,2.0,2.0.") |
| parser.add_argument("--margin-mm", type=float, default=20.0) |
| parser.add_argument("--limit", type=int, default=0) |
| parser.add_argument("--progress-every", type=int, default=10) |
| parser.add_argument("--overwrite", action="store_true") |
| parser.add_argument("--compressed", action="store_true", help="Use compressed NPZ. Slower, smaller.") |
| args = parser.parse_args() |
|
|
| root = args.project_root.resolve() |
| config_path = root / "data" / "processed_training" / "cache_config.json" |
| config_path.parent.mkdir(parents=True, exist_ok=True) |
| config_path.write_text(json.dumps(vars(args) | {"project_root": str(root)}, indent=2)) |
|
|
| if args.dataset in {"waw", "all"}: |
| build_waw_cache(args, root) |
| if args.dataset in {"msd", "all"}: |
| build_msd_cache(args, root) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|