File size: 26,993 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
from __future__ import annotations

import shutil
from pathlib import Path

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
import numpy as np
import pandas as pd


ROOT = Path(__file__).resolve().parents[1]
RESULTS = ROOT / "results"
FIGURES = ROOT / "figures"
SOURCE = FIGURES / "source_data_v4"

BLUE = "#2B6CB0"
RED = "#C94C4C"
TEAL = "#138A8A"
GOLD = "#D69E2E"
PURPLE = "#7656A8"
GREY = "#68737D"
LIGHT = "#EDF2F7"
METHOD_COLORS = {
    "ExprLogReg": GREY,
    "MLP": GOLD,
    "GeneAwareDeepSet": PURPLE,
    "IDSelfLoopGAT": TEAL,
    "AcidGNetID": RED,
}


def setup_style() -> None:
    mpl.rcParams.update(
        {
            "font.family": "Arial",
            "font.size": 8.5,
            "axes.titlesize": 10,
            "axes.labelsize": 9,
            "axes.linewidth": 0.7,
            "xtick.labelsize": 7.5,
            "ytick.labelsize": 7.5,
            "legend.fontsize": 7.5,
            "svg.fonttype": "none",
            "pdf.fonttype": 42,
            "savefig.facecolor": "white",
        }
    )


def clean_axis(ax: plt.Axes) -> None:
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.tick_params(width=0.7, length=3)


def panel(ax: plt.Axes, letter: str) -> None:
    ax.text(-0.14, 1.08, letter, transform=ax.transAxes, fontsize=13, fontweight="bold", va="top")


def save(fig: plt.Figure, stem: str) -> None:
    FIGURES.mkdir(parents=True, exist_ok=True)
    fig.savefig(FIGURES / f"{stem}.png", dpi=600, bbox_inches="tight")
    fig.savefig(FIGURES / f"{stem}.pdf", bbox_inches="tight")
    fig.savefig(FIGURES / f"{stem}.svg", bbox_inches="tight")
    plt.close(fig)


def copy_source(filename: str) -> None:
    SOURCE.mkdir(parents=True, exist_ok=True)
    shutil.copy2(RESULTS / filename, SOURCE / filename)


def diagram_card(
    ax: plt.Axes,
    x: float,
    y: float,
    w: float,
    h: float,
    *,
    accent: str,
    eyebrow: str,
    title: str,
    detail: str,
    highlight: bool = False,
) -> None:
    """Draw a restrained, left-aligned evidence or architecture card."""
    edge = accent if highlight else "#D8E0E8"
    face = "#F8FAFC" if not highlight else "#FFF8F8"
    ax.add_patch(
        FancyBboxPatch(
            (x, y),
            w,
            h,
            boxstyle="round,pad=0.012,rounding_size=0.018",
            fc=face,
            ec=edge,
            lw=1.0 if highlight else 0.8,
        )
    )
    ax.add_patch(
        FancyBboxPatch(
            (x, y + h - 0.022),
            w,
            0.022,
            boxstyle="round,pad=0,rounding_size=0.012",
            fc=accent,
            ec="none",
        )
    )
    ax.text(x + 0.018, y + h - 0.052, eyebrow.upper(), color=accent, fontsize=6.3, fontweight="bold", va="top")
    ax.text(x + 0.018, y + h - 0.103, title, color="#1F2D3D", fontsize=8.4, fontweight="bold", va="top")
    ax.text(x + 0.018, y + 0.035, detail, color="#5B6773", fontsize=6.8, va="bottom", linespacing=1.25)


def route_arrow(ax: plt.Axes, start: tuple[float, float], end: tuple[float, float], *, dashed: bool = False) -> None:
    ax.add_patch(
        FancyArrowPatch(
            start,
            end,
            arrowstyle="-|>",
            mutation_scale=10,
            lw=1.05,
            color="#8A96A3",
            linestyle=(0, (3, 2)) if dashed else "solid",
        )
    )


