File size: 6,214 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
#!/usr/bin/env python
"""classifier2: END-TO-END add-only union on the DEV-TEST cohorts, scored with cascade2_score.metrics on the RAW grid
(identical definitions to scores/delbankconv_x.json: 26-conn components >= 10 vox, any-overlap detection, S+M < 30 mL).
  final = base (raw grid) UNION prep_to_raw(draw(accepted candidates))
  base  : d331 (arch2stage t1prob >= 0.5, raw) | delbankconv (cascade2/pred/delbankconv_x) | none
  draw  : lpd (dethead_apply.drawn_union semantics: dilated-2 candidate & p_D331 >= 0.1, else T1-dark core) | heat
Sweep over an absolute score grid; thresholds for reporting are chosen OFF-test (see cls2_report.py).
  cls2_e2e_test.py --heads h1,h2 [--bases d331,delbankconv] [--draw lpd] --chunk i --nchunk n -> classifier2/e2e/<tag>/<cid>.pkl
  cls2_e2e_test.py summary --tag T
"""
from __future__ import annotations
import argparse, json, pickle, sys, time
from pathlib import Path
import numpy as np
import pandas as pd
import scipy.ndimage as ndi

sys.path.insert(0, str(Path(__file__).resolve().parent))
import cls2_common as Q   # noqa: E402

GRID = np.r_[1 / (1 + np.exp(-np.linspace(-5, 6, 45))), np.inf]


def per_cand_draw(L, n, h, t1z, brain, p, mode):
    import dethead_e2e as E2
    out = []
    objs = ndi.find_objects(L)
    for c in range(1, n + 1):
        sl0 = objs[c - 1]
        lo = [max(s.start - 4, 0) for s in sl0]; hi = [min(s.stop + 4, L.shape[i]) for i, s in enumerate(sl0)]
        sl = tuple(slice(a, b) for a, b in zip(lo, hi))
        m = L[sl] == c
        if mode == "heat":
            d = m
        else:
            d = ndi.binary_dilation(m, iterations=2) & brain[sl] & (p[sl] >= E2.TLOW)
            if not d.any():
                dout = ndi.distance_transform_edt(~m)
                ring = (~m) & (dout > 3) & (dout <= 6) & brain[sl]
                ref = t1z[sl][ring].mean() if ring.any() else 0.0
                d = m & (t1z[sl] < ref - 1.0)
        out.append((sl, d))
    return out


def run(a):
    import SimpleITK as sitk, dethead_cand as K, devset_common as D, cascade2_score as S, cls2_testprep as P
    heads = a.heads.split(",")
    scores = {}
    for h in heads:
        import cls2_eval as E
        s = E.head_scores(h, "test") if not h.startswith("col:") else None
        scores[h] = s.set_index(["key", "src", "cid"])["score"] if s is not None else None
    tab = None
    if any(h.startswith("col:") for h in heads):
        import cls2_table as T
        tab = T.load("test")[0].set_index(["key", "src", "cid"])
    od = Q.OUT / "e2e" / a.tag
    for cid in Q.test_cids(tuple(a.cohorts.split(",")))[a.chunk::a.nchunk]:
        op = od / f"{cid}.pkl"
        if op.exists():
            continue
        t0 = time.time()
        t1, fl, h, p, brain, gt_pp, props = P.prep(cid)
        ctx = K.patient_ctx(t1, brain, props, cid)
        L, n = K.candidates(h, brain)
        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)
        bases = {}
        for b in a.bases.split(","):
            if b == "d331":
                bases[b] = Q.read_nii(Q.D331_TEST / f"{cid}.nii.gz") / 250.0 >= 0.5
            elif b == "none":
                bases[b] = np.zeros(gt.shape, bool)
            else:
                bases[b] = Q.read_nii(Q.C.OUT / "pred" / f"{b}_x" / f"{cid}.nii.gz") == 1
        draws = per_cand_draw(L, n, h, ctx["t1z"], brain, p, a.draw)
        rows = []; cache = {}
        for hd in heads:
            if hd.startswith("col:"):
                sc = np.array([tab[hd[4:]].get((cid, "real", c), np.nan) for c in range(1, n + 1)])
            else:
                sc = np.array([scores[hd].get((cid, "real", c), np.nan) for c in range(1, n + 1)])
            sc = np.nan_to_num(sc, nan=-np.inf)
            for qi, t in enumerate(GRID):
                acc = tuple(np.flatnonzero(sc >= t).tolist())
                if acc not in cache:
                    dpp = np.zeros(L.shape, bool)
                    for i in acc:
                        sl, d = draws[i]; dpp[sl] |= d
                    draw_raw = D.prep_to_raw(dpp.astype(np.uint8), props, fill=0, order=0) > 0 if acc else np.zeros(gt.shape, bool)
                    cache[acc] = {b: S.metrics(gt, base | draw_raw, vml, far) for b, base in bases.items()}
                for b in bases:
                    rows.append({"cid": cid, "cohort": cid.split("_")[0], "head": hd, "base": b, "qi": qi, "t": float(t), "n_acc": len(acc), "m": cache[acc][b]})
        od.mkdir(parents=True, exist_ok=True)
        pickle.dump(rows, open(Q.guard_write(op), "wb"))
        print("E2E", cid, n, len(rows), f"{time.time() - t0:.0f}s", flush=True)
    print("E2E_DONE", flush=True)


def summarize(tag, cohorts=("atlas", "north")):
    import cascade2_score as S
    rows = []
    for p in sorted((Q.OUT / "e2e" / tag).glob("*.pkl")):
        rows += pickle.load(open(p, "rb"))
    df = pd.DataFrame(rows)
    df = df[df["cohort"].isin(cohorts)]
    out = []
    for (hd, b, qi), g in df.groupby(["head", "base", "qi"]):
        M = np.array([S.counts(m) for m in g["m"]], float)
        st = S.stats_from(M)
        out.append({"head": hd, "base": b, "qi": qi, "t": g["t"].iloc[0], "n_acc_case": g["n_acc"].mean(), **{k: st[k] for k in (
            "sm_recall", "les_precision", "les_recall", "les_f1", "dice", "fp_per_case", "recall_lt0.1", "recall_0.1-1", "n_cases", "n_sm")}})
    return pd.DataFrame(out), df


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("mode", nargs="?", default="run")
    ap.add_argument("--heads", default=""); ap.add_argument("--bases", default="d331,delbankconv"); ap.add_argument("--draw", default="lpd")
    ap.add_argument("--tag", default="r1"); ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1)
    ap.add_argument("--cohorts", default="atlas,north,lab")
    a = ap.parse_args()
    if a.mode == "run":
        run(a)
    else:
        s, _ = summarize(a.tag)
        pd.set_option("display.width", 250)
        print(s.round(3).to_string())