Datasets:
Add MirrorPeptidizer benchmark (D/L comparison, new targets, ablation, figure data, SI)
0613483 verified Download scripts/plot_si_design_landscape.py from dahuilangda/MirrorPeptidizer: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/datasets/dahuilangda/MirrorPeptidizer/resolve/main/scripts/plot_si_design_landscape.py
- Command line
-
hf download hf://datasets/dahuilangda/MirrorPeptidizer/scripts/plot_si_design_landscape.py
-
curl -L -o plot_si_design_landscape.py https://huggingface.co/datasets/dahuilangda/MirrorPeptidizer/resolve/main/scripts/plot_si_design_landscape.py
18.7 kB
| """Supplementary figure: D-peptide design landscape for MDM2, PDL1, IL23R. | |
| A single combined SI figure (4 rows x 3 target columns) summarising, for the | |
| retained D-peptide designs of each target: | |
| (a) peptide-length distribution of retained sequences | |
| (b) secondary-structure composition (helix / sheet / ppII / coil) | |
| (c) receptor-contact fingerprints (fraction of residues touching receptor) | |
| (d) distinct surface-site backbone clusters (PCA of surface geometry, with | |
| one representative backbone labelled per cluster) | |
| All data are read from existing benchmark CSVs; no new computation on PDBs is | |
| required. Style helpers (PALETTE, apply_nature_style, save_pub_fig, | |
| add_panel_label) are imported from plot_ablation_dl_figures so this script stays | |
| consistent with the rest of the SI figures. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| from matplotlib.lines import Line2D | |
| from matplotlib.patches import Patch | |
| # Shared publication style (same source as the other SI figures). | |
| from plot_ablation_dl_figures import ( | |
| PALETTE, | |
| apply_nature_style, | |
| save_pub_fig, | |
| add_panel_label, | |
| ) | |
| ROOT = Path(__file__).resolve().parents[2] | |
| BENCH = ROOT / "benchmark" | |
| FIGDATA = BENCH / "figure_data" | |
| TARGETS = ["MDM2", "PDL1", "IL23R"] | |
| TARGET_COLORS = { | |
| "MDM2": PALETTE["blue_main"], | |
| "PDL1": PALETTE["blue_secondary"], | |
| "IL23R": PALETTE["orange"], | |
| } | |
| # SS panel colours: a readable 4-class ramp anchored on the blue family. | |
| SS_CLASSES = ["ss_helix", "ss_sheet", "ss_ppII", "ss_coil"] | |
| SS_LABELS = ["Helix", "Sheet", "ppII", "Coil"] | |
| SS_COLORS = [ | |
| PALETTE["blue_main"], | |
| PALETTE["green"], | |
| PALETTE["orange"], | |
| PALETTE["neutral_light"], | |
| ] | |
| # Discrete cluster palette (distinguishable, colour-blind friendly-ish). | |
| CLUSTER_COLORS = [ | |
| PALETTE["blue_main"], | |
| PALETTE["orange"], | |
| PALETTE["green"], | |
| PALETTE["red_strong"], | |
| PALETTE["blue_light"], | |
| PALETTE["neutral_mid"], | |
| ] | |
| # Surface-geometry features used to define a binding-site cluster. | |
| GEOMETRY_FEATURES = [ | |
| "radial_percentile", | |
| "outward_nearby_fraction", | |
| "binder_atoms_within_contact", | |
| "median_receptor_distance", | |
| ] | |
| RANDOM_STATE = 42 | |
| # --------------------------------------------------------------------------- # | |
| # Data loading # | |
| # --------------------------------------------------------------------------- # | |
| def load_retained(target: str) -> pd.DataFrame: | |
| """Retained D-peptide sequences for a target (post geometry + complexity QC).""" | |
| path = BENCH / "dl_downsampled" / f"{target}_D_peptide_filtered.csv" | |
| df = pd.read_csv(path) | |
| df = df.dropna(subset=["score", "sequence"]).copy() | |
| df["length"] = df["length"].astype(int) | |
| return df | |
| def load_ss_contacts() -> pd.DataFrame: | |
| """Per-pose secondary structure + receptor-contact fingerprint (D-peptide).""" | |
| path = BENCH / "poly_alanine_diagnosis.csv" | |
| df = pd.read_csv(path) | |
| df = df[df["target"].isin(TARGETS)].copy() | |
| return df | |
| def load_surface_backbones(target: str) -> pd.DataFrame: | |
| """Surface-passing D-peptide backbones for a target (one row per backbone PDB).""" | |
| path = BENCH / "geometric_pose_classification.csv" | |
| df = pd.read_csv(path) | |
| sub = df[ | |
| (df["target"] == target) | |
| & (df["peptide_mode"] == "D_peptide") | |
| & (df["passes_surface"] == True) # noqa: E712 — pandas truthiness | |
| ].copy() | |
| # pose_pdb is the unique per-backbone key (length,pose is 2x duplicated). | |
| sub = sub.drop_duplicates(subset=["pose_pdb"]).reset_index(drop=True) | |
| return sub | |
| # --------------------------------------------------------------------------- # | |
| # Panel helpers # | |
| # --------------------------------------------------------------------------- # | |
| def plot_length_panel(ax, df: pd.DataFrame, target: str): | |
| """Row (a): retained-sequence counts per peptide length, stacked bars.""" | |
| counts = df.groupby("length").size().sort_index() | |
| lengths = counts.index.tolist() | |
| color = TARGET_COLORS[target] | |
| ax.bar(lengths, counts.values, width=0.8, color=color, edgecolor="white", | |
| linewidth=0.3) | |
| for x, y in zip(lengths, counts.values): | |
| ax.text(x, y, f"{int(y)}", ha="center", va="bottom", fontsize=6, | |
| color=PALETTE["neutral_dark"]) | |
| ax.set_xlabel("Peptide length (residues)") | |
| if target == TARGETS[0]: | |
| ax.set_ylabel("Retained sequences") | |
| ax.set_ylim(0, counts.max() * 1.18) | |
| ax.set_xticks(lengths) | |
| return counts | |
| def plot_ss_panel(ax, ss_df: pd.DataFrame, target: str): | |
| """Row (b): mean fractional secondary-structure composition, stacked bar.""" | |
| sub = ss_df[ss_df["target"] == target] | |
| means = np.array([sub[c].mean() for c in SS_CLASSES]) | |
| # Renormalise the four classes so they sum to 1 (they already nearly do). | |
| means = means / means.sum() | |
| cum = 0.0 | |
| for frac, label, color in zip(means, SS_LABELS, SS_COLORS): | |
| ax.bar(0, frac, bottom=cum, width=0.6, color=color, edgecolor="white", | |
| linewidth=0.4) | |
| if frac >= 0.04: | |
| ax.text(0, cum + frac / 2, f"{label}\n{frac*100:.0f}%", | |
| ha="center", va="center", fontsize=6.5, | |
| color="white" if color != PALETTE["neutral_light"] else | |
| PALETTE["neutral_dark"]) | |
| cum += frac | |
| ax.set_xlim(-0.6, 0.6) | |
| ax.set_ylim(0, 1) | |
| ax.set_xticks([0]) | |
| ax.set_xticklabels([target]) | |
| ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0]) | |
| if target == TARGETS[0]: | |
| ax.set_ylabel("Mean SS fraction") | |
| # Always list the full 4-class breakdown so thin segments (e.g. MDM2, | |
| # which is ~90% helix) are visible even when their in-bar label is suppressed. | |
| breakdown = " ".join(f"{l}:{m*100:.0f}%" for l, m in zip(SS_LABELS, means)) | |
| ax.text(0.5, -0.22, f"{breakdown}\nn = {len(sub)} poses", | |
| transform=ax.transAxes, ha="center", va="top", fontsize=6, | |
| color=PALETTE["neutral_mid"]) | |
| return means | |
| def plot_contact_panel(ax, ss_df: pd.DataFrame, target: str): | |
| """Row (c): receptor-contact fingerprint violin (frac residues touching).""" | |
| sub = ss_df[ss_df["target"] == target] | |
| vals = sub["frac_residues_touching_receptor"].values | |
| color = TARGET_COLORS[target] | |
| parts = ax.violinplot([vals], positions=[0], widths=0.7, showextrema=False) | |
| for body in parts["bodies"]: | |
| body.set_facecolor(color) | |
| body.set_edgecolor(color) | |
| body.set_alpha(0.45) | |
| bp = ax.boxplot([vals], positions=[0], widths=0.15, patch_artist=True, | |
| showfliers=False, zorder=3) | |
| for elem in bp["boxes"]: | |
| elem.set_facecolor("white") | |
| elem.set_edgecolor(PALETTE["neutral_dark"]) | |
| elem.set_linewidth(0.7) | |
| for elem in bp["medians"]: | |
| elem.set_color(PALETTE["red_strong"]) | |
| elem.set_linewidth(1.0) | |
| for elem in bp["whiskers"]: | |
| elem.set_color(PALETTE["neutral_dark"]) | |
| elem.set_linewidth(0.7) | |
| # jittered observations | |
| rng = np.random.default_rng(RANDOM_STATE) | |
| jitter = rng.uniform(-0.12, 0.12, size=len(vals)) | |
| ax.scatter(jitter, vals, s=6, color=color, alpha=0.55, edgecolors="none", | |
| zorder=2, rasterized=True) | |
| med = float(np.median(vals)) | |
| ax.axhline(med, color=PALETTE["red_strong"], lw=0.6, ls="--", zorder=1) | |
| ax.text(0.48, med, f"med {med:.2f}", transform=ax.get_yaxis_transform(), | |
| ha="left", va="center", fontsize=6.5, color=PALETTE["red_strong"]) | |
| ax.set_xlim(-0.6, 0.6) | |
| ax.set_ylim(-0.02, 1.02) | |
| ax.set_xticks([0]) | |
| ax.set_xticklabels([target]) | |
| if target == TARGETS[0]: | |
| ax.set_ylabel("Frac. residues\ntouching receptor") | |
| ax.text(0.5, -0.22, f"n = {len(sub)} poses", transform=ax.transAxes, | |
| ha="center", va="top", fontsize=6.5, color=PALETTE["neutral_mid"]) | |
| return vals | |
| def _cluster_backbones(df: pd.DataFrame): | |
| """PCA(2D) + KMeans on standardised surface-geometry features. | |
| Returns (embedding, labels, k, representative_idx, model) where | |
| representative_idx is the row index of the backbone nearest each centroid. | |
| """ | |
| from sklearn.preprocessing import StandardScaler | |
| from sklearn.decomposition import PCA | |
| from sklearn.cluster import KMeans | |
| from sklearn.metrics import silhouette_score | |
| # Build feature matrix: continuous geometry metrics + one-hot of the | |
| # occupied-octant count (the spatial spread signature of the binding site). | |
| feat = df[GEOMETRY_FEATURES].astype(float).values | |
| oct_count = df["occupied_octants"].astype(int).clip(0, 8).values | |
| n_oct = 9 | |
| onehot = np.eye(n_oct)[oct_count] | |
| X = np.hstack([feat, onehot]) | |
| Xs = StandardScaler().fit_transform(X) | |
| pca = PCA(n_components=2, random_state=RANDOM_STATE) | |
| emb = pca.fit_transform(Xs) | |
| # Choose k by silhouette score in [3, 6], bounded by sample count. | |
| n = len(df) | |
| k_max = min(6, max(3, n - 1)) | |
| candidates = range(3, k_max + 1) | |
| best_k, best_score, best_labels = 4, -1.0, None | |
| for k in candidates: | |
| km = KMeans(n_clusters=k, random_state=RANDOM_STATE, n_init=10).fit(Xs) | |
| if len(set(km.labels_)) < 2: | |
| continue | |
| s = silhouette_score(Xs, km.labels_) | |
| if s > best_score: | |
| best_score, best_k, best_labels = s, k, km.labels_ | |
| km = KMeans(n_clusters=best_k, random_state=RANDOM_STATE, n_init=10).fit(Xs) | |
| labels = km.labels_ | |
| # Representative per cluster = backbone whose PCA embedding is nearest the | |
| # cluster's mean embedding in PCA space. | |
| rep_idx = [] | |
| for c in range(best_k): | |
| members = np.where(labels == c)[0] | |
| if len(members) == 0: | |
| rep_idx.append(None) | |
| continue | |
| centroid = emb[members].mean(axis=0) | |
| d = np.linalg.norm(emb[members] - centroid, axis=1) | |
| rep_idx.append(int(members[np.argmin(d)])) | |
| return emb, labels, best_k, rep_idx, pca | |
| def plot_cluster_panel(ax, surf_df: pd.DataFrame, target: str, | |
| representatives: list[dict]): | |
| """Row (d): surface-site backbone clusters in PCA space.""" | |
| df = surf_df.reset_index(drop=True) | |
| emb, labels, k, rep_idx, pca = _cluster_backbones(df) | |
| for c in range(k): | |
| m = labels == c | |
| ax.scatter(emb[m, 0], emb[m, 1], s=14, alpha=0.65, | |
| color=CLUSTER_COLORS[c % len(CLUSTER_COLORS)], | |
| edgecolors="none", rasterized=True) | |
| if rep_idx[c] is not None: | |
| ax.scatter(emb[rep_idx[c], 0], emb[rep_idx[c], 1], s=70, | |
| marker="*", color=CLUSTER_COLORS[c % len(CLUSTER_COLORS)], | |
| edgecolors="black", linewidths=0.5, zorder=5) | |
| pose = df.loc[rep_idx[c], "pose"] | |
| length = df.loc[rep_idx[c], "length"] | |
| ax.annotate( | |
| f"#{int(pose)}\n({int(length)} aa)", | |
| xy=(emb[rep_idx[c], 0], emb[rep_idx[c], 1]), | |
| xytext=(4, 4), textcoords="offset points", | |
| fontsize=6, color=PALETTE["neutral_dark"], | |
| ) | |
| representatives.append({ | |
| "target": target, | |
| "cluster": c + 1, | |
| "pose": int(pose), | |
| "length": int(length), | |
| "pose_pdb": df.loc[rep_idx[c], "pose_pdb"], | |
| }) | |
| ev = pca.explained_variance_ratio_ | |
| ax.set_xlabel(f"PC1 ({ev[0]*100:.0f}%)") | |
| if target == TARGETS[0]: | |
| ax.set_ylabel(f"PC2 ({ev[1]*100:.0f}%)") | |
| ax.set_xticks([]) | |
| ax.set_yticks([]) | |
| ax.set_title(f"{target} (k={k})", fontsize=8, color=PALETTE["neutral_dark"]) | |
| return k | |
| # --------------------------------------------------------------------------- # | |
| # Main # | |
| # --------------------------------------------------------------------------- # | |
| def main(): | |
| apply_nature_style(font_size=8) | |
| retained = {t: load_retained(t) for t in TARGETS} | |
| ss_df = load_ss_contacts() | |
| # Sanity-check against the SI table (unique retained D-peptide sequences). | |
| expected_unique = {"MDM2": 1804, "PDL1": 1676, "IL23R": 1262} | |
| for t in TARGETS: | |
| n_uniq = retained[t]["sequence"].nunique() | |
| if n_uniq != expected_unique[t]: | |
| print(f" [warn] {t}: {n_uniq} unique sequences " | |
| f"(SI table expects {expected_unique[t]})") | |
| # Export the underlying figure data. | |
| FIGDATA.mkdir(parents=True, exist_ok=True) | |
| pd.concat( | |
| [retained[t].assign(target=t) for t in TARGETS], | |
| ignore_index=True, | |
| )[["target", "length", "pose", "sequence", "score"]].to_csv( | |
| FIGDATA / "fig_si_design_landscape_length.csv", index=False | |
| ) | |
| ss_export = ss_df[["target", "length", "pose", "sequence", "score", | |
| *SS_CLASSES, "mean_receptor_contacts_per_res", | |
| "frac_residues_touching_receptor"]] | |
| ss_export.to_csv(FIGDATA / "fig_si_design_landscape_ss.csv", index=False) | |
| ss_export.to_csv(FIGDATA / "fig_si_design_landscape_contacts.csv", | |
| index=False) | |
| # ----- assemble the figure: 4 rows x 3 target columns ------------------- # | |
| fig, axes = plt.subplots( | |
| 4, 3, figsize=(9.2, 9.4), | |
| gridspec_kw={"height_ratios": [1.0, 0.85, 0.95, 1.15]}, | |
| ) | |
| representatives: list[dict] = [] | |
| for col, target in enumerate(TARGETS): | |
| # (a) length | |
| ax = axes[0, col] | |
| plot_length_panel(ax, retained[target], target) | |
| add_panel_label(ax, "a" if col == 0 else "") | |
| if col != 0: | |
| ax.set_ylabel("") | |
| # (b) secondary structure | |
| ax = axes[1, col] | |
| plot_ss_panel(ax, ss_df, target) | |
| add_panel_label(ax, "b" if col == 0 else "") | |
| # (c) receptor contacts | |
| ax = axes[2, col] | |
| plot_contact_panel(ax, ss_df, target) | |
| add_panel_label(ax, "c" if col == 0 else "") | |
| # (d) surface-site clusters | |
| ax = axes[3, col] | |
| surf = load_surface_backbones(target) | |
| k = plot_cluster_panel(ax, surf, target, representatives) | |
| add_panel_label(ax, "d" if col == 0 else "") | |
| # Shared legends, stacked vertically below the figure grid so they cannot | |
| # overlap each other (the cluster legend is wide at 7 items) and stay clear | |
| # of the "a/b/c/d" panel labels at the top. | |
| ss_handles = [Patch(facecolor=c, edgecolor="white", label=l) | |
| for c, l in zip(SS_COLORS, SS_LABELS)] | |
| cluster_handles = [Line2D([0], [0], marker="o", color="w", | |
| markerfacecolor=CLUSTER_COLORS[i % len(CLUSTER_COLORS)], | |
| markersize=6, label=f"cluster {i+1}") | |
| for i in range(6)] | |
| star_handle = Line2D([0], [0], marker="*", color="w", | |
| markerfacecolor=PALETTE["neutral_mid"], | |
| markeredgecolor="black", markersize=9, | |
| label="representative") | |
| # cluster legend on the lower row (it's wider), SS legend above it. | |
| fig.legend(handles=cluster_handles + [star_handle], loc="lower center", | |
| bbox_to_anchor=(0.5, -0.01), ncol=8, fontsize=7, | |
| handletextpad=0.3, columnspacing=0.7, | |
| title="Surface-site clusters", title_fontsize=7, | |
| borderaxespad=0) | |
| fig.legend(handles=ss_handles, loc="lower center", | |
| bbox_to_anchor=(0.5, 0.045), ncol=4, fontsize=7, | |
| handletextpad=0.4, columnspacing=1.0, | |
| title="Secondary structure", title_fontsize=7, | |
| borderaxespad=0) | |
| # Reserve room at the bottom for the two stacked legends. | |
| fig.subplots_adjust(hspace=0.62, wspace=0.28, top=0.97, bottom=0.12, | |
| left=0.09, right=0.975) | |
| # NOTE: save_pub_fig() runs tight_layout(pad=1.2), which fights the manual | |
| # margins and the bottom figlegend on this complex 4x3 grid. Save directly | |
| # with the same triple-format + dpi convention so style stays consistent. | |
| FIGDIR = BENCH / "figures" | |
| FIGDIR.mkdir(parents=True, exist_ok=True) | |
| for ext in ("svg", "pdf", "png"): | |
| fig.savefig(FIGDIR / f"fig_si_design_landscape.{ext}", | |
| bbox_inches="tight", | |
| dpi=300 if ext == "png" else None) | |
| plt.close(fig) | |
| # Persist representatives + per-backbone cluster assignments. | |
| rep_df = pd.DataFrame(representatives) | |
| # Attach the best-score designed sequence for the representative backbone. | |
| # A backbone is keyed by (target, length, pose) — `pose` alone is reused | |
| # across lengths within a target. | |
| seq_lookup = {} | |
| for t in TARGETS: | |
| best = (retained[t].sort_values("score") | |
| .drop_duplicates(["length", "pose"], keep="first")) | |
| seq_lookup[t] = dict(zip(zip(best["length"], best["pose"]), | |
| zip(best["sequence"], best["score"]))) | |
| rep_df[["sequence", "score"]] = rep_df.apply( | |
| lambda r: pd.Series(seq_lookup[r["target"]].get( | |
| (int(r["length"]), int(r["pose"])), ("", np.nan))), | |
| axis=1, | |
| ) | |
| rep_df = rep_df[["target", "cluster", "pose", "length", "sequence", "score", | |
| "pose_pdb"]] | |
| rep_df.to_csv(FIGDATA / "fig_si_design_landscape_cluster_representatives.csv", | |
| index=False) | |
| # Persist per-backbone cluster membership (full, for reproducibility). | |
| cluster_rows = [] | |
| for t in TARGETS: | |
| surf = load_surface_backbones(t).reset_index(drop=True) | |
| _, labels, k, _, _ = _cluster_backbones(surf) | |
| for i, row in surf.iterrows(): | |
| cluster_rows.append({ | |
| "target": t, "pose": int(row["pose"]), "length": int(row["length"]), | |
| "cluster": int(labels[i]) + 1, | |
| "pose_pdb": row["pose_pdb"], | |
| }) | |
| pd.DataFrame(cluster_rows).to_csv( | |
| FIGDATA / "fig_si_design_landscape_clusters.csv", index=False) | |
| # ----- console summary (for the rebuttal) ------------------------------ # | |
| print("\n=== SI design-landscape summary ===") | |
| for t in TARGETS: | |
| surf = load_surface_backbones(t) | |
| _, _, k, _, _ = _cluster_backbones(surf.reset_index(drop=True)) | |
| ss_n = (ss_df["target"] == t).sum() | |
| print(f"{t}: retained={len(retained[t])} " | |
| f"(unique {retained[t]['sequence'].nunique()}), " | |
| f"SS poses={ss_n}, surface backbones={len(surf)}, clusters k={k}") | |
| print("\nCluster representatives:") | |
| print(rep_df.to_string(index=False)) | |
| if __name__ == "__main__": | |
| main() | |