Datasets:
Add MirrorPeptidizer benchmark (D/L comparison, new targets, ablation, figure data, SI)
0613483 verified Download scripts/plot_representative_structures.py from dahuilangda/MirrorPeptidizer: direct link, hf CLI and curl.
- Browser
- Download file 9.9 kB
-
https://huggingface.co/datasets/dahuilangda/MirrorPeptidizer/resolve/main/scripts/plot_representative_structures.py
- Command line
-
hf download hf://datasets/dahuilangda/MirrorPeptidizer/scripts/plot_representative_structures.py
-
curl -L -o plot_representative_structures.py https://huggingface.co/datasets/dahuilangda/MirrorPeptidizer/resolve/main/scripts/plot_representative_structures.py
9.9 kB
| """Supplementary figure: representative D-peptide backbones from distinct | |
| surface-site clusters. | |
| For each design target (MDM2, PDL1, IL23R) the two largest surface-site | |
| clusters are selected and one representative backbone (the cluster centroid) | |
| is rendered as a 3D Cα trace: receptor in light grey, designed peptide in the | |
| target colour. This directly addresses the reviewer's request for | |
| "representative structures from distinct surface-site clusters". | |
| Rendering is done entirely in matplotlib (mplot3d) — no PyMOL dependency — and | |
| the figure follows the same publication style (PALETTE, apply_nature_style, | |
| save_pub_fig → PDF+PNG+SVG) as the rest of the SI. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| from mpl_toolkits.mplot3d import Axes3D # noqa: F401 (registers 3d projection) | |
| 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"], | |
| } | |
| N_REPS_PER_TARGET = 2 # pick the N largest clusters per target | |
| # --------------------------------------------------------------------------- # | |
| # PDB parsing # | |
| # --------------------------------------------------------------------------- # | |
| def parse_ca_coords(pdb_path: Path) -> dict[str, np.ndarray]: | |
| """Return {chain_id: (N, 3) array of Cα coordinates} from a PDB file.""" | |
| coords: dict[str, list[list[float]]] = {} | |
| with open(pdb_path) as f: | |
| for line in f: | |
| if not line.startswith(("ATOM", "HETATM")): | |
| continue | |
| atom = line[13:15].strip() | |
| if atom != "CA": | |
| continue | |
| chain = line[21] | |
| x = float(line[30:38]) | |
| y = float(line[38:46]) | |
| z = float(line[46:54]) | |
| coords.setdefault(chain, []).append([x, y, z]) | |
| return {ch: np.array(v) for ch, v in coords.items()} | |
| # --------------------------------------------------------------------------- # | |
| # Structure selection # | |
| # --------------------------------------------------------------------------- # | |
| def select_representatives() -> pd.DataFrame: | |
| """Pick the N largest-cluster representatives per target. | |
| Reads the per-backbone cluster assignment CSV (produced by | |
| plot_si_design_landscape.py) and the cluster-representative table, then | |
| keeps the representatives belonging to the N largest clusters per target. | |
| """ | |
| clusters = pd.read_csv(FIGDATA / "fig_si_design_landscape_clusters.csv") | |
| reps = pd.read_csv( | |
| FIGDATA / "fig_si_design_landscape_cluster_representatives.csv") | |
| # cluster sizes per target | |
| sizes = (clusters.groupby(["target", "cluster"]) | |
| .size().reset_index(name="size")) | |
| selected = [] | |
| for target in TARGETS: | |
| tsizes = sizes[sizes["target"] == target].sort_values( | |
| "size", ascending=False) | |
| top_clusters = tsizes.head(N_REPS_PER_TARGET)["cluster"].tolist() | |
| for cl in top_clusters: | |
| row = reps[(reps["target"] == target) | |
| & (reps["cluster"] == cl)].iloc[0] | |
| sz = int(tsizes[tsizes["cluster"] == cl]["size"].iloc[0]) | |
| selected.append({ | |
| "target": target, | |
| "cluster": int(cl), | |
| "cluster_size": sz, | |
| "pose": int(row["pose"]), | |
| "length": int(row["length"]), | |
| "sequence": row["sequence"], | |
| "score": row["score"], | |
| "pose_pdb": str(ROOT / row["pose_pdb"]), | |
| }) | |
| return pd.DataFrame(selected) | |
| # --------------------------------------------------------------------------- # | |
| # 3D rendering # | |
| # --------------------------------------------------------------------------- # | |
| def plot_structure_3d(ax, pdb_path: Path, target: str, info: dict): | |
| """Render receptor (grey Cα trace) + peptide (coloured Cα trace) in 3D.""" | |
| coords = parse_ca_coords(pdb_path) | |
| # Chain A = receptor, chain B = peptide (convention from the pipeline). | |
| rec_chain = "A" if "A" in coords else sorted(coords.keys())[0] | |
| pep_chain = "B" if "B" in coords else sorted(coords.keys())[-1] | |
| rec = coords[rec_chain] | |
| pep = coords[pep_chain] | |
| # Receptor: thin, semi-transparent grey Cα trace. | |
| ax.plot(rec[:, 0], rec[:, 1], rec[:, 2], | |
| color=PALETTE["neutral_light"], linewidth=0.6, alpha=0.35, | |
| zorder=1) | |
| ax.scatter(rec[:, 0], rec[:, 1], rec[:, 2], | |
| s=1.5, color=PALETTE["neutral_light"], alpha=0.25, | |
| depthshade=True, zorder=1) | |
| # Peptide: thick coloured Cα trace with residue markers. | |
| color = TARGET_COLORS[target] | |
| ax.plot(pep[:, 0], pep[:, 1], pep[:, 2], | |
| color=color, linewidth=2.2, alpha=0.95, zorder=3) | |
| ax.scatter(pep[:, 0], pep[:, 1], pep[:, 2], | |
| s=22, color=color, edgecolors="white", linewidths=0.3, | |
| depthshade=True, zorder=4) | |
| # Mark N- and C-termini of the peptide. | |
| ax.scatter(pep[0, 0], pep[0, 1], pep[0, 2], s=40, marker="v", | |
| color=color, edgecolors="black", linewidths=0.4, zorder=5) | |
| ax.scatter(pep[-1, 0], pep[-1, 1], pep[-1, 2], s=40, marker="^", | |
| color=color, edgecolors="black", linewidths=0.4, zorder=5) | |
| # Centre the view on the peptide centroid for a consistent framing. | |
| centre = pep.mean(axis=0) | |
| span = max(rec.ptp(axis=0).max(), 20.0) * 0.55 | |
| ax.set_xlim(centre[0] - span, centre[0] + span) | |
| ax.set_ylim(centre[1] - span, centre[1] + span) | |
| ax.set_zlim(centre[2] - span, centre[2] + span) | |
| # Clean 3D axes: no ticks, light panes. | |
| ax.set_xticks([]) | |
| ax.set_yticks([]) | |
| ax.set_zticks([]) | |
| for pane_axis in (ax.xaxis, ax.yaxis, ax.zaxis): | |
| pane_axis.pane.set_facecolor((1, 1, 1, 0.0)) | |
| pane_axis.pane.set_edgecolor((0.9, 0.9, 0.9, 0.5)) | |
| pane_axis.line.set_color((0.8, 0.8, 0.8, 0.5)) | |
| ax.grid(False) | |
| # Consistent viewing angle. | |
| ax.view_init(elev=18, azim=-55) | |
| # Title with target, cluster, pose, length. | |
| ax.set_title( | |
| f"{target} cluster {info['cluster']} (n={info['cluster_size']})\n" | |
| f"pose {info['pose']} · {info['length']} aa", | |
| fontsize=7, color=PALETTE["neutral_dark"], pad=2) | |
| # --------------------------------------------------------------------------- # | |
| # Main # | |
| # --------------------------------------------------------------------------- # | |
| def main(): | |
| apply_nature_style(font_size=8) | |
| reps = select_representatives() | |
| n_rows = N_REPS_PER_TARGET # 2 representatives per target | |
| n_cols = len(TARGETS) # 3 targets | |
| fig, axes = plt.subplots(n_rows, n_cols, | |
| figsize=(8.4, 5.8), | |
| subplot_kw={"projection": "3d"}) | |
| axes = np.atleast_2d(axes) | |
| for row in range(n_rows): | |
| for col, target in enumerate(TARGETS): | |
| ax = axes[row, col] | |
| idx = col * n_rows + row # column-major: target groups by column | |
| info = reps.iloc[idx] | |
| plot_structure_3d(ax, Path(info["pose_pdb"]), | |
| target, info) | |
| # Column header on the first row only. | |
| if row == 0: | |
| ax.text2D(0.5, 1.08, target, transform=ax.transAxes, | |
| ha="center", va="bottom", fontsize=8.5, | |
| fontweight="bold", | |
| color=TARGET_COLORS[target]) | |
| # Panel label (use text2D because Axes3D.text requires 3D coordinates). | |
| # Place it well above the 3D box and outside the subplot so tight bbox | |
| # captures it cleanly without clipping. | |
| axes[0, 0].text2D(0.0, 1.18, "a", transform=axes[0, 0].transAxes, | |
| fontsize=10, fontweight="bold", color="black", | |
| ha="left", va="bottom") | |
| # Legend (receptor vs peptide vs termini) — placed below. | |
| from matplotlib.lines import Line2D | |
| legend_handles = [ | |
| Line2D([0], [0], color=PALETTE["neutral_light"], lw=1.2, | |
| alpha=0.6, label="receptor (Cα trace)"), | |
| Line2D([0], [0], color=PALETTE["blue_main"], lw=2.2, | |
| label="designed D-peptide"), | |
| Line2D([0], [0], marker="v", color="w", markerfacecolor=PALETTE["blue_main"], | |
| markersize=7, label="N-terminus"), | |
| Line2D([0], [0], marker="^", color="w", markerfacecolor=PALETTE["blue_main"], | |
| markersize=7, label="C-terminus"), | |
| ] | |
| fig.legend(handles=legend_handles, loc="lower center", | |
| ncol=4, fontsize=7, bbox_to_anchor=(0.5, -0.01), | |
| handletextpad=0.4, columnspacing=1.2) | |
| fig.subplots_adjust(left=-0.02, right=1.02, top=0.92, bottom=0.06, | |
| wspace=0.02, hspace=0.15) | |
| save_pub_fig(fig, "fig_si_representative_structures") | |
| # Export the selection table. | |
| reps_out = reps.drop(columns=["pose_pdb"]).copy() | |
| reps_out["pose_pdb"] = reps["pose_pdb"].str.replace( | |
| str(ROOT) + "/", "", regex=False) | |
| reps_out.to_csv(FIGDATA / "fig_si_representative_structures.csv", | |
| index=False) | |
| # Console summary. | |
| print("\n=== Representative structures (selected) ===") | |
| print(reps_out[["target", "cluster", "cluster_size", "pose", "length", | |
| "sequence", "score"]].to_string(index=False)) | |
| if __name__ == "__main__": | |
| main() | |