def fig1_crc_program() -> None:
    de = pd.read_csv(RESULTS / "hct116_limma_trend_de.csv")
    crc = pd.read_csv(RESULTS / "v4_crc_selected_gene_concordance.csv")
    summary = pd.read_csv(RESULTS / "v4_crc_supplement_summary.csv").iloc[0]
    mapping_path = ROOT / "metadata/ensembl_gene_mapping.csv"
    mapping = pd.read_csv(mapping_path).set_index("gene_id").symbol.to_dict()
    de["significant"] = (de.fdr <= 0.05) & (de.log2fc.abs() >= 1)
    de["symbol"] = de.gene_id.map(mapping).fillna(de.gene_id)

    fig, axes = plt.subplots(2, 2, figsize=(11.2, 8.0), gridspec_kw={"hspace": 0.42, "wspace": 0.32})
    ax = axes[0, 0]
    ax.text(0.015, 0.91, "PRIMARY", color="white", fontsize=6.5, fontweight="bold", va="center",
            bbox={"boxstyle": "round,pad=0.28", "fc": BLUE, "ec": "none"})
    ax.text(0.015, 0.845, "Unbiased sample-level RNA-seq", color="#465463", fontsize=7.1, va="top")
    diagram_card(ax, 0.015, 0.50, 0.285, 0.27, accent=BLUE, eyebrow="experiment",
                 title="GSE253054 · HCT116", detail="pH 6.5 vs 7.4\nn = 5 + 5")
    diagram_card(ax, 0.365, 0.50, 0.255, 0.27, accent=TEAL, eyebrow="analysis",
                 title="limma-trend", detail="38,122 genes tested\nFDR + effect size")
    diagram_card(ax, 0.685, 0.50, 0.300, 0.27, accent=RED, eyebrow="discovery set",
                 title="1,932 CRATGs", detail="FDR ≤ 0.05 · |log2FC| ≥ 1\neligible for discovery", highlight=True)
    route_arrow(ax, (0.305, 0.635), (0.36, 0.635))
    route_arrow(ax, (0.625, 0.635), (0.68, 0.635))

    ax.plot([0.015, 0.985], [0.43, 0.43], color="#D8E0E8", lw=0.8)
    ax.text(0.015, 0.37, "CONTEXT", color="white", fontsize=6.5, fontweight="bold", va="center",
            bbox={"boxstyle": "round,pad=0.28", "fc": GOLD, "ec": "none"})
    ax.text(0.015, 0.305, "Author-selected gene table", color="#465463", fontsize=7.1, va="top")
    diagram_card(ax, 0.015, 0.035, 0.285, 0.22, accent=GOLD, eyebrow="reported subset",
                 title="Liu 2025 · HCT15", detail="735 changed genes")
    diagram_card(ax, 0.365, 0.035, 0.255, 0.22, accent=PURPLE, eyebrow="mapping",
                 title="700 matched", detail="to HCT116 estimates")
    diagram_card(ax, 0.685, 0.035, 0.300, 0.22, accent=GREY, eyebrow="audit only",
                 title="Direction check", detail="context, not classifier validation")
    route_arrow(ax, (0.305, 0.145), (0.36, 0.145), dashed=True)
    route_arrow(ax, (0.625, 0.145), (0.68, 0.145), dashed=True)
    ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off"); ax.set_title("Evidence hierarchy prevents validation overclaim", pad=8)
    panel(ax, "a")

    ax = axes[0, 1]
    nonsig = ~de.significant
    ax.scatter(de.loc[nonsig, "log2fc"], -np.log10(de.loc[nonsig, "fdr"].clip(1e-300)), s=5, c="#C9D1D9", alpha=0.45, linewidths=0)
    colors = np.where(de.loc[de.significant, "log2fc"] > 0, RED, BLUE)
    ax.scatter(de.loc[de.significant, "log2fc"], -np.log10(de.loc[de.significant, "fdr"].clip(1e-300)), s=8, c=colors, alpha=0.72, linewidths=0)
    ax.axvline(-1, color=GREY, lw=0.7, ls="--"); ax.axvline(1, color=GREY, lw=0.7, ls="--")
    ax.axhline(-np.log10(0.05), color=GREY, lw=0.7, ls="--")
    labelled = de[de.significant].nsmallest(4, "fdr")
    for _, row in labelled.iterrows():
        ax.annotate(str(row.symbol), (row.log2fc, -np.log10(max(row.fdr, 1e-300))), xytext=(3, 3), textcoords="offset points", fontsize=6.5)
    ax.set_xlabel("log2 fold change (chronic acid vs control)"); ax.set_ylabel("−log10 FDR")
    ax.set_title("HCT116 chronic-acidosis response")
    ax.text(0.98, 0.96, "1,932 significant genes", transform=ax.transAxes, ha="right", va="top", fontsize=8, color=RED)
    clean_axis(ax); panel(ax, "b")

    ax = axes[1, 0]
    same = crc.same_direction.astype(bool)
    ax.scatter(crc.loc[~same, "reported_log2fc"], crc.loc[~same, "log2fc"], s=11, c="#BFC7CF", alpha=0.55, label="opposite direction")
    ax.scatter(crc.loc[same, "reported_log2fc"], crc.loc[same, "log2fc"], s=11, c=TEAL, alpha=0.65, label="same direction")
    ax.axhline(0, lw=0.6, color=GREY); ax.axvline(0, lw=0.6, color=GREY)
    ax.set_xlabel("HCT15 reported log2FC (selected table)"); ax.set_ylabel("HCT116 limma log2FC")
    ax.set_title("Cell-line-specific directionality")
    ax.text(0.03, 0.96, f"Spearman ρ={summary.spearman_rho:.2f}\nP={summary.spearman_p:.1e}", transform=ax.transAxes, va="top")
    ax.legend(frameon=False, loc="lower left", markerscale=1.4)
    clean_axis(ax); panel(ax, "c")

    ax = axes[1, 1]
    values = [summary.same_direction_fraction, 1 - summary.same_direction_fraction]
    ax.bar([0, 1], values, color=[TEAL, "#C9D1D9"], width=0.62)
    ax.axhline(0.5, color=GREY, lw=0.8, ls="--")
    ax.set_xticks([0, 1], ["same\ndirection", "opposite\ndirection"])
    ax.set_ylim(0, 0.75); ax.set_ylabel("Fraction of 700 overlapping genes")
    ax.set_title("Published HCT15 subset does not replicate globally")
    for i, value in enumerate(values):
        ax.text(i, value + 0.025, f"{value:.1%}", ha="center", fontweight="bold")
    ax.text(0.02, 0.96, "Selection boundary: author-reported changed genes only", transform=ax.transAxes, va="top", fontsize=7, color="#8A4B08")
    clean_axis(ax); panel(ax, "d")
    fig.suptitle("Figure 1 | CRC acid-adaptation programs are substantial but model-specific", fontsize=13, y=1.01)
    save(fig, "Fig1_v4_CRC_acid_program")
    pd.DataFrame(
        [
            ["primary", "GSE253054", "HCT116 pH 6.5 vs 7.4; n=5+5", "unbiased sample-level RNA-seq"],
            ["primary", "limma-trend", "38,122 genes tested", "differential-expression analysis"],
            ["primary", "CRATGs", "1,932 genes; FDR<=0.05; |log2FC|>=1", "eligible for discovery"],
            ["context", "Liu 2025", "HCT15; 735 author-reported changed genes", "selection-biased table"],
            ["context", "directional audit", "700 genes mapped", "not classifier validation"],
        ],
        columns=["evidence_tier", "step", "detail", "interpretation"],
    ).to_csv(SOURCE / "Fig1a_evidence_hierarchy.csv", index=False)
    for f in ["hct116_limma_trend_de.csv", "v4_crc_selected_gene_concordance.csv", "v4_crc_supplement_summary.csv"]:
        copy_source(f)


