File size: 8,865 Bytes
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""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_<X>        D331 training patient X (1,087) with G1 synthetic FLAIR (Dataset961 dxb_<X>; NORTH-free generator)
  cg<v>_<X>      the same patient with confirmation-FLAIR render variant v (data/seg/pkl = dxb_<X> links; channel 1 is
                 REPLACED at load time by renders/<rtag>/v<v>/<X>.b2nd, a z-scored float16 FLAIR in dxb_<X>'s geometry)
  r_contra_<id>  real CONTRA T1 + FLAIR pair (58; Dataset945)
  val_<k>        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_<X> (data/seg/pkl = dxb_<X> links; channel 1 replaced by stored out-of-fold heat),
  r_contra_<id> (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"                        # <det_tag>/<stage-2 key>.b2nd  (uint8 x250, preprocessed geometry)
HEAT_TEST = OUT / "heat_test"                      # <det_tag>/<cid>.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_<X> = online-rendered key (one per patient); cg<v>_<X> = 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