#!/usr/bin/env python """classifier2 PURE-CLASSIFIER evaluation (user design, 2026-11-17): every head judged as a yes/no on stage-1 candidates (heat >= 0.5 blobs, >= 10 vox, 1 mm pp grid), independent of D331 / delbankconv masks (no union, no base). Truth versions: (i) GT only: positive = candidate overlaps a GT lesion (dethead 'pos'); lesions = GT S+M lesions. (ii) GT U user-rated-lesion: positive also if the candidate overlaps a site the user rated 'lesion' in any blinded round; rated-lesion sites not overlapping a GT lesion are added as extra lesions for the FROC. (iii) as (ii) but non-GT candidates WITHOUT any user rating are UNKNOWN (excluded from negatives / FP counts). Ratings loader (hook for new rounds): RATING_SOURCES = [(round, key json, ratings dir, mask source)], one json per item id {label, note, order, at}. Site masks are reconstructed exactly (vox asserted) on the raw nibabel grid: source gt -> cc3d26(GT & brain) == comp; del -> cc3d26(del_detA_ii_x pred & brain); fp -> cc3d26(delbankconv_x pred & brain); d331 -> cc3d26(D331 pred & brain); foci -> round2/parts/_labels.npz['foci'] == comp; round4 -> round4x_sitemasks.npz. The pilot was CONTRA-only (no dev-test candidates) -> not used. Test cohorts are only scored (prereg 35q). cls2_pure_eval.py sites -> classifier2/feat/rated_sites.pkl (candidate-level rating flags + rated-lesion pseudo-lesions) cls2_pure_eval.py eval -> classifier2/scores/pure_eval.json """ from __future__ import annotations import json, os, pickle, sys from pathlib import Path import numpy as np import pandas as pd sys.path.insert(0, str(Path(__file__).resolve().parent)) import cls2_common as Q # noqa: E402 REV = Q.WS / "outputs/direction2/review" SCR = Path("/__redacted__") RATING_SOURCES = [ ("round2", REV / "round2/round2_key.json", SCR / "r2_ratings/ratings"), ("round3", REV / "round3/round3_key.json", SCR / "r3_ratings/ratings"), ("round4a", REV / "round4a/round4a_key.json", SCR / "r4a_ratings/ratings"), ("round4b", REV / "round4b/round4b_key.json", SCR / "r4b_ratings/ratings"), ("round6", REV / "round6/round6_key.json", SCR / "r6_ratings/ratings"), # skipped until the ratings dir exists ] HEADS = ["s_sepd", "pstackN_ens_d331", "g_d331f", "col:p_d331_max", "col:h_mean"] + \ [h for h in os.environ.get("CLS2_EXTRA_HEADS", "").split(",") if h] def load_ratings(): rows = [] for rnd, kp, rd in RATING_SOURCES: if not (kp.exists() and rd.exists()): print("skip (missing)", rnd); continue key = json.load(open(kp))["items"] for f in sorted(rd.glob("*.json")): it = f.stem if it not in key: continue lab = json.load(open(f)).get("label") rows.append(dict(round=rnd, item_id=it, label=lab, **{k: key[it].get(k) for k in ("cid", "source", "comp", "vox", "category", "stratum", "centroid_raw_ijk")})) return pd.DataFrame(rows) def site_mask(r, cache): import cc3d, nibabel as nib, diag2_sb as SB cid = r["cid"] if cid not in cache: t1, fl, gt, excl, brain, sp, aff = SB.load_case_raw(cid) cache.clear(); cache[cid] = {"t1": t1, "gt": gt, "brain": brain, "lab": {}} c = cache[cid] src = r["source"] if (REV / r["round"] / f"{r['round']}_sitemasks.npz").exists(): # rounds with stored site masks (4a, 4b, 5, 6, ...) z = np.load(REV / r["round"] / f"{r['round']}_sitemasks.npz"); m = np.zeros(c["t1"].shape, bool); m[tuple(z[r["item_id"]].astype(int).T)] = True return m if src not in c["lab"]: if src == "gt": v = c["gt"] elif src == "foci": c["lab"][src] = np.load(REV / "round2/parts" / f"{cid}_labels.npz")["foci"] else: path = {"del": Q.C.OUT / "pred/del_detA_ii_x", "fp": Q.C.OUT / "pred/delbankconv_x"}.get(src) if src == "d331": import diag2_common as G path = None; v = np.asarray(nib.load(str(G.guard(G.D331_PRED / f"test_{cid}.nii.gz"))).dataobj) > 0.5 else: v = np.asarray(nib.load(str(path / f"{cid}.nii.gz")).dataobj) > 0.5 if src != "foci": c["lab"][src] = cc3d.connected_components((v & c["brain"]).astype(np.uint8), connectivity=26) lab = c["lab"][src] m = lab == int(r["comp"]) if int(m.sum()) != int(r["vox"]): # label numbering differs between cc3d runs (diag2_sb vs here): match by voxel count + key centroid (exact component) sz = np.bincount(lab.ravel()) cands = [k for k in np.flatnonzero(sz == int(r["vox"])) if k > 0] cen = np.array(r["centroid_raw_ijk"], float) d = [np.abs(np.argwhere(lab == k).mean(0) - cen).max() for k in cands] assert cands and min(d) < 0.6, (r["round"], r["item_id"], src, r["vox"], d) m = lab == cands[int(np.argmin(d))] return m def sites(): import dethead_cand as K, cls2_testprep as P R = load_ratings() R = R[R["cid"].notna() & R["cid"].str.split("_").str[0].isin(Q.TEST_COHORTS)].sort_values("cid") out_c, out_l, cache = [], [], {} pp_cache = {} for _, r in R.iterrows(): cid = r["cid"] m = site_mask(r, cache) if cid not in pp_cache: t1, fl, h, p, brain, gt_pp, props = P.prep(cid) L, n = K.candidates(h, brain) import cc3d pp_cache.clear(); pp_cache[cid] = (L, props, gt_pp, cc3d.connected_components(gt_pp.astype(np.uint8), connectivity=26)) L, props, gt_pp, GL = pp_cache[cid] mp = K.dev_to_pp(m.transpose(2, 1, 0).astype(np.float32), props, L.shape, order=0) > 0.5 ids = sorted(set(np.unique(L[mp]).tolist()) - {0}) for i in ids: out_c.append(dict(key=cid, cid=i, round=r["round"], item_id=r["item_id"], label=r["label"], source=r["source"])) out_l.append(dict(key=cid, round=r["round"], item_id=r["item_id"], label=r["label"], source=r["source"], vox=int(mp.sum()), cands=ids, overlaps_gt=bool((mp & gt_pp).any()), gt_gids=sorted(set(np.unique(GL[mp]).tolist()) - {0}), category=r.get("category"))) pickle.dump({"cand": pd.DataFrame(out_c), "sites": pd.DataFrame(out_l), "ratings": R}, open(Q.guard_write(Q.OUT / "feat/rated_sites.pkl"), "wb")) print("SITES", len(R), "rated items on test cohorts;", len(out_c), "candidate-item links") def pr_curve(y, s, n=25): o = np.argsort(-s); ys = y[o]; tp = np.cumsum(ys); prec = tp / np.arange(1, len(ys) + 1); rec = tp / max(ys.sum(), 1) qs = np.linspace(0, len(ys) - 1, n).astype(int) return [[round(float(rec[q]), 4), round(float(prec[q]), 4), round(float(s[o][q]), 4)] for q in qs] def evaluate(): import cls2_eval as E, dethead_metrics as M from sklearn.metrics import roc_auc_score, average_precision_score S = pickle.load(open(Q.OUT / "feat/rated_sites.pkl", "rb")) rc, rs = S["cand"], S["sites"] P = E.pops() rated_c = set(map(tuple, rc[["key", "cid"]].to_numpy())) lab_c = {L_: set(map(tuple, rc.loc[rc["label"] == L_, ["key", "cid"]].to_numpy())) for L_ in ("lesion", "wmh", "mimic", "unsure")} # GT lesions (pp-grid gid) rated mimic and never rated lesion/wmh -> version (iii) g_m = {(k, g) for k, gl, lb in zip(rs["key"], rs["gt_gids"], rs["label"]) if lb == "mimic" for g in gl} g_y = {(k, g) for k, gl, lb in zip(rs["key"], rs["gt_gids"], rs["label"]) if lb in ("lesion", "wmh") for g in gl} g_mimic = g_m - g_y # PRIMARY definition (user Option A, prereg 35r): iib = GT U rated 'lesion' U rated 'wmh'; i and iia secondary; iii = iia minus mimic-rated GT VERS = {"iib_gt_or_lesion_wmh": ("lesion", "wmh"), "i_gt": (), "iia_gt_or_lesion": ("lesion",), "iii_iia_minus_mimic_gt": ("lesion",)} res = {"primary_definition": "iib_gt_or_lesion_wmh (GT U rated lesion U rated WMH; user Option A, prereg 35r)", "definition": __doc__, "rating_rounds": [r for r, _, _ in RATING_SOURCES], "mimic_rated_gt_lesions": sorted(map(list, g_mimic)), "pools": {}} for pool in ("test_atlas", "test_north", "test_prim", "test_lab"): tab, les = P[pool] keys = set(tab["key"]) kk = list(zip(tab["key"], tab["cid"])) tab = tab.assign(rated=[k in rated_c for k in kk], **{f"r_{L_}": [k in lab_c[L_] for k in kk] for L_ in lab_c}) # candidate -> GT gids (>= 10 vox lesions) for version (iii) c2g = {} for k, g, cl in zip(les["key"], les["gid"], les["cands"]): for c in cl: c2g.setdefault((k, c), set()).add(g) info = {"n_cand": int(len(tab)), "n_pos_gt": int(tab["pos"].sum()), "n_rated_cand": int(tab["rated"].sum()), **{f"n_rated_{L_}_cand_nonGT": int((tab[f"r_{L_}"] & (tab["pos"] == 0)).sum()) for L_ in lab_c}, "n_unrated_nonGT_cand": int((~tab["rated"] & (tab["pos"] == 0)).sum()), "n_SM_GT_lesions": int((les["vox"] < 30000).sum()), "n_mimic_rated_GT_lesions": int(sum(k in keys for k, g in g_mimic)), "heads": {}} for ver, labs in VERS.items(): ex = rs[rs["label"].isin(labs) & ~rs["overlaps_gt"] & rs["key"].isin(keys) & (rs["cands"].map(len) > 0)] ex = ex.assign(_cs=ex["cands"].map(lambda c: tuple(sorted(c)))).drop_duplicates(subset=["key", "_cs"]) info[f"n_extra_sites_{ver}"] = int(len(ex)) for h in HEADS: t = E.attach(tab, h, pool) if t is None: continue t = t.assign(score=t["score"].fillna(-1e9)) hv = {} for ver, labs in VERS.items(): tt = t.copy(); tt["amb"] = 0 ypos = tt["pos"] == 1 for L_ in labs: ypos = ypos | tt[f"r_{L_}"] L2 = les if ver.startswith("iii"): drop = [(k, c) for k, c in zip(tt["key"], tt["cid"]) if c2g.get((k, c)) and c2g[(k, c)] <= {g for kk_, g in g_mimic if kk_ == k}] dset = set(drop) ypos = ypos & ~pd.Series([((k, c) in dset) and not tt_r for k, c, tt_r in zip(tt["key"], tt["cid"], tt["r_lesion"])], index=tt.index) L2 = les[[(k, g) not in g_mimic for k, g in zip(les["key"], les["gid"])]] tt["pos"] = ypos.astype(int) L2 = L2.assign(psrc="gt") if labs: ex = rs[rs["label"].isin(labs) & ~rs["overlaps_gt"] & rs["key"].isin(keys) & (rs["cands"].map(len) > 0)] ex = ex.assign(_cs=ex["cands"].map(lambda c: tuple(sorted(c))), _o=ex["label"].map({"lesion": 0, "wmh": 1})) ex = ex.sort_values("_o").drop_duplicates(subset=["key", "_cs"]) L2 = pd.concat([L2, pd.DataFrame({"key": ex["key"], "src": "real", "gid": -1, "vox": ex["vox"].clip(lower=10), "cands": ex["cands"], "sbin": "rated", "psrc": "rated_" + ex["label"]})], ignore_index=True) r = M.summarize(tt, L2, "score") best, nsc, ncase = M.froc_table(tt, L2, "score") Lsm = L2[L2["vox"] < 30000] by_src = {} for b in (0.5, 1, 2): _, thr = M.recall_at_budget(best, nsc, ncase, b) by_src[f"recall@{b}fp"] = {g: [int((best[(Lsm["psrc"] == g).to_numpy()] > thr).sum()), int((Lsm["psrc"] == g).sum())] for g in ("gt", "rated_lesion", "rated_wmh") if (Lsm["psrc"] == g).any()} y = tt["pos"].to_numpy(); s = tt["score"].to_numpy() hv[ver] = {"auc": float(roc_auc_score(y, s)) if 0 < y.sum() < len(y) else None, "ap": float(average_precision_score(y, s)) if 0 < y.sum() < len(y) else None, "n_pos": int(y.sum()), "froc_low": r["froc_low"], "rec@0.5fp": r["rec@0.5fp"], "rec@1fp": r["rec@1fp"], "rec@2fp": r["rec@2fp"], "n_lesions": r["n_sm"], "ceiling": r["ceiling"], "recall_by_positive_source_[hit,n]": by_src, "n_pos_cand_by_source": {"gt": int((t["pos"] == 1).sum()), "+lesion_rated_nonGT": int(((t["pos"] == 0) & t["r_lesion"]).sum()) if "lesion" in labs else 0, "+wmh_rated_nonGT_nonlesion": int(((t["pos"] == 0) & t["r_wmh"] & ~t["r_lesion"]).sum()) if "wmh" in labs else 0}, "pr_curve_[rec,prec,thr]": pr_curve(y, s)} info["heads"][h] = hv res["pools"][pool] = info res["added_adjudication"] = added_adjudication(S["ratings"]) Q.jdump(res, Q.OUT / ("scores/pure_eval.json" if not os.environ.get("CLS2_PURE_OUT") else f"scores/{os.environ['CLS2_PURE_OUT']}.json")) for pool, info in res["pools"].items(): print(f"== {pool}: " + ", ".join(f"{k} {v}" for k, v in info.items() if k.startswith("n_"))) for h, hv in info["heads"].items(): print(f" {h:18s} " + " | ".join(f"{v}: {x['auc'] or float('nan'):.3f}/{x['ap'] or float('nan'):.3f}/{x['froc_low']:.3f}" for v, x in hv.items())) print(json.dumps(res["added_adjudication"], indent=1)) def added_adjudication(R): """round-4 ADDED components (e2e operating points): adjudicated precision on rated items.""" out = {} for rnd, pools in (("round4a", {"added_FP": 38, "added_TP": 5}), ("round4b", {"added_FP": 295, "added_TP": 231})): r = R[(R["round"] == rnd) & R["category"].isin(["added_FP", "added_TP"])] cnt = {c: dict(r[r["category"] == c]["label"].value_counts()) for c in ("added_FP", "added_TP")} d = {"counts_by_category_label": {c: {k: int(v) for k, v in x.items()} for c, x in cnt.items()}, "n_rated": int(len(r))} for ver, yes in (("iia", ("lesion",)), ("iib", ("lesion", "wmh")), ("iii", ("lesion",))): gt_ok = r["category"].eq("added_TP") & (~r["label"].eq("mimic") if ver == "iii" else True) y = gt_ok | r["label"].isin(yes) d[f"precision_{ver}_rated"] = [int(y.sum()), int(len(r)), round(float(y.mean()), 3)] # stratum-weighted estimate (round4b samples 40 of 295 FP, 20 of 231 TP) w = np.where(r["category"] == "added_FP", pools["added_FP"] / max((r["category"] == "added_FP").sum(), 1), pools["added_TP"] / max((r["category"] == "added_TP").sum(), 1)) d[f"precision_{ver}_weighted"] = round(float((w * y).sum() / w.sum()), 3) out[rnd] = d return out R5_RATINGS = SCR / "r5_ratings/ratings" # round-5 (CONTRA, off-test) ratings: one json per item id def round5_curve(ratings_dir=None): """OFF-TEST (ii-b) precision-vs-threshold curve of s_sepd from the round-5 CONTRA ratings. yes(ii-b) = GT overlap OR rated lesion OR rated WMH; (ii-a) without WMH; 'unsure' reported separately (counted as no and excluded variants). Bin-weighted (bin population / sampled) estimates of precision among ALL CONTRA candidates with score >= t.""" rd = Path(ratings_dir) if ratings_dir else R5_RATINGS key = json.load(open(REV / "round5/round5_key.json"))["items"] rows = [] for it, v in key.items(): f = rd / f"{it}.json" if f.exists(): rows.append(dict(item_id=it, label=json.load(open(f)).get("label"), **v)) df = pd.DataFrame(rows) if df.empty: print("no round-5 ratings yet in", rd); return df["w"] = df["bin_population"] / df["bin_sampled"] out = {"n_rated": int(len(df)), "label_counts": df["label"].value_counts().to_dict(), "curve": []} for t in [0.2, 0.45, 0.6, 0.7, 0.8, 0.802, 0.85, 0.875, 0.9, 0.924, 0.95, 0.98]: g = df[df["s_sepd_oof"] >= t] if g.empty: continue yb = (g["gt_overlap"] == 1) | g["label"].isin(["lesion", "wmh"]); ya = (g["gt_overlap"] == 1) | g["label"].eq("lesion") known = ~g["label"].eq("unsure") out["curve"].append({"t": t, "n": int(len(g)), "prec_iib": round(float(yb.mean()), 3), "prec_iia": round(float(ya.mean()), 3), "prec_iib_weighted": round(float((g["w"] * yb).sum() / g["w"].sum()), 3), "prec_iib_unsure_excluded": round(float(yb[known].mean()), 3) if known.any() else None, "prec_gt_only": round(float((g["gt_overlap"] == 1).mean()), 3)}) Q.jdump(out, Q.OUT / "scores/round5_curve.json") print(json.dumps(out, indent=1)) if __name__ == "__main__": {"sites": sites, "eval": evaluate, "round5": round5_curve}[sys.argv[1]]()