def fig2_design() -> None:
    graph = pd.read_csv(RESULTS / "v4_graph_diagnostics.csv")
    model = pd.read_csv(RESULTS / "v4_loco_summary.csv")
    fig, axes = plt.subplots(2, 2, figsize=(11.2, 7.8), gridspec_kw={"hspace": 0.45, "wspace": 0.35})
    ax = axes[0, 0]
    ax.add_patch(FancyBboxPatch((0.045, 0.84), 0.91, 0.085, boxstyle="round,pad=0.012,rounding_size=0.02",
                                fc="#EEF5FB", ec="none"))
    ax.text(0.50, 0.882, "Shared topology · individualized node features · continuous experimental acid output",
            ha="center", va="center", fontsize=7.2, color="#35536D", fontweight="bold")
    steps = [
        (0.025, BLUE, "01 · INPUT", "Patient RNA", "rank(xg)\none value / gene"),
        (0.270, PURPLE, "02 · IDENTITY", "Gene-ID token", "learned eg\nidentity retained"),
        (0.515, RED, "03 · GRAPH", "2× GATv2", "STRING v12\nscore ≥700"),
        (0.760, TEAL, "04 · READOUT", "Gated pooling", "p(acid)\ncontinuous output"),
    ]
    for x0, color, eyebrow, title, detail in steps:
        diagram_card(ax, x0, 0.34, 0.215, 0.39, accent=color, eyebrow=eyebrow, title=title, detail=detail,
                     highlight=(eyebrow.startswith("03")))
    for start, end in [((0.242, .535), (.265, .535)), ((.487, .535), (.510, .535)), ((.732, .535), (.755, .535))]:
        route_arrow(ax, start, end)
    ax.text(0.03, 0.255, "MATCHED CONTROLS", fontsize=6.4, fontweight="bold", color="#5B6773")
    control_specs = [
        (0.03, 0.08, 0.255, "Expression-only"),
        (0.305, 0.08, 0.225, "No-edge GAT"),
        (0.550, 0.08, 0.420, "Degree-preserving rewires"),
    ]
    for x0, y0, w0, label in control_specs:
        ax.add_patch(FancyBboxPatch((x0, y0), w0, 0.11, boxstyle="round,pad=0.01,rounding_size=0.02",
                                    fc="#F4F6F8", ec="#D8E0E8", lw=0.8))
        ax.text(x0 + w0 / 2, y0 + 0.055, label, ha="center", va="center", fontsize=6.9, color="#3F4C59")
    ax.text(0.97, 0.025, "same split · same tuning budget", ha="right", va="bottom", fontsize=6.2, color="#7A8691")
    ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off"); ax.set_title("Identity-aware AcidGNet with topology-matched controls")
    panel(ax, "a")

    ax = axes[0, 1]
    order = graph.sort_values("held_out")
    x = np.arange(len(order))
    ax.bar(x - 0.18, order.directed_edges, width=0.36, color=RED, label="directed edges")
    ax.bar(x + 0.18, order.isolated_nodes, width=0.36, color="#AAB4BE", label="isolated nodes")
    ax.set_xticks(x, order.held_out, rotation=35, ha="right"); ax.set_ylabel("Count")
    ax.set_title("Fold-specific STRING graphs remain sparse")
    ax.legend(frameon=False, ncol=2, loc="upper right")
    clean_axis(ax); panel(ax, "b")

    ax = axes[1, 0]
    model = model.sort_values("mean_parameters")
    ax.barh(model.method, model.mean_parameters, color=[METHOD_COLORS.get(m, GREY) for m in model.method])
    ax.set_xlabel("Mean trainable parameters per fold")
    ax.set_title("Capacity is reported, not hidden")
    for i, value in enumerate(model.mean_parameters):
        ax.text(value + 60, i, f"{value:,.0f}", va="center", fontsize=7)
    ax.set_xlim(0, model.mean_parameters.max() * 1.18); clean_axis(ax); panel(ax, "c")

    ax = axes[1, 1]
    gates = [
        ("Identity repair", "PASS", "gene identity retained"),
        ("Domain holdout", "PASS", "macro AUROC = 0.797"),
        ("STRING > graph null", "FAIL", "paired P = 0.313"),
        ("Confounder robustness", "FAIL", "AUROC = 0.602"),
        ("External transfer", "FAIL", "AUROC = 0.500"),
    ]
    ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
    ax.text(0.035, 0.885, "GATE", fontsize=6.3, fontweight="bold", color="#6C7884")
    ax.text(0.505, 0.885, "STATUS", fontsize=6.3, fontweight="bold", color="#6C7884", ha="center")
    ax.text(0.665, 0.885, "OBSERVED EVIDENCE", fontsize=6.3, fontweight="bold", color="#6C7884")
    y_positions = [0.78, 0.655, 0.53, 0.405, 0.28]
    for idx, ((gate, state, evidence), y0) in enumerate(zip(gates, y_positions), start=1):
        bg = "#F8FAFC" if idx % 2 else "white"
        ax.add_patch(FancyBboxPatch((0.02, y0 - 0.045), 0.96, 0.10,
                                    boxstyle="round,pad=0.006,rounding_size=0.012", fc=bg, ec="#E4E9EE", lw=0.55))
        ax.text(0.04, y0 + 0.005, f"{idx:02d}", va="center", fontsize=6.2, color="#98A2AC")
        ax.text(0.105, y0 + 0.005, gate, va="center", fontsize=7.2, color="#253444", fontweight="bold")
        color = TEAL if state == "PASS" else RED
        fill = "#E8F5F2" if state == "PASS" else "#FCEEEE"
        ax.add_patch(FancyBboxPatch((0.445, y0 - 0.025), 0.12, 0.06,
                                    boxstyle="round,pad=0.01,rounding_size=0.025", fc=fill, ec="none"))
        ax.text(0.505, y0 + 0.005, "PASS" if state == "PASS" else "FAIL", ha="center", va="center",
                fontsize=6.3, fontweight="bold", color=color)
        ax.text(0.665, y0 + 0.005, evidence, va="center", fontsize=6.7, color="#4B5967")
    ax.add_patch(FancyBboxPatch((0.02, 0.06), 0.96, 0.115, boxstyle="round,pad=0.01,rounding_size=0.018",
                                fc="#FFF2F2", ec="#E6A1A1", lw=0.8))
    ax.text(0.055, 0.130, "DOWNSTREAM ANALYSES REMAIN CLOSED", fontsize=6.6, fontweight="bold", color=RED, va="center")
    ax.text(0.055, 0.090, "Patient AAS · immune inference · driver/target claims", fontsize=6.2,
            color="#704343", va="center")
    ax.set_title("Predeclared evidence gates govern downstream claims")
    panel(ax, "d")
    fig.suptitle("Figure 2 | Identity-aware AcidGNet is evaluated under explicit evidence gates", fontsize=13, y=1.01)
    save(fig, "Fig2_v4_identity_aware_AcidGNet")
    pd.DataFrame(
        [
            [1, "Patient RNA", "rank(xg); one scalar per gene"],
            [2, "Gene-ID token", "learned eg; identity retained"],
            [3, "GATv2", "STRING v12; score >=700"],
            [4, "Gated pooling", "continuous experimental acid output"],
        ],
        columns=["step", "module", "detail"],
    ).to_csv(SOURCE / "Fig2a_architecture_steps.csv", index=False)
    pd.DataFrame(gates, columns=["gate", "status", "observed_evidence"]).to_csv(
        SOURCE / "Fig2d_evidence_gates.csv", index=False
    )
    for f in ["v4_graph_diagnostics.csv", "v4_loco_summary.csv", "v4_claim_audit.csv"]:
        copy_source(f)


