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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#!/usr/bin/env python3
"""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)  # type: ignore[return-value]
    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:
    # Prefer a phase with manual tumor supervision so the support map keeps its
    # native grid before other phases are resampled onto it.
    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()