File size: 16,297 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python
"""classifier3: END-TO-END Pipeline B on the dev-test for the new candidate settings / heads (prereg 35s: scoring only).

Variants (classifier3/variants.json, written from OFF-TEST thresholds before any test scoring):
  {name: {old_head, t_old, setting|null, new_head|null, t_new|null}}
  accepted = old-tier classifier2 candidates (ii3 heat >= 0.5) with old_head >= t_old  U  new-tier candidates of `setting`
             (cls3_cand.new_cands) with new_head >= t_new.
Drawers: lpd (crude, CPU); p2heat (heat prompt = max(ii3 heat x dil2(old accepted), setting heat x dil2(new accepted)));
p2ball (ball prompt, centroid, r4; heat for the centroid = the same composite). Composition exactly cls2_drawer_test /
prompt2_score: final = max(p_base, p_drawer x draw_mask(drawer comps touching cube-dil-2 accepted)) >= 0.5; base delbankconv_x.
Drawer predictions are reused from classifier2 (drawer/<m>/pred/acc0802|acc0692[_centroid_r4]) whenever the accepted set equals the
classifier2 set at that threshold (no new candidate accepted and old head = s_sepd), else inferred here (GPU).
Scoring: cascade2_score.metrics on the raw grid (GT scorer) + pooled voxel Dice + whole-output adjudication of every predicted
component >= 10 vox (rated rounds 2-6, cls2_fp_review semantics; yes = GT-touching or rated lesion / WMH; no = mimic) with the
tier of added components (new-tier vs old-tier) recorded so the new additions' rating coverage is reported separately.
  cls3_e2e.py prep  [--chunk i --nchunk n]  (CPU)  -> drawer/acc/<variant>/<cid>.nii.gz, e2e/prep/<cid>.pkl (lpd masks, needs-infer)
  cls3_e2e.py infer --model p2heat|p2ball [--chunk i --nchunk n] (GPU)
  cls3_e2e.py score [--chunk i --nchunk n]  (CPU)  -> e2e/cases/<cid>.pkl
  cls3_e2e.py summary                              -> scores/e2e_summary.csv / .json
"""
from __future__ import annotations
import argparse, json, os, pickle, sys, time
from pathlib import Path
import numpy as np
import scipy.ndimage as ndi

sys.path.insert(0, str(Path(__file__).resolve().parent))
import cls3_common as Q3   # noqa: E402
Q = Q3.Q
TAG = os.environ.get("CLS3_VTAG", "")          # "" -> variants.json / e2e/ ; "full" -> variants_full.json / e2e_full/
VAR = Q3.OUT / (f"variants_{TAG}.json" if TAG else "variants.json")
DR = Q3.OUT / "drawer"
E2 = Q3.OUT / (f"e2e_{TAG}" if TAG else "e2e")
DRAWERS = {"p2heat": ("acc{k}", "heat"), "p2ball": ("acc{k}_centroid_r4", "ball")}
SETVAR = {"ii3": "ii3", "mx2": "max_ii3_iv2", "mx3": "max_ii3_iv3", "iv2": "iv2", "iv3": "iv3"}


def write_like(arr, ref_path, out, dtype):
    import SimpleITK as sitk
    Q3.guard_write(out)
    ref = sitk.ReadImage(str(ref_path)); im = sitk.GetImageFromArray(np.asarray(arr).astype(dtype)); im.CopyInformation(ref)
    Path(out).parent.mkdir(parents=True, exist_ok=True)
    tmp = str(out) + f".tmp{os.getpid()}.nii.gz"; sitk.WriteImage(im, tmp, True); os.replace(tmp, out)


def variants():
    return json.load(open(VAR))


def old_scores(head):
    import pandas as pd
    p = Q3.OUT / "scores" / head / "test.pkl"
    p = p if p.exists() else Q3.OUT2 / "scores" / head / "test.pkl"
    return pd.read_pickle(p).set_index(["key", "cid"])["score"]


