#!/usr/bin/env python """classifier2: DEV-TEST preparation (NORTH, ATLAS-43 official, LAB; prereg 35q). Label-free inputs + labels attached after. Per case (raw D943 imagesTs: T1 _0000, real FLAIR _0001; stage-1 test heat detA_ii_x/mean; D331 prob arch2stage/t1prob): 1. T1 -> D331-plans nnU-Net preprocessing (dethead_apply.preprocess_t1: crop nonzero, 1 mm, z-score in mask); heat / D331 prob / FLAIR cropped with the same bbox and linearly resampled (dethead_cand.dev_to_pp); GT nearest. 2. candidates + label-free features exactly as dethead_cand (heat >= 0.5, >= 10 vox, 26-conn), WITH FLAIR features and p_d331 features; labels from the GT afterwards (dethead_cand.label_cands). 3. dethead crops (fine/coarse/fit, with FLAIR). Outputs: classifier2/vol/test/.npz (pp volumes, compact) + _props.pkl; classifier2/cand/test/.npz (dethead json format, + crops). NEVER used for training (dev-test only). cls2_testprep.py --chunk i --nchunk n """ from __future__ import annotations import argparse, json, pickle, sys, time from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) import cls2_common as Q # noqa: E402 def prep(cid): import dethead_apply as A import dethead_cand as K vp = Q.OUT / "vol" / "test" / f"{cid}.npz" if vp.exists(): z = np.load(vp) props = pickle.load(open(str(vp)[:-4] + "_props.pkl", "rb")) return (z["t1"].astype(np.float32), z["fl"].astype(np.float32), z["heat"].astype(np.float32) / 250, z["p331"].astype(np.float32) / 250, z["seg"] != -1, z["gt"] > 0, props) t1p = Q.guard(Q.D943R / "imagesTs" / f"test_{cid}_0000.nii.gz") flp = Q.guard(Q.D943R / "imagesTs" / f"test_{cid}_0001.nii.gz") t1, seg, props = A.preprocess_t1(t1p) brain = seg != -1 t1 = np.where(brain, t1, 0).astype(np.float32) shp = t1.shape fl = K.dev_to_pp(Q.read_nii(flp), props, shp) * brain heat = K.dev_to_pp(Q.read_nii(Q.HEAT_TEST / f"{cid}.nii.gz"), props, shp) * brain pr = Q.read_nii(Q.D331_TEST / f"{cid}.nii.gz") pr = pr / 250.0 if pr.max() > 1.5 else pr p = K.dev_to_pp(pr, props, shp) * brain gt = K.dev_to_pp((Q.read_nii(Q.label_path(cid)) > 0).astype(np.float32), props, shp, order=0) > 0.5 Q.save_npz(vp, t1=t1.astype(np.float16), fl=fl.astype(np.float16), heat=np.clip(np.round(heat * 250), 0, 250).astype(np.uint8), p331=np.clip(np.round(p * 250), 0, 250).astype(np.uint8), seg=np.where(brain, 0, -1).astype(np.int8), gt=gt.astype(np.uint8)) pickle.dump(props, open(Q.guard_write(str(vp)[:-4] + "_props.pkl"), "wb")) heat = np.round(heat * 250) / 250; p = np.round(p * 250) / 250 return t1, fl, heat.astype(np.float32), p.astype(np.float32), brain, gt, props def process(cid): import dethead_cand as K, dethead_crops as R op = Q.OUT / "cand" / "test" / f"{cid}.npz" if op.exists(): return t0 = time.time() t1, fl, h, p, brain, gt, props = prep(cid) ctx = K.patient_ctx(t1, brain, props, cid) flz = K.norm_flair(fl, ctx) L, n = K.candidates(h, brain) fe = K.cand_feats(L, n, h, ctx, flz, {"d331": p}) lab, les = K.label_cands(L, n, gt, ctx) res = {"key": cid, "pop": "test", "fold": -1, "t1_nawm": ctx["t1_nawm"], "vent_ml": ctx["vent_ml"], "sources": {"real": {"feats": fe, "labels": lab, "lesions": les, "n": n}}} kw = {"json": np.array(json.dumps(res, default=float))} if n: cr = R.crops_for_volume(R.canon(ctx["t1z"], props), R.canon(h, props), R.canon(L, props), list(range(1, n + 1)), R.canon(flz, props)) kw.update({f"crop_{k}": v for k, v in cr.items()}) Q.save_npz(op, **kw) print("TESTCAND", cid, n, int(sum(l["pos"] for l in lab)), len(les), f"{time.time() - t0:.0f}s", flush=True) def main(): ap = argparse.ArgumentParser() ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1) ap.add_argument("--cids", default="") a = ap.parse_args() cids = a.cids.split(",") if a.cids else Q.test_cids()[a.chunk::a.nchunk] for c in cids: try: process(c) except Exception as e: import traceback; traceback.print_exc(); print("FAIL", c, repr(e)[:200], flush=True) print("TESTPREP_DONE", flush=True) if __name__ == "__main__": main()