def fig3_benchmark() -> None:
    metrics = pd.read_csv(RESULTS / "v4_loco_metrics.csv")
    summary = pd.read_csv(RESULTS / "v4_model_comparison_exact.csv")
    methods = ["ExprLogReg", "MLP", "GeneAwareDeepSet", "IDSelfLoopGAT", "AcidGNetID"]
    domains = ["FaDu", "HCT116", "MCF7", "MDA-MB-231", "PANC1", "SiHa"]
    heat = metrics.pivot(index="method", columns="held_out", values="auroc").reindex(index=methods, columns=domains)
    cmap = LinearSegmentedColormap.from_list("score", ["#F7FAFC", "#90CDF4", "#2B6CB0"])
    fig, axes = plt.subplots(2, 2, figsize=(11.2, 8.0), gridspec_kw={"hspace": .44, "wspace": .34})
    ax = axes[0, 0]
    im = ax.imshow(heat, vmin=0, vmax=1, cmap=cmap, aspect="auto")
    ax.set_xticks(range(len(domains)), domains, rotation=35, ha="right"); ax.set_yticks(range(len(methods)), methods)
    for i in range(len(methods)):
        for j in range(len(domains)):
            ax.text(j, i, f"{heat.iloc[i, j]:.2f}", ha="center", va="center", fontsize=6.5, color="white" if heat.iloc[i, j] > .7 else "#243447")
    fig.colorbar(im, ax=ax, fraction=.045, pad=.03, label="AUROC"); ax.set_title("Leave-one-cell-line-out AUROC")
    panel(ax, "a")

    ax = axes[0, 1]
    macro = metrics.groupby("method")[["auroc", "auprc"]].mean().reindex(methods)
    y = np.arange(len(methods)); ax.scatter(macro.auroc, y + .11, color=[METHOD_COLORS[m] for m in methods], s=44, label="AUROC")
    ax.scatter(macro.auprc, y - .11, facecolors="none", edgecolors=[METHOD_COLORS[m] for m in methods], s=44, label="AUPRC")
    ax.set_yticks(y, methods); ax.set_xlim(.45, .9); ax.axvline(.5, color=GREY, lw=.7, ls="--"); ax.set_xlabel("Macro mean across six domains")
    ax.set_title("Average discrimination")
    ax.legend(frameon=False, loc="lower right"); clean_axis(ax); panel(ax, "b")

    ax = axes[1, 0]
    p = metrics.pivot(index="held_out", columns="method", values="auroc")
    delta = p.AcidGNetID - p.ExprLogReg
    x = np.arange(len(delta)); ax.bar(x, delta.values, color=np.where(delta.values >= 0, TEAL, RED))
    ax.axhline(0, color="#243447", lw=.8); ax.set_xticks(x, delta.index, rotation=35, ha="right")
    exact_p = summary.set_index("method").loc["AcidGNetID", "exact_paired_sign_flip_p"]
    ax.set_ylabel("ΔAUROC: AcidGNet − expression"); ax.set_title(f"No consistent advantage (exact paired P={exact_p:.3f})")
    clean_axis(ax); panel(ax, "c")

    ax = axes[1, 1]
    brier = metrics.groupby("method").brier.mean().reindex(methods)
    ax.bar(np.arange(len(methods)), brier, color=[METHOD_COLORS[m] for m in methods])
    ax.set_xticks(np.arange(len(methods)), ["ExprLR", "MLP", "DeepSet", "No-edge\nGAT", "AcidGNet"], rotation=25, ha="right")
    ax.set_ylabel("Mean Brier score (lower is better)"); ax.set_title("AcidGNet discrimination does not imply calibration")
    clean_axis(ax); panel(ax, "d")
    fig.suptitle("Figure 3 | Identity-aware AcidGNet improves its average AUROC but not robustly", fontsize=13, y=1.01)
    save(fig, "Fig3_v4_six_domain_benchmark")
    for f in ["v4_loco_metrics.csv", "v4_loco_predictions.csv", "v4_model_comparison_exact.csv"]:
        copy_source(f)