def new_scores():
    import pandas as pd
    return pd.read_pickle(Q3.OUT / "newtier" / "scores_test.pkl")


def full_scores():
    import pandas as pd
    return pd.read_pickle(Q3.OUT / "full" / "scores_test.pkl")


def k_of(t):
    return "0802" if abs(t - 0.802) < 1e-6 else ("0692" if abs(t - 0.692) < 1e-6 else None)


def prep_case(cid, V):
    import dethead_cand as K, devset_common as D, cls2_testprep as P, cls2_e2e_test as X, cls3_cand as CC, cls2_drawer_test as DT
    op = E2 / "prep" / f"{cid}.pkl"
    if op.exists():
        old = pickle.load(open(op, "rb"))
        if set(old["variants"]) >= set(V):
            return
    t1, fl, h3, p, brain, gt, props = P.prep(cid)
    ctx = K.patient_ctx(t1, brain, props, cid)
    L, n = K.candidates(h3, brain)
    draws_old = X.per_cand_draw(L, n, h3, ctx["t1z"], brain, p, "lpd")
    ns = new_scores(); ns = ns[ns["key"] == cid]
    oscache, hcache, out = {}, {}, {"cid": cid, "variants": {}}
    for nm, v in V.items():
        if v["old_head"] not in oscache:
            oscache[v["old_head"]] = old_scores(v["old_head"])
        sc = oscache[v["old_head"]]
        acc_old = [c for c in range(1, n + 1) if sc.get((cid, c), -1) >= v["t_old"]]
        La = np.where(np.isin(L, acc_old), L, 0).astype(np.int32)
        dpp = np.zeros(L.shape, bool)
        for c in acc_old:
            sl, d = draws_old[c - 1]; dpp[sl] |= d
        acc_new = []
        if v.get("full"):                     # single-tier replacement candidate set (cls3_full); no classifier2 tier
            s = v["full"]; hv, tau = s.split("_t")
            hs = h3 if hv == "ii3" else (np.round(K.dev_to_pp(Q3.test_heat(cid, SETVAR[hv]), props, t1.shape) * brain * 250) / 250).astype(np.float32)
            LA, na = K.candidates(hs, brain, float(tau))
            fs = full_scores(); fs = fs[(fs["key"] == cid) & (fs["setting"] == s)].set_index("cid")[v["full_head"]]
            acc = [c for c in range(1, na + 1) if fs.get(c, -1) >= v["t_full"]]
            old_any = np.zeros(na + 1, bool)
            if n:
                old_any[np.unique(LA[L > 0])] = True
            La = np.zeros(L.shape, np.int32); dpp = np.zeros(L.shape, bool)
            dr = X.per_cand_draw(LA, na, hs, ctx["t1z"], brain, p, "lpd") if na else []
            for c in acc:
                La[LA == c] = c if old_any[c] else 1000 + c
                sl, d = dr[c - 1]; dpp[sl] |= d
            acc_old = [c for c in acc if old_any[c]]; acc_new = [c for c in acc if not old_any[c]]
        elif v.get("setting"):
            s = v["setting"]; hv, tau = s.split("_t")
            if s not in hcache:
                hs = h3 if hv == "ii3" else np.round(K.dev_to_pp(Q3.test_heat(cid, SETVAR[hv]), props, t1.shape) * brain * 250) / 250
                LF, nf = CC.new_cands(h3, hs.astype(np.float32), brain, float(tau))
                hcache[s] = (hs, LF, nf, X.per_cand_draw(LF, nf, hs, ctx["t1z"], brain, p, "lpd") if nf else [])
            hs, LF, nf, dr = hcache[s]
            ss = ns[ns["setting"] == s].set_index("cid")[v["new_head"]]
            acc_new = [c for c in range(1, nf + 1) if ss.get(c, -1) >= v["t_new"]]
            for c in acc_new:
                La[LF == c] = 1000 + c
                sl, d = dr[c - 1]; dpp[sl] |= d
        la_raw = D.prep_to_raw(La, props, fill=0, order=0).astype(np.int32)
        write_like(la_raw.astype(np.uint16), DT.t1_path(cid), Q3.guard_write(DR / "acc" / nm / f"{cid}.nii.gz"), np.uint16)
        lpd_raw = D.prep_to_raw(dpp.astype(np.uint8), props, fill=0, order=0) > 0
        k = k_of(v["t_old"]) if v.get("t_old") is not None else None
        reuse = (not acc_new) and v["old_head"] == "s_sepd" and k is not None and not v.get("noreuse") and not v.get("full")
        out["variants"][nm] = {"n_old": len(acc_old), "n_new": len(acc_new), "reuse_k": k if reuse else None,
                               "lpd_ijk": np.argwhere(lpd_raw).astype(np.int16)}
    E2.joinpath("prep").mkdir(parents=True, exist_ok=True)
    pickle.dump(out, open(Q3.guard_write(op), "wb"))
    print("PREP", cid, {k: (v["n_old"], v["n_new"], v["reuse_k"]) for k, v in out["variants"].items()}, flush=True)


