File size: 22,235 Bytes
c289d87 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 | 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
|