File size: 3,525 Bytes
76eb7b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Cross-validated report: agreement with the teacher by region and manufacturer, pooled over folds.

Agreement is the variance of the teacher's routine-dose slab embedding explained by a route (R²,
averaged over the 512 features), with 95% intervals from a case-level bootstrap.

    python -m proj2rep report --data DATA --work WORK
Writes WORK/report/agreement.csv, WORK/report/stress.csv and prints both tables.
"""

import argparse
from pathlib import Path

import numpy as np
import pandas as pd

from .data import load_cohort


def r2(x, t):
    return float(np.mean(1 - ((x - t) ** 2).sum(0) / ((t - t.mean(0)) ** 2).sum(0)))


def bootstrap(parts, keys, b=500, seed=0):
    """parts: {case: {key: (n, 512)}}; {key: (estimate, low, high, cases)} for each route against teacher_full,
    each route scored on every case that has it."""
    rng = np.random.default_rng(seed)
    out = {}
    for k in keys:
        cases = [c for c in parts if k in parts[c]]
        if not cases:
            continue

        def stat(who, k=k):
            return r2(np.concatenate([parts[c][k] for c in who]), np.concatenate([parts[c]["teacher_full"] for c in who]))

        draws = [stat(rng.choice(cases, len(cases))) for _ in range(b)]
        out[k] = (stat(cases), *np.quantile(draws, [0.025, 0.975]), len(cases))
    return out


def load_parts(work, sub, cohort):
    parts = {}
    for f in sorted((Path(work) / sub).glob("fold*/*.npz")):
        if f.stem in set(cohort.ids()):
            with np.load(f) as d:
                parts[f.stem] = {k: d[k] for k in d.files if not k.endswith("_regions")}
    return parts


def table(parts, cohort, keys):
    t = cohort.table.set_index("case_id")
    groups = {"all": list(parts)}
    for (reg, man), g in t.loc[list(parts)].groupby(["region", "manufacturer"]):
        groups[f"{reg} / {man}"] = g.index.tolist()
    rows = []
    for name, ids in groups.items():
        sub = {c: parts[c] for c in ids}
        for k, (est, lo, hi, n) in bootstrap(sub, [k for k in keys if any(k in v for v in sub.values())]).items():
            rows.append({"group": name, "route": k, "cases": n, "r2": est, "low": lo, "high": hi})
    return pd.DataFrame(rows)


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--data", required=True)
    p.add_argument("--work", required=True)
    a = p.parse_args(argv)
    cohort = load_cohort(a.data, work_dir=a.work)
    out = Path(a.work) / "report"
    out.mkdir(parents=True, exist_ok=True)
    pd.set_option("display.width", 200)

    ev = load_parts(a.work, "eval", cohort)
    if ev:
        t = table(ev, cohort, ["raw_full", "raw_low", "teacher_low"])
        t.to_csv(out / "agreement.csv", index=False)
        print("Held-out agreement with the teacher (R²):")
        print(t.pivot_table(index="group", columns="route", values="r2", sort=False).round(3).to_string(), "\n")

    st = load_parts(a.work, "stress", cohort)
    if st:
        keys = sorted({k for v in st.values() for k in v if k.startswith(("raw_", "plain_"))})
        t = table(st, cohort, keys)
        t[["route", "condition"]] = t.route.str.split("_", n=1, expand=True)
        t.to_csv(out / "stress.csv", index=False)
        print("Stress test (R² against the teacher on the routine-dose image):")
        print(t.pivot_table(index=["group", "condition"], columns="route", values="r2", sort=False).round(3).to_string())


if __name__ == "__main__":
    main()