Download src/plot_v5_crc_external.py from xuyun/AcidGNet_HCT116: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/datasets/xuyun/AcidGNet_HCT116/resolve/main/src/plot_v5_crc_external.py
- Command line
-
hf download hf://datasets/xuyun/AcidGNet_HCT116/src/plot_v5_crc_external.py
-
curl -L -o plot_v5_crc_external.py https://huggingface.co/datasets/xuyun/AcidGNet_HCT116/resolve/main/src/plot_v5_crc_external.py
16.9 kB
| from __future__ import annotations | |
| import shutil | |
| from pathlib import Path | |
| import matplotlib as mpl | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import pandas as pd | |
| from matplotlib.patches import FancyArrowPatch, FancyBboxPatch | |
| ROOT = Path(__file__).resolve().parents[1] | |
| RESULTS = ROOT / "results" | |
| FIGURES = ROOT / "figures" | |
| SOURCE = FIGURES / "source_data_v5" | |
| SEED = 20260809 | |
| 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, | |
| "axes.titlesize": 10, | |
| "axes.labelsize": 8.5, | |
| "axes.linewidth": 0.7, | |
| "xtick.labelsize": 7, | |
| "ytick.labelsize": 7, | |
| "legend.fontsize": 7, | |
| "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.13, 1.07, 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(*filenames: str) -> None: | |
| SOURCE.mkdir(parents=True, exist_ok=True) | |
| for filename in filenames: | |
| shutil.copy2(RESULTS / filename, SOURCE / filename) | |
| def fig6_crc_external_biology() -> None: | |
| de = pd.read_csv(RESULTS / "v5_crc_aa_hct116_de.csv") | |
| con = pd.read_csv(RESULTS / "v5_crc_hct116_crossstudy_concordance.csv") | |
| con_summary = pd.read_csv(RESULTS / "v5_crc_hct116_crossstudy_summary.csv").iloc[0] | |
| fg = pd.read_csv(RESULTS / "v5_crc_aa_hct116_reactome_fgsea.csv") | |
| fig, axes = plt.subplots(2, 2, figsize=(11.5, 8.2), gridspec_kw={"hspace": 0.42, "wspace": 0.34}) | |
| ax = axes[0, 0] | |
| boxes = [ | |
| (0.02, 0.58, 0.28, 0.24, "Open author repository\ncommit + SHA256 locked\n63,152 genes", BLUE), | |
| (0.37, 0.58, 0.25, 0.24, "AA-HCT116 RNA-seq\n3 parental + 3 adapted\nindependent laboratory", TEAL), | |
| (0.69, 0.58, 0.28, 0.24, "Frozen external test\nno threshold/model tuning\n20 exact label allocations", RED), | |
| (0.20, 0.13, 0.26, 0.22, "limma-voom\n13,956 genes tested\n1,714 stringent DEGs", PURPLE), | |
| (0.55, 0.13, 0.29, 0.22, "Reactome GSEA +\ncross-study HCT116 audit\nheterogeneity retained", GOLD), | |
| ] | |
| for x, y, w, h, text, color in boxes: | |
| ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02", fc=color, ec="none", alpha=0.14)) | |
| ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", fontsize=7.3, color="#243447") | |
| for start, end in [((0.30, 0.70), (0.37, 0.70)), ((0.62, 0.70), (0.69, 0.70)), ((0.50, 0.58), (0.34, 0.35)), ((0.56, 0.58), (0.68, 0.35))]: | |
| ax.add_patch(FancyArrowPatch(start, end, arrowstyle="-|>", mutation_scale=10, lw=1, color=GREY)) | |
| ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off") | |
| ax.set_title("Independent CRC chronic-acidosis evidence layer") | |
| panel(ax, "a") | |
| ax = axes[0, 1] | |
| sig = (de.fdr <= 0.05) & (de.log2fc.abs() >= 1) | |
| ax.scatter(de.loc[~sig, "log2fc"], -np.log10(de.loc[~sig, "fdr"].clip(1e-300)), s=5, c="#BBC4CC", alpha=0.45, linewidth=0) | |
| colors = np.where(de.loc[sig, "log2fc"] > 0, RED, BLUE) | |
| ax.scatter(de.loc[sig, "log2fc"], -np.log10(de.loc[sig, "fdr"].clip(1e-300)), s=7, c=colors, alpha=0.7, linewidth=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="--") | |
| label = de.loc[sig & de.symbol.notna()].nsmallest(6, "fdr") | |
| for row in label.itertuples(): | |
| ax.text(row.log2fc, -np.log10(max(row.fdr, 1e-300)) + 0.25, row.symbol, fontsize=6, ha="center") | |
| ax.set_xlabel("log2 fold change (acid-adapted / parental)") | |
| ax.set_ylabel("−log10 FDR") | |
| ax.set_title("AA-HCT116 transcriptional remodeling") | |
| ax.text(0.02, 0.98, "1,714 DEGs", transform=ax.transAxes, va="top", color=RED, fontweight="bold") | |
| clean_axis(ax); panel(ax, "b") | |
| ax = axes[1, 0] | |
| both = (con.fdr_Pellegrini2018 <= 0.05) & (con.log2fc_Pellegrini2018_adapted_vs_parental.abs() >= 1) & (con.fdr_GSE253054 <= 0.05) & (con.log2fc_GSE253054_HCT116_acid_vs_control.abs() >= 1) | |
| ax.scatter(con.loc[~both, "log2fc_GSE253054_HCT116_acid_vs_control"], con.loc[~both, "log2fc_Pellegrini2018_adapted_vs_parental"], s=5, c="#BBC4CC", alpha=0.35, linewidth=0) | |
| ax.scatter(con.loc[both, "log2fc_GSE253054_HCT116_acid_vs_control"], con.loc[both, "log2fc_Pellegrini2018_adapted_vs_parental"], s=10, c=RED, alpha=0.65, linewidth=0) | |
| ax.axhline(0, color=GREY, lw=0.6); ax.axvline(0, color=GREY, lw=0.6) | |
| ax.set_xlabel("GSE253054 HCT116 log2FC") | |
| ax.set_ylabel("Pellegrini 2018 AA-HCT116 log2FC") | |
| ax.set_title("Cross-study overlap exceeds chance, but effects diverge") | |
| ax.text(0.03, 0.97, f"ρ={con_summary.spearman_log2fc:.2f}\nDEG overlap OR={con_summary.significant_overlap_fisher_or:.2f}\nP={con_summary.significant_overlap_fisher_p:.1e}", transform=ax.transAxes, va="top", fontsize=7) | |
| clean_axis(ax); panel(ax, "c") | |
| ax = axes[1, 1] | |
| selected_names = [ | |
| "Fatty acid metabolism", | |
| "Aerobic respiration and respiratory electron transport", | |
| "Respiratory electron transport", | |
| "Mitochondrial translation", | |
| "Mitochondrial biogenesis", | |
| "Selective autophagy", | |
| "Glutamate and glutamine metabolism", | |
| "Glutathione conjugation", | |
| ] | |
| focus = fg.set_index("pathway").reindex(selected_names).dropna().reset_index() | |
| focus = focus.sort_values("NES") | |
| colors = np.where(focus.padj <= 0.05, np.where(focus.NES > 0, RED, BLUE), "#AAB3BB") | |
| ax.barh(np.arange(len(focus)), focus.NES, color=colors, alpha=0.85) | |
| ax.axvline(0, color=GREY, lw=0.7) | |
| ax.set_yticks(np.arange(len(focus))) | |
| ax.set_yticklabels(focus.pathway.str.replace("Aerobic respiration and ", "Aerobic respiration +\n", regex=False), fontsize=6.5) | |
| ax.set_xlabel("Normalized enrichment score") | |
| ax.set_title("Metabolic programs are remodeled, not uniformly activated") | |
| for i, row in focus.reset_index(drop=True).iterrows(): | |
| x = row.NES - 0.05 if row.NES >= 0 else row.NES + 0.08 | |
| ax.text(x, i, f"FDR={row.padj:.3g}", va="center", ha="right" if row.NES >= 0 else "left", fontsize=6) | |
| clean_axis(ax); panel(ax, "d") | |
| fig.suptitle("Fig. 6 | Independent CRC chronic-acidosis data reveal a reproducible but heterogeneous response", y=0.995, fontsize=12, fontweight="bold") | |
| save(fig, "Fig6_v5_independent_CRC_biology") | |
| copy_source( | |
| "v5_crc_aa_hct116_de.csv", | |
| "v5_crc_aa_hct116_reactome_fgsea.csv", | |
| "v5_crc_hct116_crossstudy_concordance.csv", | |
| "v5_crc_hct116_crossstudy_summary.csv", | |
| ) | |
| def fig7_crc_external_model() -> None: | |
| metrics = pd.read_csv(RESULTS / "v5_crc_external_metrics.csv") | |
| panels = pd.read_csv(RESULTS / "v5_crc_external_panel_sensitivity.csv") | |
| perms = pd.read_csv(RESULTS / "v5_crc_external_label_permutations.csv") | |
| perm_summary = pd.read_csv(RESULTS / "v5_crc_external_label_permutation_summary.csv") | |
| curve = pd.read_csv(RESULTS / "v5_crc_external_learning_curve.csv") | |
| fig, axes = plt.subplots(2, 2, figsize=(11.5, 8.2), gridspec_kw={"hspace": 0.48, "wspace": 0.32}) | |
| ax = axes[0, 0] | |
| methods = ["ExprLogReg", "MLP", "GeneAwareDeepSet", "IDSelfLoopGAT", "AcidGNetID"] | |
| y = np.arange(len(methods)) | |
| for offset, scenario, marker in [(-0.12, "all_source_domains", "o"), (0.12, "exclude_all_HCT116_training", "s")]: | |
| use = metrics.set_index(["scenario", "method"]).loc[scenario] | |
| vals = [use.loc[m, "auroc"] for m in methods] | |
| ax.scatter(vals, y + offset, s=45, marker=marker, c=[METHOD_COLORS[m] for m in methods], edgecolor="white", linewidth=0.5, label=scenario.replace("_", " ")) | |
| ax.axvline(0.5, color=GREY, lw=0.7, ls="--") | |
| ax.set_yticks(y); ax.set_yticklabels(methods); ax.invert_yaxis() | |
| ax.set_xlim(-0.03, 1.05); ax.set_xlabel("External AA-HCT116 AUROC (n=3+3)") | |
| ax.set_title("Frozen external discrimination is baseline-led") | |
| ax.legend(loc="lower left", fontsize=6.5) | |
| clean_axis(ax); panel(ax, "a") | |
| ax = axes[0, 1] | |
| for scenario, ls in [("all_source_domains", "-"), ("exclude_all_HCT116_training", "--")]: | |
| for method in ["ExprLogReg", "AcidGNetID"]: | |
| use = panels[(panels.scenario == scenario) & (panels.method == method)].sort_values("panel_size") | |
| ax.plot(use.panel_size, use.auroc, marker="o", lw=1.4, ls=ls, color=METHOD_COLORS[method], alpha=0.9, label=f"{method}; {'all' if scenario.startswith('all') else 'HCT116 excluded'}") | |
| ax.axhline(0.5, color=GREY, lw=0.7, ls=":") | |
| ax.set_xticks([100, 200, 300, 500]); ax.set_ylim(-0.03, 1.05) | |
| ax.set_xlabel("Training-fold variance panel size") | |
| ax.set_ylabel("External AUROC") | |
| ax.set_title("AcidGNet is sensitive to panel size and lineage exclusion") | |
| ax.legend(fontsize=6, ncol=2, loc="lower left") | |
| clean_axis(ax); panel(ax, "b") | |
| ax = axes[1, 0] | |
| groups = [] | |
| labels = [] | |
| observed = [] | |
| colors = [] | |
| for scenario in ["all_source_domains", "exclude_all_HCT116_training"]: | |
| for method in ["ExprLogReg", "AcidGNetID"]: | |
| use = perms[(perms.scenario == scenario) & (perms.method == method)] | |
| groups.append(use.loc[use.kind.ne("observed"), "auroc"].to_numpy()) | |
| labels.append(f"{method}\n{'all' if scenario.startswith('all') else 'no HCT116'}") | |
| observed.append(float(use.loc[use.kind.eq("observed"), "auroc"].iloc[0])) | |
| colors.append(METHOD_COLORS[method]) | |
| parts = ax.violinplot(groups, positions=np.arange(1, 5), showextrema=False, widths=0.75) | |
| for body, color in zip(parts["bodies"], colors): | |
| body.set_facecolor(color); body.set_edgecolor("none"); body.set_alpha(0.24) | |
| rng = np.random.default_rng(20260809) | |
| for i, (values, obs, color) in enumerate(zip(groups, observed, colors), 1): | |
| ax.scatter(i + rng.uniform(-0.16, 0.16, len(values)), values, s=8, c=color, alpha=0.35, linewidth=0) | |
| ax.scatter(i, obs, marker="*", s=95, c=color, edgecolor="black", linewidth=0.4, zorder=5) | |
| row = perm_summary[(perm_summary.scenario == ("all_source_domains" if i <= 2 else "exclude_all_HCT116_training")) & (perm_summary.method == ("ExprLogReg" if i % 2 == 1 else "AcidGNetID"))].iloc[0] | |
| ax.text(i, 1.04, f"P={row.permutation_p_ge_observed:.2f}", ha="center", va="bottom", fontsize=6.5) | |
| ax.axhline(0.5, color=GREY, lw=0.7, ls="--") | |
| ax.set_xticks(np.arange(1, 5)); ax.set_xticklabels(labels, fontsize=6.5) | |
| ax.set_ylim(-0.03, 1.12); ax.set_ylabel("External AUROC") | |
| ax.set_title("Training-label nulls do not support a graph-model advantage") | |
| clean_axis(ax); panel(ax, "c") | |
| ax = axes[1, 1] | |
| for method in ["ExprLogReg", "AcidGNetID"]: | |
| use = curve[curve.method == method] | |
| for k, group in use.groupby("n_training_domains"): | |
| jitter = np.random.default_rng(SEED + int(k)).uniform(-0.08, 0.08, len(group)) | |
| ax.scatter(np.full(len(group), int(k)) + jitter, group.auroc, s=12, color=METHOD_COLORS[method], alpha=0.25, linewidth=0) | |
| summary = use.groupby("n_training_domains").auroc.agg(["mean", "std", "count"]).reset_index() | |
| err = summary["std"].fillna(0) | |
| ax.errorbar(summary.n_training_domains, summary["mean"], yerr=err, marker="o", lw=1.5, capsize=2.5, color=METHOD_COLORS[method], label=method) | |
| ax.axhline(0.5, color=GREY, lw=0.7, ls="--") | |
| ax.set_xticks([2, 3, 4, 5, 6]); ax.set_ylim(-0.03, 1.08) | |
| ax.set_xlabel("Number of source domains") | |
| ax.set_ylabel("AA-HCT116 AUROC across domain combinations") | |
| ax.set_title("More domains do not monotonically improve AcidGNet") | |
| ax.legend() | |
| clean_axis(ax); panel(ax, "d") | |
| fig.suptitle("Fig. 7 | Independent CRC validation exposes model and topology instability", y=0.995, fontsize=12, fontweight="bold") | |
| save(fig, "Fig7_v5_CRC_external_model_robustness") | |
| copy_source( | |
| "v5_crc_external_metrics.csv", | |
| "v5_crc_external_panel_sensitivity.csv", | |
| "v5_crc_external_label_permutations.csv", | |
| "v5_crc_external_label_permutation_summary.csv", | |
| "v5_crc_external_learning_curve.csv", | |
| ) | |
| def fig_s1_topology_null() -> None: | |
| topology = pd.read_csv(RESULTS / "v5_crc_external_topology_sensitivity.csv") | |
| nulls = pd.read_csv(RESULTS / "v5_crc_external_coherent_graph_nulls.csv") | |
| summary = pd.read_csv(RESULTS / "v5_crc_external_coherent_graph_null_summary.csv") | |
| graphs = pd.read_csv(RESULTS / "v5_crc_external_topology_graphs.csv") | |
| fig, axes = plt.subplots(1, 3, figsize=(12.2, 3.6), gridspec_kw={"wspace": 0.34}) | |
| ax = axes[0] | |
| topologies = ["full_STRING", "training_acid_coherent_STRING", "no_PPI_edges"] | |
| labels = ["Full STRING", "Acid-coherent\nSTRING", "No PPI edges"] | |
| x = np.arange(3) | |
| width = 0.34 | |
| for offset, scenario, color in [(-width / 2, "all_source_domains", BLUE), (width / 2, "exclude_all_HCT116_training", RED)]: | |
| use = topology.set_index(["scenario", "topology"]).loc[scenario] | |
| ax.bar(x + offset, [use.loc[t, "auroc"] for t in topologies], width=width, color=color, alpha=0.8, label="All domains" if scenario.startswith("all") else "HCT116 excluded") | |
| ax.axhline(0.5, color=GREY, lw=0.7, ls="--") | |
| ax.set_xticks(x); ax.set_xticklabels(labels, fontsize=6.5); ax.set_ylim(0, 1.08) | |
| ax.set_ylabel("External AUROC"); ax.set_title("Topology sensitivity") | |
| ax.legend(fontsize=6.5); clean_axis(ax); panel(ax, "a") | |
| ax = axes[1] | |
| for i, scenario in enumerate(["all_source_domains", "exclude_all_HCT116_training"], 1): | |
| values = nulls[(nulls.scenario == scenario) & (nulls.kind == "degree_preserving")].auroc.to_numpy() | |
| parts = ax.violinplot([values], positions=[i], showextrema=False, widths=0.75) | |
| color = BLUE if i == 1 else RED | |
| parts["bodies"][0].set_facecolor(color); parts["bodies"][0].set_alpha(0.25); parts["bodies"][0].set_edgecolor("none") | |
| rng = np.random.default_rng(20260809 + i) | |
| ax.scatter(i + rng.uniform(-0.16, 0.16, len(values)), values, s=9, color=color, alpha=0.4, linewidth=0) | |
| obs = float(nulls[(nulls.scenario == scenario) & (nulls.kind == "observed_acid_coherent")].auroc.iloc[0]) | |
| p = float(summary.loc[summary.scenario == scenario, "exact_p_ge_observed"].iloc[0]) | |
| ax.scatter(i, obs, marker="*", s=100, color=color, edgecolor="black", linewidth=0.4) | |
| ax.text(i, 1.03, f"P={p:.2f}", ha="center", fontsize=7) | |
| ax.axhline(0.5, color=GREY, lw=0.7, ls="--") | |
| ax.set_xticks([1, 2]); ax.set_xticklabels(["All domains", "HCT116 excluded"]) | |
| ax.set_ylim(-0.03, 1.12); ax.set_ylabel("External AUROC") | |
| ax.set_title("Acid-coherent graph vs degree-matched nulls") | |
| clean_axis(ax); panel(ax, "b") | |
| ax = axes[2] | |
| use = graphs[graphs.topology.isin(["full_STRING", "training_acid_coherent_STRING"])].copy() | |
| labels = [f"{'All' if r.scenario.startswith('all') else 'No HCT116'}\n{'Full' if r.topology == 'full_STRING' else 'Coherent'}" for r in use.itertuples()] | |
| ax.bar(np.arange(len(use)), use.undirected_edges, color=[BLUE, TEAL, RED, GOLD], alpha=0.8) | |
| ax.set_xticks(np.arange(len(use))); ax.set_xticklabels(labels, fontsize=6.5) | |
| ax.set_ylabel("Undirected edges") | |
| ax.set_title("The coherent graph is very sparse") | |
| for i, row in enumerate(use.itertuples()): | |
| ax.text(i, row.undirected_edges + 2, f"{row.undirected_edges}\niso={row.isolated_fraction:.0%}", ha="center", fontsize=6) | |
| clean_axis(ax); panel(ax, "c") | |
| fig.suptitle("Supplementary Fig. S1 | Acid-coherent topology remains exploratory", y=1.01, fontsize=11, fontweight="bold") | |
| save(fig, "FigS1_v5_acid_coherent_graph_null") | |
| copy_source( | |
| "v5_crc_external_topology_sensitivity.csv", | |
| "v5_crc_external_topology_graphs.csv", | |
| "v5_crc_external_coherent_graph_nulls.csv", | |
| "v5_crc_external_coherent_graph_null_summary.csv", | |
| ) | |
| def main() -> None: | |
| setup_style() | |
| fig6_crc_external_biology() | |
| fig7_crc_external_model() | |
| fig_s1_topology_null() | |
| print("Generated Fig6, Fig7 and FigS1 in PNG/PDF/SVG with source-data copies.") | |
| if __name__ == "__main__": | |
| main() | |