"""Plot FuzzyScore distributions for D/L-peptide designs. Mirrors ``plot_dl_synthesis_distribution`` but swaps the x-axis to the ``bo.scoring.FuzzyScore`` geometric-mean desirability score. Per the README spec, FuzzyScore combines per-property desirability functions (here: ProteinMPNN NLL and SWI solubility) into a unified score in (0, 1]. Desirability control points are anchored to the combined D+L 10/90 percentiles of each property (per target); weights are equal (importance=1, i.e. pure desirability in the geometric mean). Same targets (PDL1, MDM2, IL23R), same buried-pose filter, same D/L down-sampling as the ProteinMPNN and synthesis figures, so all three are row-for-row comparable. Tune ``DESIR_WEIGHT`` or the percentile anchors if a different trade-off is desired. """ 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 FuzzyScore, swi # noqa: E402 DESIR_WEIGHT = 1.0 # importance per property (1 = pure desirability) PCT_LOW, PCT_HIGH = 10, 90 # percentile anchors for the control points def _desirability_controls(combined): """Build MPNN-NLL and SWI desirability control points from combined D+L.""" mp_low, mp_high = np.percentile(combined["score"], [PCT_LOW, PCT_HIGH]) sw_low, sw_high = np.percentile(combined["SWI"], [PCT_LOW, PCT_HIGH]) # NLL: lower is better -> high desirability at the low end mpnn_points = [{"x": float(mp_low), "y": 1.0}, {"x": float(mp_high), "y": 0.0}] # SWI: higher is better -> high desirability at the high end swi_points = [{"x": float(sw_low), "y": 0.0}, {"x": float(sw_high), "y": 1.0}] return {"score": mpnn_points, "SWI": swi_points} def _add_fuzzyscore(df, controls): """Attach the bo FuzzyScore to a per-design DataFrame.""" df = df.copy() df["SWI"] = df["sequence"].map(swi) fs = FuzzyScore(df) out = fs.fuzzy_score( score=(controls["score"], DESIR_WEIGHT), SWI=(controls["SWI"], DESIR_WEIGHT), ) return out def plot_dl_fuzzyscore_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 = _load_filtered_dl_df(target, "D_peptide") l_df = _load_filtered_dl_df(target, "L_peptide") d_df["SWI"] = d_df["sequence"].map(swi) l_df["SWI"] = l_df["sequence"].map(swi) # Match D count, identical sampling seed to the other D/L figures 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() controls = _desirability_controls(pd.concat([d_df, l_df])) d_df = _add_fuzzyscore(d_df, controls) l_df = _add_fuzzyscore(l_df, controls) d_scores = d_df["FuzzyScore"].to_numpy() l_scores = l_df["FuzzyScore"].to_numpy() 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} — FuzzyScore") 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_fuzzyscore_distribution") def main(): plot_dl_fuzzyscore_distribution() if __name__ == "__main__": main()