File size: 23,421 Bytes
c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 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 603 604 605 606 607 608 609 | from __future__ import annotations
import csv
import json
import math
import subprocess
import shutil
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from .config_io import dump_json_like, load_structured_file
from .provenance import RDockPipelineError, probe_version, require_executable, require_file
from .rdock import RDockEngine, RDockRunConfig, load_target_config
from .sdf import ligand_id_from_block, parse_tags, split_sdf_file
IGNORED_SOLVENT_RESNAMES = {
"HOH",
"WAT",
"DOD",
"SOL",
"EDO",
"GOL",
"PEG",
"PG4",
"PGE",
"MPD",
"EOH",
"IPA",
"DMS",
"ACT",
"ACY",
"FMT",
"TRS",
"MES",
"BME",
}
IGNORED_BUFFER_RESNAMES = {
"SO4",
"PO4",
"CL",
"BR",
"IOD",
"NO3",
"SCN",
"IMD",
"CIT",
"ACE",
}
METAL_ELEMENTS = {
"LI",
"NA",
"K",
"RB",
"CS",
"MG",
"CA",
"SR",
"BA",
"ZN",
"FE",
"CO",
"NI",
"CU",
"MN",
"CD",
"HG",
"AG",
"AU",
}
def count_sdf_records(path: str | Path) -> int:
return len(split_sdf_file(path))
def list_known_good_complexes(config_path: str | Path) -> list[dict[str, Any]]:
payload = load_structured_file(config_path)
complexes = payload.get("complexes")
if not isinstance(complexes, list):
raise RDockPipelineError(f"`complexes` list missing in {config_path}")
return [dict(item) for item in complexes]
def _parse_pdb_atom_line(line: str) -> dict[str, Any]:
record = line[:6].strip()
atom_name = line[12:16].strip()
resname = line[17:20].strip().upper()
chain = line[21:22].strip()
residue_id = line[22:26].strip()
try:
x = float(line[30:38].strip())
y = float(line[38:46].strip())
z = float(line[46:54].strip())
except ValueError:
x = y = z = math.nan
element = line[76:78].strip().upper() or "".join(char for char in atom_name if char.isalpha())[:2].upper()
return {
"record": record,
"atom_name": atom_name,
"resname": resname,
"chain": chain,
"residue_id": residue_id,
"x": x,
"y": y,
"z": z,
"element": element,
"line": line,
}
def _is_heavy_atom(element: str) -> bool:
return bool(element) and element != "H"
def _classify_hetero_group(resname: str, elements: set[str], heavy_atom_count: int) -> tuple[bool, str]:
if resname in IGNORED_SOLVENT_RESNAMES:
return True, "solvent"
if resname in IGNORED_BUFFER_RESNAMES:
return True, "buffer_or_salt"
if elements and elements.issubset(METAL_ELEMENTS):
return True, "ion_or_metal"
if heavy_atom_count <= 1:
return True, "tiny_fragment"
return False, ""
def list_hetero_ligands(pdb_like: str | Path, min_reference_ligand_atoms: int = 8) -> list[dict[str, Any]]:
source = require_file(pdb_like, "PDB/mmCIF structure")
groups: dict[tuple[str, str, str], dict[str, Any]] = {}
for line in source.read_text(encoding="utf-8", errors="ignore").splitlines():
if not line.startswith("HETATM"):
continue
atom = _parse_pdb_atom_line(line)
key = (atom["resname"], atom["chain"], atom["residue_id"])
group = groups.setdefault(
key,
{
"resname": atom["resname"],
"chain": atom["chain"],
"residue_id": atom["residue_id"],
"atom_count": 0,
"heavy_atom_count": 0,
"elements": set(),
},
)
group["atom_count"] += 1
if _is_heavy_atom(atom["element"]):
group["heavy_atom_count"] += 1
if atom["element"]:
group["elements"].add(atom["element"])
rows: list[dict[str, Any]] = []
for _, group in sorted(groups.items()):
ignored, reason = _classify_hetero_group(
str(group["resname"]),
set(group["elements"]),
int(group["heavy_atom_count"]),
)
rows.append(
{
"resname": str(group["resname"]),
"chain": str(group["chain"]),
"residue_id": str(group["residue_id"]),
"atom_count": int(group["atom_count"]),
"heavy_atom_count": int(group["heavy_atom_count"]),
"ignored": ignored,
"ignored_reason": reason,
"candidate_ligand": (not ignored) and int(group["heavy_atom_count"]) >= int(min_reference_ligand_atoms),
}
)
return rows
def auto_detect_reference_ligand(
pdb_like: str | Path,
receptor_chain: str,
min_reference_ligand_atoms: int = 8,
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
source = require_file(pdb_like, "PDB/mmCIF structure")
hetero = list_hetero_ligands(source, min_reference_ligand_atoms=min_reference_ligand_atoms)
receptor_chains = {item.strip() for item in receptor_chain.split(",") if item.strip()}
receptor_atoms: list[tuple[float, float, float]] = []
ligand_atoms: dict[tuple[str, str, str], list[tuple[float, float, float]]] = {}
for line in source.read_text(encoding="utf-8", errors="ignore").splitlines():
if not line.startswith(("ATOM", "HETATM")):
continue
atom = _parse_pdb_atom_line(line)
if line.startswith("ATOM") and (not receptor_chains or atom["chain"] in receptor_chains):
if not math.isnan(atom["x"]):
receptor_atoms.append((atom["x"], atom["y"], atom["z"]))
elif line.startswith("HETATM"):
key = (atom["resname"], atom["chain"], atom["residue_id"])
ligand_atoms.setdefault(key, [])
if not math.isnan(atom["x"]):
ligand_atoms[key].append((atom["x"], atom["y"], atom["z"]))
if not receptor_atoms:
raise RDockPipelineError(f"No receptor atoms found in {source} for chain(s) {receptor_chain}")
def _min_distance(points: list[tuple[float, float, float]]) -> float:
best = math.inf
for lx, ly, lz in points:
for rx, ry, rz in receptor_atoms:
dist = math.dist((lx, ly, lz), (rx, ry, rz))
if dist < best:
best = dist
return best
candidates: list[dict[str, Any]] = []
for row in hetero:
key = (str(row["resname"]), str(row["chain"]), str(row["residue_id"]))
points = ligand_atoms.get(key, [])
if not points:
continue
min_dist = _min_distance(points)
enriched = dict(row)
enriched["min_distance_to_receptor"] = min_dist
enriched["contact_candidate"] = bool(row["candidate_ligand"]) and min_dist <= 6.0
candidates.append(enriched)
viable = [row for row in candidates if row["candidate_ligand"]]
if not viable:
raise RDockPipelineError(
f"No suitable reference ligand candidates found in {source}. "
f"Available hetero entries: {candidates[:20]}"
)
viable.sort(
key=lambda item: (
int(bool(item.get("contact_candidate"))),
int(item.get("heavy_atom_count", 0)),
int(item.get("atom_count", 0)),
-float(item.get("min_distance_to_receptor", math.inf)),
),
reverse=True,
)
return viable[0], candidates
def resolve_known_good_defaults(
config_path: str | Path,
pdb_id: str,
receptor_chain: str | None,
ligand_resname: str | None,
ligand_chain: str | None,
) -> dict[str, str]:
pdb_upper = pdb_id.upper().strip()
matches = [item for item in list_known_good_complexes(config_path) if str(item.get("pdb_id", "")).upper() == pdb_upper]
if not matches:
return {
"pdb_id": pdb_upper,
"receptor_chain": receptor_chain or "",
"reference_ligand_resname": ligand_resname or "",
"reference_ligand_chain": ligand_chain or "",
}
chosen = matches[0]
return {
"pdb_id": pdb_upper,
"receptor_chain": receptor_chain or str(chosen.get("receptor_chain", "")),
"reference_ligand_resname": ligand_resname or str(chosen.get("reference_ligand_resname", "")),
"reference_ligand_chain": ligand_chain or str(chosen.get("reference_ligand_chain", "")),
}
def download_pdb_structure(pdb_id: str, out_dir: str | Path, force: bool = False) -> Path:
target_dir = Path(out_dir)
target_dir.mkdir(parents=True, exist_ok=True)
pdb_id = pdb_id.upper().strip()
pdb_path = target_dir / f"{pdb_id.lower()}.pdb"
if pdb_path.exists() and pdb_path.stat().st_size > 0 and not force:
return pdb_path
url = f"https://files.rcsb.org/download/{pdb_id}.pdb"
try:
urllib.request.urlretrieve(url, pdb_path)
except Exception as exc:
curl = shutil.which("curl")
if curl:
proc = subprocess.run(
[curl, "-fsSL", url, "-o", str(pdb_path)],
check=False,
capture_output=True,
text=True,
)
if proc.returncode == 0 and pdb_path.exists() and pdb_path.stat().st_size > 0:
return require_file(pdb_path, f"downloaded PDB for {pdb_id}")
raise RDockPipelineError(
f"Failed to download PDB {pdb_id} from {url}. urllib error: {exc}. "
f"curl stderr: {proc.stderr.strip() or '<empty>'}. "
f"Check network access or provide a locally cached PDB in {target_dir}."
) from exc
raise RDockPipelineError(
f"Failed to download PDB {pdb_id} from {url}: {exc}. "
"curl is not available for fallback; check network access or pre-stage the PDB file locally."
) from exc
return require_file(pdb_path, f"downloaded PDB for {pdb_id}")
def extract_receptor_and_reference_ligand(
pdb_like: str | Path,
receptor_chain: str,
ligand_resname: str,
ligand_chain: str,
out_dir: str | Path,
min_reference_ligand_atoms: int = 8,
) -> tuple[Path, Path, list[dict[str, str]]]:
source = require_file(pdb_like, "PDB/mmCIF structure")
out_root = Path(out_dir)
out_root.mkdir(parents=True, exist_ok=True)
receptor = out_root / "target_raw.pdb"
ligand_pdb = out_root / "reference_ligand_raw.pdb"
receptor_lines: list[str] = []
ligand_lines: list[str] = []
hetero_rows = list_hetero_ligands(source, min_reference_ligand_atoms=min_reference_ligand_atoms)
receptor_chains = {item.strip() for item in receptor_chain.split(",") if item.strip()}
wanted_resname = ligand_resname.upper().strip()
wanted_chain = ligand_chain.strip()
wanted_keys = {
(str(item["resname"]), str(item["chain"]), str(item["residue_id"]))
for item in hetero_rows
if str(item["resname"]) == wanted_resname and (not wanted_chain or str(item["chain"]) == wanted_chain)
}
for line in source.read_text(encoding="utf-8", errors="ignore").splitlines():
record = line[:6].strip()
atom = _parse_pdb_atom_line(line)
chain = str(atom["chain"])
resname = str(atom["resname"])
if record == "ATOM" and (not receptor_chains or chain in receptor_chains):
receptor_lines.append(line)
if record == "HETATM":
key = (resname, chain, str(atom["residue_id"]))
if key in wanted_keys:
ligand_lines.append(line)
if not receptor_lines:
raise RDockPipelineError(f"No receptor atoms found in {source} for chain(s) {receptor_chain}")
if not ligand_lines:
raise RDockPipelineError(
f"Reference ligand {wanted_resname} chain {wanted_chain or '*'} not found in {source}. "
f"Available hetero ligands: {hetero_rows[:20]}"
)
receptor.write_text("\n".join(receptor_lines + ["END", ""]), encoding="utf-8")
ligand_pdb.write_text("\n".join(ligand_lines + ["END", ""]), encoding="utf-8")
return receptor, ligand_pdb, hetero_rows
def validate_dataset_dir(dataset_dir: str | Path, check_rdock_tools: bool = False) -> dict[str, Any]:
root = Path(dataset_dir)
manifest_path = root / "dataset_manifest.json"
manifest = json.loads(require_file(manifest_path, "dataset manifest").read_text(encoding="utf-8"))
required = {
"target_mol2": root / "target" / "target.mol2",
"all_ligands_sdf": root / "ligands" / "all_ligands.sdf",
"invalid_ligands_csv": root / "ligands" / "invalid_ligands.csv",
"preparation_report": root / "qc" / "preparation_report.md",
"target_config": root / "target" / "rdock_prm" / "target_config.yaml",
}
for label, path in required.items():
require_file(path, label)
ligand_count = count_sdf_records(required["all_ligands_sdf"])
expected_count = int(manifest.get("ligands_prepared", 0))
if expected_count and ligand_count != expected_count:
raise RDockPipelineError(
f"Ligand count mismatch for {root}: manifest says {expected_count}, SDF contains {ligand_count}"
)
reference_ligand = root / "target" / "reference_ligand.sdf"
ref_count = count_sdf_records(reference_ligand) if reference_ligand.exists() else 0
target_config = load_target_config(required["target_config"])
cavity = require_file(target_config.cavity_as, "rDock cavity .as file from dataset")
if cavity.stat().st_size <= 0:
raise RDockPipelineError(f"Invalid empty cavity file in dataset: {cavity}")
ligand_source = str(manifest.get("ligand_source", ""))
if ligand_source.startswith("pubchem") and not manifest.get("pubchem_diagnostics"):
require_file(root / "logs" / "pubchem_diagnostics.json", "PubChem diagnostics log")
tools: dict[str, str] = {}
if check_rdock_tools:
tools = {
"rbdock": probe_version(require_executable("rbdock")),
"rbcavity": probe_version(require_executable("rbcavity")),
"obabel": probe_version(require_executable("obabel")),
}
return {
"dataset_dir": str(root),
"manifest": manifest,
"ligand_count": ligand_count,
"reference_records": ref_count,
"has_reference_ligand": ref_count > 0,
"target_config": str(required["target_config"]),
"executables": tools,
}
def create_dataset_manifest(
dataset_dir: str | Path,
payload: dict[str, Any],
) -> Path:
root = Path(dataset_dir)
payload = dict(payload)
payload["created_at"] = datetime.now(UTC).isoformat()
return dump_json_like(root / "dataset_manifest.json", payload)
def _first_pdb_id(raw_dir: Path) -> str:
for candidate in sorted(list(raw_dir.glob("*.pdb")) + list(raw_dir.glob("*.cif")) + list(raw_dir.glob("*.mmcif"))):
stem = candidate.stem.strip()
if stem:
return stem[:4].upper()
return ""
def _infer_reference_fields(target_dir: Path) -> tuple[str, str]:
raw_pdb = target_dir / "reference_ligand_raw.pdb"
if raw_pdb.exists():
for line in raw_pdb.read_text(encoding="utf-8", errors="ignore").splitlines():
if line.startswith("HETATM"):
atom = _parse_pdb_atom_line(line)
return str(atom["resname"]), str(atom["chain"])
return "", ""
def _infer_receptor_chain(target_dir: Path) -> str:
receptor = target_dir / "target_raw.pdb"
chains: list[str] = []
if receptor.exists():
for line in receptor.read_text(encoding="utf-8", errors="ignore").splitlines():
if line.startswith("ATOM"):
chain = _parse_pdb_atom_line(line)["chain"]
if chain and chain not in chains:
chains.append(str(chain))
return ",".join(chains[:4])
def _read_smiles_rows(smi_path: Path) -> list[dict[str, str]]:
rows: list[dict[str, str]] = []
for idx, line in enumerate(smi_path.read_text(encoding="utf-8", errors="ignore").splitlines()):
text = line.strip()
if not text or text.startswith("#"):
continue
parts = text.replace(",", " ").split()
smiles = parts[0]
ligand_id = parts[1] if len(parts) > 1 else f"lig_{idx:05d}"
rows.append({"ligand_id": ligand_id, "smiles": smiles})
return rows
def repair_dataset_dir(dataset_dir: str | Path) -> dict[str, Any]:
root = Path(dataset_dir)
target = root / "target"
ligands = root / "ligands"
logs = root / "logs"
qc = root / "qc"
rdock_prm = target / "rdock_prm"
raw = root / "raw"
warnings: list[str] = []
ligands.mkdir(parents=True, exist_ok=True)
logs.mkdir(parents=True, exist_ok=True)
qc.mkdir(parents=True, exist_ok=True)
metadata_csv = ligands / "ligand_metadata.csv"
smi_path = ligands / "all_ligands.smi"
sdf_path = ligands / "all_ligands.sdf"
if not metadata_csv.exists():
rows = _read_smiles_rows(smi_path) if smi_path.exists() else [{"ligand_id": ligand_id_from_block(block, parse_tags(block), idx), "smiles": ""} for idx, block in enumerate(split_sdf_file(sdf_path))]
with metadata_csv.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=["ligand_id", "smiles"])
writer.writeheader()
writer.writerows(rows)
warnings.append("reconstructed ligand_metadata.csv")
invalid_csv = ligands / "invalid_ligands.csv"
if not invalid_csv.exists():
invalid_csv.write_text("ligand_id,reason\n", encoding="utf-8")
warnings.append("created empty invalid_ligands.csv")
target_config_path = rdock_prm / "target_config.yaml"
if target_config_path.exists():
target_config = load_target_config(target_config_path)
dump_json_like(
target_config_path,
{
"receptor": target_config.receptor,
"reference_ligand": target_config.reference_ligand,
"target_dir": target_config.target_dir,
"receptor_mol2": target_config.receptor_mol2,
"receptor_prm": target_config.receptor_prm,
"cavity_as": target_config.cavity_as,
"pocket_center": target_config.pocket_center,
"pocket_radius": target_config.pocket_radius,
"diagnostics": target_config.diagnostics,
},
)
manifest_path = root / "dataset_manifest.json"
if not manifest_path.exists():
pdb_id = _first_pdb_id(raw)
ligand_resname, ligand_chain = _infer_reference_fields(target)
receptor_chain = _infer_receptor_chain(target)
ligand_source = "smiles_file"
pubchem_payload: dict[str, Any] = {}
pubchem_path = logs / "pubchem_diagnostics.json"
if pubchem_path.exists():
try:
pubchem_payload = json.loads(pubchem_path.read_text(encoding="utf-8"))
except Exception:
pubchem_payload = {}
ligand_source = str(pubchem_payload.get("source") or "pubchem_similarity")
create_dataset_manifest(
root,
{
"pdb_id": pdb_id,
"receptor_chain": receptor_chain,
"reference_ligand_resname": ligand_resname,
"reference_ligand_chain": ligand_chain,
"n_ligands_requested": len(_read_smiles_rows(smi_path)) if smi_path.exists() else count_sdf_records(sdf_path),
"ligands_prepared": count_sdf_records(sdf_path),
"paths": {
"target_mol2": str(target / "target.mol2"),
"reference_ligand_sdf": str(target / "reference_ligand.sdf"),
"all_ligands_sdf": str(sdf_path),
"all_ligands_smi": str(smi_path),
"rdock_prm_dir": str(rdock_prm),
"target_config_yaml": str(target_config_path),
},
"ligand_source": ligand_source,
"pubchem_diagnostics": pubchem_payload,
"pocket_definition_mode": "dataset_manifest",
"has_reference_ligand": (target / "reference_ligand.sdf").exists(),
"reference_features_enabled": False,
"production_reference_free_mode": False,
"warnings": ["dataset manifest reconstructed during repair"],
},
)
warnings.append("reconstructed dataset_manifest.json")
else:
try:
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
except Exception:
payload = {}
if isinstance(payload, dict):
changed = False
defaults = {
"pocket_definition_mode": "dataset_manifest",
"has_reference_ligand": (target / "reference_ligand.sdf").exists(),
"reference_features_enabled": False,
"production_reference_free_mode": False,
}
for key, value in defaults.items():
if key not in payload:
payload[key] = value
changed = True
if changed:
create_dataset_manifest(root, payload)
warnings.append("updated dataset_manifest.json with optional reference-free fields")
report_path = qc / "preparation_report.md"
if not report_path.exists():
report_path.write_text(
"\n".join(
[
f"# Dataset Preparation Report: {root.name}",
"",
"- report_status: `reconstructed`",
f"- target_mol2: `{target / 'target.mol2'}`",
f"- reference_ligand_sdf: `{target / 'reference_ligand.sdf'}`",
f"- all_ligands_sdf: `{sdf_path}`",
f"- all_ligands_smi: `{smi_path}`",
*[f"- warning: `{warning}`" for warning in warnings],
]
)
+ "\n",
encoding="utf-8",
)
warnings.append("reconstructed qc/preparation_report.md")
return {"dataset_dir": str(root), "warnings": warnings}
def copy_prepared_target_bundle(target_config_dir: str | Path, dataset_target_dir: str | Path) -> dict[str, str]:
src = Path(target_config_dir)
dst = Path(dataset_target_dir)
dst.mkdir(parents=True, exist_ok=True)
copied: dict[str, str] = {}
for path in src.iterdir():
if path.is_file():
shutil.copy2(path, dst / path.name)
copied[path.name] = str(dst / path.name)
return copied
def prepare_dataset_target_with_rdock(
receptor_pdb: str | Path,
reference_ligand_sdf: str | Path,
out_dir: str | Path,
jobs: int | str = "auto",
cpu_fraction: float = 0.85,
) -> dict[str, Any]:
engine = RDockEngine(RDockRunConfig(jobs=jobs, cpu_fraction=cpu_fraction))
target_config = engine.prepare_target(receptor_pdb, reference_ligand_sdf, out_dir)
return {
"target_config_yaml": str(Path(out_dir) / "target_config.yaml"),
"target_config": target_config.__dict__,
}
def read_ligand_metadata(path: str | Path) -> list[dict[str, str]]:
with require_file(path, "ligand metadata CSV").open("r", encoding="utf-8", newline="") as handle:
return list(csv.DictReader(handle))
|