File size: 7,667 Bytes
a521a25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import itertools
import json
from pathlib import Path

import matplotlib as mpl

mpl.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score


ROOT = Path(__file__).resolve().parents[1]
SEED = 20260810
BOOTSTRAPS = 5000


def stratified_bootstrap(y: np.ndarray, p: np.ndarray, rng: np.random.Generator):
    pos = np.flatnonzero(y == 1)
    neg = np.flatnonzero(y == 0)
    aucs, aps, briers = [], [], []
    for _ in range(BOOTSTRAPS):
        idx = np.r_[rng.choice(pos, len(pos), replace=True), rng.choice(neg, len(neg), replace=True)]
        aucs.append(roc_auc_score(y[idx], p[idx]))
        aps.append(average_precision_score(y[idx], p[idx]))
        briers.append(brier_score_loss(y[idx], p[idx]))
    return {
        "auroc_ci_low": np.quantile(aucs, 0.025),
        "auroc_ci_high": np.quantile(aucs, 0.975),
        "auprc_ci_low": np.quantile(aps, 0.025),
        "auprc_ci_high": np.quantile(aps, 0.975),
        "brier_ci_low": np.quantile(briers, 0.025),
        "brier_ci_high": np.quantile(briers, 0.975),
    }


def exact_balanced_permutation(y: np.ndarray, p: np.ndarray):
    n = len(y)
    n_pos = int(y.sum())
    observed_auc = roc_auc_score(y, p)
    observed_ap = average_precision_score(y, p)
    aucs, aps = [], []
    for pos in itertools.combinations(range(n), n_pos):
        yp = np.zeros(n, dtype=int)
        yp[list(pos)] = 1
        aucs.append(roc_auc_score(yp, p))
        aps.append(average_precision_score(yp, p))
    aucs = np.asarray(aucs)
    aps = np.asarray(aps)
    return {
        "permutations": len(aucs),
        "auroc_exact_p": float(np.mean(aucs >= observed_auc - 1e-12)),
        "auprc_exact_p": float(np.mean(aps >= observed_ap - 1e-12)),
    }


def summarize_external():
    pred = pd.read_csv(ROOT / "results/external_GSE200546_predictions.csv")
    rows = []
    for i, (method, d) in enumerate(pred.groupby("method", sort=False)):
        y = d.y.to_numpy(dtype=int)
        p = d.prob.to_numpy(dtype=float)
        point = {
            "method": method,
            "n": len(d),
            "n_acid": int(y.sum()),
            "n_control": int((1 - y).sum()),
            "auroc": roc_auc_score(y, p),
            "auprc": average_precision_score(y, p),
            "brier": brier_score_loss(y, p),
        }
        point.update(stratified_bootstrap(y, p, np.random.default_rng(SEED + i)))
        point.update(exact_balanced_permutation(y, p))
        rows.append(point)
    out = pd.DataFrame(rows)
    out.to_csv(ROOT / "results/external_GSE200546_uncertainty.csv", index=False)
    return out


def summarize_strict_cv():
    d = pd.read_csv(ROOT / "results/strict_cv_metrics.csv")
    out = (
        d.groupby("method", sort=False)
        .agg(
            n_domains=("held_out", "nunique"),
            auroc_mean=("auroc", "mean"),
            auroc_min=("auroc", "min"),
            auroc_max=("auroc", "max"),
            auprc_mean=("auprc", "mean"),
            auprc_min=("auprc", "min"),
            auprc_max=("auprc", "max"),
            brier_mean=("brier", "mean"),
        )
        .reset_index()
    )
    out.to_csv(ROOT / "results/strict_cv_summary.csv", index=False)
    return d, out


