from __future__ import annotations import json import re import subprocess import urllib.parse from pathlib import Path from typing import Any, Dict, Iterable, List import numpy as np import pandas as pd import requests from rdkit import Chem, DataStructs from rdkit.Chem import AllChem from rdkit.Chem.Scaffolds import MurckoScaffold def _curl_get_text(url: str, timeout: int = 30) -> str: cp = subprocess.run( [ "curl", "-L", "--silent", "--show-error", "--fail", "--retry", "2", "--retry-delay", "1", "--max-time", str(int(timeout)), url, ], capture_output=True, text=True, check=False, ) if cp.returncode != 0: raise RuntimeError(f"curl failed for {url}: {cp.stderr.strip()}") return cp.stdout def _http_json(url: str, timeout: int = 30) -> Dict[str, Any]: # Prefer curl on this workstation because requests+TLS has been unstable. try: return json.loads(_curl_get_text(url, timeout=timeout)) except Exception: pass r = requests.get(url, timeout=timeout) r.raise_for_status() return r.json() def _http_text(url: str, timeout: int = 60) -> str: try: return _curl_get_text(url, timeout=timeout) except Exception: pass r = requests.get(url, timeout=timeout) r.raise_for_status() return r.text def _canonicalize_smiles(smiles: str) -> str | None: mol = Chem.MolFromSmiles(str(smiles)) if mol is None: return None return Chem.MolToSmiles(mol, canonical=True) def _morgan_bv(smiles: str, nbits: int = 2048): mol = Chem.MolFromSmiles(smiles) if mol is None: return None return AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=nbits) def _tanimoto(smiles_a: str, smiles_b: str) -> float: fp_a = _morgan_bv(smiles_a) fp_b = _morgan_bv(smiles_b) if fp_a is None or fp_b is None: return 0.0 return float(DataStructs.TanimotoSimilarity(fp_a, fp_b)) def _scaffold_smiles(smiles: str) -> str | None: mol = Chem.MolFromSmiles(smiles) if mol is None: return None try: return MurckoScaffold.MurckoScaffoldSmiles(mol=mol) except Exception: return None def _chemcomp_info(comp_id: str) -> Dict[str, Any]: d = _http_json(f"https://data.rcsb.org/rest/v1/core/chemcomp/{comp_id}", timeout=30) desc = d.get("rcsb_chem_comp_descriptor", {}) smiles = desc.get("SMILES_stereo") or desc.get("SMILES") return { "comp_id": comp_id, "name": d.get("chem_comp", {}).get("name"), "formula_weight": d.get("chem_comp", {}).get("formula_weight"), "smiles": smiles, "inchi_key": desc.get("InChIKey"), } 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" out_path.write_text(_http_text(url, timeout=60), encoding="utf-8") return out_path def _pubchem_similarity_cids(smiles: str, threshold: int, max_records: int) -> list[int]: enc = urllib.parse.quote(smiles, safe="") url = ( "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/" f"{enc}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}" ) try: d = _http_json(url, timeout=30) cids = [int(x) for x in d.get("IdentifierList", {}).get("CID", [])] if cids: return cids except Exception: pass # CID-based fallback for molecules where SMILES endpoint is sparse. cid_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/{enc}/cids/JSON" try: cands = [int(x) for x in _http_json(cid_url, timeout=20).get("IdentifierList", {}).get("CID", [])] except Exception: return [] if not cands: return [] cid = cands[0] sim_url = ( "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/cid/" f"{cid}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}" ) try: return [int(x) for x in _http_json(sim_url, timeout=30).get("IdentifierList", {}).get("CID", [])] except Exception: return [] def _pubchem_properties_for_cids(cids: Iterable[int]) -> pd.DataFrame: cids = list(cids) if not cids: return pd.DataFrame( columns=[ "cid", "smiles", "molecular_formula", "molecular_weight", "xlogp", "tpsa", "hbd", "hba", "rotatable_bonds", "heavy_atom_count", ] ) rows: list[dict[str, Any]] = [] # 200 CIDs/request is a stable balance on PubChem for URL size and throughput. chunk_size = 200 for i in range(0, len(cids), chunk_size): chunk = cids[i : i + chunk_size] joined = ",".join(str(x) for x in chunk) url = ( "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" f"{joined}/property/SMILES,ConnectivitySMILES,MolecularFormula,MolecularWeight," "XLogP,TPSA,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount/JSON" ) props = [] for _attempt in range(3): try: props = _http_json(url, timeout=30).get("PropertyTable", {}).get("Properties", []) except Exception: props = [] if props: break if not props: continue for p in props: rows.append( { "cid": int(p.get("CID")), "smiles": str(p.get("SMILES") or p.get("ConnectivitySMILES") or ""), "molecular_formula": p.get("MolecularFormula"), "molecular_weight": p.get("MolecularWeight"), "xlogp": p.get("XLogP"), "tpsa": p.get("TPSA"), "hbd": p.get("HBondDonorCount"), "hba": p.get("HBondAcceptorCount"), "rotatable_bonds": p.get("RotatableBondCount"), "heavy_atom_count": p.get("HeavyAtomCount"), } ) return pd.DataFrame(rows) def _fetch_chembl_smiles(target_chembl_id: str, max_rows: int) -> pd.DataFrame: if int(max_rows) <= 0: return pd.DataFrame( columns=[ "smiles", "molecule_chembl_id", "assay_chembl_id", "standard_type", "standard_units", "standard_value", "source_database", ] ) rows: list[dict[str, Any]] = [] limit = 1000 offset = 0 while len(rows) < max_rows: url = ( "https://www.ebi.ac.uk/chembl/api/data/activity.json" f"?target_chembl_id={target_chembl_id}&limit={limit}&offset={offset}" ) try: d = _http_json(url, timeout=30) except Exception: break acts = d.get("activities", []) if not acts: break for a in acts: smi = _canonicalize_smiles(str(a.get("canonical_smiles") or "")) if smi is None: continue rows.append( { "smiles": smi, "molecule_chembl_id": a.get("molecule_chembl_id"), "assay_chembl_id": a.get("assay_chembl_id"), "standard_type": a.get("standard_type"), "standard_units": a.get("standard_units"), "standard_value": a.get("standard_value"), "source_database": "ChEMBL", } ) if len(rows) >= max_rows: break offset += limit if d.get("page_meta", {}).get("next") is None: break return pd.DataFrame(rows) def _generate_fallback_smiles(seed_smiles: str, needed: int) -> List[str]: """Conservative, deterministic fallback if database retrieval is insufficient.""" variants: List[str] = [] candidates = [seed_smiles] replacements = [ ("Cl", "F"), ("F", "Cl"), ("OC", "OCC"), ("CC", "CCC"), ] while candidates and len(variants) < needed: smi = candidates.pop(0) for a, b in replacements: if a not in smi: continue cand = smi.replace(a, b, 1) c = _canonicalize_smiles(cand) if c is None: continue if c not in variants: variants.append(c) if len(variants) >= needed: break return variants def build_large_benchmark_library(config: Dict[str, Any], root: Path, logger) -> Dict[str, Any]: dataset_cfg = config["benchmark_dataset"] target_cfg = config["target"] ref_cfg = config["reference"] out_dir = root / dataset_cfg["output_dir"] out_dir.mkdir(parents=True, exist_ok=True) reference_path = out_dir / "reference_ligands.csv" raw_path = out_dir / "shared_library_raw.csv" dedup_path = out_dir / "shared_library_dedup.csv" shuffled_path = out_dir / "shared_library_shuffled.csv" provenance_path = out_dir / "ligand_provenance.csv" metadata_path = out_dir / "ligand_metadata.csv" similarity_path = out_dir / "similarity_distribution.csv" reuse_existing = bool(dataset_cfg.get("reuse_existing", True)) required = [reference_path, raw_path, dedup_path, shuffled_path, provenance_path, metadata_path] docking_target_path = root / target_cfg["docking_target_path"] if reuse_existing and all(p.exists() for p in required): if not similarity_path.exists(): dedup_existing = pd.read_csv(dedup_path) _write_similarity_distribution(dedup_existing, similarity_path) if not docking_target_path.exists(): _download_pdb(str(ref_cfg["pdb_id"]), docking_target_path) return { "reference_df": pd.read_csv(reference_path), "raw_df": pd.read_csv(raw_path), "dedup_df": pd.read_csv(dedup_path), "shuffled_df": pd.read_csv(shuffled_path), "provenance_df": pd.read_csv(provenance_path), "metadata_df": pd.read_csv(metadata_path), "similarity_df": pd.read_csv(similarity_path), "target_path": docking_target_path, "out_dir": out_dir, } ref_smiles_cfg = str(ref_cfg.get("reference_smiles") or dataset_cfg.get("reference_smiles") or "").strip() ref_name_cfg = str(ref_cfg.get("reference_name") or dataset_cfg.get("reference_name") or "").strip() ref_formula_weight_cfg = dataset_cfg.get("reference_formula_weight", np.nan) ref_comp: Dict[str, Any] if ref_smiles_cfg: ref_smiles = _canonicalize_smiles(ref_smiles_cfg) if ref_smiles is None: raise RuntimeError("Invalid configured reference_smiles") ref_comp = { "comp_id": str(ref_cfg["ligand_comp_id"]), "name": ref_name_cfg or str(ref_cfg["ligand_comp_id"]), "formula_weight": ref_formula_weight_cfg, "smiles": ref_smiles, "inchi_key": "", } else: ref_comp = _chemcomp_info(str(ref_cfg["ligand_comp_id"])) ref_smiles = _canonicalize_smiles(str(ref_comp["smiles"] or "")) if ref_smiles is None: raise RuntimeError("Invalid reference SMILES from RCSB chemcomp endpoint") ref_df = pd.DataFrame( [ { "reference_id": str(ref_cfg["reference_id"]), "pdb_id": str(ref_cfg["pdb_id"]), "ligand_comp_id": str(ref_cfg["ligand_comp_id"]), "ligand_name": ref_comp["name"], "reference_smiles": ref_smiles, "source_structure": str(ref_cfg["pdb_id"]), } ] ) ref_df.to_csv(reference_path, index=False) _download_pdb(str(ref_cfg["pdb_id"]), docking_target_path) target_size = int(dataset_cfg.get("target_size", 7500)) min_keep = float(dataset_cfg.get("min_similarity_keep", 0.25)) max_records = int(dataset_cfg.get("pubchem_max_records", 50000)) thresholds = [int(x) for x in dataset_cfg.get("pubchem_thresholds", [95, 90, 85, 80, 75, 70, 65, 60, 55, 50])] records: Dict[str, Dict[str, Any]] = {} for thr in thresholds: cids = _pubchem_similarity_cids(ref_smiles, threshold=thr, max_records=max_records) # Keep API workload bounded to what is still needed for target size. remaining = max(0, int(target_size) - len(records)) if remaining <= 0: break # Query a modest over-sampling margin to compensate duplicates/canonicalization. limit = min(len(cids), max(remaining + 600, 1200)) cids = cids[:limit] props = _pubchem_properties_for_cids(cids) if props.empty: continue for row in props.itertuples(index=False): c = _canonicalize_smiles(str(row.smiles)) if c is None: continue sim = _tanimoto(ref_smiles, c) if sim < min_keep: continue prev = records.get(c) base = { "ligand_id": "", "smiles": c, "source": "database", "source_database": "PubChem", "source_type": "retrieved", "original_database_id": f"CID:{int(row.cid)}", "reference_similarity": float(sim), "scaffold_core": _scaffold_smiles(c), "scaffold_match": int(_scaffold_smiles(c) == _scaffold_smiles(ref_smiles)), "retrieval_threshold": int(thr), "is_reference": False, "parent_reference_ligand": str(ref_cfg["reference_id"]), "molecular_formula": row.molecular_formula, "molecular_weight": row.molecular_weight, "xlogp": row.xlogp, "tpsa": row.tpsa, "hbd": row.hbd, "hba": row.hba, "rotatable_bonds": row.rotatable_bonds, "heavy_atom_count": row.heavy_atom_count, } if prev is None or (float(base["reference_similarity"]) > float(prev["reference_similarity"])): records[c] = base logger.info("PubChem threshold=%s cumulative=%s", thr, len(records)) if len(records) >= int(target_size * 1.2): break # ChEMBL supplement if needed (still database-first). if len(records) < target_size: chembl_target = str(dataset_cfg.get("chembl_target_id", "CHEMBL5023")) chembl_max = int(dataset_cfg.get("chembl_max_rows", 25000)) cdf = _fetch_chembl_smiles(target_chembl_id=chembl_target, max_rows=chembl_max) for row in cdf.itertuples(index=False): c = _canonicalize_smiles(str(row.smiles)) if c is None or c in records: continue sim = _tanimoto(ref_smiles, c) if sim < min_keep: continue records[c] = { "ligand_id": "", "smiles": c, "source": "database", "source_database": "ChEMBL", "source_type": "retrieved", "original_database_id": str(row.molecule_chembl_id or ""), "reference_similarity": float(sim), "scaffold_core": _scaffold_smiles(c), "scaffold_match": int(_scaffold_smiles(c) == _scaffold_smiles(ref_smiles)), "retrieval_threshold": np.nan, "is_reference": False, "parent_reference_ligand": str(ref_cfg["reference_id"]), "molecular_formula": np.nan, "molecular_weight": np.nan, "xlogp": np.nan, "tpsa": np.nan, "hbd": np.nan, "hba": np.nan, "rotatable_bonds": np.nan, "heavy_atom_count": np.nan, } if len(records) >= int(target_size * 1.2): break logger.info("ChEMBL supplement cumulative=%s", len(records)) # Ensure reference is present. records[ref_smiles] = { "ligand_id": str(ref_cfg["reference_id"]), "smiles": ref_smiles, "source": "reference", "source_database": "RCSB", "source_type": "reference", "original_database_id": str(ref_cfg["ligand_comp_id"]), "reference_similarity": 1.0, "scaffold_core": _scaffold_smiles(ref_smiles), "scaffold_match": 1, "retrieval_threshold": np.nan, "is_reference": True, "parent_reference_ligand": str(ref_cfg["reference_id"]), "molecular_formula": np.nan, "molecular_weight": ref_comp.get("formula_weight"), "xlogp": np.nan, "tpsa": np.nan, "hbd": np.nan, "hba": np.nan, "rotatable_bonds": np.nan, "heavy_atom_count": np.nan, } raw_df = pd.DataFrame(records.values()) raw_df = raw_df.sort_values(["is_reference", "reference_similarity"], ascending=[False, False]).reset_index(drop=True) raw_df.to_csv(raw_path, index=False) dedup_df = raw_df.drop_duplicates(subset=["smiles"], keep="first").reset_index(drop=True) allow_generated = bool(dataset_cfg.get("allow_generated_fallback", True)) if dedup_df.shape[0] < target_size and allow_generated: need = int(target_size - dedup_df.shape[0]) generated = _generate_fallback_smiles(seed_smiles=ref_smiles, needed=need * 2) gen_rows = [] for s in generated: if s in set(dedup_df["smiles"].astype(str).tolist()): continue sim = _tanimoto(ref_smiles, s) gen_rows.append( { "ligand_id": "", "smiles": s, "source": "generated", "source_database": "generated", "source_type": "generated", "original_database_id": "", "reference_similarity": float(sim), "scaffold_core": _scaffold_smiles(s), "scaffold_match": int(_scaffold_smiles(s) == _scaffold_smiles(ref_smiles)), "retrieval_threshold": np.nan, "is_reference": False, "parent_reference_ligand": str(ref_cfg["reference_id"]), "molecular_formula": np.nan, "molecular_weight": np.nan, "xlogp": np.nan, "tpsa": np.nan, "hbd": np.nan, "hba": np.nan, "rotatable_bonds": np.nan, "heavy_atom_count": np.nan, } ) if len(gen_rows) >= need: break if gen_rows: dedup_df = pd.concat([dedup_df, pd.DataFrame(gen_rows)], axis=0, ignore_index=True) dedup_df = dedup_df.sort_values(["is_reference", "source_type", "reference_similarity"], ascending=[False, True, False]).reset_index( drop=True ) if dedup_df.shape[0] > target_size: refs = dedup_df[dedup_df["is_reference"].astype(bool)].copy() non_refs = dedup_df[~dedup_df["is_reference"].astype(bool)].copy() keep = max(0, target_size - refs.shape[0]) dedup_df = pd.concat([refs, non_refs.head(keep)], axis=0, ignore_index=True) dedup_df = dedup_df.reset_index(drop=True) for i in range(dedup_df.shape[0]): if bool(dedup_df.loc[i, "is_reference"]): dedup_df.loc[i, "ligand_id"] = str(ref_cfg["reference_id"]) else: dedup_df.loc[i, "ligand_id"] = f"lb_{i:05d}" dedup_df.to_csv(dedup_path, index=False) shuffle_seed = int(dataset_cfg.get("shuffle_seed", 1337)) shuffled_df = dedup_df.sample(frac=1.0, random_state=shuffle_seed).reset_index(drop=True) shuffled_df["shuffle_seed"] = shuffle_seed shuffled_df.to_csv(shuffled_path, index=False) provenance_df = dedup_df[ [ "ligand_id", "smiles", "source", "source_database", "source_type", "original_database_id", "is_reference", "parent_reference_ligand", "reference_similarity", "scaffold_core", "scaffold_match", "retrieval_threshold", ] ].copy() provenance_df.to_csv(provenance_path, index=False) metadata_df = dedup_df[ [ "ligand_id", "smiles", "molecular_formula", "molecular_weight", "xlogp", "tpsa", "hbd", "hba", "rotatable_bonds", "heavy_atom_count", ] ].copy() metadata_df.to_csv(metadata_path, index=False) similarity_df = _write_similarity_distribution(dedup_df, similarity_path) return { "reference_df": ref_df, "raw_df": raw_df, "dedup_df": dedup_df, "shuffled_df": shuffled_df, "provenance_df": provenance_df, "metadata_df": metadata_df, "similarity_df": similarity_df, "target_path": docking_target_path, "out_dir": out_dir, "shuffle_seed": shuffle_seed, } def _write_similarity_distribution(df: pd.DataFrame, path: Path) -> pd.DataFrame: vals = pd.to_numeric(df.get("reference_similarity", pd.Series(dtype=float)), errors="coerce").dropna() bins = np.linspace(0.0, 1.0, 21) hist, edges = np.histogram(vals.to_numpy(dtype=float), bins=bins) out = pd.DataFrame( { "bin_left": edges[:-1], "bin_right": edges[1:], "count": hist, "fraction": hist / max(1, int(hist.sum())), } ) out.to_csv(path, index=False) return out