Download runtime/code/whisper_synth/src/direction2/boundary_audit.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 5.09 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/boundary_audit.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/boundary_audit.py
-
curl -L -o boundary_audit.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/boundary_audit.py
5.09 kB
| """Main session 2026-11-17: boundary / voxel-level audit of stage-2 and Pipeline-B outputs on the dev-test (raw grid). | |
| Per case and setting: Dice; voxel error decomposition of 1 - Dice into FP-boundary (pred voxels in components touching GT), | |
| FP-component (pred components touching no GT), FN-boundary (missed voxels of detected GT lesions), FN-missed (voxels of GT | |
| lesions no prediction touches). Per detected GT lesion (>= 10 vox): lesion Dice, volume ratio pred/GT, surface Dice @1/@2 mm, | |
| ASSD, HD95, signed mean surface distance (+ = prediction surface outside GT). Writes boundary/rows_<setting>.pkl. | |
| usage: boundary_audit.py [--procs N]""" | |
| import sys, pickle, argparse | |
| from multiprocessing import Pool | |
| from pathlib import Path | |
| import numpy as np, scipy.ndimage as ndi | |
| B = Path("/__EAGLE_BUNDLE_ROOT__/whisper_synth/outputs/direction2") | |
| PRED = B / "cascade2/pred"; DRW = B / "classifier2/drawer/p2heat"; OUT = B / "boundary" | |
| ARMS = ["del0_x", "delbankconv_x", "delbankconv0_x", "delbankconv0nofade_x", "delbankconvnoupi_x", "delbankconvtruth_x", "delbankwf_x"] | |
| def surf(m): | |
| return m & ~ndi.binary_erosion(m) | |
| def lesion_metrics(g, p, sp): | |
| """g, p: local bool masks (same crop).""" | |
| out = {"gt_vox": int(g.sum()), "pred_vox": int(p.sum())} | |
| inter = (g & p).sum(); out["dice"] = 2 * inter / (g.sum() + p.sum()); out["vol_ratio"] = p.sum() / g.sum() | |
| sg, spp = surf(g), surf(p) | |
| dg = ndi.distance_transform_edt(~g, sampling=sp); dgi = ndi.distance_transform_edt(g, sampling=sp) | |
| dp = ndi.distance_transform_edt(~p, sampling=sp) | |
| d_p2g = dg[spp]; d_g2p = dp[sg] | |
| signed = np.where(g[spp], -dgi[spp], dg[spp]) # + outside GT | |
| allx = np.concatenate([d_p2g, d_g2p]) | |
| out.update(assd=float(allx.mean()), hd95=float(np.percentile(allx, 95)), signed=float(signed.mean()), | |
| sdice1=float(((d_p2g <= 1).sum() + (d_g2p <= 1).sum()) / len(allx)), | |
| sdice2=float(((d_p2g <= 2).sum() + (d_g2p <= 2).sum()) / len(allx))) | |
| return out | |
| def analyse(gt, pr, sp, vml): | |
| import cc3d | |
| LG = cc3d.connected_components(gt.astype(np.uint8), connectivity=26); LP = cc3d.connected_components(pr.astype(np.uint8), connectivity=26) | |
| tp = int((gt & pr).sum()); fp = int((pr & ~gt).sum()); fn = int((gt & ~pr).sum()) | |
| pt = np.unique(LP[gt & pr]); pt = pt[pt > 0] | |
| touch_p = np.isin(LP, pt) | |
| gtt = np.unique(LG[gt & pr]); gtt = gtt[gtt > 0] | |
| det_g = np.isin(LG, gtt) | |
| dec = {"tp": tp, "fp_boundary": int((pr & ~gt & touch_p).sum()), "fp_component": int((pr & ~gt & ~touch_p).sum()), | |
| "fn_boundary": int((gt & ~pr & det_g).sum()), "fn_missed": int((gt & ~pr & ~det_g).sum())} | |
| dec["dice"] = 2 * tp / (2 * tp + fp + fn) if (tp + fp + fn) else 1.0 | |
| les = [] | |
| gsz = np.bincount(LG.ravel()); objs = ndi.find_objects(LG) | |
| for g in gtt: | |
| if gsz[g] < 10: | |
| continue | |
| o = objs[g - 1]; pad = [int(np.ceil(6 / s)) + 1 for s in sp] | |
| sl = tuple(slice(max(0, s.start - a), min(n, s.stop + a)) for s, a, n in zip(o, pad, gt.shape)) | |
| gl = LG[sl] == g | |
| ptl = np.unique(LP[sl][gl & (LP[sl] > 0)]) | |
| pl = np.isin(LP[sl], ptl) & ~((LG[sl] > 0) & ~gl) # pred comps touching this lesion, minus other GT lesions | |
| m = lesion_metrics(gl, pl, sp); m["gt_ml"] = float(gsz[g] * vml); les.append(m) | |
| return dec, les | |
| def one(args): | |
| cid, settings = args | |
| import SimpleITK as sitk, cls2_common as Q, prompt2_score as PS | |
| li = sitk.ReadImage(str(Q.label_path(cid))); gt = sitk.GetArrayFromImage(li) > 0 | |
| sp = tuple(li.GetSpacing()[::-1]); vml = float(np.prod(sp)) / 1000 | |
| rd = lambda p: sitk.GetArrayFromImage(sitk.ReadImage(str(p))) | |
| masks = {"d331": rd(Q.D331_TEST / f"{cid}.nii.gz") / 250.0 >= 0.5} | |
| for a in ARMS: | |
| p = PRED / a / f"{cid}.nii.gz" | |
| if p.exists(): | |
| masks[a] = rd(p) == 1 | |
| pb = rd(PRED / "delbankconv_x/prob" / f"{cid}.nii.gz") / 250.0 | |
| for v, k in (("acc0802", "0802"), ("acc0692", "0692")): | |
| pv = rd(DRW / "pred" / v / f"{cid}.nii.gz") / 250.0; acc = rd(DRW / "acc" / k / f"{cid}.nii.gz") > 0 | |
| masks[f"conv+p2heat@{k}"] = np.maximum(pb, pv * PS.draw_mask(pv, acc)) >= 0.5 | |
| po = rd(DRW / "pred/oracle" / f"{cid}.nii.gz") / 250.0 | |
| masks["conv+p2heat_oracle"] = np.maximum(pb, po * PS.draw_mask(po, gt)) >= 0.5 | |
| res = {} | |
| for s, m in masks.items(): | |
| if m.shape != gt.shape: | |
| continue | |
| dec, les = analyse(gt, m, sp, vml) | |
| res[s] = {"cid": cid, "cohort": cid.split("_")[0], "dec": dec, "les": les} | |
| return res | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(); ap.add_argument("--procs", type=int, default=12); a = ap.parse_args() | |
| import cls2_common as Q | |
| cids = list(Q.test_cids()) | |
| with Pool(a.procs) as pool: | |
| allr = pool.map(one, [(c, None) for c in cids]) | |
| out = {} | |
| for r in allr: | |
| for s, v in r.items(): | |
| out.setdefault(s, []).append(v) | |
| pickle.dump(out, open(OUT / "boundary_rows.pkl", "wb")) | |
| print("BOUNDARY_DONE", {s: len(v) for s, v in out.items()}, flush=True) | |