from __future__ import annotations import random from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Sequence import numpy as np import pandas as pd import requests from Bio.Align import substitution_matrices from Bio.PDB.Polypeptide import protein_letters_3to1 from libs.encoders.protein_encoder import ProteinEncoder from libs.utils.io_pdb import load_structure AA_ALPHABET = list("ACDEFGHIKLMNPQRSTVWY") HYDROPHOBIC = set("AVILMFWY") POSITIVE = set("KRH") NEGATIVE = set("DE") @dataclass class PeptideBenchmarkConfig: target_name: str reference_pdb_id: str receptor_chain_id: str peptide_chain_id: str n_variants: int random_seed: int min_length: int = 8 max_length: int = 20 def download_pdb(pdb_id: str, out_path: Path) -> Path: out_path.parent.mkdir(parents=True, exist_ok=True) url = f"https://files.rcsb.org/download/{pdb_id}.pdb" resp = requests.get(url, timeout=60) resp.raise_for_status() out_path.write_text(resp.text, encoding="utf-8") return out_path def extract_chain_sequence(structure_path: str | Path, chain_id: str) -> str: structure = load_structure(structure_path, structure_id="peptide_like") model = next(structure.get_models()) if chain_id not in model: raise ValueError(f"Chain `{chain_id}` not found in structure `{structure_path}`") seq: List[str] = [] for residue in model[chain_id].get_residues(): if residue.id[0] != " ": continue seq.append(protein_letters_3to1.get(residue.resname.upper(), "X")) out = "".join(seq).replace("X", "") if not out: raise ValueError(f"No peptide/protein residues extracted for chain `{chain_id}` in `{structure_path}`") return out def _seq_identity(a: str, b: str) -> float: n = min(len(a), len(b)) if n == 0: return 0.0 return float(sum(1 for i in range(n) if a[i] == b[i]) / n) def _blosum62_mean(a: str, b: str) -> float: matrix = substitution_matrices.load("BLOSUM62") n = min(len(a), len(b)) if n == 0: return 0.0 scores = [] for i in range(n): aa = a[i] bb = b[i] if (aa, bb) in matrix: scores.append(float(matrix[(aa, bb)])) elif (bb, aa) in matrix: scores.append(float(matrix[(bb, aa)])) if not scores: return 0.0 return float(np.mean(scores)) def _frac(seq: str, residues: Sequence[str]) -> float: if not seq: return 0.0 r = set(residues) return float(sum(1 for x in seq if x in r) / len(seq)) def _anchor_positions(reference: str) -> List[int]: # For alpha-helical MDM2-like peptides anchors often include aromatic/hydrophobic residues. ranked = sorted(range(len(reference)), key=lambda i: (reference[i] in {"F", "W", "L", "Y"}, i), reverse=True) out = sorted(ranked[:3]) return out def _mutate_sequence(reference: str, rng: random.Random, anchor_pos: Sequence[int]) -> str: seq = list(reference) n_mut = 1 if rng.random() < 0.65 else 2 for _ in range(n_mut): i = rng.randrange(len(seq)) if i in anchor_pos and rng.random() < 0.8: continue if seq[i] in HYDROPHOBIC: candidates = [x for x in AA_ALPHABET if x in HYDROPHOBIC] elif seq[i] in POSITIVE: candidates = [x for x in AA_ALPHABET if x in POSITIVE] elif seq[i] in NEGATIVE: candidates = [x for x in AA_ALPHABET if x in NEGATIVE] else: candidates = AA_ALPHABET seq[i] = rng.choice(candidates) return "".join(seq) def build_peptide_like_dataset(cfg: PeptideBenchmarkConfig, structure_path: Path) -> pd.DataFrame: reference_seq = extract_chain_sequence(structure_path, cfg.peptide_chain_id) if not (cfg.min_length <= len(reference_seq) <= cfg.max_length): raise ValueError( f"Reference peptide length {len(reference_seq)} is outside configured bounds " f"[{cfg.min_length}, {cfg.max_length}]" ) rng = random.Random(cfg.random_seed) anchor_pos = _anchor_positions(reference_seq) rows: List[Dict[str, object]] = [ { "ligand_id": "pep_ref_000", "sequence": reference_seq, "is_reference": True, "source": "experimental_reference", "parent_reference_id": "pep_ref_000", } ] seen = {reference_seq} while len(rows) < max(2, int(cfg.n_variants)): s = _mutate_sequence(reference_seq, rng, anchor_pos) if s in seen: continue seen.add(s) rows.append( { "ligand_id": f"pep_var_{len(rows)-1:03d}", "sequence": s, "is_reference": False, "source": "generated_conservative_variant", "parent_reference_id": "pep_ref_000", } ) df = pd.DataFrame(rows) df["sequence_identity_to_ref"] = df["sequence"].map(lambda s: _seq_identity(str(s), reference_seq)) df["blosum62_to_ref"] = df["sequence"].map(lambda s: _blosum62_mean(str(s), reference_seq)) return df def _peptide_features(sequence: str, reference_seq: str, anchor_pos: Sequence[int]) -> Dict[str, float]: seq = str(sequence) ref = str(reference_seq) n = min(len(seq), len(ref)) anchors = [i for i in anchor_pos if i < n] anchor_match = float(np.mean([1.0 if seq[i] == ref[i] else 0.0 for i in anchors])) if anchors else 0.0 hydrophobic_diff = abs(_frac(seq, list(HYDROPHOBIC)) - _frac(ref, list(HYDROPHOBIC))) charge_diff = abs((_frac(seq, list(POSITIVE)) - _frac(seq, list(NEGATIVE))) - (_frac(ref, list(POSITIVE)) - _frac(ref, list(NEGATIVE)))) len_penalty = abs(len(seq) - len(ref)) / max(1, len(ref)) return { "seq_identity": _seq_identity(seq, ref), "blosum62_mean": _blosum62_mean(seq, ref), "anchor_match": anchor_match, "hydrophobic_fraction": _frac(seq, list(HYDROPHOBIC)), "charged_fraction": _frac(seq, list(POSITIVE) + list(NEGATIVE)), "hydrophobic_diff_to_ref": hydrophobic_diff, "charge_diff_to_ref": charge_diff, "length_penalty": len_penalty, "aromatic_count": float(sum(1 for x in seq if x in {"F", "W", "Y"})), } def _proxy_affinity_score(features: Dict[str, float], target_extent: float) -> float: # Lower is better (affinity-like proxy). raw = ( 2.0 * (1.0 - features["seq_identity"]) + 1.4 * (1.0 - features["anchor_match"]) + 1.0 * features["hydrophobic_diff_to_ref"] + 0.7 * features["charge_diff_to_ref"] + 0.8 * features["length_penalty"] - 0.06 * features["blosum62_mean"] ) # mild target-structure scaling (keeps pipeline linked to structural context) scale = 1.0 + min(0.2, max(0.0, target_extent / 200.0)) return float(raw * scale) def run_peptide_like_proxy_benchmark( cfg: PeptideBenchmarkConfig, structure_path: Path, ) -> Dict[str, pd.DataFrame]: ligands_df = build_peptide_like_dataset(cfg, structure_path=structure_path) ref_seq = str(ligands_df.loc[ligands_df["is_reference"].astype(bool), "sequence"].iloc[0]) anchor_pos = _anchor_positions(ref_seq) protein_encoding = ProteinEncoder().encode_structure( target_id=f"{cfg.target_name}_{cfg.reference_pdb_id}_{cfg.receptor_chain_id}", structure_path=structure_path, ) target_extent = float(protein_encoding.structure_features.get("mean_spatial_extent", 0.0)) feature_rows: List[Dict[str, object]] = [] rank_rows: List[Dict[str, object]] = [] for row in ligands_df.itertuples(index=False): feats = _peptide_features(str(row.sequence), reference_seq=ref_seq, anchor_pos=anchor_pos) score = _proxy_affinity_score(feats, target_extent=target_extent) feature_rows.append( { "ligand_id": str(row.ligand_id), "sequence": str(row.sequence), "is_reference": bool(row.is_reference), **feats, "target_mean_spatial_extent": target_extent, } ) rank_rows.append( { "ligand_id": str(row.ligand_id), "sequence": str(row.sequence), "is_reference": bool(row.is_reference), "source": str(row.source), "parent_reference_id": str(row.parent_reference_id), "sequence_identity_to_ref": float(row.sequence_identity_to_ref), "blosum62_to_ref": float(row.blosum62_to_ref), "backend_name": "peptide_proxy", "backend_mode": "proxy-peptide-like", "score_source": "sequence_structural_proxy_v1", "quantity_type": "affinity_proxy", "fallback_used": False, "success": True, "docking_score": float(score), "final_score": float(score), "message": "", } ) features_df = pd.DataFrame(feature_rows) ranking = pd.DataFrame(rank_rows).sort_values("final_score", ascending=True).reset_index(drop=True) ranking["rank"] = np.arange(1, ranking.shape[0] + 1) return { "ranking_df": ranking, "features_df": features_df, "ligands_df": ligands_df, "protein_features": pd.DataFrame([protein_encoding.structure_features | protein_encoding.sequence_features]), }