Download scripts/benchmark_pdb_500_smiles.py from QPromaQ/Docking_project: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/scripts/benchmark_pdb_500_smiles.py
- Command line
-
hf download hf://datasets/QPromaQ/Docking_project/scripts/benchmark_pdb_500_smiles.py
-
curl -L -o benchmark_pdb_500_smiles.py https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/scripts/benchmark_pdb_500_smiles.py
11.6 kB
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import shutil | |
| import urllib.request | |
| from pathlib import Path | |
| import sys | |
| from statistics import mean, median | |
| ROOT = Path(__file__).resolve().parents[1] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from docking_pipeline.provenance import CommandRunner, RDockPipelineError, fail_if_bad_command, probe_version, require_executable, require_file | |
| from docking_pipeline.rdock import RDockEngine, RDockRunConfig | |
| from docking_pipeline.reports.plots import plot_score_outputs | |
| EXAMPLES = """Example: | |
| python scripts/benchmark_pdb_500_smiles.py \\ | |
| --pdb-id 4HG7 \\ | |
| --receptor-chain A \\ | |
| --reference-ligand-resname NUT \\ | |
| --smiles-file data/examples/example_500_smiles.smi \\ | |
| --max-ligands 500 \\ | |
| --out results/benchmarks/pdb_4hg7_500smiles \\ | |
| --n-runs 50 \\ | |
| --jobs auto \\ | |
| --cpu-fraction 0.85 \\ | |
| """ | |
| def _download_pdb(pdb_id: str, out_dir: Path) -> Path: | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| pdb = out_dir / f"{pdb_id.lower()}.pdb" | |
| if pdb.exists() and pdb.stat().st_size > 0: | |
| return pdb | |
| local_matches = sorted(ROOT.glob(f"data/**/*{pdb_id.lower()}*.pdb")) + sorted(ROOT.glob(f"data/**/*{pdb_id.upper()}*.pdb")) | |
| for candidate in local_matches: | |
| if candidate.is_file() and candidate.stat().st_size > 0: | |
| shutil.copy2(candidate, pdb) | |
| return pdb | |
| url = f"https://files.rcsb.org/download/{pdb_id.upper()}.pdb" | |
| urllib.request.urlretrieve(url, pdb) | |
| return require_file(pdb, "downloaded PDB") | |
| def _extract_receptor_and_ligand( | |
| pdb: Path, | |
| receptor_chain: str, | |
| ligand_resname: str, | |
| ligand_chain: str | None, | |
| out_dir: Path, | |
| ) -> tuple[Path, Path]: | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| receptor = out_dir / "receptor.pdb" | |
| ligand_pdb = out_dir / "reference_ligand.pdb" | |
| receptor_lines: list[str] = [] | |
| ligand_lines: list[str] = [] | |
| chains = {c.strip() for c in receptor_chain.split(",") if c.strip()} | |
| ligand_resname = ligand_resname.upper() | |
| ligand_chain = (ligand_chain or "").strip() | |
| for line in pdb.read_text(encoding="utf-8", errors="ignore").splitlines(): | |
| rec = line[:6].strip() | |
| chain = line[21:22].strip() | |
| resname = line[17:20].strip().upper() | |
| if rec == "ATOM" and (not chains or chain in chains): | |
| receptor_lines.append(line) | |
| if rec == "HETATM" and resname == ligand_resname and (not ligand_chain or chain == ligand_chain): | |
| ligand_lines.append(line) | |
| if not receptor_lines: | |
| raise RDockPipelineError(f"No receptor ATOM records found for chain(s) {receptor_chain} in {pdb}") | |
| if not ligand_lines: | |
| raise RDockPipelineError( | |
| f"No reference ligand HETATM records found for resname={ligand_resname} chain={ligand_chain or '*'} in {pdb}" | |
| ) | |
| 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 | |
| def _read_smiles(path: Path, max_ligands: int) -> list[tuple[str, str]]: | |
| rows: list[tuple[str, str]] = [] | |
| for idx, line in enumerate(path.read_text(encoding="utf-8").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((smiles, ligand_id)) | |
| if len(rows) >= max_ligands: | |
| break | |
| if not rows: | |
| raise RDockPipelineError(f"No SMILES records found in {path}") | |
| return rows | |
| def _write_smi(rows: list[tuple[str, str]], path: Path) -> Path: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text("\n".join(f"{smi} {lig}" for smi, lig in rows) + "\n", encoding="utf-8") | |
| return path | |
| def _convert_with_obabel(input_path: Path, output_path: Path, args: list[str], runner: CommandRunner, stage: str, cwd: Path) -> Path: | |
| obabel = require_executable("obabel") | |
| rec = runner.run( | |
| stage, | |
| [obabel, str(input_path.resolve()), *args, "-O", str(output_path.resolve())], | |
| cwd, | |
| cwd / f"{stage}.stdout.log", | |
| cwd / f"{stage}.stderr.log", | |
| ) | |
| fail_if_bad_command(rec, f"OpenBabel {stage}") | |
| return require_file(output_path, f"OpenBabel output for {stage}") | |
| def _plan(args: argparse.Namespace) -> dict[str, object]: | |
| smiles = _read_smiles(Path(args.smiles_file), args.max_ligands) | |
| return { | |
| "pdb_id": args.pdb_id, | |
| "receptor_chain": args.receptor_chain, | |
| "reference_ligand_resname": args.reference_ligand_resname, | |
| "reference_ligand_chain": args.reference_ligand_chain or "", | |
| "smiles_file": args.smiles_file, | |
| "ligand_count": len(smiles), | |
| "out": args.out, | |
| "n_runs": args.n_runs, | |
| "jobs": args.jobs, | |
| "cpu_fraction": args.cpu_fraction, | |
| "commands": [ | |
| "download PDB from RCSB if absent", | |
| "extract receptor chain and reference ligand", | |
| "obabel reference_ligand.pdb -O reference_ligand.sdf", | |
| "obabel ligands.smi --gen3d -O ligands.sdf", | |
| "rbcavity -r receptor.prm -was", | |
| "rbdock chunked by --jobs", | |
| ], | |
| } | |
| def run(args: argparse.Namespace) -> dict[str, object]: | |
| out = Path(args.out) | |
| if out.exists() and args.force and not (args.dry_run or args.plan_only): | |
| shutil.rmtree(out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| plan = _plan(args) | |
| if args.dry_run or args.plan_only: | |
| (out / "benchmark_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8") | |
| print(json.dumps(plan, indent=2)) | |
| return {"dry_run": True, "plan": plan} | |
| for tool in ("obabel", "rbcavity", "rbdock"): | |
| require_executable(tool) | |
| runner = CommandRunner(out / "commands.log") | |
| pdb = _download_pdb(args.pdb_id, out / "inputs") | |
| receptor, ligand_pdb = _extract_receptor_and_ligand(pdb, args.receptor_chain, args.reference_ligand_resname, args.reference_ligand_chain, out / "target") | |
| ligand_sdf = _convert_with_obabel(ligand_pdb, out / "target" / "reference_ligand.sdf", [], runner, "reference_ligand_to_sdf", out) | |
| smiles_rows = _read_smiles(Path(args.smiles_file), args.max_ligands) | |
| smi = _write_smi(smiles_rows, out / "ligands" / "ligands.smi") | |
| ligands_sdf = _convert_with_obabel(smi, out / "ligands" / "ligands.sdf", ["--gen3d", "-h"], runner, "smiles_to_3d_sdf", out) | |
| engine = RDockEngine( | |
| RDockRunConfig( | |
| n_runs=args.n_runs, | |
| jobs=args.jobs, | |
| cpu_fraction=args.cpu_fraction, | |
| dock_prm=args.dock_prm, | |
| rbt_root=args.rbt_root, | |
| ) | |
| ) | |
| target_config = engine.prepare_target(receptor, ligand_sdf, out / "target_prepared") | |
| artifacts = engine.dock_sdf(target_config, ligands_sdf, out, n_runs=args.n_runs, jobs=args.jobs, run_id=out.name) | |
| plots = plot_score_outputs(artifacts.best_per_ligand_csv, out / "plots", title_prefix=f"{args.pdb_id} rDock") | |
| best_rows = _read_csv_rows(Path(artifacts.best_per_ligand_csv)) | |
| scores = [float(row["SCORE"]) for row in best_rows if row.get("SCORE") not in (None, "")] | |
| metrics = { | |
| "pdb_id": args.pdb_id, | |
| "requested_ligands": len(smiles_rows), | |
| "successful_ligands": len(best_rows), | |
| "failed_ligands": max(0, len(smiles_rows) - len(best_rows)), | |
| "pose_count": sum(1 for _ in _read_csv_rows(Path(artifacts.scores_long_csv))), | |
| "n_runs": int(args.n_runs), | |
| "jobs": args.jobs, | |
| "score_min": min(scores) if scores else None, | |
| "score_median": median(scores) if scores else None, | |
| "score_mean": mean(scores) if scores else None, | |
| "score_max": max(scores) if scores else None, | |
| "top_ligand_id": best_rows[0].get("ligand_id") if best_rows else None, | |
| "top_SCORE": float(best_rows[0]["SCORE"]) if best_rows and best_rows[0].get("SCORE") else None, | |
| } | |
| metrics_dir = out / "metrics" | |
| metrics_dir.mkdir(parents=True, exist_ok=True) | |
| (metrics_dir / "benchmark_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8") | |
| (metrics_dir / "validation_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8") | |
| manifest = json.loads(Path(artifacts.manifest).read_text(encoding="utf-8")) | |
| manifest.update( | |
| { | |
| "benchmark": "pdb_500_smiles", | |
| "pdb_id": args.pdb_id, | |
| "ligand_count_requested": len(smiles_rows), | |
| "metrics": metrics, | |
| "metrics_json": str(metrics_dir / "benchmark_metrics.json"), | |
| "plots": plots, | |
| "executables": {"obabel": probe_version(require_executable("obabel"))}, | |
| } | |
| ) | |
| Path(artifacts.manifest).write_text(json.dumps(manifest, indent=2), encoding="utf-8") | |
| _append_benchmark_report(out / "report.md", args, artifacts.best_per_ligand_csv, plots) | |
| return {"run_dir": str(out), "manifest": artifacts.manifest} | |
| def _read_csv_rows(path: Path) -> list[dict[str, str]]: | |
| with path.open("r", encoding="utf-8", newline="") as handle: | |
| return list(csv.DictReader(handle)) | |
| def _append_benchmark_report(report: Path, args: argparse.Namespace, best_csv: str, plots: list[str]) -> None: | |
| top = [] | |
| with Path(best_csv).open("r", encoding="utf-8", newline="") as handle: | |
| for idx, row in enumerate(csv.DictReader(handle)): | |
| if idx >= 20: | |
| break | |
| top.append(f"- `{row.get('ligand_id')}` SCORE `{row.get('SCORE')}`") | |
| with report.open("a", encoding="utf-8") as handle: | |
| handle.write("\n\n## PDB Benchmark Summary\n") | |
| handle.write(f"- PDB: `{args.pdb_id}`\n") | |
| handle.write(f"- Receptor chain: `{args.receptor_chain}`\n") | |
| handle.write(f"- Reference ligand: `{args.reference_ligand_resname}`\n") | |
| handle.write(f"- SMILES file: `{args.smiles_file}`\n") | |
| handle.write("\n## Top 20 Ligands\n") | |
| handle.write("\n".join(top) + "\n") | |
| handle.write("\n## Plots\n") | |
| handle.write("\n".join(f"- `{p}`" for p in plots) + "\n") | |
| def main() -> int: | |
| parser = argparse.ArgumentParser( | |
| description="Run an independent real PDB complex + up to 500 SMILES rDock benchmark.", | |
| epilog=EXAMPLES, | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| ) | |
| parser.add_argument("--pdb-id", required=True) | |
| parser.add_argument("--receptor-chain", required=True) | |
| parser.add_argument("--reference-ligand-resname", required=True) | |
| parser.add_argument("--reference-ligand-chain") | |
| parser.add_argument("--smiles-file", required=True) | |
| parser.add_argument("--max-ligands", type=int, default=500) | |
| parser.add_argument("--out", required=True) | |
| parser.add_argument("--n-runs", type=int, default=50) | |
| parser.add_argument("--jobs", default="auto") | |
| parser.add_argument("--cpu-fraction", type=float, default=0.85) | |
| parser.add_argument("--ph", type=float, default=7.4) | |
| parser.add_argument("--force", action="store_true") | |
| parser.add_argument("--dock-prm") | |
| parser.add_argument("--rbt-root") | |
| parser.add_argument("--dry-run", action="store_true") | |
| parser.add_argument("--plan-only", action="store_true") | |
| result = run(parser.parse_args()) | |
| if not result.get("dry_run"): | |
| print(json.dumps(result, indent=2)) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |