#!/usr/bin/env python """Run the deploy-candidate stroke cascade "c2t(b)" (as of 2026-11-21) end to end on any set of co-registered T1 + FLAIR NIfTI pairs, and optionally evaluate against ground-truth masks. This is NOT a re-implementation: every stage calls the project's own functions (whisper_synth/src/direction2) in the same order and with the same arguments as the integrator's dev-test path (cls2_testprep -> cascade2_infer test -> int_candscore / int_candgen fm4 -> stk_fm4 x2 + c4b_apply / c4b_fm4feat -> stk g_xc5b_c2t -> int_e2e infer (p2heat) -> int_compose.forced_draw -> int_peakcls --sat extra -> int_fpdecomp.compose_gate). See README.md for the component list, thresholds and assumptions. Stages (each cached in OUT/work//, so a crashed or requeued run resumes with --resume): prep T1 -> D331-plans nnU-Net preprocessing (crop to nonzero, 1 mm, z-score in mask); brain = filled nonzero T1 region [CPU] detect 4 detector networks (renderer folds iv_f0/1/2 + ivT f0) on [T1, FLAIR]; T1 is zeroed inside the network [GPU] d331 D331 T1-only probability (raw grid) [GPU, fp32] c2t c2t T1 evidence map (D331-preprocessed grid) [GPU] cands fm4 candidates + 355 g_xc5 features + 17 c2t features -> g_xc5b_c2t score -> accept (>= threshold) [CPU + GPU D331 deep features] draw p2heat drawer: prompt = fm4 heat x cube-dilate(accepted, 2), one whole-volume pass [GPU, fp32] gate forced draw; keep the largest piece per accepted candidate + extras with s_sepd >= gate threshold -> final mask [CPU + GPU D331 deep features] heat3 (base pipelines) ivT folds 1 + 2 (fold 0 reused from detect) -> ivT3 mean heat exactly as cascade2_infer.test_mean [GPU] base (base pipelines) Dataset979 DelBankConvRen[Tiny] on [T1, ivT3 heat] -> p(lesion), as cascade2_infer.seg [GPU] compose (non-default pipelines) base = p >= .5; union = c2t(b) final | base; nogate = drawn, no gate (int_compose "dm"); union_nogate = nogate | base (int_baseunion.py definitions) [CPU] eval (needs a GT mask) lesion / component / Dice / boundary metrics with the int_scorecard definitions [CPU] Pipelines (--pipeline; default c2tb = the validated c2t(b) cascade, unchanged): c2tb final mask = gated c2t(b) -> cases//_mask.nii.gz base ivT3 heat -> DelBankConv base, p >= .5 -> cases//_mask.nii.gz union c2t(b) final OR base -> cases//_mask.nii.gz union_nogate c2t(b) drawing without the fragment gate OR base -> cases//_mask.nii.gz nogate c2t(b) drawing without the fragment gate -> cases//_mask.nii.gz best3 RECOMMENDED: five masks from one run (shared stages; the smooth variants cost no extra GPU work) cases//_cascade.nii.gz c2t(b) with the G2 step gate + S* growth cases//_cascade_smooth.nii.gz c2t(b) with the smooth G2s-interp gate + S* growth cases//_delbankconv.nii.gz Ren DelBankConv base, p >= .5 cases//_twopath.nii.gz cascade OR delbankconv cases//_twopath_smooth.nii.gz cascade_smooth OR delbankconv all every mask from one run (shared stages) -> cases//_mask_{c2tb,nogate,base,union,union_nogate,cascade_g2s,cascade_smooth,twopath,twopath_smooth}.nii.gz --base_model ren|rentiny selects the base network (cascade_config.json "base"; default = base.default_model). Usage: run_cascade.py --cases cases.csv --out OUT [--pipeline c2tb|base|union|union_nogate|nogate|all] [--base_model ren|rentiny] [--eval] [--keep_intermediates] [--resume] [--stages prep,detect,...] [--chunk i --nchunk n] run_cascade.py --t1_glob '/data/*_T1.nii.gz' --flair_glob '/data/*_FLAIR.nii.gz' [--gt_glob '/data/*_lesion.nii.gz'] --out OUT ... run_cascade.py --out OUT --summarize_only (rebuild OUT/eval/summary.md from the per-case eval files) cases.csv columns: case_id, t1, flair, [gt], [mask] (mask optional: multiplied into T1 and FLAIR when the inputs are not skull-stripped) """ from __future__ import annotations import argparse, contextlib, csv, glob, hashlib, json, os, pickle, platform, re, shutil, socket, sys, time, traceback from pathlib import Path import numpy as np TOOL = Path(__file__).resolve().parent CFG = json.load(open(TOOL / "cascade_config.json")) BASE = Path(CFG["base_dir"]) SRC = BASE / "whisper_synth/src/direction2" # ---- environment identical to the project's run_py.sh wrappers (must be set before the project modules are imported) for k, v in {"nnUNet_raw": str(BASE / "nnunet_raw"), "nnUNet_preprocessed": str(BASE / "nnunet_preprocessed"), "nnUNet_results": str(BASE / "whisper_results"), "TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD": "1"}.items(): os.environ.setdefault(k, v) os.environ.update({"C2_ZERO_OUTSIDE": "1", "C2_EXCLUDE_MALFORMED": "1", "INT_IV3": "1", "INT_HEAT": "fm4", "OPENBLAS_NUM_THREADS": "1"}) for p in (str(SRC), str(BASE / "whisper_synth/src"), str(BASE / "src/nnUNet")): if p not in sys.path: sys.path.insert(0, p) STAGES = ("prep", "detect", "d331", "c2t", "cands", "draw", "gate", "eval") DET_ORDER = ("iv_f0", "iv_f1", "iv_f2", "ivT_f0") # ---- 2026-11-22 extension: base / union pipelines (the c2tb stage list above is unchanged) ALL_STAGES = ("prep", "detect", "d331", "c2t", "cands", "draw", "gate", "heat3", "base", "compose", "eval") PIPELINES = {"c2tb": ("c2tb",), "base": ("base",), "union": ("union",), "union_nogate": ("union_nogate",), "nogate": ("nogate",), "best3": ("cascade_g2s", "cascade_smooth", "base", "twopath", "twopath_smooth"), "all": ("c2tb", "nogate", "base", "union", "union_nogate", "cascade_g2s", "cascade_smooth", "twopath", "twopath_smooth")} KIND_LABEL = {"c2tb": "c2t(b) final (gated)", "nogate": "c2t(b) drawn, no fragment gate", "base": "DelBankConv base (ivT3 heat), p >= .5", "union": "c2t(b) final OR base", "union_nogate": "c2t(b) drawn, no gate, OR base", "cascade_g2s": "cascade: c2t(b) with the G2 step gate + S* growth", "cascade_smooth": "cascade_smooth: c2t(b) with the smooth G2s-interp gate + S* growth", "twopath": "two-path: cascade (G2 x S*) OR DelBankConv base", "twopath_smooth": "two-path smooth: cascade_smooth OR DelBankConv base"} # best3 output file / eval-dir names (internal kind -> plain name) OUTNAME = {"best3": {"cascade_g2s": "cascade", "cascade_smooth": "cascade_smooth", "base": "delbankconv", "twopath": "twopath", "twopath_smooth": "twopath_smooth"}} BASE_KINDS = {"base", "union", "union_nogate", "twopath", "twopath_smooth"} GATE_KINDS = {"c2tb", "union", "cascade_g2s", "cascade_smooth", "twopath", "twopath_smooth"} # kinds that need the gate stage (s_sepd scores of the extras) G2S_KINDS = {"cascade_g2s", "cascade_smooth", "twopath", "twopath_smooth"} CASCADE_G2S = ("cascade_g2s", "cascade_smooth") # written by the gate stage (both variants always together) def interp_thr(ml, lo, hi, v_lo, v_hi): """int_tiny_smooth.interp_thr (rule G2s-interp), with its V_LO / V_HI passed in from cascade_config.json.""" x = (np.log10(max(ml, 1e-9)) - np.log10(v_lo)) / (np.log10(v_hi) - np.log10(v_lo)) return lo + (hi - lo) * float(np.clip(x, 0.0, 1.0)) HEAT3_ORDER = ("ivT_f0", "ivT_f1", "ivT_f2") def pipeline_stages(pipe): """stages a pipeline needs, in ALL_STAGES order (c2tb -> exactly the validated STAGES[:-1]).""" k = set(PIPELINES[pipe]); st = set() if k - {"base"}: st |= {"prep", "detect", "d331", "c2t", "cands", "draw"} if k & GATE_KINDS: st.add("gate") if k & BASE_KINDS: st |= {"heat3", "base", "d331"} # d331 only feeds the D331-blind eval column for the base alone if k - {"c2tb", "cascade_g2s", "cascade_smooth"}: st.add("compose") return [s for s in ALL_STAGES if s in st] def ndi_find_objects(a): import scipy.ndimage as ndi return ndi.find_objects(a) def log(*a): print(time.strftime("%Y-%m-%d %H:%M:%S"), *a, flush=True) # ================================================================================================ small I/O helpers def read_img(p): import SimpleITK as sitk return sitk.ReadImage(str(p)) def read_arr(p, dtype=np.float32): import SimpleITK as sitk return sitk.GetArrayFromImage(read_img(p)).astype(dtype) def write_like(arr, ref_path, out, dtype): import SimpleITK as sitk ref = read_img(ref_path) arr = np.asarray(arr) assert arr.shape == sitk.GetArrayFromImage(ref).shape, (out, arr.shape) im = sitk.GetImageFromArray(arr.astype(dtype)); im.CopyInformation(ref) Path(out).parent.mkdir(parents=True, exist_ok=True) tmp = str(out) + f".tmp{os.getpid()}.nii.gz"; sitk.WriteImage(im, tmp, True); os.replace(tmp, out) def save_npz(path, **kw): Path(path).parent.mkdir(parents=True, exist_ok=True) tmp = str(path) + f".tmp{os.getpid()}.npz"; np.savez_compressed(tmp, **kw); os.replace(tmp, path) def dump_json(obj, path): Path(path).parent.mkdir(parents=True, exist_ok=True) tmp = str(path) + f".tmp{os.getpid()}"; json.dump(obj, open(tmp, "w"), indent=1, default=_jd); os.replace(tmp, path) def _jd(o): if isinstance(o, (np.integer,)): return int(o) if isinstance(o, (np.floating,)): return float(o) if isinstance(o, np.bool_): return bool(o) if isinstance(o, Path): return str(o) return str(o) def rd250(a): """cls3_common._rd semantics: stored uint8 x250 -> probability (divide only when max > 1.5, as the project reader does).""" a = np.asarray(a, np.float32) return a / 250.0 if a.max() > 1.5 else a def sha256(p, cache): st = os.stat(p); key = f"{p}|{st.st_size}|{int(st.st_mtime)}" if key not in cache: h = hashlib.sha256() with open(p, "rb") as f: for b in iter(lambda: f.read(1 << 22), b""): h.update(b) cache[key] = h.hexdigest() return cache[key] @contextlib.contextmanager def fp32_gpu(): """Run a GPU pass in plain float32 (autocast off, TF32 off) for stages whose stored reference ran on CPU in float32 (D331 probability, D331 deep features, p2heat drawer); keeps GPU results numerically equal to the CPU reference.""" import torch class _NoAutocast: def __init__(self, *a, **k): pass def __enter__(self): return self def __exit__(self, *a): return False def __call__(self, f): return f orig = torch.autocast; tf = (torch.backends.cudnn.allow_tf32, torch.backends.cuda.matmul.allow_tf32) torch.autocast = _NoAutocast; torch.backends.cudnn.allow_tf32 = False; torch.backends.cuda.matmul.allow_tf32 = False try: yield finally: torch.autocast = orig; torch.backends.cudnn.allow_tf32, torch.backends.cuda.matmul.allow_tf32 = tf # ================================================================================================ cases class Case: def __init__(self, cid, t1, flair, gt=None, mask=None): self.cid, self.t1, self.flair, self.gt, self.mask = cid, str(t1), str(flair), (str(gt) if gt else None), (str(mask) if mask else None) self.t1_in, self.fl_in = self.t1, self.flair def safe_id(s): s = re.sub(r"[^A-Za-z0-9._+-]+", "_", s.strip()).strip("_") assert s, "empty case_id" return s def glob_cases(t1g, flg, gtg=None): def match(pat): rx = re.compile("^" + re.escape(pat).replace(r"\*", "(.+?)") + "$") out = {} for f in sorted(glob.glob(pat)): m = rx.match(f) if m: out["_".join(m.groups())] = f return out T, Fl = match(t1g), match(flg); G = match(gtg) if gtg else {} miss = sorted(set(T) ^ set(Fl)) if miss: log("WARNING: unpaired ids (skipped):", miss[:20]) return [Case(safe_id(k), T[k], Fl[k], G.get(k)) for k in sorted(set(T) & set(Fl))] def read_cases(path): rows = list(csv.DictReader(open(path))) assert rows, f"no rows in {path}" need = {"case_id", "t1", "flair"}; assert need <= set(rows[0]), f"{path} needs columns {sorted(need)} (+ optional gt, mask)" out = [Case(safe_id(r["case_id"]), r["t1"], r["flair"], (r.get("gt") or "").strip() or None, (r.get("mask") or "").strip() or None) for r in rows] ids = [c.cid for c in out]; assert len(set(ids)) == len(ids), "duplicate case_id" return out # ================================================================================================ models class Models: """lazily loaded networks / classifiers; GPU networks stay resident across cases.""" def __init__(self, device): import torch self.device = device; self.dev = torch.device(device); self._m = {} def det(self, name): if name not in self._m: import cascade2_infer as I, cascade2_common as C f = CFG["detector"]["folds"][name] assert C.fold_index(C.DET, f["fold_name"]) == f["fold"], (name, f) self._m[name] = I.predictor(I.model_dir(C.DET, f["trainer"]), [f["fold"]], self.device) return self._m[name] def d331(self): if "d331" not in self._m: import cascade2_infer as I, devset_common as D assert D.model_fold("d331") == 0 self._m["d331"] = I.predictor(D.model_dir("d331"), [0], self.device) return self._m["d331"] def d331_net(self): net = self.d331().network.to(self.dev).eval() return net def drawer(self): if "drawer" not in self._m: import cascade2_infer as I, cascade2_common as C, prompt2_infer as PI d = CFG["drawer"] assert PI.MODELS["p2heat"][0] == d["trainer"] and PI.FOLD == d["fold_name"] and C.fold_index(C.DEL, PI.FOLD) == d["fold"] self._m["drawer"] = I.predictor(I.model_dir(C.DEL, d["trainer"]), [d["fold"]], self.device) return self._m["drawer"] def c2t(self): if "c2t" not in self._m: import torch, c4b_train3 as T3 pt = BASE / CFG["model_files"]["c2t evidence net"]; meta = json.load(open(BASE / CFG["model_files"]["c2t evidence net meta"])) net = T3.make_net(False, meta.get("nout", meta["ncls"]), meta.get("in_ch", 1)).to(self.dev) net.load_state_dict(torch.load(pt, map_location=self.dev, weights_only=False)); net.eval() assert not meta.get("mirror"), "mirror-input evidence nets are not part of c2t(b)" self._m["c2t"] = (net, int(meta.get("patch", 128)), meta) return self._m["c2t"] def clf(self): if "clf" not in self._m: self._m["clf"] = pickle.load(open(BASE / CFG["classifier"]["model"], "rb")) return self._m["clf"] # ---- base pipelines def det_heat3(self, name): """ivT detector folds for the ivT3 mean heat (fold 0 is the same network as detector ivT_f0).""" key = f"heat3_{name}" if key not in self._m: import cascade2_infer as I, cascade2_common as C h = CFG["base"]["heat"]; f = h["folds"][name] assert C.fold_index(C.DET, f["fold_name"]) == f["fold"], (name, f) self._m[key] = I.predictor(I.model_dir(C.DET, h["trainer"]), [f["fold"]], self.device) return self._m[key] def base(self, model, ckpt): """Dataset979 DelBankConv base, loaded exactly as cascade2_infer.seg (nnUNetPredictor, step 0.5, Gaussian, no mirroring).""" key = f"base_{model}_{ckpt}" if key not in self._m: import cascade2_infer as I, cascade2_common as C b = CFG["base"]; m = b["models"][model] assert C.fold_index(C.DEL, b["fold_name"]) == b["fold"] and C.PLANS[C.DEL] == b["plans"], b self._m[key] = I.predictor(I.model_dir(C.DEL, m["trainer"]), [b["fold"]], self.device, False, ckpt) return self._m[key] # ================================================================================================ the runner class Runner: def __init__(self, a): self.a = a; self.out = Path(a.out); self.M = None; self.mem = {} # ---------------------------------------------------------------- per-case cache in memory (D331 deep features, patient context) def _case_mem(self, cid): if self.mem.get("cid") != cid: self.mem = {"cid": cid} return self.mem def models(self): if self.M is None: self.M = Models(self.a.device) return self.M def W(self, c): return self.out / "work" / c.cid def O(self, c): return self.out / "cases" / c.cid # ---------------------------------------------------------------- pipeline outputs (c2tb: mask_path(c, "c2tb") = cases//_mask.nii.gz) def kinds(self): return PIPELINES[self.a.pipeline] def multi(self): return len(PIPELINES[self.a.pipeline]) > 1 def mask_path(self, c, kind): if kind not in self.kinds(): return self.W(c) / f"mask_{kind}.nii.gz" # intermediate (e.g. the c2t(b) final inside the union / best3 pipelines) on = OUTNAME.get(self.a.pipeline) if on: return self.O(c) / f"{c.cid}_{on[kind]}.nii.gz" if self.multi(): return self.O(c) / f"{c.cid}_mask_{kind}.nii.gz" return self.O(c) / f"{c.cid}_mask.nii.gz" def eval_path(self, c, kind): if self.multi(): return self.out / "eval" / OUTNAME.get(self.a.pipeline, {}).get(kind, kind) / "cases" / f"{c.cid}.json" return self.out / "eval" / "cases" / f"{c.cid}.json" # ---------------------------------------------------------------- input checks / harmonisation def inputs(self, c, info): import SimpleITK as sitk W = self.W(c); W.mkdir(parents=True, exist_ok=True) t1 = read_img(c.t1); fl = read_img(c.flair) info["t1_size"] = list(t1.GetSize()); info["t1_spacing"] = [round(x, 4) for x in t1.GetSpacing()] same = (t1.GetSize() == fl.GetSize() and np.allclose(t1.GetSpacing(), fl.GetSpacing(), atol=1e-4) and np.allclose(t1.GetOrigin(), fl.GetOrigin(), atol=1e-3) and np.allclose(t1.GetDirection(), fl.GetDirection(), atol=1e-4)) c.t1_in, c.fl_in = c.t1, c.flair if not same: p = W / "flair_on_t1grid.nii.gz" if not p.exists(): r = sitk.Resample(fl, t1, sitk.Transform(), sitk.sitkLinear, 0.0, sitk.sitkFloat32) tmp = str(p) + f".tmp{os.getpid()}.nii.gz"; sitk.WriteImage(r, tmp, True); os.replace(tmp, p) c.fl_in = str(p); info.setdefault("warnings", []).append("FLAIR grid differs from T1 grid: FLAIR resampled onto the T1 grid (linear, world coordinates; assumes it is already co-registered)") if c.mask: pm = W / "t1_masked.nii.gz"; pf = W / "flair_masked.nii.gz" if not (pm.exists() and pf.exists()): m = sitk.GetArrayFromImage(read_img(c.mask)) > 0 for src, dst in ((c.t1_in, pm), (c.fl_in, pf)): im = read_img(src); a = sitk.GetArrayFromImage(im); assert a.shape == m.shape, f"mask grid != image grid for {c.cid}" o = sitk.GetImageFromArray(np.where(m, a, 0).astype(a.dtype)); o.CopyInformation(im) tmp = str(dst) + f".tmp{os.getpid()}.nii.gz"; sitk.WriteImage(o, tmp, True); os.replace(tmp, dst) c.t1_in, c.fl_in = str(pm), str(pf); info["brain_mask"] = c.mask a = sitk.GetArrayFromImage(read_img(c.t1_in)) nz = float((a != 0).mean()); info["t1_nonzero_fraction"] = round(nz, 4) if nz > 0.6: info.setdefault("warnings", []).append(f"T1 nonzero fraction {nz:.2f}: T1 does not look skull-stripped; the brain mask is the nonzero T1 region (give a 'mask' column)") # ---------------------------------------------------------------- stage: prep def prep(self, c, info): import dethead_apply as A W = self.W(c) t1, seg, props = A.preprocess_t1(c.t1_in) brain = seg != -1 t1 = np.where(brain, t1, 0).astype(np.float32) # parity: the dev-test path read the preprocessed T1 back from the classifier2 cache, stored as float16 (cls2_testprep.prep) save_npz(W / "prep.npz", t1=t1.astype(np.float16), brain=brain) tmp = str(W / "props.pkl") + f".tmp{os.getpid()}"; pickle.dump(props, open(tmp, "wb")); os.replace(tmp, W / "props.pkl") info["pp_shape"] = list(t1.shape); info["brain_ml"] = float(brain.sum()) / 1000.0 def load_prep(self, c): W = self.W(c); z = np.load(W / "prep.npz") return z["t1"].astype(np.float32), z["brain"].astype(bool), pickle.load(open(W / "props.pkl", "rb")) # ---------------------------------------------------------------- stage: detect (cascade2_infer.run_test, per fold) def detect(self, c, info): import cascade2_infer as I files = [c.t1_in, c.fl_in]; t1b = read_arr(c.t1_in) > 0; out = {} for nm in DET_ORDER: p = I.predict_raw(self.models().det(nm), files) * t1b out[nm] = np.clip(np.round(p * 250), 0, 250).astype(np.uint8) save_npz(self.W(c) / "heat_folds.npz", **out) def heats_raw(self, c): """-> (renderer fold heats [3], ivT f0, iv3 mean, fm4 heat) on the raw grid, exactly as cls3_common.test_heat / int_e2e.get_heat.""" z = np.load(self.W(c) / "heat_folds.npz") f = [rd250(z[k].astype(np.float32)) for k in ("iv_f0", "iv_f1", "iv_f2")] ivT = rd250(z["ivT_f0"].astype(np.float32)) iv3 = (np.round(np.mean(f, 0) * 250) / 250).astype(np.float32) fm4 = np.maximum(iv3, np.round(ivT * 250) / 250).astype(np.float32) return f, ivT, iv3, fm4 # ---------------------------------------------------------------- stage: d331 (arch2stage_t1prob) def d331(self, c, info): from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO img, props = SimpleITKIO().read_images([c.t1_in]) with (fp32_gpu() if self.a.device != "cpu" else contextlib.nullcontext()): _s, prob = self.models().d331().predict_single_npy_array(img, props, None, None, True) write_like(np.clip(np.round(np.asarray(prob)[1] * 250), 0, 250).astype(np.uint8), c.t1_in, self.W(c) / "d331_prob.nii.gz", np.uint8) def p331_pp(self, c, props, shape, brain): import dethead_cand as K pr = rd250(read_arr(self.W(c) / "d331_prob.nii.gz")) p = K.dev_to_pp(pr, props, shape) * brain return np.clip(np.round(p * 250), 0, 250).astype(np.uint8).astype(np.float32) / 250 # cls2_testprep cache round trip # ---------------------------------------------------------------- stage: c2t (c4b_apply.infer) def c2t(self, c, info): import c4b_apply as AP t1, brain, props = self.load_prep(c) tb = t1[brain] assert abs(float(tb.mean())) < 0.5 and 0.6 < float(tb.std()) < 1.6, ("preprocessing mismatch (not brain-masked z-score)", float(tb.mean()), float(tb.std())) net, P, meta = self.models().c2t() ev = np.mean([AP.infer(net, t1, brain, self.models().dev, P=P, step=P // 2, extra=None, ncls=meta["ncls"])], 0) save_npz(self.W(c) / "c2t_ev.npz", ev=np.clip(np.round(ev * 250), 0, 250).astype(np.uint8)) # ---------------------------------------------------------------- shared: patient context + D331 deep features (cls3_cand.score_setting inputs) def ctx_feats(self, c, t1, brain, props): import torch, dethead_cand as K, cls2_d331feat as DF mem = self._case_mem(c.cid) if "ctx" not in mem: mem["ctx"] = K.patient_ctx(t1, brain, props, c.cid) if "d331" not in mem: t0 = time.time(); dev = self.models().dev with (fp32_gpu() if self.a.device != "cpu" else contextlib.nullcontext()), torch.no_grad(): d1, d2, mg = DF.features(self.models().d331_net(), np.where(brain, t1, 0).astype(np.float32), dev, DF.gaussian(dev)) mem["d331"] = (d1.cpu(), d2.cpu(), mg.cpu()) # pooled on the CPU like the reference (score_setting device = cpu) del d1, d2, mg if dev.type == "cuda": torch.cuda.empty_cache() mem["t_d331feat"] = time.time() - t0 return mem["ctx"], {"d331": mem["d331"]} def score_components(self, c, L, n, h, t1, brain, props, probs, setting): """cls3_cand.score_setting on an explicit label map (int_candscore / int_peakcls monkey-patch new_cands the same way).""" import torch, cls3_cand as CC ctx, cache = self.ctx_feats(c, t1, brain, props) CC.new_cands = lambda h_ref, h_set, brain_, tau_, L=L, n=n: (L, n) gt0 = np.zeros(brain.shape, bool) # labels are not used by any score (GT never enters the cascade) r, X = CC.score_setting(c.cid, setting, t1, brain, props, ctx, gt0, h, h, 0.5, probs, cache, torch.device("cpu")) return r, X # ---------------------------------------------------------------- stage: cands (int_candscore run + stk_fm4 x2 + c4b_fm4feat + stk g_xc5b_c2t) def cands(self, c, info): import cc3d, pandas as pd, scipy.ndimage as ndi import dethead_cand as K, int_candgen as CG, stk_pass1 as P1, stk_common as SC, c4b_apply as AP, devset_common as D t1, brain, props = self.load_prep(c); shp = t1.shape; W = self.W(c) f, ivT, iv3, fm4 = self.heats_raw(c) pp = lambda a: (np.round(K.dev_to_pp(a, props, shp) * brain * 250) / 250).astype(np.float32) folds = [pp(x) for x in f] + [pp(ivT)] # int_candgen.fold_heats (test, INT_HEAT=fm4) h = np.maximum((np.round(K.dev_to_pp(iv3, props, shp) * brain * 250) / 250).astype(np.float32), folds[3]).astype(np.float32) L, n = CG.gen(CFG["detector"]["candidate_rule"], h, brain, folds) p = self.p331_pp(c, props, shp, brain) probs = {"d331": p} info["n_candidates"] = int(n) cols = ["cid", "vox", "ml_pp", "centroid_zyx_raw", "part_score", "score", "accepted"] if n: r, X = self.score_components(c, L, n, h, t1, brain, props, probs, "iv3_t0.5") df = pd.DataFrame(json.loads(json.dumps(r["feats"], default=float))) df = pd.concat([df.reset_index(drop=True), pd.DataFrame(X.astype(np.float32), columns=[f"d331f_{i}" for i in range(X.shape[1])])], axis=1) ctx, _ = self.ctx_feats(c, t1, brain, props) Lp = cc3d.connected_components(((p >= 0.5) & brain).astype(np.uint8), connectivity=26); psz = np.bincount(Lp.ravel()) x2 = pd.DataFrame(json.loads(json.dumps(P1.x2_feats(L, n, h, p, ctx, brain, Lp, psz), default=float))) ev = np.load(W / "c2t_ev.npz")["ev"].astype(np.float32) / 250.0 assert ev.shape == t1.shape, (ev.shape, t1.shape) f03 = ndi.mean((ev > 0.3).astype(np.float32), L, np.arange(1, n + 1)) b1 = pd.DataFrame(AP.pool(ev, L, n, brain, t1)); b1["ev_frac03"] = [float(f03[k - 1]) for k in b1["cid"]] b1 = b1.drop(columns=["cid"]).rename(columns=lambda x: f"b1_{x}") df = pd.concat([pd.DataFrame({"cid": np.arange(1, n + 1)}), df, x2, b1], axis=1) M = self.models().clf() Xc = df[M["features"]].to_numpy(np.float32) df["part_score"] = M["part_final"].predict_proba(Xc)[:, 1] df["score"] = M["comb_final"].predict_proba(np.column_stack([SC.lg(df["part_score"].to_numpy()), df["log_vox"].to_numpy(float)]))[:, 1] df["accepted"] = df["score"] >= CFG["classifier"]["accept_threshold"] else: df = pd.DataFrame(columns=cols + ["log_vox"]) Lraw = D.prep_to_raw(L.astype(np.int32), props, fill=0, order=0).astype(np.uint16) write_like(Lraw, c.t1_in, W / "cand_lab_raw.nii.gz", np.uint16) if n: cen = ndi.center_of_mass(np.ones(Lraw.shape, np.uint8), Lraw.astype(np.int32), np.arange(1, n + 1)) df["centroid_zyx_raw"] = [";".join(f"{v:.1f}" for v in cc_) if np.all(np.isfinite(cc_)) else "" for cc_ in cen] df["ml_pp"] = df["vox"].astype(float) / 1000.0 ids = df.loc[df["accepted"].astype(bool), "cid"].astype(int).to_numpy() if n else np.zeros(0, int) acc = np.where(np.isin(Lraw.astype(np.int32), ids), Lraw, 0).astype(np.uint16) write_like(acc, c.t1_in, W / "acc_raw.nii.gz", np.uint16) df.to_pickle(W / "cands.pkl.tmp"); os.replace(W / "cands.pkl.tmp", W / "cands.pkl") info["n_accepted"] = int(len(ids)); info["t_d331_deepfeat_s"] = round(self._case_mem(c.cid).get("t_d331feat", 0.0), 1) def write_cand_csv(self, c): import pandas as pd df = pd.read_pickle(self.W(c) / "cands.pkl") keep = ["cid", "vox", "ml_pp", "centroid_zyx_raw", "score", "part_score", "accepted", "h_peak", "h_mean", "p_d331_max", "p_d331_mean", "b1_ev_max", "b1_ev_box3max", "t1_mean", "c6_t1", "dv_min", "pos_lr", "pos_ap", "pos_si"] o = df[[k for k in keep if k in df.columns]].copy() o.insert(1, "case_id", c.cid); o["threshold"] = CFG["classifier"]["accept_threshold"] o.to_csv(self.O(c) / f"{c.cid}_candidates.csv", index=False, float_format="%.6g") # ---------------------------------------------------------------- stage: draw (int_e2e.infer, p2heat) def draw(self, c, info): import prompt2_infer as PI from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO _, _, _, heat = self.heats_raw(c) la = read_arr(self.W(c) / "acc_raw.nii.gz", np.int32) if not la.any(): # nothing accepted: the forced drawing is empty whatever the drawer says p1 = np.zeros(la.shape, np.float32); info["drawer_skipped"] = "no accepted candidate" else: img, props = SimpleITKIO().read_images([c.t1_in]) pm = PI.prompt_from_candidates("heat", heat, la, PI.describe(la, heat)) x = np.concatenate([img, pm[None].astype(np.float32)], 0).astype(np.float32) with (fp32_gpu() if self.a.device != "cpu" else contextlib.nullcontext()): _s, prob = self.models().drawer().predict_single_npy_array(x, props, None, None, True) p1 = np.asarray(prob, np.float32)[1] write_like(np.clip(np.round(p1 * 250), 0, 250).astype(np.uint8), c.t1_in, self.W(c) / "drawer_prob.nii.gz", np.uint8) # ---------------------------------------------------------------- stage: gate (int_peakcls --sat extra --heat fm4 + int_fpdecomp.compose_gate) def gate(self, c, info): import pandas as pd, scipy.ndimage as ndi, dethead_cand as K, int_compose as IC, cls3_newtier as NT W = self.W(c) t1, brain, props = self.load_prep(c); shp = t1.shape P = read_arr(W / "drawer_prob.nii.gz") / 250.0 la = read_arr(W / "acc_raw.nii.gz", np.int32) main, ex = IC.extras_map(P, la) _, _, _, heat = self.heats_raw(c) heat = (np.round(heat * 250) / 250).astype(np.float32) h = (np.round(K.dev_to_pp(heat, props, shp) * brain * 250) / 250).astype(np.float32) res = {} if ex.any(): Sp = np.round(K.dev_to_pp(ex.astype(np.float32), props, shp, order=0)).astype(np.int32) * brain ids = [int(x) for x in np.unique(Sp) if x > 0] if ids: remap = np.zeros(int(Sp.max()) + 1, np.int32); remap[ids] = np.arange(1, len(ids) + 1) Lx = remap[Sp]; n = len(ids) probs = {"d331": self.p331_pp(c, props, shp, brain)} r, X = self.score_components(c, Lx, n, h, t1, brain, props, probs, "iv2_t0.5") df = pd.DataFrame(r["feats"]); df = pd.concat([df, pd.DataFrame(X.astype(np.float32), columns=[f"d331f_{i}" for i in range(X.shape[1])])], axis=1) sc = NT.head_fz(df) res = {str(ids[i]): float(sc[i]) for i in range(n)} thr = CFG["gate"]["threshold"]; keep, rows = [], [] vml = float(np.prod(read_img(c.t1_in).GetSpacing())) / 1000.0 for k, o in enumerate(ndi.find_objects(ex), start=1): if o is None: continue s = res.get(str(k)); kept = s is not None and s >= thr if kept: keep.append(k) rows.append({"case_id": c.cid, "extra_id": k, "vox_raw": int((ex[o] == k).sum()), "ml": int((ex[o] == k).sum()) * vml, "s_sepd": s if s is not None else np.nan, "kept": bool(kept), "note": "" if s is not None else "vanished on the 1 mm grid: unscored, dropped (as int_fpdecomp.compose_gate)"}) fin = main | (np.isin(ex, keep) if keep else np.zeros_like(main)) write_like(fin.astype(np.uint8), c.t1_in, self.mask_path(c, "c2tb"), np.uint8) cols = ["case_id", "extra_id", "vox_raw", "ml", "s_sepd", "kept", "note"] if set(self.kinds()) & G2S_KINDS: self.g2s_gate(c, info, P, main, ex, res, rows, vml) cols[6:6] = ["kept_g2", "kept_smooth"] pd.DataFrame(rows, columns=cols).to_csv(self.O(c) / f"{c.cid}_extras.csv", index=False, float_format="%.6g") info.update(n_extras=len(rows), n_extras_kept=len(keep), final_ml=float(fin.sum()) * vml, final_components=int(__import__("cc3d").connected_components(fin.astype(np.uint8), connectivity=26).max())) # ---------------------------------------------------------------- G2 gate x S* growth (int_dicegap.py run(), lines 89-101) def g2s_gate(self, c, info, P, main, ex, res, rows, vml): """Both cascade gate variants from the gate stage's own s_sepd scores (`res`) and drawer probability P; unscored extras dropped: cascade_g2s G2 step: thr = tiny if the extra's raw-grid volume < 0.1 mL else big (int_dicegap / int_tiny G2) cascade_smooth G2s-interp: thr linear in log10(mL) between test_lo (0.03 mL) and test_hi (0.3 mL) (int_tiny_smooth) then S* = int_softjoin.generous(g, P, 0.1, 0, ...): hysteresis growth into connected drawer p >= .1 (no new islands).""" import int_softjoin as SJ FG = CFG["g2s_gate"]; gi = FG["g2interp"]; keep = {"g2": [], "smooth": []} by_id = {r["extra_id"]: r for r in rows} for k, o in enumerate(ndi_find_objects(ex), start=1): if o is None: continue ml = int((ex[o] == k).sum()) * vml; s = res.get(str(k)) thr = {"g2": FG["G2"]["tiny"] if ml < FG["G2"]["tiny_ml"] else FG["G2"]["big"], "smooth": interp_thr(ml, gi["test_lo"], gi["test_hi"], gi["v_lo"], gi["v_hi"])} for v, t in thr.items(): ok = s is not None and s >= t if ok: keep[v].append(k) by_id[k][f"kept_{v}"] = bool(ok) brain = read_arr(c.t1_in) > 0; sp = read_img(c.t1_in).GetSpacing()[::-1]; sj = FG["softjoin"] for v, kind in (("g2", "cascade_g2s"), ("smooth", "cascade_smooth")): g = main | (np.isin(ex, keep[v]) if keep[v] else np.zeros_like(main)) fx = SJ.generous(g, P, sj["t"], sj["k_mm"], None, None, None, brain, sp) write_like(np.asarray(fx, bool).astype(np.uint8), c.t1_in, self.mask_path(c, kind), np.uint8) info.update({f"n_extras_kept_{v}": len(keep[v]), f"{kind}_ml": float(fx.sum()) * vml}) # ---------------------------------------------------------------- stage: heat3 (cascade2_infer.run_test for ivT f1/f2 + test_mean) def heat3(self, c, info): import cascade2_infer as I, cascade2_common as C W = self.W(c); files = [c.t1_in, c.fl_in]; t1b = read_arr(c.t1_in) > 0; u8 = {} if (W / "heat_folds.npz").exists(): # ivT f0 = the same network (Dataset977 C2D3_ivT fold 25), already run by detect u8["ivT_f0"] = np.load(W / "heat_folds.npz")["ivT_f0"] for nm in HEAT3_ORDER: if nm not in u8: p = I.predict_raw(self.models().det_heat3(nm), files) * t1b u8[nm] = np.clip(np.round(p * C.HEAT_SCALE), 0, 250).astype(np.uint8) # run_test: stored fold heat, uint8 x250 save_npz(W / "heat_ivT3_folds.npz", **u8) ps = [u8[nm].astype(np.float32) / C.HEAT_SCALE for nm in HEAT3_ORDER] # test_mean: fold dirs in sorted order f0, f1, f2 h = np.mean(ps, 0) h = np.round(np.clip(h, 0, 1) * t1b * C.HEAT_SCALE) / C.HEAT_SCALE write_like(h, c.t1_in, W / "ivt3_heat.nii.gz", np.float32) info["ivt3_heat_max"] = float(h.max()) # ---------------------------------------------------------------- stage: base (cascade2_infer.seg on (T1, ivT3 heat)) def base(self, c, info): from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO W = self.W(c) img, props = SimpleITKIO().read_images([c.t1_in, str(W / "ivt3_heat.nii.gz")]) _s, prob = self.models().base(self.a.base_model, self.a.base_checkpoint).predict_single_npy_array(img, props, None, None, True) write_like(np.clip(np.round(np.asarray(prob)[1] * 250), 0, 250).astype(np.uint8), c.t1_in, W / "base_prob.nii.gz", np.uint8) # ---------------------------------------------------------------- stage: compose (int_baseunion.py definitions) def compose(self, c, info): import cc3d, int_compose as IC W = self.W(c); ks = set(self.kinds()); M = {} if ks & BASE_KINDS: M["base"] = read_arr(W / "base_prob.nii.gz") / 250.0 >= CFG["base"]["threshold"] if ks & {"nogate", "union_nogate"}: P = read_arr(W / "drawer_prob.nii.gz") / 250.0 la = read_arr(W / "acc_raw.nii.gz", np.int32) M["nogate"] = IC.compose_full(P, la, "dm") # drawn components touching cube-dil-2 of an accepted candidate; no forced draw, no gate if "union" in ks: M["union"] = (read_arr(self.mask_path(c, "c2tb")) > 0) | M["base"] if "union_nogate" in ks: M["union_nogate"] = M["nogate"] | M["base"] if "twopath" in ks: M["twopath"] = (read_arr(self.mask_path(c, "cascade_g2s")) > 0) | M["base"] if "twopath_smooth" in ks: M["twopath_smooth"] = (read_arr(self.mask_path(c, "cascade_smooth")) > 0) | M["base"] vml = float(np.prod(read_img(c.t1_in).GetSpacing())) / 1000.0 for k in [k for k in self.kinds() if k not in ("c2tb",) + CASCADE_G2S]: m = np.asarray(M[k], bool) write_like(m.astype(np.uint8), c.t1_in, self.mask_path(c, k), np.uint8) info[f"{k}_ml"] = float(m.sum()) * vml info[f"{k}_components"] = int(cc3d.connected_components(m.astype(np.uint8), connectivity=26).max()) # ---------------------------------------------------------------- stage: eval (int_scorecard definitions, official-style truth) def evaluate(self, c, info): if not c.gt: return res = {k: self._evaluate_mask(c, self.mask_path(c, k), self.eval_path(c, k)) for k in self.kinds()} info["eval"] = next(iter(res.values())) if len(res) == 1 else res def _evaluate_mask(self, c, mask_p, out_json): import cc3d, scipy.ndimage as ndi, int_scorecard as SCD, int_boundary as BD gi = read_img(c.gt); gt = read_arr(c.gt) > 0 fin = read_arr(mask_p) > 0 assert gt.shape == fin.shape, f"GT grid {gt.shape} != T1 grid {fin.shape} for {c.cid}" sp = gi.GetSpacing()[::-1]; vml = float(np.prod(gi.GetSpacing())) / 1000.0 pp = self.W(c) / "d331_prob.nii.gz" p331 = rd250(read_arr(pp)) if pp.exists() else None G, ng = cc3d.connected_components(gt.astype(np.uint8), connectivity=26, return_N=True) blind = {g: float(p331[o][G[o] == g].max()) < 0.05 for g, o in enumerate(ndi.find_objects(G), start=1) if o is not None} if p331 is not None else {} les = SCD.lesion_stats(fin, G, ng, vml, blind, sp) n_all, n_tp, _ = SCD.comp_stats(fin, gt, np.zeros_like(gt)) n_les = int(sum(1 for o in ndi.find_objects(G) if o is not None and (G[o] > 0).sum() >= 10)) row = dict(case_id=c.cid, tp=int((fin & gt).sum()), pred=int(fin.sum()), gt=int(gt.sum()), comps=n_all, comps_tp=n_tp, n_les=n_les, vml=vml, d331_available=p331 is not None, les=[dict(ml=x[0], hit=bool(x[1]), lesion_dice=x[2], d331_blind=(x[3] if p331 is not None else None), **(x[4] or {})) for x in les]) dump_json(row, out_json) m = case_metrics(row) return {k: m[k] for k in ("dice", "recall_ge0.1", "precision_comp", "fp_comps", "lesion_count_diff")} # ---------------------------------------------------------------- per case driver def outputs_of(self, c, st): W = self.W(c) return {"prep": [W / "prep.npz", W / "props.pkl"], "detect": [W / "heat_folds.npz"], "d331": [W / "d331_prob.nii.gz"], "c2t": [W / "c2t_ev.npz"], "cands": [W / "cands.pkl", W / "acc_raw.nii.gz"], "draw": [W / "drawer_prob.nii.gz"], "gate": [self.mask_path(c, "c2tb")] + ([self.mask_path(c, k) for k in CASCADE_G2S] if set(self.kinds()) & G2S_KINDS else []), "heat3": [W / "heat_ivT3_folds.npz", W / "ivt3_heat.nii.gz"], "base": [W / "base_prob.nii.gz"], "compose": [self.mask_path(c, k) for k in self.kinds() if k not in ("c2tb",) + CASCADE_G2S], "eval": [self.eval_path(c, k) for k in self.kinds()]}[st] def run_case(self, c, stages): import torch O = self.O(c); O.mkdir(parents=True, exist_ok=True) lp = O / f"{c.cid}_log.json" info = json.load(open(lp)) if lp.exists() else {} finals = [self.mask_path(c, k) for k in self.kinds()] finished = info.get("status") == "ok" and all(p.exists() for p in finals) if self.a.resume and finished: need_eval = "eval" in stages and c.gt and not all(self.eval_path(c, k).exists() for k in self.kinds()) if not need_eval: log("SKIP (done)", c.cid); return info stages = ["eval"] # the cascade itself is finished (its stage cache may be cleaned): evaluate only info.update(case_id=c.cid, t1=c.t1, flair=c.flair, gt=c.gt, mask=c.mask, cascade=f"{CFG['name']} as of {CFG['as_of']}", host=socket.gethostname(), slurm_job=os.environ.get("SLURM_JOB_ID"), status="running") if self.a.pipeline != "c2tb": info.update(pipeline=self.a.pipeline, outputs={k: str(self.mask_path(c, k)) for k in self.kinds()}) if set(self.kinds()) & BASE_KINDS: info.update(base_model=self.a.base_model, base_trainer=CFG["base"]["models"][self.a.base_model]["trainer"], base_checkpoint=self.a.base_checkpoint) info.setdefault("timing_s", {}); info.pop("error", None) t_case = time.time(); ran = set() if self.models().dev.type == "cuda": torch.cuda.reset_peak_memory_stats() if stages != ["eval"]: self.inputs(c, info) for st in stages: if st == "eval" and not c.gt: continue if self.a.resume and all(p.exists() for p in self.outputs_of(c, st)): log(c.cid, st, "cached"); continue t0 = time.time() getattr(self, {"eval": "evaluate"}.get(st, st))(c, info); ran.add(st) info["timing_s"][st] = round(time.time() - t0, 1) log(c.cid, st, f"{info['timing_s'][st]:.1f}s") if st == "cands": self.write_cand_csv(c) dump_json(info, lp) if (self.W(c) / "cands.pkl").exists() and not (O / f"{c.cid}_candidates.csv").exists(): self.write_cand_csv(c) if self.models().dev.type == "cuda": info["gpu_peak_alloc_GB"] = round(torch.cuda.max_memory_allocated() / 2 ** 30, 2) info["gpu_peak_reserved_GB"] = round(torch.cuda.max_memory_reserved() / 2 ** 30, 2) info["wall_s_this_run"] = round(time.time() - t_case, 1) done = all(p.exists() for p in finals) info["status"] = "ok" if done else "partial" if done and (ran - {"eval"}): if self.a.keep_intermediates: for src, dst in ((self.W(c) / "drawer_prob.nii.gz", O / f"{c.cid}_drawer_prob.nii.gz"), (self.W(c) / "base_prob.nii.gz", O / f"{c.cid}_base_prob.nii.gz")): if src.exists(): shutil.copy2(src, dst) if (self.W(c) / "heat_folds.npz").exists(): _, _, _, fm4 = self.heats_raw(c) write_like(np.clip(np.round(fm4 * 250), 0, 250).astype(np.uint8), c.t1_in, O / f"{c.cid}_fm4_heat.nii.gz", np.uint8) if (self.W(c) / "ivt3_heat.nii.gz").exists(): # ivT3 heat is a multiple of 1/250: uint8 x250 is lossless h3 = read_arr(self.W(c) / "ivt3_heat.nii.gz") write_like(np.clip(np.round(h3 * 250), 0, 250).astype(np.uint8), c.t1_in, O / f"{c.cid}_ivt3_heat.nii.gz", np.uint8) else: # keep only the D331 probability (needed for the D331-blind eval column) for p in self.W(c).iterdir(): if p.name != "d331_prob.nii.gz": p.unlink() if p.is_file() else shutil.rmtree(p) dump_json(info, lp) return info # ================================================================================================ evaluation summaries (int_scorecard.summary aggregation) def case_metrics(r): L = r["les"] def rec(sel): xs = [x for x in L if sel(x)] return sum(x["hit"] for x in xs) / len(xs) if xs else np.nan r01 = rec(lambda x: x["ml"] >= 0.1); prec = r["comps_tp"] / r["comps"] if r["comps"] else np.nan ldh = [x["lesion_dice"] for x in L if x["hit"]] m = {"case_id": r["case_id"], "dice": 2 * r["tp"] / max(r["pred"] + r["gt"], 1), "pred_ml": r["pred"] * r["vml"], "gt_ml": r["gt"] * r["vml"], "vol_ratio": r["pred"] / r["gt"] if r["gt"] else np.nan, "n_lesions": len(L), "n_lesions_ge0.1": sum(x["ml"] >= 0.1 for x in L), "recall_all": rec(lambda x: True), "recall_ge0.1": r01, "recall_lt0.1": rec(lambda x: x["ml"] < 0.1), "recall_blind_ge0.1": rec(lambda x: x["ml"] >= 0.1 and bool(x.get("d331_blind"))) if r.get("d331_available") else np.nan, "pred_comps": r["comps"], "tp_comps": r["comps_tp"], "fp_comps": r["comps"] - r["comps_tp"], "precision_comp": prec, "f1_lesion": 2 * r01 * prec / (r01 + prec) if (r01 and prec and np.isfinite(r01) and np.isfinite(prec)) else np.nan, "median_lesion_dice_hit": float(np.median(ldh)) if ldh else np.nan, "lesion_count_diff": r["comps"] - r["n_les"], "lesion_count_absdiff": abs(r["comps"] - r["n_les"])} import int_boundary as BD B = [x for x in L if x["hit"] and "nsd1" in x] for k in BD.BKEYS: v = [x[k] for x in B if x.get(k) is not None and not (isinstance(x[k], float) and np.isnan(x[k]))] m[f"bnd_{k}_{'rate' if k == 'hd_outlier' else 'median'}"] = (float(np.mean(v)) if k == "hd_outlier" else float(np.median(v))) if v else np.nan return m def pooled_metrics(R): """int_scorecard.summary for one pool (lesions pooled over cases; component precision pooled; case Dice = mean of per-case Dice).""" import int_boundary as BD L = [x for r in R for x in r["les"]]; nc = len(R) def rec(sel): xs = [x for x in L if sel(x)] return sum(x["hit"] for x in xs) / len(xs) if xs else np.nan r01 = rec(lambda x: x["ml"] >= 0.1); ca = sum(r["comps"] for r in R); ct = sum(r["comps_tp"] for r in R) prec = ct / ca if ca else np.nan vr = [r["pred"] / r["gt"] for r in R if r["gt"] > 0]; ldh = [x["lesion_dice"] for x in L if x["hit"]] m = {"n_cases": nc, "n_lesions": len(L), "n_lesions_ge0.1": sum(x["ml"] >= 0.1 for x in L), "recall_all": rec(lambda x: True), "recall_ge0.1": r01, "recall_lt0.1": rec(lambda x: x["ml"] < 0.1), "recall_blind_ge0.1": rec(lambda x: x["ml"] >= 0.1 and bool(x.get("d331_blind"))) if all(r.get("d331_available") for r in R) else np.nan, "precision_comp": prec, "fp_comps_per_case": (ca - ct) / nc if nc else np.nan, "f1_lesion": 2 * r01 * prec / (r01 + prec) if (r01 and prec and np.isfinite(r01) and np.isfinite(prec)) else np.nan, "case_dice": float(np.mean([2 * r["tp"] / max(r["pred"] + r["gt"], 1) for r in R])) if R else np.nan, "pooled_dice": 2 * sum(r["tp"] for r in R) / max(sum(r["pred"] + r["gt"] for r in R), 1), "vol_ratio_pooled": sum(r["pred"] for r in R) / max(sum(r["gt"] for r in R), 1), "vol_ratio_median": float(np.median(vr)) if vr else np.nan, "median_lesion_dice_hit": float(np.median(ldh)) if ldh else np.nan, "lesion_count_absdiff_per_case": float(np.mean([abs(r["comps"] - r["n_les"]) for r in R])) if R else np.nan, "lesion_count_diff_per_case": float(np.mean([r["comps"] - r["n_les"] for r in R])) if R else np.nan} B = [x for x in L if x["hit"] and "nsd1" in x] for k in BD.BKEYS: v = [x[k] for x in B if x.get(k) is not None and not (isinstance(x[k], float) and np.isnan(x[k]))] if v: m[f"bnd_{k}_{'rate' if k == 'hd_outlier' else 'median'}"] = float(np.mean(v)) if k == "hd_outlier" else float(np.median(v)) return m def run_pipeline(out): """(pipeline, base_model) recorded in OUT's manifest (runs made before 2026-11-22 have no 'pipeline' arg: c2tb).""" out = Path(out) for p in [out / "manifest.json"] + sorted(out.glob("manifest_*.json")): if p.exists(): a = json.load(open(p)).get("args", {}) return a.get("pipeline") or "c2tb", a.get("base_model") return None, None def pipeline_title(pipe, base_model, kind=None): if pipe in (None, "c2tb") and kind in (None, "c2tb"): return f"# Cascade {CFG['name']} (as of {CFG['as_of']}): evaluation" k = kind or pipe; bm = f"; base = {CFG['base']['models'][base_model]['trainer']}" if base_model and k in BASE_KINDS else "" if pipe in OUTNAME: return f"# best3 output {OUTNAME[pipe].get(k, k)}: {KIND_LABEL[k]} ({CFG['name']} runner, as of {CFG['as_of']}{bm}): evaluation" return f"# Pipeline {k}: {KIND_LABEL[k]} ({CFG['name']} runner, as of {CFG['as_of']}{bm}): evaluation" def summarize(out): out = Path(out); E = out / "eval" pipe, bm = run_pipeline(out) if len(PIPELINES.get(pipe or "c2tb", ("c2tb",))) == 1: return summarize_dir(E, pipeline_title(pipe, bm)) rows = [] for k in PIPELINES[pipe]: nm = OUTNAME.get(pipe, {}).get(k, k) pm = summarize_dir(E / nm, pipeline_title(pipe, bm, k)) if pm: rows.append({"pipeline": nm, **pm}) if not rows: return dump_json({r["pipeline"]: r for r in rows}, E / "summary.json") keys = ["n_cases", "recall_all", "recall_ge0.1", "recall_lt0.1", "recall_blind_ge0.1", "precision_comp", "fp_comps_per_case", "f1_lesion", "case_dice", "pooled_dice", "vol_ratio_pooled", "vol_ratio_median", "median_lesion_dice_hit", "lesion_count_diff_per_case", "bnd_nsd2_median", "bnd_hd95_median"] W = [(f"# best3: cascade / delbankconv / twopath from one run (" if pipe == "best3" else "# All pipelines from one run (") + f"{CFG['name']} runner, as of {CFG['as_of']}; base = {CFG['base']['models'][bm]['trainer'] if bm else '?'}" + ("; cascade = G2 step x S*, cascade_smooth = G2s-interp x S*" if uses_g2s(pipe) else "") + "): evaluation", "", "Same definitions as each eval//summary.md (int_scorecard). Per-case and per-lesion tables are in eval//.", "", "| metric | " + " | ".join(r["pipeline"] for r in rows) + " |", "|---|" + "---|" * len(rows)] for k in keys: W.append(f"| {k} | " + " | ".join((f"{r.get(k):.4g}" if isinstance(r.get(k), float) else str(r.get(k, "n/a"))) for r in rows) + " |") (E / "summary.md").write_text("\n".join(W) + "\n") log("SUMMARY written", E / "summary.md") def summarize_dir(E, title): import pandas as pd R = [json.load(open(p)) for p in sorted((E / "cases").glob("*.json"))] if not R: log("no eval files under", E / "cases"); return per = pd.DataFrame([case_metrics(r) for r in R]); per.to_csv(E / "per_case.csv", index=False, float_format="%.5g") lr = [{"case_id": r["case_id"], "lesion": i + 1, **x} for r in R for i, x in enumerate(r["les"])] pd.DataFrame(lr).to_csv(E / "lesions.csv", index=False, float_format="%.5g") pm = pooled_metrics(R); dump_json(pm, E / "summary.json") W = [title, "", f"{len(R)} cases with ground truth. Definitions = int_scorecard (truth components 26-connected, >= 10 voxels; hit = any overlap; " "component precision over predicted components >= 10 voxels; case Dice = mean of per-case Dice; pooled Dice = 2 sum TP / sum (pred + GT); " "boundary metrics = int_boundary on hit lesions, medians over lesions; D331-blind = max D331 p < .05 inside the lesion).", "", "## Pooled", "", "| metric | value |", "|---|---|"] W += [f"| {k} | {v:.4g} |" if isinstance(v, float) else f"| {k} | {v} |" for k, v in pm.items()] show = ["case_id", "dice", "recall_all", "recall_ge0.1", "precision_comp", "fp_comps", "f1_lesion", "vol_ratio", "median_lesion_dice_hit", "lesion_count_diff", "bnd_nsd2_median", "bnd_hd95_median"] W += ["", "## Per case (full table: per_case.csv; per lesion: lesions.csv)", "", "| " + " | ".join(show) + " |", "|" + "---|" * len(show)] for _, r in per.iterrows(): W.append("| " + " | ".join(str(r[k]) if k == "case_id" else (f"{r[k]:.3f}" if pd.notna(r[k]) else "nan") for k in show) + " |") (E / "summary.md").write_text("\n".join(W) + "\n") log("SUMMARY written", E / "summary.md") return pm # ================================================================================================ manifest def uses_base(pipe): return bool(set(PIPELINES[pipe]) & BASE_KINDS) def uses_g2s(pipe): return bool(set(PIPELINES[pipe]) & G2S_KINDS) def base_files(model, ckpt="checkpoint_final.pth"): """model files of the base route: ivT folds 1 + 2 (fold 0 = 'detector ivT_f0 checkpoint') and the chosen base network.""" bf = CFG["base_model_files"] files = {k: bf[k] for k in ("detector ivT_f1 checkpoint", "detector ivT_f2 checkpoint", f"base {model} plans")} ck = bf[f"base {model} checkpoint"] if ckpt != CFG["base"]["checkpoint"]: # smoke tests only: an unvalidated checkpoint never matches a pinned key files[f"base {model} checkpoint [{ckpt}, UNVALIDATED]"] = str(Path(ck).parent / ckpt) else: files[f"base {model} checkpoint"] = ck return files def manifest(a, cases): out = Path(a.out); out.mkdir(parents=True, exist_ok=True) prev, prev_bm = run_pipeline(out) if prev is not None and (prev != a.pipeline or (uses_base(a.pipeline) and prev_bm not in (None, a.base_model))): raise SystemExit(f"{out} was made with --pipeline {prev}" + (f" --base_model {prev_bm}" if prev_bm else "") + f"; use a new OUTDIR for --pipeline {a.pipeline}" + (f" --base_model {a.base_model}" if uses_base(a.pipeline) else "")) ckp = out / ".checksums.json"; cache = json.load(open(ckp)) if ckp.exists() else {} files = {**CFG["model_files"], **{f"source {Path(s).name}": s for s in CFG["source_files"]}} if uses_base(a.pipeline): files.update(base_files(a.base_model, a.base_checkpoint)) if uses_g2s(a.pipeline): files.update({f"source {Path(s).name}": s for s in CFG["g2s_gate"]["source_files"]}) missing = [f"{k}: {BASE / p}" for k, p in files.items() if not (BASE / p).exists()] assert not missing, "missing model / source files:\n " + "\n ".join(missing) sums = {k: {"path": str(BASE / p), "sha256": sha256(str(BASE / p), cache)} for k, p in files.items()} dump_json(cache, ckp) pinned = CFG.get("sha256", {}) bad = [k for k, v in sums.items() if k in pinned and pinned[k] != v["sha256"]] unpinned = [k for k in sums if k not in pinned] if unpinned: log("WARNING: no pinned checksum (not yet validated) for:", ", ".join(unpinned)) if bad and not a.allow_model_change: raise SystemExit("model / source files differ from the pinned c2t(b) checksums (cascade_config.json 'sha256'): " + ", ".join(bad) + "\nIf the deploy candidate changed on purpose, update cascade_config.json (see README) or pass --allow_model_change.") try: ev = json.load(open(BASE / "whisper_synth/outputs/direction2/integrator/e2e_variants.json")).get("f4_g_xc5b_c2t_dev_B1.0", {}) gj = json.load(open(BASE / CFG["gate"]["file"]))["rules"][CFG["gate"]["rule"]]["thr"] thr_check = {"accept_threshold_matches_e2e_variants": abs(ev.get("thr", -1) - CFG["classifier"]["accept_threshold"]) < 1e-12, "gate_threshold_matches_gate_json": abs(gj - CFG["gate"]["threshold"]) < 1e-12} except Exception as e: # noqa: BLE001 thr_check = {"error": repr(e)} import importlib vers = {} for m in ("torch", "numpy", "scipy", "sklearn", "SimpleITK", "nnunetv2", "cc3d", "pandas"): try: vers[m] = getattr(importlib.import_module(m), "__version__", "?") except Exception: # noqa: BLE001 vers[m] = "not importable" man = {"cascade": CFG["name"], "as_of": CFG["as_of"], "description": CFG["description"], "created": time.strftime("%Y-%m-%d %H:%M:%S"), "host": socket.gethostname(), "slurm_job": os.environ.get("SLURM_JOB_ID"), "array_task": os.environ.get("SLURM_ARRAY_TASK_ID"), "args": vars(a), "n_cases": len(cases), "thresholds": {"accept": CFG["classifier"]["accept_threshold"], "gate": CFG["gate"]["threshold"], "candidate_rule": CFG["detector"]["candidate_rule"], "drawer_compose": CFG["drawer"]["compose"]}, "threshold_check": thr_check, "files": sums, "pinned_mismatch": bad, "versions": vers, "python": platform.python_version()} if a.pipeline != "c2tb": man["pipeline"] = {"name": a.pipeline, "outputs": {k: KIND_LABEL[k] for k in PIPELINES[a.pipeline]}, "unpinned_files": unpinned} if uses_base(a.pipeline): b = CFG["base"] man["pipeline"].update(base_model=a.base_model, base_trainer=b["models"][a.base_model]["trainer"], base_fold=f"{b['fold_name']} ({b['fold']})", base_checkpoint=a.base_checkpoint, base_checkpoint_validated=a.base_checkpoint == b["checkpoint"], heat=b["heat"]["recipe"]) man["thresholds"]["base"] = b["threshold"] if uses_g2s(a.pipeline): FG = CFG["g2s_gate"] man["pipeline"].update(g2s_gate=FG["description"]) man["thresholds"]["g2s_gate"] = {"G2": {k: FG["G2"][k] for k in ("tiny", "big", "tiny_ml")}, "g2interp": {k: FG["g2interp"][k] for k in ("v_lo", "v_hi", "test_lo", "test_hi")}, "softjoin": FG["softjoin"]} try: tj = json.load(open(BASE / "whisper_synth/outputs/direction2/integrator/tiny/thresholds.json"))["gate"]["test"]["G2"] sj = json.load(open(BASE / "whisper_synth/outputs/direction2/integrator/tiny/smooth_fit.json"))["interp"] man["threshold_check"]["g2s_gate_G2_matches_thresholds_json"] = abs(tj["tiny"] - FG["G2"]["tiny"]) < 1e-12 and abs(tj["big"] - FG["G2"]["big"]) < 1e-12 man["threshold_check"]["g2s_gate_interp_matches_smooth_fit_json"] = all(abs(sj[k] - FG["g2interp"][k]) < 1e-12 for k in ("v_lo", "v_hi", "test_lo", "test_hi")) except Exception as e: # noqa: BLE001 man["threshold_check"]["g2s_gate_error"] = repr(e) tag = f"_{os.environ.get('SLURM_ARRAY_TASK_ID')}" if os.environ.get("SLURM_ARRAY_TASK_ID") else "" dump_json(man, out / f"manifest{tag}.json") return man # ================================================================================================ main def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--cases"); ap.add_argument("--t1_glob"); ap.add_argument("--flair_glob"); ap.add_argument("--gt_glob") ap.add_argument("--out"); ap.add_argument("--eval", action="store_true", help="evaluate cases that have a GT mask") ap.add_argument("--keep_intermediates", action="store_true", help="keep the stage cache + write the drawer soft map and fm4 heat per case") ap.add_argument("--pipeline", default="c2tb", choices=list(PIPELINES), help="c2tb (default, the validated c2t(b) cascade) | base | union | union_nogate | nogate | best3 | all") ap.add_argument("--base_model", default=CFG["base"]["default_model"], choices=list(CFG["base"]["models"]), help=f"base network for base / union pipelines (default {CFG['base']['default_model']})") ap.add_argument("--base_checkpoint", default=CFG["base"]["checkpoint"], help="SMOKE TESTS ONLY: another checkpoint file of the base fold (unvalidated)") ap.add_argument("--stages", default=None, help=f"comma list from {','.join(ALL_STAGES)} (default: every stage the pipeline needs, but eval; --eval adds eval)") ap.add_argument("--resume", action="store_true", help="skip stages / cases whose outputs already exist (requeue-safe)") ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1) ap.add_argument("--device", default=None, help="cuda (default when available) or cpu") ap.add_argument("--summarize_only", action="store_true"); ap.add_argument("--allow_model_change", action="store_true") ap.add_argument("--pin_checksums", action="store_true", help="write the current sha256 of every model / source file into cascade_config.json and exit") ap.add_argument("--pin_keys", default=None, help="with --pin_checksums: pin ONLY these comma-separated keys (from base_model_files / model_files) " "and only if not pinned yet; every other pin is left untouched") ap.add_argument("--pin_replace", default=None, help="with --pin_keys: REASON (recorded in cascade_config.json 'sha256_replaced'); also replace keys " "that are already pinned. Use only after a parity re-check on the new file passed.") a = ap.parse_args() if a.summarize_only: assert a.out, "--out is required"; summarize(a.out); return if a.pin_checksums and a.pin_keys: allf = {**CFG["model_files"], **CFG["base_model_files"], **{f"source {Path(s).name}": s for s in CFG["source_files"] + CFG["g2s_gate"]["source_files"]}} cache = {}; sh = CFG.setdefault("sha256", {}); done = [] for k in [k.strip() for k in a.pin_keys.split(",") if k.strip()]: assert k in allf, f"unknown key {k}" if k in sh and not a.pin_replace: log("already pinned (left unchanged):", k); continue if k in sh: CFG.setdefault("sha256_replaced", {})[k] = {"old": sh[k], "replaced_on": time.strftime("%Y-%m-%d %H:%M:%S"), "reason": a.pin_replace} if not (BASE / allf[k]).exists(): log("missing, not pinned:", k); continue sh[k] = sha256(str(BASE / allf[k]), cache); done.append(k) if done: CFG.setdefault("sha256_pinned_keys_on", {}).update({k: time.strftime("%Y-%m-%d %H:%M:%S") for k in done}) tmp = str(TOOL / "cascade_config.json") + ".tmp"; json.dump(CFG, open(tmp, "w"), indent=2); os.replace(tmp, TOOL / "cascade_config.json") log("pinned", done); return if a.pin_checksums: files = {**CFG["model_files"], **{f"source {Path(s).name}": s for s in CFG["source_files"]}} files.update({k: p for k, p in CFG["base_model_files"].items() if (BASE / p).exists()}) cache = {}; CFG["sha256"] = {k: sha256(str(BASE / p), cache) for k, p in files.items()} CFG["sha256_pinned_on"] = time.strftime("%Y-%m-%d %H:%M:%S") tmp = str(TOOL / "cascade_config.json") + ".tmp"; json.dump(CFG, open(tmp, "w"), indent=2); os.replace(tmp, TOOL / "cascade_config.json") log("pinned", len(CFG["sha256"]), "checksums into", TOOL / "cascade_config.json"); return assert a.out, "--out is required" import torch a.device = a.device or ("cuda" if torch.cuda.is_available() else "cpu") nthr = int(os.environ.get("SLURM_CPUS_PER_TASK", "4")); torch.set_num_threads(nthr) if a.cases: cases = read_cases(a.cases) else: assert a.t1_glob and a.flair_glob, "give --cases or --t1_glob + --flair_glob" cases = glob_cases(a.t1_glob, a.flair_glob, a.gt_glob) assert cases, "no cases" for c in cases: for p in (c.t1, c.flair) + ((c.gt,) if c.gt else ()) + ((c.mask,) if c.mask else ()): assert os.path.exists(p), f"{c.cid}: missing file {p}" need = pipeline_stages(a.pipeline) stages = need if a.stages is None else [s.strip() for s in a.stages.split(",") if s.strip()] assert all(s in ALL_STAGES for s in stages), f"unknown stage in {stages}" if a.eval and "eval" not in stages: stages.append("eval") stages = [s for s in ALL_STAGES if s in stages and (s in need or s == "eval")] if a.pipeline == "c2tb": assert all(s in STAGES for s in stages) mine = cases[a.chunk::a.nchunk] man = manifest(a, cases) log(f"cascade {CFG['name']} as of {CFG['as_of']} | pipeline {a.pipeline}" + (f" (base {a.base_model} = {CFG['base']['models'][a.base_model]['trainer']}, {a.base_checkpoint})" if uses_base(a.pipeline) else "") + (" (cascade: G2 step and G2s-interp, each x S*)" if uses_g2s(a.pipeline) else "") + f" | device {a.device} | {len(mine)}/{len(cases)} cases (chunk {a.chunk}/{a.nchunk}) | stages {stages}" + (f" | WARNING pinned checksum mismatch {man['pinned_mismatch']}" if man["pinned_mismatch"] else "")) R = Runner(a); fails = [] for i, c in enumerate(mine): log(f"=== [{i + 1}/{len(mine)}] {c.cid}") try: info = R.run_case(c, stages) log("CASE_DONE", c.cid, json.dumps({k: info.get(k) for k in ("status", "n_candidates", "n_accepted", "n_extras", "n_extras_kept", "final_ml", "wall_s_this_run", "gpu_peak_alloc_GB", "eval") if k in info or a.pipeline == "c2tb"} | {f"{k}_ml": info[f"{k}_ml"] for k in PIPELINES[a.pipeline] if f"{k}_ml" in info}, default=_jd)) except Exception as e: # noqa: BLE001 traceback.print_exc(); fails.append(c.cid) lp = R.O(c) / f"{c.cid}_log.json"; d = json.load(open(lp)) if lp.exists() else {"case_id": c.cid} d.update(status="failed", error=repr(e)[:500]); dump_json(d, lp) log("CASE_FAILED", c.cid, repr(e)[:300]) if "eval" in stages: summarize(a.out) log("RUN_DONE", f"{len(mine) - len(fails)} ok, {len(fails)} failed", fails) sys.exit(1 if fails and len(fails) == len(mine) else 0) if __name__ == "__main__": main()