def fig4_graph_null() -> None:
    nulls = pd.read_csv(RESULTS / "v4_degree_preserving_nulls.csv")
    summary = pd.read_csv(RESULTS / "v4_graph_null_summary.csv")
    graph = pd.read_csv(RESULTS / "v4_graph_diagnostics.csv")
    seeds = pd.read_csv(RESULTS / "v4_loco_seed_metrics.csv")
    domains = summary.held_out.tolist()
    fig, axes = plt.subplots(2, 2, figsize=(11.2, 8.0), gridspec_kw={"hspace": .44, "wspace": .34})
    ax = axes[0, 0]
    rng = np.random.default_rng(20260809)
    for i, domain in enumerate(domains):
        values = nulls[(nulls.held_out == domain) & (nulls.kind == "degree_preserving")].auroc
        ax.scatter(i + rng.normal(0, .045, len(values)), values, s=20, color="#9BA7B2", alpha=.7)
        obs = summary.loc[summary.held_out == domain, "observed_string_auroc"].iloc[0]
        ax.scatter(i, obs, s=58, marker="D", color=RED, edgecolor="white", linewidth=.7, zorder=4)
    ax.set_xticks(range(len(domains)), domains, rotation=35, ha="right"); ax.set_ylabel("AUROC (fixed seed, 100 epochs)")
    ax.set_title("STRING versus 10 degree-preserving rewires/domain")
    ax.scatter([], [], color="#9BA7B2", s=20, label="rewired"); ax.scatter([], [], color=RED, marker="D", s=45, label="STRING")
    ax.legend(frameon=False, ncol=2, loc="lower right"); clean_axis(ax); panel(ax, "a")

    ax = axes[0, 1]
    delta = summary.delta_string_minus_rewired_mean
    ax.bar(np.arange(len(domains)), delta, color=np.where(delta >= 0, TEAL, RED))
    ax.axhline(0, color="#243447", lw=.8); ax.set_xticks(range(len(domains)), domains, rotation=35, ha="right")
    pooled_p = summary.pooled_exact_paired_sign_flip_p.dropna().iloc[0]
    ax.set_ylabel("STRING AUROC − mean rewired AUROC"); ax.set_title(f"Topology-specific gain not established (P={pooled_p:.3f})")
    clean_axis(ax); panel(ax, "b")

    ax = axes[1, 0]
    x = np.arange(len(graph)); ax.bar(x - .18, graph.isolated_fraction, width=.36, color=GOLD, label="isolated fraction")
    ax.bar(x + .18, graph.largest_component / graph.nodes, width=.36, color=BLUE, label="largest component fraction")
    ax.set_xticks(x, graph.held_out, rotation=35, ha="right"); ax.set_ylim(0, 1); ax.set_ylabel("Fraction of graph nodes")
    ax.set_title("Sparse graphs limit message propagation"); ax.legend(frameon=False)
    clean_axis(ax); panel(ax, "c")

    ax = axes[1, 1]
    methods = ["MLP", "GeneAwareDeepSet", "IDSelfLoopGAT", "AcidGNetID"]
    data = [seeds.loc[seeds.method == method, "auroc"].values for method in methods]
    bp = ax.boxplot(data, labels=["MLP", "DeepSet", "No-edge\nGAT", "AcidGNet"], patch_artist=True, showfliers=False)
    for patch_box, method in zip(bp["boxes"], methods): patch_box.set_facecolor(METHOD_COLORS[method]); patch_box.set_alpha(.45)
    ax.axhline(.5, color=GREY, lw=.7, ls="--"); ax.set_ylabel("Per-seed, per-domain AUROC")
    ax.set_title("Seed variability is substantial (18 values/model)")
    clean_axis(ax); panel(ax, "d")
    fig.suptitle("Figure 4 | Apparent AcidGNet performance is not specific to STRING topology", fontsize=13, y=1.01)
    save(fig, "Fig4_v4_graph_null_controls")
    for f in ["v4_degree_preserving_nulls.csv", "v4_graph_null_summary.csv", "v4_graph_diagnostics.csv", "v4_loco_seed_metrics.csv"]:
        copy_source(f)


