Download runtime/code/whisper_synth/src/direction2/cls2_drawer_test.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 17.5 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cls2_drawer_test.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/cls2_drawer_test.py
-
curl -L -o cls2_drawer_test.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/cls2_drawer_test.py
17.5 kB
| #!/usr/bin/env python | |
| """classifier2: DRAWER CASCADE on the dev-test cohorts (prereg 35s: scoring / selection allowed, never training). | |
| Drawer = prompt2 draw-only stage 2 (MODELS / encodings / prompt builders imported from prompt2_infer, unchanged): | |
| p2heat (heat encoding; trained) ; p2ball / p2ballk (ball encoding) as soon as prompt2/locks/<m>_x.TRAINED exists. | |
| Prompts on the RAW test grid (T1 _0000 geometry; nnU-Net predict_single_npy_array exactly as prompt2_infer.Runner): | |
| acc<t> : s_sepd-ACCEPTED candidates at t (0.802 = frozen B0.25, 0.692 = B0.5). Candidates/scores live on the 1 mm pp grid | |
| (cls2 candidate tables); the accepted label map is mapped to the raw grid (devset_common.prep_to_raw, order 0) and | |
| the prompt built with prompt2_infer.prompt_from_candidates(enc, heat_raw, acc_lab_raw, describe(...)). | |
| oracle : prompt2_infer.oracle_prompt(enc, heat_raw, GT_raw) (drawing ceiling; GT used only to build the evaluation prompt) | |
| zero : no prompt | |
| Composition = prompt2_score (draw_mask: components of p_drawer >= 0.5 touching the cube-dilated (2) accepted mask; add-only | |
| union max(p_base, p_drawer * draw_mask)); bases = delbankconv_x, D331. Oracle: draw_mask against GT. Also the zero-prompt | |
| drawer restricted to accepted candidates, and the lpd crude draw at the SAME exact thresholds (cls2_e2e_test semantics). | |
| Scoring = cascade2_score.metrics on the raw grid. | |
| cls2_drawer_test.py infer --model p2heat --chunk i --nchunk n (GPU) -> classifier2/drawer/<model>/{pred/<variant>/<cid>.nii.gz, acc/<t>/<cid>.nii.gz} | |
| cls2_drawer_test.py score --model p2heat [--chunk i --nchunk n] (CPU) -> classifier2/drawer/<model>/cases/<cid>.pkl | |
| cls2_drawer_test.py summary --model p2heat -> classifier2/scores/drawer_<model>.json / .csv | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, os, pickle, sys, time | |
| from pathlib import Path | |
| import numpy as np | |
| import scipy.ndimage as ndi | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import cls2_common as Q # noqa: E402 | |
| TS = {"0802": 0.802, "0692": 0.692} | |
| RESCORE = False | |
| # drawer2 agent (2026-11-17): multi-scale-prompt drawer and per-candidate crop drawer (cascade2_prompt2.py). Variants | |
| # acc<k>_pp_sized / oracle / zero; prompts = candidate-sized balls built on the 1 mm nnU-Net preprocessed grid (drawer2_infer.py). | |
| DRAWER2_MODELS = {"p2ballms": ("nnUNetTrainer_C2PBallMS", "ms"), "p2crop": ("nnUNetTrainer_C2PCrop", "crop")} | |
| def drawer2_case(a, pr, enc, cid, od, outs, img, props, heat): | |
| import drawer2_infer as D2I | |
| las = {} | |
| for k, t in TS.items(): | |
| ap = od / "acc" / k / f"{cid}.nii.gz"; shared = DR / "p2heat" / "acc" / k / f"{cid}.nii.gz" | |
| if ap.exists(): | |
| la = Q.read_nii(ap, np.int32) | |
| else: | |
| la = Q.read_nii(shared, np.int32) if shared.exists() else accepted_raw(cid, t) | |
| write_like(la.astype(np.uint16), t1_path(cid), ap, np.uint16) | |
| las[f"acc{k}_pp_sized"] = la | |
| gt = Q.read_nii(Q.label_path(cid)) > 0 | |
| t0 = time.time() | |
| res, info = D2I.infer_case(pr, enc, img, props, heat, las, gt) | |
| for v, p1 in res.items(): | |
| write_like(np.clip(np.round(p1 * 250), 0, 250).astype(np.uint8), t1_path(cid), outs[v], np.uint8) | |
| log("DRW2", a.model, cid, json.dumps(info), {v: int((p >= 0.5).sum()) for v, p in res.items()}, f"{time.time() - t0:.1f}s") | |
| EXTRA_MODELS = {"p2ballpo": ("nnUNetTrainer_C2PBallPO", "ball"), # round-2 drawers (cascade2_prompt.py); local extension of | |
| "p2balloff": ("nnUNetTrainer_C2PBallOff", "ball")} # prompt2_infer.MODELS (that file is not edited) | |
| DEFAULT_RADIUS = {"p2balloff": "sized"} | |
| def ball_prompt(heat, la, t1raw, place="centroid", radius="r4"): | |
| """test-time ball prompts for accepted candidates (label map la, raw grid). | |
| place: centroid = prompt2_infer.describe centre (heat-weighted centroid, argmax if outside); | |
| hybrid = centroid unless robust-z T1 at the centroid > ring mean - 0.5 (ring = 1-3 voxels around the candidate), | |
| then the darkest-T1 voxel within 4 voxels of the centroid inside the 2-voxel-dilated candidate. | |
| radius: r4 = 4 voxels; sized = cascade2_prompt.sized_ball_radius(candidate voxels) = clip(0.6 * equiv-sphere r, 2, 5).""" | |
| import prompt2_infer as PI | |
| from cascade2_prompt import ball_mask, sized_ball_radius | |
| out = np.zeros(heat.shape, np.float32) | |
| if not la.any(): | |
| return out, [] | |
| br = t1raw > 0 | |
| v = t1raw[br]; med = np.median(v); iqr = np.percentile(v, 75) - np.percentile(v, 25) | |
| z = (t1raw - med) / (0.7413 * iqr + 1e-6) | |
| info = [] | |
| objs = ndi.find_objects(la) | |
| for c in PI.describe(la, heat): | |
| i = c["id"]; o = objs[i - 1] | |
| pad = 6 | |
| sl = tuple(slice(max(0, s_.start - pad), min(n_, s_.stop + pad)) for s_, n_ in zip(o, la.shape)) | |
| m = la[sl] == i | |
| ce = np.array(c["centre"]) - np.array([s_.start for s_ in sl]) | |
| moved = False | |
| if place == "hybrid": | |
| ring = ndi.binary_dilation(m, iterations=3) & ~m & br[sl] | |
| zl = z[sl] | |
| if ring.any() and zl[tuple(ce)] > zl[ring].mean() - 0.5: | |
| dil = ndi.binary_dilation(m, iterations=2) | |
| g = np.indices(m.shape); d2 = sum((gi - ci) ** 2 for gi, ci in zip(g, ce)) | |
| cand = dil & (d2 <= 16) & br[sl] | |
| if cand.any(): | |
| zz = np.where(cand, zl, np.inf); ce = np.array(np.unravel_index(int(np.argmin(zz)), zz.shape)); moved = True | |
| r = 4.0 if radius == "r4" else sized_ball_radius(int(m.sum())) | |
| gc = ce + np.array([s_.start for s_ in sl]) | |
| out = np.maximum(out, ball_mask(heat.shape, gc, r)) | |
| info.append({"id": int(i), "centre": [int(x) for x in gc], "r": round(float(r), 2), "moved": moved}) | |
| return out, info | |
| DR = Q.OUT / "drawer" | |
| def log(*a): | |
| print(time.strftime("%H:%M:%S"), *a, flush=True) | |
| def write_like(arr, ref_path, out, dtype): | |
| import SimpleITK as sitk | |
| Q.guard_write(out) | |
| ref = sitk.ReadImage(str(ref_path)); im = sitk.GetImageFromArray(np.asarray(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 t1_path(cid): | |
| return Q.guard(Q.D943R / "imagesTs" / f"test_{cid}_0000.nii.gz") | |
| def accepted_raw(cid, t): | |
| """accepted pp candidates (s_sepd >= t) -> raw-grid label map (sitk order), labels preserved.""" | |
| import pandas as pd, dethead_cand as K, devset_common as D, cls2_testprep as P | |
| t1, fl, h, p, brain, gt, props = P.prep(cid) | |
| L, n = K.candidates(h, brain) | |
| sc = pd.read_pickle(Q.OUT / "scores/s_sepd/test.pkl").set_index(["key", "cid"])["score"] | |
| acc = [c for c in range(1, n + 1) if sc.get((cid, c), -1) >= t] | |
| La = np.where(np.isin(L, acc), L, 0).astype(np.int32) | |
| return D.prep_to_raw(La, props, fill=0, order=0).astype(np.int32) | |
| def infer(a): | |
| import torch, prompt2_infer as PI, cascade2_infer as I | |
| from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO | |
| MODELS = {**PI.MODELS, **EXTRA_MODELS, **DRAWER2_MODELS} | |
| trainer, enc = MODELS[a.model] | |
| assert (Q.WS / f"outputs/direction2/prompt2/locks/{a.model}_x.TRAINED").exists(), f"{a.model} not trained" | |
| dev = "cuda" if torch.cuda.is_available() else "cpu" | |
| pr = None | |
| cids = Q.test_cids()[a.chunk::a.nchunk] | |
| for cid in (cids[::-1] if a.reverse else cids): | |
| od = DR / a.model | |
| vsuf = "" if enc == "heat" else ("_pp_sized" if enc in ("ms", "crop") else f"_{a.place}_{a.radius or DEFAULT_RADIUS.get(a.model, 'r4')}") | |
| outs = {v: od / "pred" / v / f"{cid}.nii.gz" for v in [f"acc{k}{vsuf}" for k in TS] + ["oracle", "zero"]} | |
| if all(p.exists() for p in outs.values()): | |
| continue | |
| if pr is None: | |
| pr = I.predictor(I.model_dir(Q.C.DEL, trainer), [Q.C.fold_index(Q.C.DEL, PI.FOLD)], dev) | |
| img, props = SimpleITKIO().read_images([str(t1_path(cid))]) | |
| heat = Q.read_nii(Q.HEAT_TEST / f"{cid}.nii.gz") | |
| if enc in ("ms", "crop"): # drawer2 models: prompts on the 1 mm preprocessed grid (drawer2_infer.py) | |
| drawer2_case(a, pr, enc, cid, od, outs, img, props, heat); continue | |
| t1raw = np.asarray(img[0], np.float32) | |
| prompts = {} | |
| for k, t in TS.items(): | |
| ap = od / "acc" / k / f"{cid}.nii.gz" | |
| if ap.exists(): | |
| la = Q.read_nii(ap, np.int32) | |
| else: | |
| la = accepted_raw(cid, t); write_like(la.astype(np.uint16), t1_path(cid), ap, np.uint16) | |
| if enc == "heat": | |
| prompts[f"acc{k}"] = PI.prompt_from_candidates(enc, heat, la, PI.describe(la, heat)) if la.any() else np.zeros(heat.shape, np.float32) | |
| else: | |
| pm_, inf_ = ball_prompt(heat, la, t1raw, a.place, a.radius or DEFAULT_RADIUS.get(a.model, "r4")) | |
| prompts[f"acc{k}{vsuf}"] = pm_ | |
| ip = od / "ballinfo" / f"acc{k}{vsuf}" / f"{cid}.json"; ip.parent.mkdir(parents=True, exist_ok=True) | |
| json.dump(inf_, open(Q.guard_write(ip), "w")) | |
| gt = Q.read_nii(Q.label_path(cid)) > 0 | |
| prompts["oracle"] = PI.oracle_prompt(enc, heat, gt) | |
| prompts["zero"] = np.zeros(heat.shape, np.float32) | |
| for v, pm in prompts.items(): | |
| if outs[v].exists(): | |
| continue | |
| t0 = time.time() | |
| assert pm.shape == img.shape[1:], (cid, pm.shape, img.shape) | |
| x = np.concatenate([img, pm[None].astype(np.float32)], 0).astype(np.float32) | |
| _s, prob = pr.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), t1_path(cid), outs[v], np.uint8) | |
| log("DRW", a.model, v, cid, int((p1 >= 0.5).sum()), f"{time.time() - t0:.1f}s") | |
| log("DRW_INFER_DONE", a.model, a.chunk, a.nchunk) | |
| def score_case(model, cid): | |
| import cascade2_score as S, prompt2_score as PS | |
| import dethead_cand as K, devset_common as D, cls2_testprep as P, cls2_e2e_test as X, pandas as pd | |
| od = DR / model; op = od / "cases" / f"{cid}.pkl" | |
| if op.exists() and not RESCORE: | |
| return | |
| import SimpleITK as sitk | |
| li = sitk.ReadImage(str(Q.label_path(cid))); gt = sitk.GetArrayFromImage(li) > 0 | |
| sp = li.GetSpacing()[::-1]; vml = float(np.prod(sp)) / 1000 | |
| far = ndi.distance_transform_edt(~gt, sampling=sp) > 10 if gt.any() else np.ones_like(gt) | |
| pb = {"delbankconv": Q.read_nii(Q.C.OUT / "pred/delbankconv_x/prob" / f"{cid}.nii.gz") / 250.0, | |
| "d331": Q.read_nii(Q.D331_TEST / f"{cid}.nii.gz") / 250.0} | |
| bb = {"delbankconv": Q.read_nii(Q.C.OUT / "pred/delbankconv_x" / f"{cid}.nii.gz") == 1, "d331": pb["d331"] >= 0.5} | |
| accv = sorted(d.name for d in (od / "pred").iterdir() if d.name.startswith("acc") and (d / f"{cid}.nii.gz").exists()) | |
| pv = {v: Q.read_nii(od / "pred" / v / f"{cid}.nii.gz") / 250.0 for v in accv + ["oracle", "zero"]} | |
| acc = {k: Q.read_nii(od / "acc" / k / f"{cid}.nii.gz", np.int32) > 0 for k in TS} | |
| # lpd crude draw at the same exact thresholds (pp grid -> raw) | |
| t1, fl, h, p, brain, gt_pp, props = P.prep(cid) | |
| ctx = K.patient_ctx(t1, brain, props, cid) | |
| L, n = K.candidates(h, brain) | |
| sc = pd.read_pickle(Q.OUT / "scores/s_sepd/test.pkl").set_index(["key", "cid"])["score"] | |
| scv = np.array([sc.get((cid, c), -1) for c in range(1, n + 1)]) | |
| draws = X.per_cand_draw(L, n, h, ctx["t1z"], brain, p, "lpd") | |
| lpd = {} | |
| for k, t in TS.items(): | |
| dpp = np.zeros(L.shape, bool) | |
| for i in np.flatnonzero(scv >= t): | |
| sl, d = draws[i]; dpp[sl] |= d | |
| lpd[k] = D.prep_to_raw(dpp.astype(np.uint8), props, fill=0, order=0) > 0 | |
| rows = [] | |
| sites = rated_sites_raw(cid, gt.shape) | |
| def add(setting, base, mask, added=None): | |
| m = S.metrics(gt, mask, vml, far) | |
| r = {"cid": cid, "cohort": cid.split("_")[0], "setting": setting, "base": base, "m": m, | |
| "added_ml": float((mask & ~bb[base]).sum() * vml) if base in bb else float(mask.sum() * vml)} | |
| if base in bb: | |
| r["added_adj"] = adjudicate_added(mask, bb[base], gt, sites) | |
| rows.append(r) | |
| for base in ("delbankconv", "d331"): | |
| add("base_alone", base, bb[base]) | |
| for v in accv: | |
| k = v[3:7] | |
| dm = PS.draw_mask(pv[v], acc[k]) | |
| add("drawer_" + v[3:], base, np.maximum(pb[base], pv[v] * dm) >= 0.5) | |
| for k in TS: | |
| add(f"lpd_{k}", base, bb[base] | lpd[k]) | |
| dz = PS.draw_mask(pv["zero"], acc[k]) | |
| add(f"drawer_zeroprompt_{k}", base, np.maximum(pb[base], pv["zero"] * dz) >= 0.5) | |
| do = PS.draw_mask(pv["oracle"], gt) | |
| add("drawer_oracle", base, np.maximum(pb[base], pv["oracle"] * do) >= 0.5) | |
| for v in accv: | |
| dm = PS.draw_mask(pv[v], acc[v[3:7]]) | |
| add("drawer_alone_" + v[3:], "none", (pv[v] * dm) >= 0.5) | |
| od.joinpath("cases").mkdir(parents=True, exist_ok=True) | |
| pickle.dump(rows, open(Q.guard_write(op), "wb")) | |
| log("DRW_SCORE", model, cid, len(rows)) | |
| def rated_sites_raw(cid, shape_sitk): | |
| """round-4 rated sites of this case as sitk-order masks with labels (yes = lesion / wmh).""" | |
| import json as _j | |
| out = [] | |
| for rnd in ("round4a", "round4b"): | |
| kd = Q.WS / f"outputs/direction2/review/{rnd}" | |
| rd = Path(f"/__redacted__") | |
| if not (kd / f"{rnd}_key.json").exists() or not rd.exists(): | |
| continue | |
| key = _j.load(open(kd / f"{rnd}_key.json"))["items"]; z = np.load(kd / f"{rnd}_sitemasks.npz") | |
| for it, v in key.items(): | |
| if v["cid"] != cid or not (rd / f"{it}.json").exists(): | |
| continue | |
| ijk = z[it].astype(int); m = np.zeros(shape_sitk, bool); m[tuple(ijk[:, ::-1].T)] = True | |
| out.append((m, _j.load(open(rd / f"{it}.json")).get("label"))) | |
| return out | |
| def adjudicate_added(mask, base, gt, sites): | |
| """added components (>= 10 vox, no base voxel): GT-TP / rated yes (lesion|wmh) / rated no / unrated.""" | |
| import cc3d | |
| F = cc3d.connected_components(mask.astype(np.uint8), connectivity=26) | |
| c = {"n_added": 0, "gt_tp": 0, "rated_yes_lesion": 0, "rated_yes_wmh": 0, "rated_no": 0, "unrated": 0} | |
| for f, o in enumerate(ndi.find_objects(F), start=1): | |
| if o is None: | |
| continue | |
| m = F[o] == f | |
| if m.sum() < 10 or (base[o] & m).any(): | |
| continue | |
| c["n_added"] += 1 | |
| if (gt[o] & m).any(): | |
| c["gt_tp"] += 1; continue | |
| labs = [lb for sm, lb in sites if (sm[o] & m).any()] | |
| if "lesion" in labs: | |
| c["rated_yes_lesion"] += 1 | |
| elif "wmh" in labs: | |
| c["rated_yes_wmh"] += 1 | |
| elif labs: | |
| c["rated_no"] += 1 | |
| else: | |
| c["unrated"] += 1 | |
| return c | |
| def summary(a): | |
| import cascade2_score as S, pandas as pd | |
| rows = [] | |
| for p in sorted((DR / a.model / "cases").glob("*.pkl")): | |
| rows += pickle.load(open(p, "rb")) | |
| df = pd.DataFrame(rows) | |
| out = [] | |
| for (st, base), g in df.groupby(["setting", "base"]): | |
| for pool, coh in (("ATLAS-43", ("atlas",)), ("NORTH", ("north",)), ("PRIMARY", ("atlas", "north")), ("LAB", ("lab",))): | |
| gg = g[g["cohort"].isin(coh)] | |
| if gg.empty: | |
| continue | |
| s = S.stats_from(np.array([S.counts(m) for m in gg["m"]], float)) | |
| adj = {} | |
| if "added_adj" in gg and gg["added_adj"].notna().any(): | |
| for d in gg["added_adj"].dropna(): | |
| for kk, vv in d.items(): | |
| adj[kk] = adj.get(kk, 0) + vv | |
| out.append({"setting": st, "base": base, "pool": pool, "n": int(s["n_cases"]), "SM": s["sm_recall"], "prec": s["les_precision"], | |
| "F1": s["les_f1"], "Dice": s["dice"], "FPc": s["fp_per_case"], "r<0.1": s["recall_lt0.1"], "r0.1-1": s["recall_0.1-1"], | |
| "r1-5": s["recall_1-5"], "nsm": s["n_sm"], **{f"add_{k}": v for k, v in adj.items()}}) | |
| T = pd.DataFrame(out) | |
| T.to_csv(Q.guard_write(Q.OUT / f"scores/drawer_{a.model}.csv"), index=False) | |
| Q.jdump({"model": a.model, "n_cases": int(df["cid"].nunique()), "rows": out}, Q.OUT / f"scores/drawer_{a.model}.json") | |
| pd.set_option("display.width", 250) | |
| print(T[T["pool"].isin(["PRIMARY", "LAB"])].round(3).to_string(index=False)) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(); ap.add_argument("mode"); ap.add_argument("--model", default="p2heat") | |
| ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1) | |
| ap.add_argument("--reverse", type=int, default=0) | |
| ap.add_argument("--place", default="centroid", choices=["centroid", "hybrid"]); ap.add_argument("--radius", default="", choices=["", "r4", "sized"]) | |
| ap.add_argument("--rescore", type=int, default=0) | |
| a = ap.parse_args() | |
| if a.mode == "infer": | |
| infer(a) | |
| elif a.mode == "score": | |
| RESCORE = bool(a.rescore) | |
| for c in Q.test_cids()[a.chunk::a.nchunk]: | |
| try: | |
| score_case(a.model, c) | |
| except Exception as e: | |
| import traceback; traceback.print_exc(); print("FAIL", c, repr(e)[:200], flush=True) | |
| log("DRW_SCORE_DONE") | |
| else: | |
| summary(a) | |