def infer(a):
    import torch, prompt2_infer as PI, cascade2_infer as I, cls2_drawer_test as DT
    from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO
    MODELS = {**PI.MODELS, **DT.EXTRA_MODELS}
    trainer, enc = MODELS[a.model]
    dev = "cuda" if torch.cuda.is_available() else "cpu"
    V = variants(); pr = None
    for cid in Q.test_cids()[a.chunk::a.nchunk]:
        pp = pickle.load(open(E2 / "prep" / f"{cid}.pkl", "rb"))
        todo = [nm for nm in V if pp["variants"][nm]["reuse_k"] is None and not (DR / a.model / nm / f"{cid}.nii.gz").exists()]
        if not todo:
            continue
        if pr is None:
            pr = I.predictor(I.model_dir(Q.C.DEL, trainer), [Q.C.fold_index(Q.C.DEL, PI.FOLD)], dev)
        img, props = SimpleITKIO().read_images([str(DT.t1_path(cid))])
        h3 = Q.read_nii(Q.HEAT_TEST / f"{cid}.nii.gz"); t1raw = np.asarray(img[0], np.float32)
        hc = {}
        for nm in todo:
            v = V[nm]
            la = Q.read_nii(DR / "acc" / nm / f"{cid}.nii.gz", np.int32)
            hs = h3
            st = v.get("setting") or v.get("full")
            if st and not st.startswith("ii3"):
                hv = st.split("_t")[0]
                if hv not in hc:
                    hc[hv] = Q3.test_heat(cid, SETVAR[hv])
                hs = hc[hv]
            newm = PI.cube_max((la >= 1000).astype(np.uint8), PI.CAND_DIL) > 0
            heat = (hs if v.get("full") else np.where(newm, np.maximum(h3, hs), h3)).astype(np.float32)
            if not la.any():
                pm = np.zeros(h3.shape, np.float32)
            elif enc == "heat":
                pm = PI.prompt_from_candidates(enc, heat, la, PI.describe(la, heat))
            else:
                pm, _ = DT.ball_prompt(heat, la, t1raw, "centroid", "r4")
            t0 = time.time()
            x = np.concatenate([img, pm[None].astype(np.float32)], 0).astype(np.float32)
            _s, prob = pr.predict_single_npy_array(x, props, None, None, True)
            p1 = np.asarray(prob, np.float32)[1]
            write_like(np.clip(np.round(p1 * 250), 0, 250).astype(np.uint8), DT.t1_path(cid), Q3.guard_write(DR / a.model / nm / f"{cid}.nii.gz"), np.uint8)
            print(time.strftime("%H:%M:%S"), "DRW3", a.model, nm, cid, int((p1 >= 0.5).sum()), f"{time.time() - t0:.1f}s", flush=True)
    print("DRW3_INFER_DONE", a.model, a.chunk, flush=True)