def fig5_transfer() -> None:
    transfer = pd.read_csv(RESULTS / "v4_cross_study_metrics.csv")
    external = pd.read_csv(RESULTS / "v4_external_metrics.csv")
    primary = pd.read_csv(RESULTS / "v4_loco_metrics.csv").groupby("method", as_index=False).auroc.mean()
    sensitivity = pd.read_csv(RESULTS / "v4_confounder_sensitivity_summary.csv")
    claims = pd.read_csv(RESULTS / "v4_claim_audit.csv")
    fig, axes = plt.subplots(2, 2, figsize=(11.2, 8.0), gridspec_kw={"hspace": .5, "wspace": .38})
    ax = axes[0, 0]
    transfer["column"] = transfer.comparison.str.replace("GSE253054_to_GSE152345", "253→152", regex=False).str.replace("GSE152345_to_GSE253054", "152→253", regex=False) + "\n" + transfer.test_domain
    methods = ["ExprLogReg", "GeneAwareDeepSet", "IDSelfLoopGAT", "AcidGNetID"]
    cols = transfer.column.drop_duplicates().tolist()
    heat = transfer.pivot(index="method", columns="column", values="auroc").reindex(index=methods, columns=cols)
    im = ax.imshow(heat, vmin=0, vmax=1, cmap=LinearSegmentedColormap.from_list("transfer", ["#FFF5F5", "#FEEBC8", "#2B6CB0"]), aspect="auto")
    ax.set_xticks(range(len(cols)), cols, rotation=35, ha="right"); ax.set_yticks(range(len(methods)), methods)
    for i in range(len(methods)):
        for j in range(len(cols)):
            ax.text(j, i, f"{heat.iloc[i, j]:.2f}", ha="center", va="center", fontsize=6.3, color="white" if heat.iloc[i, j] > .75 else "#243447")
    fig.colorbar(im, ax=ax, fraction=.045, pad=.03, label="AUROC"); ax.set_title("Bidirectional cross-study transfer is heterogeneous")
    panel(ax, "a")

    ax = axes[0, 1]
    ext = external.set_index("method").reindex(["ExprLogReg", "MLP", "GeneAwareDeepSet", "IDSelfLoopGAT", "AcidGNetID"])
    x = np.arange(len(ext)); ax.bar(x, ext.auroc, color=[METHOD_COLORS[m] for m in ext.index])
    yerr = np.vstack([ext.auroc - ext.auroc_ci_low, ext.auroc_ci_high - ext.auroc])
    ax.errorbar(x, ext.auroc, yerr=yerr, fmt="none", ecolor="#243447", capsize=2, lw=.8)
    ax.axhline(.5, color=GREY, lw=.7, ls="--"); ax.set_ylim(0, 1.08)
    ax.set_xticks(x, ["ExprLR", "MLP", "DeepSet", "No-edge\nGAT", "AcidGNet"], rotation=25, ha="right")
    ax.set_ylabel("AUROC with 95% bootstrap CI"); ax.set_title("Independent GSE200546: n=8, non-CRC")
    clean_axis(ax); panel(ax, "b")

    ax = axes[1, 0]
    methods2 = ["ExprLogReg", "AcidGNetID"]
    before = primary.set_index("method").loc[methods2, "auroc"]
    after = sensitivity.set_index("method").loc[methods2, "mean_auroc"]
    for method in methods2:
        color = METHOD_COLORS[method]
        ax.plot([0, 1], [before[method], after[method]], marker="o", lw=2, color=color, label=method)
        ax.text(1.04, after[method], f"{after[method]:.3f}", va="center", fontsize=7, color=color)
    ax.set_xticks([0, 1], ["Primary", "Exclude 13 flagged\nIFN-like/Y-linked genes"]); ax.set_xlim(-.12, 1.28); ax.set_ylim(0.45, .86)
    ax.set_ylabel("Mean leave-domain-out AUROC"); ax.set_title("AcidGNet is more sensitive to plausible confounding")
    ax.legend(frameon=False); clean_axis(ax); panel(ax, "c")

    ax = axes[1, 1]
    status_color = {"supported": TEAL, "not_supported": RED, "not_run": GREY}
    labels = ["Identity repair", "vs expression", "STRING specificity", "cross-study", "patient AAS", "drivers/targets"]
    y = np.arange(len(claims))[::-1]
    colors = [status_color[s] for s in claims.status]
    ax.barh(y, np.ones(len(y)), color=colors, alpha=.22, edgecolor=colors)
    for yi, stat in zip(y, claims.status):
        ax.text(.5, yi, stat.replace("_", " ").upper(), ha="center", va="center", fontsize=7, fontweight="bold", color=status_color[stat])
    ax.set_yticks(y, labels); ax.set_xlim(0, 1); ax.set_xticks([]); ax.set_title("Evidence-gated manuscript claims")
    for spine in ax.spines.values(): spine.set_visible(False)
    panel(ax, "d")
    fig.suptitle("Figure 5 | Transfer and sensitivity analyses block premature clinical claims", fontsize=13, y=1.01)
    save(fig, "Fig5_v4_transfer_and_claim_gates")
    for f in ["v4_cross_study_metrics.csv", "v4_external_metrics.csv", "v4_confounder_sensitivity_summary.csv", "v4_claim_audit.csv"]:
        copy_source(f)


def main() -> None:
    setup_style()
    SOURCE.mkdir(parents=True, exist_ok=True)
    fig1_crc_program()
    fig2_design()
    fig3_benchmark()
    fig4_graph_null()
    fig5_transfer()
    print("Generated five v4 figures in PNG/PDF/SVG with source tables.")


if __name__ == "__main__":
    main()