"""cascade2 (direction2, round 2 of "FLAIR-only detector -> T1 delineator"; prereg 35m/35n): shared constants and helpers. Datasets (all built from SYMLINKS to already-preprocessed cases unless stated; nothing under Dataset320_BaseExpert or brave_new_day is ever written): Dataset977_D2C2Det stage-1 detector, D331/D945 ResEnc-L plans (warm start (a): D331 whole network) Dataset978_D2C2DetBE stage-1 detector, Dataset320_BaseExpert plans (PlainConvUNet, patch 128x160x112; warm start (b)) Dataset979_D2C2Del stage-2 delineator (T1 + HEAT), ResEnc-L plans with channel 1 NoNormalization Stage-1 keys (identical in 977 and 978): syn_ D331 training patient X (1,087) with G1 synthetic FLAIR (Dataset961 dxb_; NORTH-free generator) cg_ the same patient with confirmation-FLAIR render variant v (data/seg/pkl = dxb_ links; channel 1 is REPLACED at load time by renders//v/.b2nd, a z-scored float16 FLAIR in dxb_'s geometry) r_contra_ real CONTRA T1 + FLAIR pair (58; Dataset945) val_ none in round 2: the nnU-Net "val" keys of every fold are held-out-fold cases (monitoring only; checkpoint_final is always used, so they never select weights) Stage-2 keys (979): syn_t1_ (data/seg/pkl = dxb_ links; channel 1 replaced by stored out-of-fold heat), r_contra_ (D945 data/pkl links; seg rewritten with a 1-voxel ignore band, CONTRA being FLAIR-traced). Patients, not keys, are cross-fitted: every key of patient X (syn_, cg*_, syn_t1_) lives in X's fold. """ from __future__ import annotations import fcntl, json, os, zlib from pathlib import Path import numpy as np B = Path("/__EAGLE_BUNDLE_ROOT__") WS = B / "whisper_synth" RAWR, PREP, RES = B / "nnunet_raw", B / "nnunet_preprocessed", B / "whisper_results" OUT = WS / "outputs/direction2/cascade2" A2S = WS / "outputs/direction2/arch2stage" D945P = PREP / "Dataset945_V10XSite" / "nnUNetPlans_3d_fullres" D961P = PREP / "Dataset961_V11DxNorth" / "nnUNetPlans_3d_fullres" D943R = RAWR / "Dataset943_V10DesignS" D320_PRE = PREP / "Dataset320_BaseExpert" # READ ONLY (protected) D320_RES = B / "nnunet_results/Dataset320_BaseExpert/nnUNetTrainer__nnUNetPlans__3d_fullres" # READ ONLY (protected) D331_TRAIN = WS / "outputs/direction/decisive_north/d331_train_keys.json" OFF = A2S / "atlas_official" # official ATLAS masks on the D943 grid (35m: user decision) DET, DETBE, DEL = "Dataset977_D2C2Det", "Dataset978_D2C2DetBE", "Dataset979_D2C2Del" PLANS = {DET: "nnUNetResEncUNetLPlans", DETBE: "nnUNetPlans", DEL: "nnUNetResEncUNetLPlans"} DATA_ID = "nnUNetPlans_3d_fullres" # data identifier of all three plans (and of D945/D961/D320) SUF = (".b2nd", "_seg.b2nd", ".pkl") HEAT_SCALE = 250.0 # stored heat = round(prob * 250) as uint8 K_FOLDS = 3 FOLD_SEED = 977 RENDER_DIR = OUT / "renders" HEAT_OOF = OUT / "heat_oof" # /.b2nd (uint8 x250, preprocessed geometry) HEAT_TEST = OUT / "heat_test" # /.nii.gz (float32 rounded to 1/250, T1 geometry) COMP_TABLE = OUT / "comp_table.json" # per base key: lesion components (voxels, member samples) FOLDS_JSON = OUT / "patient_folds.json" MALFORMED_JSON = OUT / "malformed_geometry_exclude.json" # 34 dxb patients with malformed preprocessed geometry (diag2) def malformed_patients(): """patient ids (dxb_ prefix stripped) excluded from MAIN-chain / ablation training, OOF inference and bake-off P2.""" if not MALFORMED_JSON.exists(): return set() return {k[4:] if k.startswith("dxb_") else k for k in json.load(open(MALFORMED_JSON))["keys"]} def exclude_malformed_env() -> bool: return os.environ.get("C2_EXCLUDE_MALFORMED", "0") == "1" # stage-1 data options (task item 6): families per option and the sampling fraction of each family DATA_OPTIONS = { "i": {"g1": 0.5, "real": 0.5}, "ii": {"g1": 0.25, "cg": 0.25, "real": 0.5}, "iii": {"cg": 0.5, "real": 0.5}, "iv": {"cg": 1.0}, } FAMILY_PREFIX = {"g1": ("syn_",), "cg": ("cg",), "real": ("r_",)} def guard(p): s = str(p) assert "XHOLDOUT" not in s.upper(), f"XHOLDOUT firewall: {p}" return p def assert_train_key(k: str): kl = k.lower() assert not any(b in kl for b in ("north", "sabre", "xholdout")), f"forbidden training key {k}" # Boyd atlas_ pairs / ATLAS-43 official (test) / raw test keys / LAB pairs (secondary test cohort) never train assert not kl.startswith(("r_atlas_", "ra_", "test_", "r_lab_")), f"forbidden training key {k}" def family(key: str) -> str: if key.startswith("syn_t1_"): return "t1" if key.startswith("syn_"): return "g1" if key.startswith("cg"): return "cg" if key.startswith("r_"): return "real" if key.startswith("val_"): return "val" raise ValueError(key) def is_online_cg(key: str) -> bool: """cg_ = online-rendered key (one per patient); cg_ = offline render variant v.""" return key.startswith("cg_") def patient(key: str) -> str: """patient id behind a key (all keys of one patient share a fold).""" if key.startswith("syn_t1_"): return key[len("syn_t1_"):] if key.startswith("syn_"): return key[4:] if key.startswith("cg"): return key.split("_", 1)[1] if key.startswith("r_"): return key[2:] raise ValueError(key) def base_key(key: str): """(preprocessed folder, file stem) holding the T1/seg/pkl of a key.""" p = patient(key) if key.startswith("r_"): return D945P, f"r_{p}" return D961P, f"dxb_{p}" def d331_keys(): k = json.load(open(guard(D331_TRAIN))) assert not any(x.startswith(("north_", "sabre_")) for x in k) return k def contra_cids(): tm = json.load(open(D943R / "test_label_map.json")) return sorted(k[5:] for k in tm if k[5:].startswith("contra_")) def link(src, dst): guard(src); guard(dst) if os.path.islink(dst): if os.path.realpath(dst) == os.path.realpath(src): return raise SystemExit(f"{dst} points elsewhere ({os.path.realpath(dst)} != {src})") assert Path(src).exists(), src os.symlink(src, dst) def ds_dirs(name): return RAWR / name, PREP / name, PREP / name / DATA_ID def locked_json_update(path: Path, fn): """read-modify-write a JSON file under an exclusive lock (fold registries are shared by concurrent jobs).""" lk = open(str(path) + ".lock", "w"); fcntl.flock(lk, fcntl.LOCK_EX) try: cur = json.load(open(path)) if path.exists() else None new = fn(cur) tmp = str(path) + ".tmp"; json.dump(new, open(tmp, "w"), indent=1); os.replace(tmp, path) return new finally: fcntl.flock(lk, fcntl.LOCK_UN) def fold_index(ds, fold_name): if str(fold_name).isdigit(): return int(fold_name) return json.load(open(PREP / ds / "c2_folds.json"))[fold_name] def stable_seed(*parts) -> int: return zlib.crc32("|".join(str(p) for p in parts).encode()) & 0x7FFFFFFF def patient_folds(k=K_FOLDS, seed=FOLD_SEED): """3-fold assignment over ALL stage-1 patients: 1,087 D331 T1-only patients + 58 CONTRA pairs. Stratified by stratum (contra / atlas / acute / lab) and, within the T1-only strata, by lesion-volume tertile (from comp_table.json when available) so folds are balanced in lesion size. CONTRA is split 20/19/19. Deterministic.""" if FOLDS_JSON.exists(): return json.load(open(FOLDS_JSON)) rng = np.random.default_rng(seed) pats = {"contra": [c for c in contra_cids()]} for x in d331_keys(): pats.setdefault(x.split("_")[0], []).append(x) vol = {} if COMP_TABLE.exists(): ct = json.load(open(COMP_TABLE))["tables"] vol = {bk[4:]: sum(c[0] for c in v) for bk, v in ct.items() if bk.startswith("dxb_")} assign = {} for stratum in sorted(pats): ps = sorted(pats[stratum]) if vol and stratum != "contra": ps = sorted(ps, key=lambda p: (vol.get(p, 0), p)) blocks = [ps[i:i + k] for i in range(0, len(ps), k)] # consecutive size-ranked blocks of k for blk in blocks: order = rng.permutation(len(blk)) for j, o in enumerate(order): assign[blk[o]] = int(j % k) else: ps = list(ps); rng.shuffle(ps) for i, p in enumerate(ps): assign[p] = int(i % k) out = {"k": k, "seed": seed, "size_stratified": bool(vol), "assign": assign, "counts": {s: [sum(assign[p] == f for p in pats[s]) for f in range(k)] for s in sorted(pats)}} json.dump(out, open(FOLDS_JSON, "w"), indent=1) return out