MirrorPeptidizer / scripts /plot_dl_synthesis_distribution.py
dahuilangda's picture
Add MirrorPeptidizer benchmark (D/L comparison, new targets, ablation, figure data, SI)
0613483 verified
Raw History Blame Contribute Delete
3.75 kB
"""Plot synthesis-feasibility score distributions for D/L-peptide designs.
Mirrors ``plot_dl_score_distribution`` (ProteinMPNN NLL) but swaps the x-axis
to the BO synthesis-feasibility score used in the ablation study
(``bo.scoring.synthesis_metrics`` -> ``synthesis_feasibility_score``). Same
targets (PDL1, MDM2, IL23R), same buried-pose filter, same D/L down-sampling,
so the two figures are directly comparable row-for-row.
"""
from pathlib import Path
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
from plot_ablation_dl_figures import ( # noqa: E402
PALETTE,
TARGETS,
_load_filtered_dl_df,
apply_nature_style,
save_pub_fig,
)
from bo.scoring import synthesis_metrics # noqa: E402
def _add_synthesis_score(df):
"""Attach the ablation-study synthesis score to a per-design DataFrame."""
df = df.copy()
seq_col = "Variants" if "Variants" in df.columns else "sequence"
metrics = pd.DataFrame([synthesis_metrics(seq) for seq in df[seq_col]])
df["synthesis_penalty"] = metrics["synthesis_penalty"].values
df["synthesis_feasibility_score"] = 100.0 * np.exp(-df["synthesis_penalty"] / 3.0)
return df
def plot_dl_synthesis_distribution():
apply_nature_style(font_size=8)
from scipy import stats as sp_stats
fig, axes = plt.subplots(1, len(TARGETS), figsize=(9.2, 2.8))
rng = np.random.default_rng(42)
for idx, target in enumerate(TARGETS):
ax = axes[idx]
d_df = _add_synthesis_score(_load_filtered_dl_df(target, "D_peptide"))
l_df = _add_synthesis_score(_load_filtered_dl_df(target, "L_peptide"))
# Match D count, identical sampling seed to the ProteinMPNN figure
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["synthesis_feasibility_score"].values
l_scores = l_df["synthesis_feasibility_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)
# feasibility: higher is better -> median still summarises the centre
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} — Synthesis feasibility score")
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_synthesis_distribution")
def main():
plot_dl_synthesis_distribution()
if __name__ == "__main__":
main()