"""Generate publication figures for ablation and D/L comparison results.""" from pathlib import Path import re import matplotlib.pyplot as plt import numpy as np import pandas as pd ROOT = Path(__file__).resolve().parents[2] BENCH = ROOT / "benchmark" FIGDIR = BENCH / "figures" PALETTE = { "blue_main": "#0F4D92", "blue_secondary": "#3775BA", "blue_light": "#7BAED4", "orange": "#E28E2C", "green": "#5BAA5B", "red_strong": "#B64342", "neutral_light": "#CFCECE", "neutral_mid": "#767676", "neutral_dark": "#4D4D4D", } MODE_LABELS = { "chroma+proteinmpnn": "Chroma+ProteinMPNN", "chroma+bo": "Chroma+BO", "chroma+proteinmpnn+bo": "Chroma+ProteinMPNN+BO", } MODE_COLORS = { "chroma+proteinmpnn": PALETTE["red_strong"], "chroma+bo": PALETTE["orange"], "chroma+proteinmpnn+bo": PALETTE["blue_main"], } TARGETS = ["PDL1", "MDM2", "IL23R"] def apply_nature_style(font_size=8, axes_linewidth=0.8): plt.rcParams["font.family"] = "sans-serif" plt.rcParams["font.sans-serif"] = ["Arial", "DejaVu Sans", "Liberation Sans"] plt.rcParams["svg.fonttype"] = "none" plt.rcParams["pdf.fonttype"] = 42 plt.rcParams["axes.spines.right"] = False plt.rcParams["axes.spines.top"] = False plt.rcParams["axes.linewidth"] = axes_linewidth plt.rcParams["legend.frameon"] = False plt.rcParams["font.size"] = font_size plt.rcParams["axes.titlesize"] = font_size + 1 plt.rcParams["axes.labelsize"] = font_size + 1 plt.rcParams["xtick.labelsize"] = font_size plt.rcParams["ytick.labelsize"] = font_size plt.rcParams["legend.fontsize"] = font_size plt.rcParams["axes.grid"] = False plt.rcParams["xtick.direction"] = "out" plt.rcParams["ytick.direction"] = "out" plt.rcParams["xtick.major.width"] = axes_linewidth plt.rcParams["ytick.major.width"] = axes_linewidth plt.rcParams["xtick.major.size"] = 3 plt.rcParams["ytick.major.size"] = 3 def add_panel_label(ax, label): ax.text( -0.10, 1.05, label, transform=ax.transAxes, fontsize=9, fontweight="bold", color="black", ha="left", va="bottom", ) def save_pub_fig(fig, name): FIGDIR.mkdir(parents=True, exist_ok=True) fig.tight_layout(pad=1.2) fig.savefig(FIGDIR / f"{name}.svg", bbox_inches="tight") fig.savefig(FIGDIR / f"{name}.pdf", bbox_inches="tight") fig.savefig(FIGDIR / f"{name}.png", dpi=300, bbox_inches="tight") plt.close(fig) def plot_ablation(): apply_nature_style(font_size=8) df = pd.read_csv(BENCH / "ablation" / "ablation_summary_pose_filtered.csv") df["mode_label"] = df["ablation"].map(MODE_LABELS) fig, axes = plt.subplots(1, 2, figsize=(6.4, 2.7)) x = np.arange(len(TARGETS)) width = 0.24 modes = ["chroma+proteinmpnn", "chroma+bo", "chroma+proteinmpnn+bo"] offsets = [-width, 0, width] ax = axes[0] for mode, offset in zip(modes, offsets): part = df[df["ablation"] == mode].set_index("target").loc[TARGETS] ax.bar( x + offset, part["best_score"], width=width, color=MODE_COLORS[mode], label=MODE_LABELS[mode], ) ax.set_ylabel("Best ProteinMPNN score (lower is better)") ax.set_xticks(x) ax.set_xticklabels(TARGETS) ax.set_ylim(0, 2.9) add_panel_label(ax, "a") ax = axes[1] for mode, offset in zip(modes, offsets): part = df[df["ablation"] == mode].set_index("target").loc[TARGETS] ax.bar( x + offset, part["best_synthesis_penalty"], width=width, color=MODE_COLORS[mode], ) ax.axhline(0.8, color=PALETTE["neutral_mid"], lw=0.8, ls="--") ax.axhline(1.6, color=PALETTE["neutral_mid"], lw=0.8, ls=":") ax.set_ylabel("Best synthesis penalty (lower is better)") ax.set_xticks(x) ax.set_xticklabels(TARGETS) ax.set_ylim(0, 2.7) ax.text(2.55, 0.82, "low", fontsize=7, color=PALETTE["neutral_mid"]) ax.text(2.45, 1.62, "moderate", fontsize=7, color=PALETTE["neutral_mid"]) add_panel_label(ax, "b") handles, labels = axes[0].get_legend_handles_labels() fig.legend(handles, labels, loc="upper center", ncol=3, bbox_to_anchor=(0.5, 1.08)) save_pub_fig(fig, "fig_ablation_bo_tradeoff") def _parse_top_diff(diff_text): rows = [] for item in str(diff_text).split(";"): item = item.strip() if not item: continue match = re.match(r"([A-Z]):D([0-9.]+)/L([0-9.]+)", item) if match: aa, d_value, l_value = match.groups() rows.append((aa, float(d_value), float(l_value))) return rows def plot_dl_comparison(): apply_nature_style(font_size=8) from sklearn.manifold import TSNE fig, axes = plt.subplots(1, 3, figsize=(9.2, 3.0)) AAS_ORDER = list("ACDEFGHIKLMNPQRSTVWY") TOP_N = 100 for idx, target in enumerate(TARGETS): ax = axes[idx] d_df = pd.read_csv(BENCH / "dl_downsampled" / f"{target}_D_peptide_filtered.csv") l_df = pd.read_csv(BENCH / "dl_downsampled" / f"{target}_L_peptide_filtered.csv") d_top = d_df.nsmallest(TOP_N, "score").drop_duplicates("sequence") l_top = l_df.nsmallest(TOP_N, "score").drop_duplicates("sequence") def _onehot_padded(sequences, max_len): aa_to_idx = {aa: i for i, aa in enumerate(AAS_ORDER)} vecs = [] for seq in sequences: vec = np.zeros(max_len * len(AAS_ORDER)) for pos, aa in enumerate(str(seq)): if aa in aa_to_idx: vec[pos * len(AAS_ORDER) + aa_to_idx[aa]] = 1.0 vecs.append(vec) return np.array(vecs) all_seqs = pd.concat([d_top, l_top])["sequence"] max_len = all_seqs.str.len().max() d_vecs = _onehot_padded(d_top["sequence"], max_len) l_vecs = _onehot_padded(l_top["sequence"], max_len) X = np.vstack([d_vecs, l_vecs]) n_d = len(d_vecs) # PCA init to reduce dimensionality before t-SNE from sklearn.decomposition import PCA n_pca = min(50, X.shape[1], X.shape[0] - 1) X_pca = PCA(n_components=n_pca, random_state=42).fit_transform(X) tsne = TSNE(n_components=2, perplexity=30, random_state=42, learning_rate="auto", init="pca") X_embed = tsne.fit_transform(X_pca) ax.scatter( X_embed[n_d:, 0], X_embed[n_d:, 1], s=28, alpha=0.6, color=PALETTE["orange"], label="L-peptide", rasterized=True, ) ax.scatter( X_embed[:n_d, 0], X_embed[:n_d, 1], s=28, alpha=0.6, color=PALETTE["blue_main"], label="D-peptide", rasterized=True, ) ax.set_xlabel(f"{target} (top {TOP_N}) — t-SNE 1") if idx == 0: ax.set_ylabel("t-SNE 2") ax.set_xticks([]) ax.set_yticks([]) panel_labels = ["a", "b", "c"] add_panel_label(ax, panel_labels[idx]) handles = [ plt.Line2D([0], [0], marker="o", color="w", markerfacecolor=PALETTE["blue_main"], markersize=8, label="D-peptide"), plt.Line2D([0], [0], marker="o", color="w", markerfacecolor=PALETTE["orange"], markersize=8, label="L-peptide"), ] fig.legend(handles=handles, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 1.04), fontsize=8, handletextpad=0.5, columnspacing=1.5) save_pub_fig(fig, "fig_dl_sequence_comparison") def _load_bad_pose_keys(peptide_mode): """Buried (inside-target) pose keys from the geometric surface filter.""" path = BENCH / "buried_pose_inventory.csv" if not path.exists(): return set() df = pd.read_csv(path) sub = df[df["peptide_mode"] == peptide_mode] return set(zip(sub["target"], sub["length"].astype(int), sub["pose"].astype(int))) def _load_filtered_dl_df(target, peptide_mode): csv_path = BENCH / target / peptide_mode / "all_results.csv" df = pd.read_csv(csv_path) bad_keys = _load_bad_pose_keys(peptide_mode) if bad_keys: keys = list(zip( [target] * len(df), df["length"].astype(int), df["pose"].astype(int), )) keep = [k not in bad_keys for k in keys] df = df.loc[keep].copy() return df.dropna(subset=["score"]) def plot_dl_score_distribution(): apply_nature_style(font_size=8) from scipy import stats as sp_stats fig, axes = plt.subplots(1, 3, figsize=(9.2, 2.8)) rng = np.random.default_rng(42) for idx, target in enumerate(TARGETS): ax = axes[idx] d_df = _load_filtered_dl_df(target, "D_peptide") l_df = _load_filtered_dl_df(target, "L_peptide") # Downsample L to match D count n_d = len(d_df) n_l = len(l_df) if n_l > n_d: l_df = l_df.sample(n=n_d, random_state=rng).copy() d_scores = d_df["score"].values l_scores = l_df["score"].values bins = np.linspace( min(d_scores.min(), l_scores.min()), max(np.percentile(d_scores, 99), np.percentile(l_scores, 99)), 50, ) ax.hist( d_scores, bins=bins, density=True, alpha=0.55, color=PALETTE["blue_main"], label="D-peptide", ) ax.hist( l_scores, bins=bins, density=True, alpha=0.55, color=PALETTE["orange"], label="L-peptide", ) ks_stat, ks_p = sp_stats.ks_2samp(d_scores, l_scores) ax.axvline(np.median(d_scores), color=PALETTE["blue_main"], ls="--", lw=0.8) ax.axvline(np.median(l_scores), color=PALETTE["orange"], ls="--", lw=0.8) ax.set_xlabel(f"{target} — ProteinMPNN score (NLL)") if idx == 0: ax.set_ylabel("Density") ax.text( 0.97, 0.95, f"$n$ = {n_d}\nKS = {ks_stat:.3f}\np < {ks_p:.1e}" if ks_p < 0.001 else f"$n$ = {n_d}\nKS = {ks_stat:.3f}\np = {ks_p:.3f}", transform=ax.transAxes, ha="right", va="top", fontsize=7, color=PALETTE["neutral_dark"], bbox=dict(boxstyle="round,pad=0.3", fc="white", ec=PALETTE["neutral_light"], lw=0.5), ) if idx == 0: ax.legend(loc="upper left", fontsize=7) save_pub_fig(fig, "fig_dl_score_distribution") def main(): plot_ablation() plot_dl_comparison() plot_dl_score_distribution() if __name__ == "__main__": main()