File size: 4,378 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
#!/usr/bin/env python
"""classifier2: candidate-FROC evaluation of heads on CONTRA (OOF), DEV-A (mean-heat sources) and the DEV-TEST cohorts.
Head scores: classifier2/scores/<name>/{oof,dev,test}.pkl or dethead/scores/<name>/{oof,dev}.pkl (key, src, cid, score).
Columns already in the tables (h_mean, p_d331_max, ...) can be given as heads too ("col:<name>").
  cls2_eval.py --heads col:h_mean,col:p_d331_max,pstackN_ens_d331,... [--boot 0] [--out name]
FROC-low = mean S+M (< 30 mL) lesion recall over 0.25-4 FP/case (dethead_metrics). Primary dev-test = ATLAS-43 + NORTH; LAB separate.
"""
from __future__ import annotations
import argparse, sys
from pathlib import Path
import numpy as np
import pandas as pd

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

FILES = {"contra": "oof.pkl", "dev": "dev.pkl", "test": "test.pkl"}


def head_scores(name, pop):
    for d in (Q.OUT / "scores" / name, Q.DH / "scores" / name):
        p = d / FILES[pop]
        if pop == "contra" and name.startswith("cnn_") and not p.exists() and list(d.glob("oof_f*.pkl")):
            s = pd.concat([pd.read_pickle(x) for x in sorted(d.glob("oof_f*.pkl"))])
            return s[s["src"] == "real"]
        if p.exists():
            s = pd.read_pickle(p)
            if "score" not in s.columns and name.startswith("cnn_"):
                s = s.rename(columns={name[4:]: "score"})
            return s[["key", "src", "cid", "score"]]
    return None


def pops():
    out = {}
    con, lcon = T.load("contra"); out["contra"] = (con, lcon)
    dev, ldev = T.load("dev")
    m = dev["src"].str.endswith("mean"); dev = dev[m]; ldev = ldev[ldev["src"].str.endswith("mean")]
    out["dev"] = (dev, ldev)
    try:
        te, lte = T.load("test")
        for nm, coh in (("test_prim", ("atlas", "north")), ("test_atlas", ("atlas",)), ("test_north", ("north",)), ("test_lab", ("lab",))):
            out[nm] = (te[te["cohort"].isin(coh)], lte[lte["cohort"].isin(coh)])
    except FileNotFoundError:
        pass
    return out


def attach(tab, name, pop):
    if name.startswith("col:"):
        c = name[4:]
        return tab.assign(score=tab[c].astype(float)) if c in tab.columns else None
    s = head_scores(name, "test" if pop.startswith("test") else pop)
    if s is None:
        return None
    s = s.set_index(["key", "src", "cid"])["score"]
    t = tab.join(s.rename("score"), on=["key", "src", "cid"])
    return t if t["score"].notna().any() else None


def evaluate(heads, nboot=0, popsel=None, quiet=False):
    P = pops(); res = {}
    for pop, (tab, les) in P.items():
        if popsel and pop not in popsel:
            continue
        for h in heads:
            t = attach(tab, h, pop)
            if t is None:
                continue
            nmiss = int(t["score"].isna().sum())
            t = t.assign(score=t["score"].fillna(-1e9))
            r = M.summarize(t, les, "score")
            r["n_missing_scores"] = nmiss
            if nboot:
                r["ci"] = M.boot(t, les, "score", n=nboot, stats=("froc_low", "auc"))
            res[(h, pop)] = r
    if not quiet:
        show(res, heads)
    return res


def show(res, heads):
    pl = ["contra", "dev", "test_prim", "test_atlas", "test_north", "test_lab"]
    print(f"{'head':34s} " + " ".join(f"{p:>16s}" for p in pl))
    for h in heads:
        cells = []
        for p in pl:
            r = res.get((h, p))
            cells.append(f"{r['froc_low']:.3f}/{r.get('auc', np.nan):.3f}" + ("*" if r["n_missing_scores"] else " ") if r else " " * 13 + "-")
        print(f"{h:34s} " + " ".join(f"{c:>16s}" for c in cells))
    r = res.get((heads[0], "test_prim"))
    if r:
        print("test_prim ceiling", round(r["ceiling"], 3), "n_sm", r["n_sm"], "ncase", r["n_case"],
              "| lab ceiling", round(res.get((heads[0], "test_lab"), {}).get("ceiling", np.nan), 3))


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--heads", required=True); ap.add_argument("--boot", type=int, default=0); ap.add_argument("--out", default="")
    a = ap.parse_args()
    hs = a.heads.split(",")
    res = evaluate(hs, a.boot)
    if a.out:
        Q.jdump({f"{h}|{p}": r for (h, p), r in res.items()}, Q.OUT / "scores" / f"eval_{a.out}.json")