AcidGNet_HCT116 / src /plot_optimized_manuscript_figures.py
xuyun's picture
Upload folder using huggingface_hub
a521a25 verified
Raw History Blame Contribute Delete
10.5 kB
from __future__ import annotations
from pathlib import Path
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "figures"
SOURCE = OUT / "source_data"
SOURCE.mkdir(parents=True, exist_ok=True)
ORDER = ["ExprLogReg", "MLP", "GCN", "AcidGNet", "SelfLoopGAT", "PermutedGraphGAT"]
LABELS = ["Expression LR", "MLP", "GCN", "AcidGNet", "Self-loop GAT", "Permuted graph GAT"]
COLORS = {
"ExprLogReg": "#3F6FA0",
"MLP": "#86A9C8",
"GCN": "#78A996",
"AcidGNet": "#C75D4B",
"SelfLoopGAT": "#D5A056",
"PermutedGraphGAT": "#9184A8",
}
def style() -> None:
mpl.rcParams.update(
{
"font.family": "sans-serif",
"font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"],
"font.size": 7,
"axes.spines.top": False,
"axes.spines.right": False,
"axes.linewidth": 0.8,
"legend.frameon": False,
"svg.fonttype": "none",
"pdf.fonttype": 42,
}
)
def panel_label(ax, label: str) -> None:
ax.text(-0.16, 1.08, label, transform=ax.transAxes, fontsize=9, fontweight="bold", va="top")
def save(fig, stem: str) -> None:
for ext in ["png", "pdf", "svg"]:
fig.savefig(OUT / f"{stem}.{ext}", dpi=600 if ext == "png" else None, bbox_inches="tight")
plt.close(fig)
def heatmap(ax, table: pd.DataFrame, title: str, vmin=0, vmax=1) -> None:
image = ax.imshow(table.to_numpy(), vmin=vmin, vmax=vmax, cmap="Blues", aspect="auto")
for i in range(table.shape[0]):
for j in range(table.shape[1]):
value = table.iloc[i, j]
ax.text(j, i, f"{value:.2f}", ha="center", va="center", fontsize=6,
color="white" if value > 0.65 else "black")
ax.set_xticks(range(table.shape[1]), table.columns)
ax.set_yticks(range(table.shape[0]), [LABELS[ORDER.index(x)] for x in table.index])
ax.set_title(title)
return image
def strict_figure() -> None:
cv = pd.read_csv(ROOT / "results/strict_cv_metrics.csv")
cv.to_csv(SOURCE / "Fig3_strict_validation_source_data.csv", index=False)
auc = cv.pivot(index="method", columns="held_out", values="auroc").loc[ORDER]
apr = cv.pivot(index="method", columns="held_out", values="auprc").loc[ORDER]
baseline = cv.loc[cv.method == "ExprLogReg", ["held_out", "auroc"]].set_index("held_out").auroc
delta = cv.copy()
delta["delta_auroc_vs_expression_lr"] = delta.apply(lambda r: r.auroc - baseline[r.held_out], axis=1)
delta.to_csv(SOURCE / "Fig3_delta_source_data.csv", index=False)
fig = plt.figure(figsize=(7.2, 5.1))
gs = fig.add_gridspec(2, 2, width_ratios=[1.05, 1.0], hspace=0.48, wspace=0.48)
ax_a = fig.add_subplot(gs[0, 0])
heatmap(ax_a, auc, "AUROC by held-out cell line")
panel_label(ax_a, "a")
ax_b = fig.add_subplot(gs[0, 1])
heatmap(ax_b, apr, "AUPRC by held-out cell line")
panel_label(ax_b, "b")
ax_c = fig.add_subplot(gs[1, 0])
neural = [m for m in ORDER if m != "ExprLogReg"]
offsets = np.linspace(-0.24, 0.24, 3)
for j, held in enumerate(["FaDu", "HCT116", "SiHa"]):
d = delta[(delta.held_out == held) & delta.method.isin(neural)].set_index("method").loc[neural]
ax_c.scatter(np.arange(len(neural)) + offsets[j], d.delta_auroc_vs_expression_lr,
s=28, label=held, alpha=0.9)
ax_c.axhline(0, color="black", lw=0.8)
ax_c.set_xticks(range(len(neural)), [LABELS[ORDER.index(m)] for m in neural], rotation=32, ha="right")
ax_c.set_ylabel("ΔAUROC versus expression LR")
ax_c.set_title("Graph models provide no consistent gain")
ax_c.legend(ncol=3, loc="lower left", fontsize=6)
panel_label(ax_c, "c")
ax_d = fig.add_subplot(gs[1, 1])
for i, method in enumerate(ORDER):
vals = cv.loc[cv.method == method, "brier"].to_numpy()
ax_d.scatter(np.full_like(vals, i, dtype=float), vals, color=COLORS[method], s=28, zorder=3)
ax_d.plot([i - 0.18, i + 0.18], [vals.mean(), vals.mean()], color="black", lw=1)
ax_d.axhline(0.25, color="0.6", ls="--", lw=0.8, label="uninformative 0.5 probability")
ax_d.set_xticks(range(len(ORDER)), LABELS, rotation=32, ha="right")
ax_d.set_ylabel("Brier score (lower is better)")
ax_d.set_title("Ranking does not imply calibration")
ax_d.legend(fontsize=6, loc="upper left")
panel_label(ax_d, "d")
fig.suptitle("Strict leave-one-cell-line-out evaluation", fontsize=10, y=0.995)
save(fig, "Fig3_strict_validation_optimized")
def external_figure() -> None:
unc = pd.read_csv(ROOT / "results/external_GSE200546_uncertainty.csv").set_index("method").loc[ORDER].reset_index()
pred = pd.read_csv(ROOT / "results/external_GSE200546_predictions.csv")
unc.to_csv(SOURCE / "Fig4_external_uncertainty_source_data.csv", index=False)
pred.to_csv(SOURCE / "Fig4_external_predictions_source_data.csv", index=False)
fig = plt.figure(figsize=(7.2, 5.0))
gs = fig.add_gridspec(2, 2, hspace=0.48, wspace=0.42)
for ax, metric, label, panel in [
(fig.add_subplot(gs[0, 0]), "auroc", "AUROC", "a"),
(fig.add_subplot(gs[0, 1]), "auprc", "AUPRC", "b"),
]:
vals = unc[metric].to_numpy()
lo = vals - unc[f"{metric}_ci_low"].to_numpy()
hi = unc[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 i, row in unc.iterrows():
ax.text(i, 0.02, f"p={row[f'{metric}_exact_p']:.2f}", ha="center", va="bottom", rotation=90, fontsize=5)
ax.axhline(0.5, color="0.6", ls="--", lw=0.8)
ax.set_ylim(0, 1.08)
ax.set_xticks(range(len(ORDER)), LABELS, rotation=32, ha="right")
ax.set_ylabel(label)
ax.set_title(f"{label} with 95% bootstrap CI")
panel_label(ax, panel)
ax_c = fig.add_subplot(gs[1, 0])
vals = unc.brier.to_numpy()
ax_c.bar(range(len(ORDER)), vals, color=[COLORS[m] for m in ORDER], width=0.72)
ax_c.axhline(0.25, color="0.4", ls="--", lw=0.8)
ax_c.set_xticks(range(len(ORDER)), LABELS, rotation=32, ha="right")
ax_c.set_ylabel("Brier score")
ax_c.set_title("External probability calibration")
panel_label(ax_c, "c")
ax_d = fig.add_subplot(gs[1, 1])
wide = pred.pivot(index=["sample", "y"], columns="method", values="prob").reset_index()
for y, color, label in [(0, "#4C78A8", "pH 7.4"), (1, "#C75D4B", "pH 6.6")]:
d = wide[wide.y == y]
ax_d.scatter(d.ExprLogReg, d.AcidGNet, s=38, color=color, label=label, edgecolor="white", linewidth=0.5)
ax_d.axhline(0.5, color="0.75", lw=0.7, ls="--")
ax_d.axvline(0.5, color="0.75", lw=0.7, ls="--")
ax_d.set_xlabel("Expression LR score")
ax_d.set_ylabel("AcidGNet score")
ax_d.set_title("Model outputs in eight external samples")
ax_d.legend(fontsize=6)
panel_label(ax_d, "d")
fig.suptitle("Independent cross-cancer technical validation (GSE200546; n=8; not CRC)", fontsize=9.5, y=0.995)
save(fig, "Fig4_external_validation_optimized")
def graph_diagnostic_figure() -> None:
graphs = pd.read_csv(ROOT / "results/strict_cv_graphs.csv")
cv = pd.read_csv(ROOT / "results/strict_cv_metrics.csv")
ext = pd.read_csv(ROOT / "results/external_GSE200546_metrics.csv").set_index("method")
abl = pd.read_csv(ROOT / "results/external_node_ablation.csv")
graph_auc = graphs.merge(cv[cv.method == "AcidGNet"][["held_out", "auroc"]], left_on="fold", right_on="held_out")
graph_auc.to_csv(SOURCE / "Fig5_graph_domain_source_data.csv", index=False)
abl_summary = abl.groupby("symbol", as_index=False).agg(mean_abs_effect=("abs_effect_all", "mean"), sd=("abs_effect_all", "std"))
abl_summary.to_csv(SOURCE / "Fig5_node_ablation_source_data.csv", index=False)
fig = plt.figure(figsize=(7.2, 4.7))
gs = fig.add_gridspec(2, 2, hspace=0.5, wspace=0.42)
ax_a = fig.add_subplot(gs[0, 0])
ax_a.bar(graphs.fold, graphs.directed_edges, color="#8A9AAA")
for i, row in graphs.iterrows():
ax_a.text(i, row.directed_edges + 5, f"{int(row.nodes)} nodes", ha="center", fontsize=6)
ax_a.set_ylabel("Directed STRING edges")
ax_a.set_title("Fold-specific graphs are sparse")
panel_label(ax_a, "a")
ax_b = fig.add_subplot(gs[0, 1])
for _, row in graph_auc.iterrows():
ax_b.scatter(row.directed_edges, row.auroc, s=42, color="#C75D4B")
ax_b.text(row.directed_edges + 4, row.auroc, row.fold, va="center", fontsize=6)
ax_b.axhline(0.5, color="0.65", ls="--", lw=0.8)
ax_b.set_xlim(70, 240)
ax_b.set_ylim(0, 1.03)
ax_b.set_xlabel("Directed STRING edges")
ax_b.set_ylabel("Held-out AcidGNet AUROC")
ax_b.set_title("Edge count does not rescue transfer")
panel_label(ax_b, "b")
ax_c = fig.add_subplot(gs[1, 0])
controls = ["ExprLogReg", "GCN", "AcidGNet", "SelfLoopGAT", "PermutedGraphGAT"]
vals = [ext.loc[m, "auroc"] for m in controls]
ax_c.bar(range(len(controls)), vals, color=[COLORS[m] for m in controls])
ax_c.axhline(0.5, color="0.65", ls="--", lw=0.8)
ax_c.set_xticks(range(len(controls)), [LABELS[ORDER.index(m)] for m in controls], rotation=30, ha="right")
ax_c.set_ylim(0, 1.02)
ax_c.set_ylabel("External AUROC")
ax_c.set_title("Specific STRING topology adds no external gain")
panel_label(ax_c, "c")
ax_d = fig.add_subplot(gs[1, 1])
top = abl_summary.nlargest(12, "mean_abs_effect").sort_values("mean_abs_effect")
lower = np.minimum(top["sd"].fillna(0).to_numpy(), top.mean_abs_effect.to_numpy())
upper = top["sd"].fillna(0).to_numpy()
ax_d.barh(top.symbol, top.mean_abs_effect, xerr=np.vstack([lower, upper]), color="0.55")
ax_d.ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
ax_d.set_xlabel("Mean absolute score change")
ax_d.set_title("Chance-level model yields negligible ablations")
panel_label(ax_d, "d")
fig.suptitle("Diagnostic evidence for graph-prior failure", fontsize=10, y=0.995)
save(fig, "Fig5_graph_prior_diagnostics")
def main() -> None:
style()
strict_figure()
external_figure()
graph_diagnostic_figure()
print("Optimized Figs. 3-5 exported as PNG/PDF/SVG with source-data CSVs.")
if __name__ == "__main__":
main()