def revised_figures(cv: pd.DataFrame, uncertainty: pd.DataFrame):
    mpl.rcParams.update(
        {
            "font.family": "sans-serif",
            "font.sans-serif": ["Arial", "DejaVu Sans"],
            "svg.fonttype": "none",
            "pdf.fonttype": 42,
            "font.size": 7,
            "axes.spines.top": False,
            "axes.spines.right": False,
        }
    )
    order = ["ExprLogReg", "MLP", "GCN", "AcidGNet", "SelfLoopGAT", "PermutedGraphGAT"]
    colors = dict(zip(order, ["#3F6FA0", "#82A6C8", "#76A996", "#C65D4B", "#D5A059", "#9182AB"]))

    fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.75))
    for ax, metric in zip(axes, ["auroc", "auprc"]):
        for j, method in enumerate(order):
            vals = cv.loc[cv.method == method, metric].to_numpy()
            ax.scatter(np.full_like(vals, j, dtype=float), vals, s=24, color=colors[method], zorder=3)
            ax.plot([j - 0.18, j + 0.18], [vals.mean(), vals.mean()], color="black", lw=1.2)
        ax.axhline(0.5, ls="--", lw=0.8, color="0.65")
        ax.set_xticks(range(len(order)), order, rotation=35, ha="right")
        ax.set_ylim(-0.03, 1.05)
        ax.set_ylabel(metric.upper())
        ax.set_title("Strict leave-one-cell-line-out\n(each point is one held-out domain)")
    fig.tight_layout()
    for ext in ["png", "pdf", "svg"]:
        fig.savefig(ROOT / f"figures/Fig4_strict_ablation.{ext}", dpi=600 if ext == "png" else None, bbox_inches="tight")
    plt.close(fig)

    u = uncertainty.set_index("method").loc[order].reset_index()
    fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.8))
    for ax, metric, label in zip(axes, ["auroc", "auprc"], ["AUROC", "AUPRC"]):
        vals = u[metric].to_numpy()
        lo = vals - u[f"{metric}_ci_low"].to_numpy()
        hi = u[f"{metric}_ci_high"].to_numpy() - vals
        ax.bar(range(len(order)), vals, color=[colors[m] for m in order], width=0.72)
        ax.errorbar(range(len(order)), vals, yerr=np.vstack([lo, hi]), fmt="none", ecolor="black", capsize=2, lw=0.8)
        for j, row in u.iterrows():
            ax.text(j, 0.03, f"p={row[f'{metric}_exact_p']:.2f}", ha="center", va="bottom", rotation=90, fontsize=5)
        ax.axhline(0.5, ls="--", lw=0.8, color="0.5")
        ax.set_xticks(range(len(order)), order, rotation=35, ha="right")
        ax.set_ylim(0, 1.08)
        ax.set_ylabel(label)
        ax.set_title(f"GSE200546 CLS1 external ranking\n95% stratified bootstrap CI; exact p")
    fig.suptitle("Cross-cancer technical validation only (n=8; not CRC)", y=1.04, fontsize=8)
    fig.tight_layout()
    for ext in ["png", "pdf", "svg"]:
        fig.savefig(ROOT / f"figures/Fig5_external_validation.{ext}", dpi=600 if ext == "png" else None, bbox_inches="tight")
    plt.close(fig)

    abl = pd.read_csv(ROOT / "results/external_node_ablation.csv")
    a = (
        abl.groupby("symbol")
        .agg(abs_effect=("abs_effect_all", "mean"), abs_effect_sd=("abs_effect_all", "std"))
        .sort_values("abs_effect")
        .tail(20)
    )
    fig, ax = plt.subplots(figsize=(5.2, 3.7))
    ax.barh(a.index, a.abs_effect, xerr=a.abs_effect_sd.fillna(0), color="0.55")
    ax.set_xlabel("Mean absolute probability change")
    ax.set_title("Exploratory node ablation is non-interpretable\nExternal AcidGNet AUROC = 0.50; effects are <0.002")
    ax.ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
    fig.tight_layout()
    for ext in ["png", "pdf", "svg"]:
        fig.savefig(ROOT / f"figures/Fig6_node_ablation.{ext}", dpi=600 if ext == "png" else None, bbox_inches="tight")
    plt.close(fig)


def main():
    uncertainty = summarize_external()
    cv, cv_summary = summarize_strict_cv()
    revised_figures(cv, uncertainty)
    report = {
        "external_n": 8,
        "external_is_crc": False,
        "bootstrap_replicates": BOOTSTRAPS,
        "balanced_exact_permutations": 70,
        "strict_cv": cv_summary.set_index("method").round(4).to_dict("index"),
        "external": uncertainty.set_index("method").round(4).to_dict("index"),
        "interpretation": "No AcidGNet superiority; node-ablation ranks are not driver evidence.",
    }
    (ROOT / "logs/postprocess_validation_summary.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()