edschen's picture
EAGLE model u_pair_2c v1 (part 3)
473c56f verified
Raw History Blame Contribute Delete
2.45 kB
"""classifier2 (direction2, 2026-11-17): stronger per-candidate detection head for Pipeline B.
Builds on dethead (dethead_*.py; reused read-only). New in classifier2: the current test cohorts (NORTH, ATLAS-43 official,
LAB) are a DEVELOPMENT test set (prereg 35q): they may be scored, never trained on (no labels / images / statistics /
thresholds / calibration fitted on them). LAB is generator-seen -> reported separately. SABRE excluded; XHOLDOUT firewalled.
Writes only under outputs/direction2/classifier2/.
"""
from __future__ import annotations
import json, os, sys
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import cascade2_common as C # noqa: E402
B = C.B
WS = C.WS
OUT = WS / "outputs/direction2/classifier2"
DH = WS / "outputs/direction2/dethead"
D943R = C.D943R
HEAT_TEST = C.HEAT_TEST / "detA_ii_x" / "mean"
D331_TEST = WS / "outputs/direction2/arch2stage/t1prob"
TEST_COHORTS = ("atlas", "north", "lab")
PRIMARY = ("atlas", "north")
def guard(p):
s = str(p).lower()
assert "xholdout" not in s, f"XHOLDOUT firewall: {p}"
assert "sabre" not in s, f"SABRE excluded: {p}"
return p
def guard_write(p):
guard(p)
assert str(Path(p).resolve()).startswith(str(OUT.resolve())), f"write outside classifier2: {p}"
return p
def test_cids(cohorts=TEST_COHORTS):
cs = sorted(p.name[:-7] for p in HEAT_TEST.glob("*.nii.gz"))
cs = [c for c in cs if c.split("_")[0] in cohorts]
for c in cs:
guard(c)
return cs
def label_path(cid):
"""same convention as cascade2_score.label_path (ATLAS-43 -> official masks)."""
assert cid.split("_")[0] in TEST_COHORTS, cid
if cid.startswith("atlas_"):
return guard(C.OFF / f"{cid}.nii.gz")
tm = json.load(open(D943R / "test_label_map.json"))
return guard(tm[f"test_{cid}"])
def save_npz(path, **kw):
guard_write(path)
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 jdump(obj, path):
guard_write(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=float); os.replace(tmp, path)
def read_nii(p, dtype=np.float32):
import SimpleITK as sitk
return sitk.GetArrayFromImage(sitk.ReadImage(str(guard(p)))).astype(dtype)