#!/usr/bin/env python """classifier3: NEW candidates for a lower heat threshold / a combined detector, with every classifier input. Two-tier candidate set (cls3_common.two_tier generalised): the classifier2 candidates (reference heat >= 0.5, >= 10 vox) keep their frozen s_sepd scores; NEW candidates = components of the setting heat >= tau (>= 10 vox) containing NO classifier2 candidate voxel. Per new candidate: dethead hand features (label-free; probs d331 [+ delbankconv on the dev-test, evaluation only]), labels (dethead_cand.label_cands, GT used only there), frozen component scores v1_t1loc / cnn_v2a / cnn_v2a_s1 (dethead final models; crops without FLAIR, as cls2_apply), and 227 frozen D331 decoder features (cls2_d331feat sliding window + pool). Settings per population (reference heat in brackets): test : ii3_t0.3, ii3_t0.4 [ii3] ; mx2_t0.5, mx2_t0.3 = max(ii3, iv2) [ii3] ; mx3_* once renderer fold 2 exists contra : ii_t0.3, ii_t0.4 [OOF ii] ; mx_t0.5, mx_t0.3 = max(OOF ii, OOF iv) [OOF ii] (keys with iv OOF heat) dev : s1_t0.3, s1_t0.4, s2_t0.3, s2_t0.4 [DEV-A mean heat of that render seed] cls3_cand.py --pop test|contra|dev --chunk i --nchunk n [--settings a,b] -> classifier3/cand//.npz """ from __future__ import annotations import argparse, json, os, pickle, sys, time from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) import cls3_common as Q3 # noqa: E402 Q = Q3.Q TEST_SETTINGS = ("ii3_t0.3", "ii3_t0.4", "mx2_t0.5", "mx2_t0.3") _NETS = {} def nets(device): import torch, dethead_cnn as N, cls2_d331feat as DF if not _NETS: for tag in ("v2a", "v2a_s1"): ck = torch.load(Q.DH / f"models/cnn_{tag}_final.pt", map_location=device) aa = ck["args"]; net = N.Net(3, aa["width"], tuple(aa["streams"])).to(device); net.load_state_dict(ck["state"]); net.eval() _NETS[tag] = net _NETS["d331"] = DF.load_net(device); _NETS["gw"] = DF.gaussian(device) _NETS["v1"] = pickle.load(open(Q.DH / "models/v1_t1loc.pkl", "rb")) return _NETS ONLY = None FULL = False # --full 1: ALL components of the setting heat >= tau (single-tier replacement candidate set) FULL_SETTINGS = {"test": ("ii3_t0.3", "mx2_t0.5", "mx2_t0.3", "iv2_t0.5", "iv2_t0.3"), "contra": ("ii_t0.3", "mx_t0.5", "mx_t0.3", "iv_t0.5", "iv_t0.3"), "dev": ("s1_t0.3", "s2_t0.3", "v1_t0.5", "v1_t0.3", "v2_t0.5", "v2_t0.3")} HIV = Q3.OUT / "heat_iv" # renderer-only heat on the off-test pops (cls3_ivheat.py) def new_cands(h_ref, h_set, brain, tau): import dethead_cand as K Lt, nt = K.candidates(h_set, brain, tau) if FULL: return Lt, nt L5, n5 = K.candidates(h_ref, brain, 0.5) has5 = np.zeros(nt + 1, bool) if n5: has5[np.unique(Lt[L5 > 0])] = True has5[0] = False keep = [k for k in range(1, nt + 1) if not has5[k]] remap = np.zeros(nt + 1, np.int32); remap[keep] = np.arange(1, len(keep) + 1) return remap[Lt], len(keep) def score_setting(key, sname, t1, brain, props, ctx, gt, h_ref, h_set, tau, probs, feat_cache, device): import pandas as pd, torch, dethead_cand as K, dethead_crops as R, dethead_cnn as N, cls2_d331feat as DF LF, n = new_cands(h_ref, h_set, brain, tau) res = {"n": n, "feats": [], "labels": [], "lesions": []} if n == 0: return res, np.zeros((0, 227), np.float16) fe = K.cand_feats(LF, n, h_set, ctx, None, probs) lab, les = K.label_cands(LF, n, gt, ctx) nn_ = nets(device) df = pd.DataFrame(fe) s_v1 = nn_["v1"]["clf"].predict_proba(df[nn_["v1"]["features"]].to_numpy(np.float32))[:, 1] cr = R.crops_for_volume(R.canon(ctx["t1z"], props), R.canon(h_set, props), R.canon(LF, props), list(range(1, n + 1)), None) cr["flf"] = cr["t1f"][:1] * 0; cr["flc"] = cr["flf"] vox = np.bincount(LF.ravel())[1:] sc = {} with torch.no_grad(): for tag in ("v2a", "v2a_s1"): sc[tag] = N.predict(nn_[tag], N.to_dev(dict(cr), device), vox, 0, device, bs=64) if "d331" not in feat_cache: feat_cache["d331"] = DF.features(nn_["d331"], np.where(brain, t1, 0).astype(np.float32), device, nn_["gw"]) d1, d2, mg = feat_cache["d331"] X = DF.pool(LF, n, brain, d1, d2, mg, device) for i in range(n): fe[i]["hs_v1_t1loc"] = float(s_v1[i]); fe[i]["hs_cnn_v2a"] = float(sc["v2a"][i]); fe[i]["hs_cnn_v2a_s1"] = float(sc["v2a_s1"][i]) res.update(feats=fe, labels=lab, lesions=les) return res, X.astype(np.float16) def load_case(pop, key): """-> t1, brain, gt, props, refs {name: heat}, sets {setting: (refname, heat, tau)}, probs.""" import dethead_cand as K if pop == "test": import cls2_testprep as P t1, fl, h3, p, brain, gt, props = P.prep(key) pb = Q.read_nii(Q.C.OUT / "pred/delbankconv_x/prob" / f"{key}.nii.gz") / 250.0 probs = {"d331": p, "delbankconv": K.dev_to_pp(pb, props, t1.shape) * brain} refs = {"ii3": h3} sets = {} f2 = (Q3.HT / "detA_iv_x/fold_c2x_iv_f2" / f"{key}.nii.gz").exists() for s in TEST_SETTINGS + ("iv2_t0.5", "iv2_t0.3") + (("mx3_t0.5", "mx3_t0.3", "iv3_t0.5", "iv3_t0.3") if f2 else ()): if ONLY and s not in ONLY: continue hv, tau = s.split("_t") var = {"ii3": "ii3", "mx2": "max_ii3_iv2", "mx3": "max_ii3_iv3", "iv2": "iv2", "iv3": "iv3"}[hv] h = h3 if var == "ii3" else np.round(K.dev_to_pp(Q3.test_heat(key, var), props, t1.shape) * brain * 250) / 250 sets[s] = ("ii3", h.astype(np.float32), float(tau)) return t1, brain, gt, props, refs, sets, probs if pop == "contra": t1, brain, gt, props, srcs, probs = K.iter_contra(key) probs = {"d331": probs["d331"]} hii = srcs["real"][0] * brain sets = {"ii_t0.3": ("ii", hii, 0.3), "ii_t0.4": ("ii", hii, 0.4)} p = Q3.HOOF / "detA_iv_x" / f"{key}.b2nd" if p.exists(): hmx = np.maximum(hii, K.load_b2(p).astype(np.float32) / Q3.C.HEAT_SCALE * brain) sets.update({"mx_t0.5": ("ii", hmx, 0.5), "mx_t0.3": ("ii", hmx, 0.3)}) p = HIV / "contra" / f"{key}.b2nd" if p.exists(): hiv = K.load_b2(p).astype(np.float32) / Q3.C.HEAT_SCALE * brain sets.update({"iv_t0.5": ("ii", hiv, 0.5), "iv_t0.3": ("ii", hiv, 0.3)}) return t1, brain, gt, props, {"ii": hii}, sets, probs import devset_common as D props = D.load_props(key); t1, sg = D.load_prep(key); brain, gt = sg != -1, sg == 1 _, pp = D.pred_paths("d331", "t1", key) probs = {"d331": K.dev_to_pp(D.read_nii(pp) / 250.0, props, t1.shape) * brain} refs, sets = {}, {} for s in D.SEEDS: p = D.heat_mean_path(key, s) if p.exists(): refs[f"s{s}"] = K.dev_to_pp(D.read_nii(p), props, t1.shape) * brain for tau in (0.3, 0.4): sets[f"s{s}_t{tau}"] = (f"s{s}", refs[f"s{s}"], tau) pv = HIV / "dev" / f"s{s}" / f"{key}.nii.gz" if pv.exists(): hv_ = K.dev_to_pp(D.read_nii(pv), props, t1.shape) * brain for tau in (0.5, 0.3): sets[f"v{s}_t{tau}"] = (f"s{s}", hv_, tau) return t1, brain, gt, props, refs, sets, probs def process(pop, key, device, only=None): import dethead_cand as K op = Q3.OUT / ("cand_full" if FULL else "cand") / pop / f"{key}.npz" if FULL: only = only or list(FULL_SETTINGS[pop]) global ONLY ONLY = only done = {} if op.exists(): z = np.load(op) done = json.loads(str(z["json"]))["settings"] if only is None or all(s in done for s in only): return t0 = time.time() t1, brain, gt, props, refs, sets, probs = load_case(pop, key) if FULL: only = only or list(FULL_SETTINGS[pop]) if only: sets = {s: v for s, v in sets.items() if s in only} ctx = K.patient_ctx(t1, brain, props, key) cache, out, Xs = {}, {"key": key, "pop": pop, "settings": dict(done)}, {} if done: z = np.load(op); Xs = {k: z[k] for k in z.files if k.startswith("X_")} for s, (rn, h, tau) in sets.items(): if s in done: continue r, X = score_setting(key, s, t1, brain, props, ctx, gt, refs[rn], h, tau, probs, cache, device) out["settings"][s] = r; Xs[f"X_{s}"] = X Q3.save_npz(op, json=np.array(json.dumps(out, default=float)), **Xs) print("CAND3", pop, key, {s: v["n"] for s, v in out["settings"].items()}, f"{time.time() - t0:.0f}s", flush=True) def main(): import torch ap = argparse.ArgumentParser() ap.add_argument("--pop", required=True); ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1) ap.add_argument("--settings", default=""); ap.add_argument("--keys", default=""); ap.add_argument("--full", type=int, default=0) a = ap.parse_args() global FULL FULL = bool(a.full) torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "1"))) import dethead_common as H, dethead_cand as K keys = a.keys.split(",") if a.keys else {"test": Q.test_cids, "contra": H.contra_keys, "dev": K.dev_keys}[a.pop]()[a.chunk::a.nchunk] device = torch.device("cuda" if torch.cuda.is_available() else "cpu") only = a.settings.split(",") if a.settings else None for k in keys: try: process(a.pop, k, device, only) except Exception as e: import traceback; traceback.print_exc(); print("FAIL", k, repr(e)[:200], flush=True) print("CAND3_DONE", a.pop, a.chunk, flush=True) if __name__ == "__main__": main()