def adjudicate(final, base, gt, newacc_raw, sites, vml):
    import cc3d
    PRI = {"lesion": 0, "wmh": 1, "mimic": 2, "unsure": 3}
    F = cc3d.connected_components(final.astype(np.uint8), connectivity=26)
    comps = []
    for f, o in enumerate(ndi.find_objects(F), start=1):
        if o is None:
            continue
        m = F[o] == f
        if m.sum() < 10:
            continue
        tp = bool((gt[o] & m).any())
        src = "base" if (base[o] & m).any() else "added"
        tier = "new" if (src == "added" and (newacc_raw[o] & m).any()) else ("old" if src == "added" else "base")
        labs = sorted({lb for sm, lb, _, _ in sites if (sm[o] & m).any()}, key=lambda x: PRI.get(x, 9))
        comps.append({"vox": int(m.sum()), "tp": tp, "source": src, "tier": tier, "rating": labs[0] if labs else "unrated"})
    return comps


def score_case(cid, models):
    import SimpleITK as sitk, cascade2_score as S, prompt2_score as PS, cls2_fp_review as FR
    op = E2 / "cases" / f"{cid}.pkl"
    V = variants()
    done = pickle.load(open(op, "rb")) if op.exists() else {"cid": cid, "rows": {}}
    li = sitk.ReadImage(str(Q.label_path(cid))); gt = sitk.GetArrayFromImage(li) > 0
    sp = li.GetSpacing()[::-1]; vml = float(np.prod(sp)) / 1000
    far = ndi.distance_transform_edt(~gt, sampling=sp) > 10 if gt.any() else np.ones_like(gt)
    pb0 = Q.read_nii(Q.C.OUT / "pred/delbankconv_x/prob" / f"{cid}.nii.gz") / 250.0
    base0 = Q.read_nii(Q.C.OUT / "pred/delbankconv_x" / f"{cid}.nii.gz") == 1
    pp = pickle.load(open(E2 / "prep" / f"{cid}.pkl", "rb"))
    zero_b = np.zeros_like(base0); zero_p = np.zeros_like(pb0)
    sites = FR.rated_sites(cid, gt.shape)
    def rec(mask, newacc, base):
        m = S.metrics(gt, mask, vml, far)
        return {"m": m, "tp_vox": int((mask & gt).sum()), "pred_vox": int(mask.sum()), "gt_vox": int(gt.sum()),
                "comps": adjudicate(mask, base, gt, newacc, sites, vml)}
    rows = done["rows"]
    if "base_alone" not in rows:
        rows["base_alone"] = rec(base0, np.zeros_like(base0), base0)
    for nm, v in V.items():
        nob = bool(v.get("nobase"))                      # PURE cascade: no delbankconv base (drawer / lpd output alone)
        base, pb = (zero_b, zero_p) if nob else (base0, pb0)
        info = pp["variants"][nm]
        la = Q.read_nii(DR / "acc" / nm / f"{cid}.nii.gz", np.int32)
        acc = la > 0; newacc = la >= 1000
        if f"{nm}|lpd" not in rows:
            lpd = np.zeros(gt.shape, bool); ijk = info["lpd_ijk"].astype(int)
            if len(ijk):
                lpd[tuple(ijk.T)] = True
            rows[f"{nm}|lpd"] = rec(base | lpd, newacc, base)
        for mdl in models:
            if f"{nm}|{mdl}" in rows:
                continue
            if info["reuse_k"]:
                pth = Q3.OUT2 / "drawer" / mdl / "pred" / DRAWERS[mdl][0].format(k=info["reuse_k"]) / f"{cid}.nii.gz"
            else:
                pth = DR / mdl / nm / f"{cid}.nii.gz"
            if not pth.exists():
                continue
            pd_ = Q.read_nii(pth) / 250.0
            rows[f"{nm}|{mdl}"] = rec(np.maximum(pb, pd_ * PS.draw_mask(pd_, acc)) >= 0.5, newacc, base)
    E2.joinpath("cases").mkdir(parents=True, exist_ok=True)
    pickle.dump(done, open(Q3.guard_write(op), "wb"))
    print("SCORE3", cid, len(rows), flush=True)


