"""Supplementary figure: ProteinMPNN sequence-recovery on mirror-image complexes. Directly supports Reviewer R2's question about regenerating the deposited D-peptide binders (3LNJ, 8F10) from ProteinMPNN: a 3-panel figure showing (a) the per-sample recovery distribution for the stapled D-peptide 8F10 (vanilla vs soluble ProteinMPNN priors), annotated with the highest single-sequence recovery achieved; (b) the per-position recovery rate along the 8F10 peptide, highlighting the buried interface hot spots (Trp2, Tyr7, Ala8) that are recovered at high frequency even though global recovery is depressed under mirror reflection; (c) a summary of mean ± SD sampled recovery across all mirror-image crystals (3LNJ_AB/CD, 8F10_AB) versus the no-mirror L-protein control (3HTN). Reads the per-sample CSVs produced by docs/scripts/run_recovery.py and the aggregated summary / per-position tables in benchmark/recovery_test/. Style helpers are imported from plot_ablation_dl_figures so the figure matches the rest of the SI. """ from __future__ import annotations import csv import statistics from pathlib import Path import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Patch from plot_ablation_dl_figures import ( PALETTE, apply_nature_style, save_pub_fig, add_panel_label, ) ROOT = Path(__file__).resolve().parents[2] REC = ROOT / "benchmark" / "recovery_test" FIGDATA = ROOT / "benchmark" / "figure_data" CHECKPOINT_COLORS = { "vanilla": PALETTE["blue_main"], "soluble": PALETTE["orange"], } CHECKPOINT_LABELS = { "vanilla": "ProteinMPNN vanilla v_48_020", "soluble": "ProteinMPNN soluble v_48_020", } # --------------------------------------------------------------------------- # # Data loading # # --------------------------------------------------------------------------- # def load_samples(label: str, checkpoint: str) -> list[float]: """Per-sample recovery rates (one float per sampled sequence).""" path = REC / f"recovery_samples_{checkpoint}_{label}.csv" with open(path) as f: return [float(r["recovery"]) for r in csv.DictReader(f)] def load_summary() -> list[dict]: with open(REC / "recovery_summary.csv") as f: return list(csv.DictReader(f)) def load_per_position(label: str, checkpoint: str) -> list[tuple[int, str, float]]: """[(position, native_residue, recovery_rate), ...] for one crystal.""" out = [] with open(REC / "recovery_per_position.csv") as f: for r in csv.DictReader(f): if r["checkpoint"] == checkpoint and r["label"] == label: out.append((int(r["position"]), r["native_residue"], float(r["recovery_rate"]))) out.sort() return out # --------------------------------------------------------------------------- # # Panels # # --------------------------------------------------------------------------- # def plot_distribution_panel(ax): """(a) Per-sample recovery distribution for 8F10 (vanilla vs soluble).""" data = {ckpt: load_samples("8F10_AB", ckpt) for ckpt in ("vanilla", "soluble")} bins = np.linspace(0.0, 0.40, 17) for ckpt in ("vanilla", "soluble"): vals = data[ckpt] ax.hist(vals, bins=bins, density=True, alpha=0.55, color=CHECKPOINT_COLORS[ckpt], label=CHECKPOINT_LABELS[ckpt]) vanilla = data["vanilla"] vmax = max(vanilla) vmean = statistics.mean(vanilla) # mean + max annotation for the vanilla curve (the reviewer-facing number) ax.axvline(vmean, color=CHECKPOINT_COLORS["vanilla"], ls="--", lw=0.9) ax.axvline(vmax, color=PALETTE["red_strong"], ls=":", lw=1.0) ax.text(vmax, ax.get_ylim()[1] * 0.92, f"max {vmax*100:.1f}%", ha="center", va="top", fontsize=7, color=PALETTE["red_strong"], bbox=dict(boxstyle="round,pad=0.25", fc="white", ec=PALETTE["neutral_light"], lw=0.5)) ax.text(0.97, 0.95, f"8F10 stapled D-peptide (15 aa)\n" f"vanilla: mean {vmean*100:.1f}%, max {vmax*100:.1f}%\n" f"soluble: mean {statistics.mean(data['soluble'])*100:.1f}%, " f"max {max(data['soluble'])*100:.1f}%", transform=ax.transAxes, ha="right", va="top", fontsize=6.5, color=PALETTE["neutral_dark"], bbox=dict(boxstyle="round,pad=0.3", fc="white", ec=PALETTE["neutral_light"], lw=0.5)) ax.set_xlabel("Sequence recovery (fraction of native positions)") ax.set_ylabel("Density (100 samples, T = 0.1)") ax.set_xlim(0, 0.40) # Legend below the plot to avoid colliding with the stats box (upper right) # and the max-line label. ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.22), ncol=2, fontsize=6.5, frameon=False) return data def plot_per_position_panel(ax): """(b) Per-position recovery rate for 8F10 (vanilla), hot spots labelled.""" rows = load_per_position("8F10_AB", "vanilla") pos = [r[0] for r in rows] native = [r[1] for r in rows] rate = np.array([r[2] for r in rows]) x = np.arange(len(pos)) # colour bars by recovery: hot spots red, cold positions light grey. colors = [] for r in rate: if r >= 0.5: colors.append(PALETTE["red_strong"]) elif r >= 0.2: colors.append(PALETTE["blue_main"]) else: colors.append(PALETTE["neutral_light"]) ax.bar(x, rate, width=0.8, color=colors, edgecolor="white", linewidth=0.3) # native residue letter under each bar for xi, nat, r in zip(x, native, rate): ax.text(xi, r + 0.02 if r < 0.95 else r - 0.06, f"{nat}{xi+1}", ha="center", va="bottom" if r < 0.95 else "top", fontsize=6, color="black" if r < 0.5 else "black") ax.set_xticks(x) ax.set_xticklabels([f"{p}" for p in pos], fontsize=6.5) ax.set_xlabel("8F10 peptide position") ax.set_ylabel("Recovery rate (vanilla)") ax.set_ylim(0, 1.08) ax.axhline(0.5, color=PALETTE["neutral_mid"], lw=0.5, ls=":") legend_handles = [ Patch(facecolor=PALETTE["red_strong"], label="hot spot (rate ≥ 0.5)"), Patch(facecolor=PALETTE["blue_main"], label="0.2–0.5"), Patch(facecolor=PALETTE["neutral_light"], label="< 0.2"), ] ax.legend(handles=legend_handles, loc="lower right", fontsize=6.5, handlelength=1.2, frameon=False) return rows def plot_summary_panel(ax): """(c) Mean ± SD sampled recovery across all crystals + no-mirror control.""" summ = load_summary() # Use vanilla checkpoint; group mirrored crystals + show 3HTN control. order = [ ("3LNJ_AB", "vanilla", True), ("3LNJ_CD", "vanilla", True), ("8F10_AB", "vanilla", True), ("3HTN_control", "vanilla", False), ] by_key = {(s["label"], s["checkpoint"]): s for s in summ} labels = [] means = [] errs = [] colors = [] for label, ckpt, mirrored in order: s = by_key[(label, ckpt)] means.append(float(s["sampled_recovery_mean"])) errs.append(float(s["sampled_recovery_std"])) colors.append(PALETTE["blue_main"] if mirrored else PALETTE["green"]) disp = "8F10_AB\n(D-stapled)" if label == "8F10_AB" else \ ("3HTN_control\n(L, no mirror)" if not mirrored else label) labels.append(disp) x = np.arange(len(labels)) ax.bar(x, means, yerr=errs, width=0.6, color=colors, edgecolor="white", linewidth=0.4, error_kw=dict(ecolor=PALETTE["neutral_dark"], lw=0.8, capsize=2)) for xi, m in zip(x, means): ax.text(xi, m + 0.015, f"{m*100:.0f}%", ha="center", va="bottom", fontsize=6.5, color=PALETTE["neutral_dark"]) ax.axhline(0.5, color=PALETTE["green"], lw=0.6, ls=":") ax.text(len(labels) - 0.4, 0.51, "no-mirror control ~50%", ha="right", va="bottom", fontsize=6, color=PALETTE["green"]) ax.set_xticks(x) ax.set_xticklabels(labels, fontsize=6.5) ax.set_ylabel("Sampled recovery (mean ± SD)") ax.set_ylim(0, 0.60) return means # --------------------------------------------------------------------------- # # Main # # --------------------------------------------------------------------------- # def main(): apply_nature_style(font_size=8) fig, axes = plt.subplots(1, 3, figsize=(9.6, 2.9), gridspec_kw={"width_ratios": [1.1, 1.3, 1.0]}) plot_distribution_panel(axes[0]) add_panel_label(axes[0], "a") plot_per_position_panel(axes[1]) add_panel_label(axes[1], "b") plot_summary_panel(axes[2]) add_panel_label(axes[2], "c") fig.subplots_adjust(wspace=0.42, left=0.07, right=0.985, bottom=0.16, top=0.95) save_pub_fig(fig, "fig_mpnn_recovery_distribution") # ---- export the figure data ------------------------------------------- # FIGDATA.mkdir(parents=True, exist_ok=True) FIGDATA.joinpath("fig_mpnn_recovery_distribution_8F10.csv").write_text( "checkpoint,sample,recovery\n" + "".join(f"{ckpt},{i},{v}\n" for ckpt in ("vanilla", "soluble") for i, v in enumerate(load_samples("8F10_AB", ckpt))) ) rows = load_per_position("8F10_AB", "vanilla") FIGDATA.joinpath("fig_mpnn_recovery_per_position.csv").write_text( "position,native_residue,recovery_rate\n" + "".join(f"{p},{n},{r}\n" for p, n, r in rows) ) # ---- console summary --------------------------------------------------- # v = load_samples("8F10_AB", "vanilla") s = load_samples("8F10_AB", "soluble") print("=== 8F10 sequence recovery (ProteinMPNN) ===") print(f"vanilla: n={len(v)} mean={statistics.mean(v)*100:.1f}% " f"SD={statistics.pstdev(v)*100:.1f}% max={max(v)*100:.1f}%") print(f"soluble: n={len(s)} mean={statistics.mean(s)*100:.1f}% " f"SD={statistics.pstdev(s)*100:.1f}% max={max(s)*100:.1f}%") print("Hot spots (vanilla, per-position rate ≥ 0.5):") for p, n, r in rows: if r >= 0.5: print(f" position {p} ({n}): {r*100:.0f}%") if __name__ == "__main__": main()