Datasets:
File size: 10,452 Bytes
0613483 | 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 | """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()
|