def summary():
    import pandas as pd, cascade2_score as S
    cases = [pickle.load(open(p, "rb")) for p in sorted((E2 / "cases").glob("*.pkl"))]
    out = []
    keys = sorted({k for c in cases for k in c["rows"]})
    for k in keys:
        for pool, coh in (("PRIMARY", ("atlas", "north")), ("ATLAS-43", ("atlas",)), ("NORTH", ("north",)), ("LAB", ("lab",))):
            rr = [c["rows"][k] for c in cases if c["cid"].split("_")[0] in coh and k in c["rows"]]
            ncoh = sum(c["cid"].split("_")[0] in coh for c in cases)
            if not rr:
                continue
            s = S.stats_from(np.array([S.counts(r["m"]) for r in rr], float))
            cs = [x for r in rr for x in r["comps"]]
            yes = sum(x["tp"] or x["rating"] in ("lesion", "wmh") for x in cs); no = sum((not x["tp"]) and x["rating"] == "mimic" for x in cs)
            uns = sum((not x["tp"]) and x["rating"] == "unsure" for x in cs); unr = sum((not x["tp"]) and x["rating"] == "unrated" for x in cs)
            nw = [x for x in cs if x["tier"] == "new"]
            out.append({"variant": k, "pool": pool, "n": len(rr), "complete": len(rr) == ncoh, "SM": s["sm_recall"], "prec_GT": s["les_precision"],
                        "F1": s["les_f1"], "Dice_case": s["dice"], "Dice_pooled": 2 * sum(r["tp_vox"] for r in rr) / max(sum(r["pred_vox"] + r["gt_vox"] for r in rr), 1),
                        "FPc": s["fp_per_case"], "comps": len(cs), "yes": yes, "no_mimic": no, "unsure": uns, "unrated": unr,
                        "adj_prec_unsure_no": yes / max(yes + no + uns, 1), "adj_prec_unsure_excl": yes / max(yes + no, 1),
                        "adj_prec_unrated_no": yes / max(len(cs), 1),
                        "new_comps": len(nw), "new_tp": sum(x["tp"] for x in nw), "new_rated_yes": sum((not x["tp"]) and x["rating"] in ("lesion", "wmh") for x in nw),
                        "new_rated_no": sum((not x["tp"]) and x["rating"] in ("mimic", "unsure") for x in nw), "new_unrated": sum((not x["tp"]) and x["rating"] == "unrated" for x in nw)})
    T = pd.DataFrame(out)
    sfx = f"_{TAG}" if TAG else ""
    T.to_csv(Q3.guard_write(Q3.OUT / f"scores/e2e_summary{sfx}.csv"), index=False)
    Q3.jdump({"rows": out}, Q3.OUT / f"scores/e2e_summary{sfx}.json")
    pd.set_option("display.width", 300); pd.set_option("display.max_rows", 500)
    print(T[T["pool"].isin(["PRIMARY", "LAB"])].round(3).to_string(index=False))


if __name__ == "__main__":
    ap = argparse.ArgumentParser(); ap.add_argument("mode"); ap.add_argument("--model", default="p2heat")
    ap.add_argument("--models", default="p2heat,p2ball")
    ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1)
    a = ap.parse_args()
    if a.mode == "infer":
        infer(a)
    elif a.mode == "summary":
        summary()
    else:
        V = variants()
        for c in Q.test_cids()[a.chunk::a.nchunk]:
            try:
                prep_case(c, V) if a.mode == "prep" else score_case(c, a.models.split(","))
            except Exception as e:
                import traceback; traceback.print_exc(); print("FAIL", c, repr(e)[:200], flush=True)
        print("DONE", a.mode, a.chunk, flush=True)