Download scripts/prepare_pdb_ligand_dataset.py from QPromaQ/Docking_project: direct link, hf CLI and curl.
- Browser
- Download file 87.5 kB
-
https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/scripts/prepare_pdb_ligand_dataset.py
- Command line
-
hf download hf://datasets/QPromaQ/Docking_project/scripts/prepare_pdb_ligand_dataset.py
-
curl -L -o prepare_pdb_ligand_dataset.py https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/scripts/prepare_pdb_ligand_dataset.py
87.5 kB
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import os | |
| import shutil | |
| import sys | |
| import time | |
| import urllib.parse | |
| import urllib.request | |
| from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed | |
| from pathlib import Path | |
| try: # pragma: no cover | |
| from rdkit import Chem, DataStructs | |
| from rdkit.Chem import rdMolDescriptors | |
| from rdkit.Chem import rdFingerprintGenerator | |
| from rdkit.Chem.Scaffolds import MurckoScaffold | |
| RDKIT_AVAILABLE = True | |
| except Exception: # pragma: no cover | |
| Chem = None # type: ignore[assignment] | |
| DataStructs = None # type: ignore[assignment] | |
| rdMolDescriptors = None # type: ignore[assignment] | |
| rdFingerprintGenerator = None # type: ignore[assignment] | |
| MurckoScaffold = None # type: ignore[assignment] | |
| RDKIT_AVAILABLE = False | |
| try: # pragma: no cover | |
| from tqdm import tqdm | |
| except Exception: # pragma: no cover | |
| tqdm = None # type: ignore[assignment] | |
| ROOT = Path(__file__).resolve().parents[1] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from docking_pipeline.dataset import ( | |
| auto_detect_reference_ligand, | |
| count_sdf_records, | |
| create_dataset_manifest, | |
| download_pdb_structure, | |
| extract_receptor_and_reference_ligand, | |
| list_hetero_ligands, | |
| list_known_good_complexes, | |
| prepare_dataset_target_with_rdock, | |
| resolve_known_good_defaults, | |
| validate_dataset_dir, | |
| ) | |
| from docking_pipeline.provenance import CommandRunner, RDockPipelineError, fail_if_bad_command, probe_version, require_executable, require_file | |
| from docking_pipeline.sdf import split_sdf_text | |
| from docking_pipeline.validation import resolve_jobs | |
| KNOWN_GOOD = ROOT / "configs" / "known_good_pdb_complexes.yaml" | |
| DEFAULT_THRESHOLD_LADDER = [95, 90, 85, 80, 75, 70] | |
| DEFAULT_BUNDLED_EXAMPLE = ROOT / "data" / "examples" / "example_smiles.smi" | |
| DEFAULT_EXAMPLE_1000 = ROOT / "data" / "examples" / "example_smiles_1000.smi" | |
| def _read_smiles(path: Path, n_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) >= n_ligands: | |
| break | |
| return rows | |
| def _read_all_smiles(path: Path) -> 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)) | |
| return rows | |
| def _default_ligand_jobs() -> int: | |
| cpu_total = os.cpu_count() or 8 | |
| return max(1, cpu_total - 4) | |
| def _mkdir_or_fail(path: Path) -> None: | |
| try: | |
| path.mkdir(parents=True, exist_ok=True) | |
| except PermissionError as exc: | |
| suggestion = Path.home() / "datasets" / path.name | |
| raise RDockPipelineError( | |
| f"Cannot create output directory {path}: permission denied. " | |
| f"Use a writable path such as {suggestion} or a relative path under your home/project directory." | |
| ) from exc | |
| def _http_json(url: str, timeout: int, retries: int = 3, pause_seconds: float = 1.0) -> dict[str, object]: | |
| last_error: Exception | None = None | |
| for attempt in range(1, retries + 1): | |
| try: | |
| request = urllib.request.Request(url, headers={"User-Agent": "portable-rdock-pipeline/1.0"}) | |
| with urllib.request.urlopen(request, timeout=timeout) as response: | |
| payload = response.read().decode("utf-8") | |
| return json.loads(payload) | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| last_error = exc | |
| if attempt < retries: | |
| time.sleep(pause_seconds * attempt) | |
| raise RDockPipelineError(f"HTTP JSON request failed after {retries} attempts for {url}: {last_error}") | |
| def _http_post_json( | |
| url: str, | |
| data: bytes, | |
| content_type: str, | |
| timeout: int, | |
| retries: int = 3, | |
| pause_seconds: float = 1.0, | |
| ) -> dict[str, object]: | |
| last_error: Exception | None = None | |
| for attempt in range(1, retries + 1): | |
| try: | |
| request = urllib.request.Request( | |
| url, | |
| data=data, | |
| headers={"User-Agent": "portable-rdock-pipeline/1.0", "Content-Type": content_type}, | |
| method="POST", | |
| ) | |
| with urllib.request.urlopen(request, timeout=timeout) as response: | |
| payload = response.read().decode("utf-8") | |
| return json.loads(payload) | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| last_error = exc | |
| if attempt < retries: | |
| time.sleep(pause_seconds * attempt) | |
| raise RDockPipelineError(f"HTTP POST JSON request failed after {retries} attempts for {url}: {last_error}") | |
| def _http_post_form_json( | |
| url: str, | |
| form: dict[str, str], | |
| timeout: int, | |
| retries: int = 3, | |
| pause_seconds: float = 1.0, | |
| ) -> dict[str, object]: | |
| body = urllib.parse.urlencode(form).encode("utf-8") | |
| return _http_post_json(url, body, "application/x-www-form-urlencoded", timeout, retries=retries, pause_seconds=pause_seconds) | |
| 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"{smiles} {ligand_id}" for smiles, ligand_id in rows) + "\n", encoding="utf-8") | |
| return path | |
| def _count_sdf_records_lenient(path: Path) -> int: | |
| if not path.exists() or path.stat().st_size <= 0: | |
| return 0 | |
| text = path.read_text(encoding="utf-8", errors="ignore") | |
| return len(split_sdf_text(text)) | |
| def _progress_log(out: Path, message: str, payload: dict[str, object] | None = None) -> None: | |
| line = message | |
| print(line, file=sys.stderr, flush=True) | |
| log_path = out / "logs" / "pubchem_progress.log" | |
| log_path.parent.mkdir(parents=True, exist_ok=True) | |
| with log_path.open("a", encoding="utf-8") as handle: | |
| handle.write(line + "\n") | |
| if payload is not None: | |
| status_path = out / "logs" / "pubchem_progress.json" | |
| status_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") | |
| def _write_partial_pubchem_hits( | |
| out: Path, | |
| rows: list[tuple[str, str]], | |
| metadata_rows: list[dict[str, object]], | |
| ) -> None: | |
| if not rows: | |
| return | |
| _write_smi(rows, out / "ligands" / "pubchem_partial_hits.smi") | |
| _write_csv(out / "ligands" / "pubchem_partial_metadata.csv", metadata_rows) | |
| def _obabel_convert(runner: CommandRunner, stage: str, input_path: Path, output_path: Path, extra_args: list[str], cwd: Path) -> Path: | |
| obabel = require_executable("obabel") | |
| rec = runner.run( | |
| stage, | |
| [obabel, str(input_path.resolve()), *extra_args, "-O", str(output_path.resolve())], | |
| cwd, | |
| cwd / "logs" / f"{stage}.stdout.log", | |
| cwd / "logs" / f"{stage}.stderr.log", | |
| ) | |
| fail_if_bad_command(rec, f"OpenBabel {stage}") | |
| return require_file(output_path, f"OpenBabel output {stage}") | |
| def _merge_sdf_files(inputs: list[Path], output_path: Path) -> Path: | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| with output_path.open("w", encoding="utf-8") as handle: | |
| for path in inputs: | |
| if not path.exists() or path.stat().st_size <= 0: | |
| continue | |
| text = path.read_text(encoding="utf-8", errors="ignore") | |
| if text and not text.endswith("\n"): | |
| text += "\n" | |
| handle.write(text) | |
| return output_path | |
| def _convert_single_ligand_with_obabel( | |
| runner: CommandRunner, | |
| row: tuple[str, str], | |
| work_dir: Path, | |
| ) -> tuple[Path | None, dict[str, object] | None]: | |
| smiles, ligand_id = row | |
| smi_path = work_dir / f"{ligand_id}.smi" | |
| sdf_path = work_dir / f"{ligand_id}.sdf" | |
| smi_path.write_text(f"{smiles} {ligand_id}\n", encoding="utf-8") | |
| try: | |
| _obabel_convert(runner, f"single_{ligand_id}_to_sdf", smi_path, sdf_path, ["--gen3d", "-h"], work_dir) | |
| if _count_sdf_records_lenient(sdf_path) != 1: | |
| raise RDockPipelineError(f"Expected 1 SDF record for ligand {ligand_id}, got {_count_sdf_records_lenient(sdf_path)}") | |
| return sdf_path, None | |
| except Exception as exc: | |
| return None, {"ligand_id": ligand_id, "smiles": smiles, "reason": str(exc), "stage": "single_ligand_fallback"} | |
| def _convert_batch_with_obabel( | |
| runner: CommandRunner, | |
| batch_rows: list[tuple[str, str]], | |
| batch_dir: Path, | |
| batch_name: str, | |
| single_fallback_workers: int, | |
| ) -> tuple[Path, list[dict[str, object]]]: | |
| batch_dir.mkdir(parents=True, exist_ok=True) | |
| batch_smi = _write_smi(batch_rows, batch_dir / f"{batch_name}.smi") | |
| batch_sdf = batch_dir / f"{batch_name}.sdf" | |
| invalid_rows: list[dict[str, object]] = [] | |
| try: | |
| _obabel_convert(runner, f"{batch_name}_to_sdf", batch_smi, batch_sdf, ["--gen3d", "-h"], batch_dir) | |
| if _count_sdf_records_lenient(batch_sdf) == len(batch_rows): | |
| return batch_sdf, invalid_rows | |
| except Exception as exc: | |
| invalid_rows.append({"ligand_id": batch_name, "smiles": "", "reason": str(exc), "stage": "batch_conversion"}) | |
| single_dir = batch_dir / f"{batch_name}_single" | |
| single_dir.mkdir(parents=True, exist_ok=True) | |
| single_outputs: dict[str, Path] = {} | |
| with ThreadPoolExecutor(max_workers=min(max(1, single_fallback_workers), len(batch_rows))) as pool: | |
| futures = { | |
| pool.submit(_convert_single_ligand_with_obabel, runner, row, single_dir): row | |
| for row in batch_rows | |
| } | |
| for future in as_completed(futures): | |
| row = futures[future] | |
| output_path, invalid = future.result() | |
| if output_path is not None: | |
| single_outputs[row[1]] = output_path | |
| if invalid is not None: | |
| invalid_rows.append(invalid) | |
| ordered_outputs = [single_outputs[ligand_id] for _, ligand_id in batch_rows if ligand_id in single_outputs] | |
| _merge_sdf_files(ordered_outputs, batch_sdf) | |
| return batch_sdf, invalid_rows | |
| def _convert_batch_with_obabel_worker( | |
| batch_rows: list[tuple[str, str]], | |
| batch_dir: str, | |
| batch_name: str, | |
| single_fallback_workers: int, | |
| ) -> tuple[str, list[dict[str, object]]]: | |
| batch_path = Path(batch_dir) | |
| runner = CommandRunner(batch_path / "logs" / "commands.log") | |
| sdf_path, invalid_rows = _convert_batch_with_obabel( | |
| runner, | |
| batch_rows, | |
| batch_path, | |
| batch_name, | |
| single_fallback_workers, | |
| ) | |
| return str(sdf_path), invalid_rows | |
| def _prepare_ligands_from_existing_smi( | |
| out: Path, | |
| runner: CommandRunner, | |
| batch_size: int, | |
| jobs: int | str, | |
| cpu_fraction: float, | |
| force_rebuild: bool = False, | |
| metadata_rows: list[dict[str, object]] | None = None, | |
| ) -> dict[str, object]: | |
| lig_root = out / "ligands" | |
| smi_path = require_file(lig_root / "all_ligands.smi", "all_ligands.smi for ligand preparation") | |
| rows = _read_all_smiles(smi_path) | |
| if not rows: | |
| raise RDockPipelineError(f"No usable SMILES rows found in {smi_path}") | |
| expected_total = len(rows) | |
| final_sdf = lig_root / "all_ligands.sdf" | |
| existing_final = _count_sdf_records_lenient(final_sdf) | |
| if existing_final > expected_total: | |
| raise RDockPipelineError( | |
| f"Existing {final_sdf} contains {existing_final} records but {smi_path} contains only {expected_total} ligands. " | |
| "Refuse to resume from an inconsistent dataset." | |
| ) | |
| if not force_rebuild and existing_final == expected_total: | |
| metadata_path = lig_root / "ligand_metadata.csv" | |
| if not metadata_path.exists(): | |
| _write_csv(metadata_path, [{"ligand_id": ligand_id, "smiles": smiles, "source": "smiles_file"} for smiles, ligand_id in rows]) | |
| invalid_path = lig_root / "invalid_ligands.csv" | |
| if not invalid_path.exists(): | |
| _write_csv(invalid_path, []) | |
| return { | |
| "mode": "prepare_ligands_only", | |
| "status": "already_complete", | |
| "expected_ligands": expected_total, | |
| "prepared_ligands": existing_final, | |
| "batch_size": batch_size, | |
| "jobs": _default_ligand_jobs() if str(jobs).strip().lower() == "auto" else resolve_jobs(jobs, cpu_fraction), | |
| "final_sdf": str(final_sdf), | |
| } | |
| batch_root = lig_root / "obabel_batches" | |
| batch_root.mkdir(parents=True, exist_ok=True) | |
| progress_path = lig_root / "ligand_preparation_progress.json" | |
| resume_prefix_count = 0 | |
| recovered_prefix_sdf: Path | None = None | |
| if not force_rebuild and existing_final > 0: | |
| existing_batch_files = list(batch_root.glob("batch_*/*.sdf")) | |
| if not existing_batch_files: | |
| resume_prefix_count = existing_final | |
| recovered_prefix_sdf = batch_root / "recovered_prefix.sdf" | |
| shutil.copy2(final_sdf, recovered_prefix_sdf) | |
| batches: list[tuple[str, list[tuple[str, str]]]] = [] | |
| for batch_index, start in enumerate(range(0, expected_total, batch_size), start=1): | |
| batches.append((f"batch_{batch_index:05d}", rows[start : start + batch_size])) | |
| resolved_jobs = _default_ligand_jobs() if str(jobs).strip().lower() == "auto" else resolve_jobs(jobs, cpu_fraction) | |
| invalid_rows: list[dict[str, object]] = [] | |
| completed_batch_outputs: dict[str, Path] = {} | |
| if recovered_prefix_sdf is not None: | |
| completed_batch_outputs["__recovered_prefix__"] = recovered_prefix_sdf | |
| pending_batches: list[tuple[str, list[tuple[str, str]]]] = [] | |
| ligands_skipped_by_prefix = 0 | |
| for batch_number, (batch_name, batch_rows) in enumerate(batches, start=1): | |
| batch_start = (batch_number - 1) * batch_size | |
| batch_end = batch_start + len(batch_rows) | |
| if resume_prefix_count and batch_end <= resume_prefix_count: | |
| ligands_skipped_by_prefix += len(batch_rows) | |
| continue | |
| if resume_prefix_count and batch_start < resume_prefix_count < batch_end: | |
| prefix_skip = resume_prefix_count - batch_start | |
| ligands_skipped_by_prefix += prefix_skip | |
| batch_rows = batch_rows[prefix_skip:] | |
| if not batch_rows: | |
| continue | |
| batch_dir = batch_root / batch_name | |
| batch_sdf = batch_dir / f"{batch_name}.sdf" | |
| if (not force_rebuild) and _count_sdf_records_lenient(batch_sdf) == len(batch_rows): | |
| completed_batch_outputs[batch_name] = batch_sdf | |
| continue | |
| pending_batches.append((batch_name, batch_rows)) | |
| progress_path.write_text( | |
| json.dumps( | |
| { | |
| "expected_ligands": expected_total, | |
| "prepared_batches": len(completed_batch_outputs), | |
| "total_batches": len(batches), | |
| "pending_batches": [name for name, _ in pending_batches[:1000]], | |
| "resumed_from_existing_final_sdf_records": resume_prefix_count, | |
| "ligands_skipped_by_prefix_resume": ligands_skipped_by_prefix, | |
| "jobs": resolved_jobs, | |
| "batch_size": batch_size, | |
| }, | |
| indent=2, | |
| ), | |
| encoding="utf-8", | |
| ) | |
| if pending_batches: | |
| progress = tqdm(total=len(pending_batches), desc="Ligand 3D batches", unit="batch") if tqdm is not None else None | |
| ligand_progress = tqdm(total=expected_total, desc="Ligands prepared", unit="lig") if tqdm is not None else None | |
| if ligand_progress is not None: | |
| ligand_progress.update(sum(_count_sdf_records_lenient(path) for path in completed_batch_outputs.values())) | |
| max_workers = min(resolved_jobs, len(pending_batches)) | |
| executor_cls = ProcessPoolExecutor | |
| pool = None | |
| try: | |
| pool = executor_cls(max_workers=max_workers) | |
| except Exception: | |
| executor_cls = ThreadPoolExecutor | |
| pool = executor_cls(max_workers=max_workers) | |
| with pool: | |
| futures = { | |
| pool.submit( | |
| _convert_batch_with_obabel_worker, | |
| batch_rows, | |
| str(batch_root / batch_name), | |
| batch_name, | |
| max(1, min(4, resolved_jobs)), | |
| ): batch_name | |
| for batch_name, batch_rows in pending_batches | |
| } | |
| for future in as_completed(futures): | |
| batch_name = futures[future] | |
| batch_sdf, batch_invalid = future.result() | |
| completed_batch_outputs[batch_name] = Path(batch_sdf) | |
| invalid_rows.extend(batch_invalid) | |
| batch_prepared = _count_sdf_records_lenient(Path(batch_sdf)) | |
| if progress is not None: | |
| progress.update(1) | |
| progress.set_postfix(last_batch=batch_name, invalid=len(invalid_rows), worker=executor_cls.__name__) | |
| if ligand_progress is not None: | |
| ligand_progress.update(batch_prepared) | |
| ligand_progress.set_postfix(last_batch=batch_name, invalid=len(invalid_rows), worker=executor_cls.__name__) | |
| prepared_count = sum(_count_sdf_records_lenient(path) for path in completed_batch_outputs.values()) | |
| progress_path.write_text( | |
| json.dumps( | |
| { | |
| "expected_ligands": expected_total, | |
| "prepared_batches": len(completed_batch_outputs), | |
| "total_batches": len(batches), | |
| "prepared_ligands_estimate": prepared_count, | |
| "resumed_from_existing_final_sdf_records": resume_prefix_count, | |
| "ligands_skipped_by_prefix_resume": ligands_skipped_by_prefix, | |
| "jobs": resolved_jobs, | |
| "batch_size": batch_size, | |
| "worker_backend": executor_cls.__name__, | |
| "last_completed_batch": batch_name, | |
| "invalid_count": len(invalid_rows), | |
| }, | |
| indent=2, | |
| ), | |
| encoding="utf-8", | |
| ) | |
| if progress is not None: | |
| progress.close() | |
| if ligand_progress is not None: | |
| ligand_progress.close() | |
| ordered_outputs: list[Path] = [] | |
| if "__recovered_prefix__" in completed_batch_outputs: | |
| ordered_outputs.append(completed_batch_outputs["__recovered_prefix__"]) | |
| ordered_outputs.extend(completed_batch_outputs[batch_name] for batch_name, _ in batches if batch_name in completed_batch_outputs) | |
| _merge_sdf_files(ordered_outputs, final_sdf) | |
| prepared_count = _count_sdf_records_lenient(final_sdf) | |
| metadata_payload = metadata_rows or _existing_ligand_metadata_payload(lig_root, expected_total) | |
| if metadata_payload is None: | |
| metadata_payload = [{"ligand_id": ligand_id, "smiles": smiles, "source": "smiles_file"} for smiles, ligand_id in rows] | |
| _write_csv(lig_root / "ligand_metadata.csv", metadata_payload) | |
| _write_csv(lig_root / "invalid_ligands.csv", invalid_rows) | |
| progress_path.write_text( | |
| json.dumps( | |
| { | |
| "expected_ligands": expected_total, | |
| "prepared_ligands": prepared_count, | |
| "invalid_ligands": len(invalid_rows), | |
| "prepared_batches": len(ordered_outputs), | |
| "total_batches": len(batches), | |
| "resumed_from_existing_final_sdf_records": resume_prefix_count, | |
| "ligands_skipped_by_prefix_resume": ligands_skipped_by_prefix, | |
| "jobs": resolved_jobs, | |
| "batch_size": batch_size, | |
| "final_sdf": str(final_sdf), | |
| "status": "complete" if prepared_count > 0 else "empty", | |
| }, | |
| indent=2, | |
| ), | |
| encoding="utf-8", | |
| ) | |
| return { | |
| "mode": "prepare_ligands_only", | |
| "status": "complete" if prepared_count > 0 else "empty", | |
| "expected_ligands": expected_total, | |
| "prepared_ligands": prepared_count, | |
| "invalid_ligands": len(invalid_rows), | |
| "batch_size": batch_size, | |
| "jobs": resolved_jobs, | |
| "resumed_from_existing_final_sdf_records": resume_prefix_count, | |
| "ligands_skipped_by_prefix_resume": ligands_skipped_by_prefix, | |
| "final_sdf": str(final_sdf), | |
| "progress_json": str(progress_path), | |
| } | |
| def _reference_ligand_to_smiles(runner: CommandRunner, reference_sdf: Path, cwd: Path) -> str: | |
| obabel = require_executable("obabel") | |
| stdout_log = cwd / "logs" / "reference_ligand_to_smiles.stdout.log" | |
| stderr_log = cwd / "logs" / "reference_ligand_to_smiles.stderr.log" | |
| rec = runner.run( | |
| "reference_ligand_to_smiles", | |
| [obabel, str(reference_sdf.resolve()), "-osmi"], | |
| cwd, | |
| stdout_log, | |
| stderr_log, | |
| ) | |
| fail_if_bad_command(rec, "OpenBabel reference ligand to SMILES") | |
| text = stdout_log.read_text(encoding="utf-8", errors="ignore").strip() | |
| if not text: | |
| raise RDockPipelineError(f"OpenBabel did not produce SMILES for reference ligand {reference_sdf}") | |
| first = text.splitlines()[0].strip() | |
| parts = first.split() | |
| if not parts: | |
| raise RDockPipelineError(f"Could not parse OpenBabel SMILES output for {reference_sdf}: {first!r}") | |
| return parts[0] | |
| def _reference_ligand_sdf_block(reference_sdf: Path) -> str: | |
| text = reference_sdf.read_text(encoding="utf-8", errors="ignore") | |
| first = text.split("$$$$", 1)[0].strip() | |
| if not first: | |
| raise RDockPipelineError(f"Reference ligand SDF is empty or unreadable: {reference_sdf}") | |
| return first + "\n$$$$\n" | |
| def _canonicalize_smiles_for_filter(smiles: str) -> str: | |
| return smiles.strip() | |
| def _looks_organic_smiles(smiles: str) -> bool: | |
| text = _canonicalize_smiles_for_filter(smiles) | |
| if not text or "." in text: | |
| return False | |
| return "C" in text or "c" in text | |
| def _parse_threshold_ladder(text: str) -> list[int]: | |
| try: | |
| values = [int(part.strip()) for part in text.split(",") if part.strip()] | |
| except Exception as exc: | |
| raise RDockPipelineError(f"Invalid --pubchem-threshold-ladder value {text!r}: {exc}") from exc | |
| if not values: | |
| raise RDockPipelineError("Empty --pubchem-threshold-ladder") | |
| return values | |
| def _resolve_threshold_ladder(args: argparse.Namespace) -> list[int]: | |
| ladder_override = str(getattr(args, "similarity_thresholds", "") or "").strip() | |
| if ladder_override: | |
| return _parse_threshold_ladder(ladder_override) | |
| start = getattr(args, "pubchem_threshold_start", None) | |
| stop = getattr(args, "pubchem_threshold_stop", None) | |
| step = int(getattr(args, "pubchem_threshold_step", 1) or 1) | |
| if start is not None or stop is not None: | |
| start_value = int(99 if start is None else start) | |
| stop_value = int(70 if stop is None else stop) | |
| if step <= 0: | |
| raise RDockPipelineError("--pubchem-threshold-step must be a positive integer") | |
| if start_value < stop_value: | |
| raise RDockPipelineError( | |
| f"Invalid PubChem threshold range: start {start_value} is lower than stop {stop_value}. " | |
| "Use a descending range such as --pubchem-threshold-start 99 --pubchem-threshold-stop 80." | |
| ) | |
| return list(range(start_value, stop_value - 1, -step)) | |
| return _parse_threshold_ladder(args.pubchem_threshold_ladder) | |
| def _pubchem_similarity_cids_from_sdf(reference_sdf_block: str, threshold: int, max_records: int, timeout: int) -> list[int]: | |
| url = ( | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/" | |
| f"sdf/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}&MaxSeconds={int(timeout)}" | |
| ) | |
| payload = _http_post_form_json(url, {"sdf": reference_sdf_block}, timeout) | |
| info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {} | |
| cids = info.get("CID", []) if isinstance(info, dict) else [] | |
| return [int(cid) for cid in cids] | |
| def _pubchem_identity_cids_from_sdf(reference_sdf_block: str, timeout: int) -> list[int]: | |
| url = ( | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastidentity/" | |
| f"sdf/cids/JSON?identity_type=same_connectivity&MaxRecords=10&MaxSeconds={int(timeout)}" | |
| ) | |
| payload = _http_post_form_json(url, {"sdf": reference_sdf_block}, timeout) | |
| info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {} | |
| cids = info.get("CID", []) if isinstance(info, dict) else [] | |
| return [int(cid) for cid in cids] | |
| def _pubchem_identity_cids_from_smiles(reference_smiles: str, timeout: int) -> list[int]: | |
| encoded = urllib.parse.quote(reference_smiles, safe="") | |
| identity_url = ( | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastidentity/" | |
| f"smiles/{encoded}/cids/JSON?identity_type=same_connectivity&MaxRecords=10&MaxSeconds={int(timeout)}" | |
| ) | |
| identity_payload = _http_json(identity_url, timeout) | |
| identity_info = identity_payload.get("IdentifierList", {}) if isinstance(identity_payload, dict) else {} | |
| identity_cids = identity_info.get("CID", []) if isinstance(identity_info, dict) else [] | |
| return [int(cid) for cid in identity_cids] | |
| def _pubchem_reference_cid( | |
| reference_smiles: str, | |
| timeout: int, | |
| reference_sdf_block: str | None = None, | |
| ) -> int | None: | |
| try: | |
| identity_cids = _pubchem_identity_cids_from_smiles(reference_smiles, timeout) | |
| if identity_cids: | |
| return int(identity_cids[0]) | |
| except Exception: # pragma: no cover - network-dependent | |
| pass | |
| if reference_sdf_block: | |
| try: | |
| identity_cids = _pubchem_identity_cids_from_sdf(reference_sdf_block, timeout) | |
| if identity_cids: | |
| return int(identity_cids[0]) | |
| except Exception: # pragma: no cover - network-dependent | |
| pass | |
| return None | |
| def _pubchem_similarity_cids_from_cid(reference_cid: int, threshold: int, max_records: int, timeout: int) -> list[int]: | |
| cid_url = ( | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/" | |
| f"cid/{int(reference_cid)}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}&MaxSeconds={int(timeout)}" | |
| ) | |
| cid_payload = _http_json(cid_url, timeout) | |
| cid_info = cid_payload.get("IdentifierList", {}) if isinstance(cid_payload, dict) else {} | |
| cid_hits = cid_info.get("CID", []) if isinstance(cid_info, dict) else [] | |
| return [int(cid) for cid in cid_hits] | |
| def _pubchem_similarity_cids( | |
| reference_smiles: str, | |
| threshold: int, | |
| max_records: int, | |
| timeout: int, | |
| reference_sdf_block: str | None = None, | |
| reference_cid: int | None = None, | |
| ) -> list[int]: | |
| errors: list[str] = [] | |
| if reference_cid is not None: | |
| try: | |
| parsed = _pubchem_similarity_cids_from_cid(reference_cid, threshold, max_records, timeout) | |
| if parsed: | |
| return parsed | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| errors.append(f"cid_fastsim:{exc}") | |
| if reference_sdf_block: | |
| try: | |
| parsed = _pubchem_similarity_cids_from_sdf(reference_sdf_block, threshold, max_records, timeout) | |
| if parsed: | |
| return parsed | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| errors.append(f"sdf_fastsim:{exc}") | |
| try: | |
| identity_cids = _pubchem_identity_cids_from_sdf(reference_sdf_block, timeout) | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| identity_cids = [] | |
| errors.append(f"sdf_identity:{exc}") | |
| if identity_cids: | |
| ref_cid = int(identity_cids[0]) | |
| cid_url = ( | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/" | |
| f"cid/{ref_cid}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}&MaxSeconds={int(timeout)}" | |
| ) | |
| try: | |
| cid_payload = _http_json(cid_url, timeout) | |
| cid_info = cid_payload.get("IdentifierList", {}) if isinstance(cid_payload, dict) else {} | |
| cid_hits = cid_info.get("CID", []) if isinstance(cid_info, dict) else [] | |
| parsed = [int(cid) for cid in cid_hits] | |
| if parsed: | |
| return parsed | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| errors.append(f"cid_fastsim_from_sdf:{exc}") | |
| encoded = urllib.parse.quote(reference_smiles, safe="") | |
| url = ( | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/" | |
| f"smiles/{encoded}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}&MaxSeconds={int(timeout)}" | |
| ) | |
| try: | |
| payload = _http_json(url, timeout) | |
| info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {} | |
| cids = info.get("CID", []) if isinstance(info, dict) else [] | |
| parsed = [int(cid) for cid in cids] | |
| if parsed: | |
| return parsed | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| errors.append(f"smiles_fastsim:{exc}") | |
| identity_url = ( | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastidentity/" | |
| f"smiles/{encoded}/cids/JSON?identity_type=same_connectivity&MaxRecords=10&MaxSeconds={int(timeout)}" | |
| ) | |
| try: | |
| identity_payload = _http_json(identity_url, timeout) | |
| identity_info = identity_payload.get("IdentifierList", {}) if isinstance(identity_payload, dict) else {} | |
| identity_cids = identity_info.get("CID", []) if isinstance(identity_info, dict) else [] | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| identity_cids = [] | |
| errors.append(f"smiles_identity:{exc}") | |
| if not identity_cids: | |
| return [] | |
| try: | |
| return _pubchem_similarity_cids_from_cid(int(identity_cids[0]), threshold, max_records, timeout) | |
| except Exception: # pragma: no cover - network-dependent | |
| return [] | |
| def _pubchem_name_search_cids(query: str, max_records: int, timeout: int) -> list[int]: | |
| encoded = urllib.parse.quote(query.strip(), safe="") | |
| url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{encoded}/cids/JSON?MaxRecords={int(max_records)}" | |
| payload = _http_json(url, timeout) | |
| info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {} | |
| cids = info.get("CID", []) if isinstance(info, dict) else [] | |
| return [int(cid) for cid in cids] | |
| def _default_pubchem_workers() -> int: | |
| cpu_count = os.cpu_count() or 4 | |
| return max(2, min(8, cpu_count // 2 or 1)) | |
| def _pubchem_fetch_properties_chunk(chunk: list[int], timeout: int) -> list[dict[str, object]]: | |
| cid_text = ",".join(str(cid) for cid in chunk) | |
| url = ( | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" | |
| f"{cid_text}/property/SMILES,ConnectivitySMILES,IUPACName,Title,MolecularFormula,MolecularWeight," | |
| "XLogP,TPSA,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount/JSON" | |
| ) | |
| payload = _http_json(url, timeout) | |
| table = payload.get("PropertyTable", {}) if isinstance(payload, dict) else {} | |
| props = table.get("Properties", []) if isinstance(table, dict) else [] | |
| return [item for item in props if isinstance(item, dict)] | |
| def _pubchem_fetch_properties_chunk_resilient( | |
| chunk: list[int], | |
| timeout: int, | |
| out: Path | None = None, | |
| progress_prefix: str = "", | |
| chunk_label: str = "", | |
| ) -> list[dict[str, object]]: | |
| if not chunk: | |
| return [] | |
| try: | |
| return _pubchem_fetch_properties_chunk(chunk, timeout) | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| if len(chunk) <= 1: | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"{progress_prefix} property fetch failed for single CID chunk {chunk_label}: {exc}", | |
| ) | |
| return [] | |
| mid = max(1, len(chunk) // 2) | |
| left = chunk[:mid] | |
| right = chunk[mid:] | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"{progress_prefix} property chunk {chunk_label} failed ({exc}); splitting {len(chunk)} CIDs into {len(left)} + {len(right)}", | |
| ) | |
| left_rows = _pubchem_fetch_properties_chunk_resilient( | |
| left, | |
| timeout, | |
| out=out, | |
| progress_prefix=progress_prefix, | |
| chunk_label=f"{chunk_label}.L", | |
| ) | |
| right_rows = _pubchem_fetch_properties_chunk_resilient( | |
| right, | |
| timeout, | |
| out=out, | |
| progress_prefix=progress_prefix, | |
| chunk_label=f"{chunk_label}.R", | |
| ) | |
| return left_rows + right_rows | |
| def _pubchem_fetch_properties( | |
| cids: list[int], | |
| timeout: int, | |
| out: Path | None = None, | |
| progress_prefix: str = "", | |
| workers: int = 1, | |
| chunk_size: int = 200, | |
| ) -> list[dict[str, object]]: | |
| if not cids: | |
| return [] | |
| chunk_size = max(1, int(chunk_size)) | |
| workers = max(1, int(workers)) | |
| chunks = [cids[start : start + chunk_size] for start in range(0, len(cids), chunk_size)] | |
| rows: list[dict[str, object]] = [] | |
| if workers == 1 or len(chunks) == 1: | |
| for index, chunk in enumerate(chunks, start=1): | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"{progress_prefix} fetching properties chunk {index}/{len(chunks)} ({len(chunk)} CIDs)", | |
| ) | |
| rows.extend( | |
| _pubchem_fetch_properties_chunk_resilient( | |
| chunk, | |
| timeout, | |
| out=out, | |
| progress_prefix=progress_prefix, | |
| chunk_label=f"{index}/{len(chunks)}", | |
| ) | |
| ) | |
| return rows | |
| with ThreadPoolExecutor(max_workers=min(workers, len(chunks))) as pool: | |
| futures = { | |
| pool.submit(_pubchem_fetch_properties_chunk, chunk, timeout): (index, chunk) | |
| for index, chunk in enumerate(chunks, start=1) | |
| } | |
| for future in as_completed(futures): | |
| index, chunk = futures[future] | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"{progress_prefix} fetching properties chunk {index}/{len(chunks)} ({len(chunk)} CIDs)", | |
| ) | |
| try: | |
| rows.extend(future.result()) | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"{progress_prefix} property chunk {index}/{len(chunks)} failed asynchronously ({exc}); retrying with recursive split", | |
| ) | |
| rows.extend( | |
| _pubchem_fetch_properties_chunk_resilient( | |
| chunk, | |
| timeout, | |
| out=out, | |
| progress_prefix=progress_prefix, | |
| chunk_label=f"{index}/{len(chunks)}", | |
| ) | |
| ) | |
| return rows | |
| def _resolve_pubchem_max_records( | |
| needed: int, | |
| record_multiplier: int, | |
| min_records_per_threshold: int, | |
| max_records_per_threshold: int, | |
| ) -> int: | |
| candidate = max(int(needed) * int(record_multiplier), int(min_records_per_threshold)) | |
| return max(1, min(candidate, int(max_records_per_threshold))) | |
| def _pubchem_similarity_rows( | |
| reference_smiles: str, | |
| reference_sdf_block: str, | |
| n_ligands: int, | |
| threshold_ladder: list[int], | |
| timeout: int, | |
| allow_partial: bool = False, | |
| out: Path | None = None, | |
| property_workers: int = 1, | |
| property_chunk_size: int = 200, | |
| record_multiplier: int = 8, | |
| min_records_per_threshold: int = 1000, | |
| max_records_per_threshold: int = 5000, | |
| ) -> tuple[list[tuple[str, str]], list[dict[str, object]], list[dict[str, object]], str | None]: | |
| collected_smiles: dict[str, tuple[str, str]] = {} | |
| metadata: list[dict[str, object]] = [] | |
| diagnostics: list[dict[str, object]] = [] | |
| reference_cid = _pubchem_reference_cid(reference_smiles, timeout, reference_sdf_block=reference_sdf_block) | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"PubChem reference CID resolution: {'resolved to CID ' + str(reference_cid) if reference_cid is not None else 'not resolved; using direct similarity fallbacks'}", | |
| { | |
| "mode": "pubchem_similarity", | |
| "reference_cid": reference_cid, | |
| "reference_cid_resolved": reference_cid is not None, | |
| }, | |
| ) | |
| for threshold in threshold_ladder: | |
| needed = max(0, n_ligands - len(collected_smiles)) | |
| if needed <= 0: | |
| break | |
| max_records = _resolve_pubchem_max_records( | |
| needed, | |
| record_multiplier=record_multiplier, | |
| min_records_per_threshold=min_records_per_threshold, | |
| max_records_per_threshold=max_records_per_threshold, | |
| ) | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"PubChem similarity threshold {threshold}: requesting up to {max_records} records; collected so far {len(collected_smiles)}/{n_ligands}", | |
| { | |
| "mode": "pubchem_similarity", | |
| "threshold": threshold, | |
| "requested_ligands": n_ligands, | |
| "collected_ligands": len(collected_smiles), | |
| "needed_ligands": needed, | |
| "max_records": max_records, | |
| }, | |
| ) | |
| similarity_kwargs: dict[str, object] = { | |
| "max_records": max_records, | |
| "timeout": timeout, | |
| "reference_sdf_block": reference_sdf_block, | |
| } | |
| if reference_cid is not None: | |
| similarity_kwargs["reference_cid"] = reference_cid | |
| try: | |
| cids = _pubchem_similarity_cids( | |
| reference_smiles, | |
| threshold, | |
| **similarity_kwargs, | |
| ) | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| diagnostics.append( | |
| { | |
| "threshold": threshold, | |
| "returned_cids": 0, | |
| "accepted_new_smiles": 0, | |
| "collected_total": len(collected_smiles), | |
| "error": str(exc), | |
| } | |
| ) | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"PubChem similarity threshold {threshold}: failed ({exc}); continuing to next threshold", | |
| ) | |
| continue | |
| if out is not None: | |
| _progress_log(out, f"PubChem similarity threshold {threshold}: received {len(cids)} CIDs") | |
| try: | |
| props = _pubchem_fetch_properties( | |
| cids, | |
| timeout, | |
| out=out, | |
| progress_prefix=f"PubChem threshold {threshold}:", | |
| workers=property_workers, | |
| chunk_size=property_chunk_size, | |
| ) | |
| except Exception as exc: # pragma: no cover - network-dependent | |
| diagnostics.append( | |
| { | |
| "threshold": threshold, | |
| "returned_cids": len(cids), | |
| "accepted_new_smiles": 0, | |
| "collected_total": len(collected_smiles), | |
| "error": f"property_fetch_failed: {exc}", | |
| } | |
| ) | |
| if out is not None: | |
| _progress_log( | |
| out, | |
| f"PubChem similarity threshold {threshold}: property fetch failed ({exc}); continuing to next threshold", | |
| ) | |
| continue | |
| accepted = 0 | |
| for item in props: | |
| smiles = str( | |
| item.get("SMILES") | |
| or item.get("ConnectivitySMILES") | |
| or item.get("CanonicalSMILES", "") | |
| ).strip() | |
| cid = int(item.get("CID", 0) or 0) | |
| if not smiles or cid <= 0 or not _looks_organic_smiles(smiles): | |
| continue | |
| ligand_id = f"pubchem_cid_{cid}" | |
| if ligand_id in collected_smiles: | |
| continue | |
| collected_smiles[ligand_id] = (smiles, ligand_id) | |
| metadata.append( | |
| { | |
| "ligand_id": ligand_id, | |
| "smiles": smiles, | |
| "source": "pubchem_similarity", | |
| "pubchem_cid": cid, | |
| "pubchem_threshold": threshold, | |
| "pubchem_title": item.get("Title", ""), | |
| "iupac_name": item.get("IUPACName", ""), | |
| "molecular_formula": item.get("MolecularFormula", ""), | |
| "molecular_weight": item.get("MolecularWeight", ""), | |
| "xlogp": item.get("XLogP", ""), | |
| "tpsa": item.get("TPSA", ""), | |
| "hbd": item.get("HBondDonorCount", ""), | |
| "hba": item.get("HBondAcceptorCount", ""), | |
| "rotatable_bonds": item.get("RotatableBondCount", ""), | |
| "heavy_atom_count": item.get("HeavyAtomCount", ""), | |
| } | |
| ) | |
| accepted += 1 | |
| if len(collected_smiles) >= n_ligands: | |
| break | |
| diagnostics.append( | |
| { | |
| "threshold": threshold, | |
| "returned_cids": len(cids), | |
| "accepted_new_smiles": accepted, | |
| "collected_total": len(collected_smiles), | |
| } | |
| ) | |
| if out is not None: | |
| _write_partial_pubchem_hits(out, list(collected_smiles.values()), metadata) | |
| _progress_log( | |
| out, | |
| f"PubChem similarity threshold {threshold}: accepted {accepted} new ligands; total {len(collected_smiles)}/{n_ligands}", | |
| { | |
| "mode": "pubchem_similarity", | |
| "threshold": threshold, | |
| "requested_ligands": n_ligands, | |
| "collected_ligands": len(collected_smiles), | |
| "accepted_new_smiles": accepted, | |
| "returned_cids": len(cids), | |
| }, | |
| ) | |
| if len(collected_smiles) >= n_ligands: | |
| _progress_log( | |
| out, | |
| f"PubChem similarity target reached: collected {len(collected_smiles)}/{n_ligands} ligands", | |
| { | |
| "mode": "pubchem_similarity", | |
| "threshold": threshold, | |
| "requested_ligands": n_ligands, | |
| "collected_ligands": len(collected_smiles), | |
| "target_reached": True, | |
| }, | |
| ) | |
| warning: str | None = None | |
| if len(collected_smiles) < n_ligands: | |
| warning = ( | |
| f"PubChem similarity search collected {len(collected_smiles)} ligands after thresholds {threshold_ladder}. " | |
| f"Requested {n_ligands}." | |
| ) | |
| if len(collected_smiles) < n_ligands and not allow_partial: | |
| raise RDockPipelineError( | |
| f"PubChem similarity search collected only {len(collected_smiles)} ligands for reference SMILES after thresholds " | |
| f"{threshold_ladder}. Requested {n_ligands}. Lower the threshold ladder, request fewer ligands, or provide --smiles-file." | |
| ) | |
| rows = list(collected_smiles.values())[:n_ligands] | |
| if out is not None: | |
| _write_partial_pubchem_hits(out, rows, metadata[:n_ligands]) | |
| return rows, metadata[:n_ligands], diagnostics, warning | |
| def _pubchem_name_rows( | |
| queries: list[str], | |
| n_ligands: int, | |
| timeout: int, | |
| ) -> tuple[list[tuple[str, str]], list[dict[str, object]], list[dict[str, object]]]: | |
| collected_smiles: dict[str, tuple[str, str]] = {} | |
| metadata: list[dict[str, object]] = [] | |
| diagnostics: list[dict[str, object]] = [] | |
| for query in [item.strip() for item in queries if item.strip()]: | |
| needed = max(0, n_ligands - len(collected_smiles)) | |
| if needed <= 0: | |
| break | |
| cids = _pubchem_name_search_cids(query, max_records=max(needed * 4, needed), timeout=timeout) | |
| props = _pubchem_fetch_properties(cids, timeout) | |
| accepted = 0 | |
| for item in props: | |
| smiles = str( | |
| item.get("SMILES") | |
| or item.get("ConnectivitySMILES") | |
| or item.get("CanonicalSMILES", "") | |
| ).strip() | |
| cid = int(item.get("CID", 0) or 0) | |
| if not smiles or cid <= 0 or not _looks_organic_smiles(smiles): | |
| continue | |
| ligand_id = f"pubchem_cid_{cid}" | |
| if ligand_id in collected_smiles: | |
| continue | |
| collected_smiles[ligand_id] = (smiles, ligand_id) | |
| metadata.append( | |
| { | |
| "ligand_id": ligand_id, | |
| "smiles": smiles, | |
| "source": "pubchem_compound_search", | |
| "pubchem_cid": cid, | |
| "pubchem_query": query, | |
| "pubchem_title": item.get("Title", ""), | |
| "iupac_name": item.get("IUPACName", ""), | |
| "molecular_formula": item.get("MolecularFormula", ""), | |
| "molecular_weight": item.get("MolecularWeight", ""), | |
| "xlogp": item.get("XLogP", ""), | |
| "tpsa": item.get("TPSA", ""), | |
| "hbd": item.get("HBondDonorCount", ""), | |
| "hba": item.get("HBondAcceptorCount", ""), | |
| "rotatable_bonds": item.get("RotatableBondCount", ""), | |
| "heavy_atom_count": item.get("HeavyAtomCount", ""), | |
| } | |
| ) | |
| accepted += 1 | |
| if len(collected_smiles) >= n_ligands: | |
| break | |
| diagnostics.append( | |
| { | |
| "query": query, | |
| "returned_cids": len(cids), | |
| "accepted_new_smiles": accepted, | |
| "collected_total": len(collected_smiles), | |
| } | |
| ) | |
| return list(collected_smiles.values())[:n_ligands], metadata[:n_ligands], diagnostics | |
| def _known_good_entry(pdb_id: str) -> dict[str, object] | None: | |
| for item in list_known_good_complexes(KNOWN_GOOD): | |
| if str(item.get("pdb_id", "")).upper() == pdb_id.upper(): | |
| return item | |
| return None | |
| def _pubchem_diagnostics_payload( | |
| source_name: str, | |
| reference_smiles: str, | |
| threshold_ladder: list[int], | |
| diagnostics: list[dict[str, object]], | |
| errors: list[str], | |
| ) -> dict[str, object]: | |
| return { | |
| "source": source_name, | |
| "reference_smiles": reference_smiles, | |
| "thresholds_tried": threshold_ladder, | |
| "requested_ligands": None, | |
| "collected_ligands": None, | |
| "endpoints_tried": [ | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/sdf/cids/JSON (POST form field: sdf=...)", | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastidentity/sdf/cids/JSON (POST form field: sdf=...)", | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{smiles}/cids/JSON", | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{query}/cids/JSON", | |
| "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cids}/property/.../JSON", | |
| ], | |
| "diagnostics": diagnostics, | |
| "errors": errors, | |
| } | |
| def _write_pubchem_diagnostics(out: Path, payload: dict[str, object]) -> Path: | |
| target = out / "logs" / "pubchem_diagnostics.json" | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_text(json.dumps(payload, indent=2), encoding="utf-8") | |
| qc_target = out / "qc" / "similarity_collection_diagnostics.json" | |
| qc_target.parent.mkdir(parents=True, exist_ok=True) | |
| qc_target.write_text(json.dumps(payload, indent=2), encoding="utf-8") | |
| return target | |
| def _resolve_smiles_source(args: argparse.Namespace) -> Path | None: | |
| if args.smiles_file: | |
| return Path(args.smiles_file) | |
| if args.ligand_source == "bundled_example": | |
| return DEFAULT_BUNDLED_EXAMPLE | |
| return None | |
| def _write_csv(path: Path, rows: list[dict[str, object]]) -> Path: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| fields: list[str] = [] | |
| for row in rows: | |
| for key in row: | |
| if key not in fields: | |
| fields.append(key) | |
| with path.open("w", encoding="utf-8", newline="") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fields) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| return path | |
| def _mol_from_smiles(smiles: str): | |
| if not RDKIT_AVAILABLE: | |
| return None | |
| try: | |
| return Chem.MolFromSmiles(str(smiles)) | |
| except Exception: | |
| return None | |
| def _canonical_smiles(smiles: str) -> str: | |
| mol = _mol_from_smiles(smiles) | |
| if mol is None: | |
| return str(smiles).strip() | |
| try: | |
| return str(Chem.MolToSmiles(mol, canonical=True)) | |
| except Exception: | |
| return str(smiles).strip() | |
| def _scaffold_smiles(mol) -> str: | |
| if not RDKIT_AVAILABLE or mol is None: | |
| return "" | |
| try: | |
| return str(MurckoScaffold.MurckoScaffoldSmiles(mol=mol) or "") | |
| except Exception: | |
| return "" | |
| def _morgan_fp(mol): | |
| if not RDKIT_AVAILABLE or mol is None: | |
| return None | |
| try: | |
| generator = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=1024) | |
| return generator.GetFingerprint(mol) | |
| except Exception: | |
| try: | |
| return rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=1024) | |
| except Exception: | |
| return None | |
| def _existing_ligand_metadata_payload(lig_root: Path, expected_total: int) -> list[dict[str, object]] | None: | |
| metadata_path = lig_root / "ligand_metadata.csv" | |
| if not metadata_path.exists(): | |
| return None | |
| try: | |
| with metadata_path.open(newline="", encoding="utf-8") as handle: | |
| rows = list(csv.DictReader(handle)) | |
| except Exception: | |
| return None | |
| return rows if len(rows) == expected_total else None | |
| def _annotate_near_duplicate_analogs( | |
| metadata_rows: list[dict[str, object]], | |
| *, | |
| tanimoto_threshold: float = 0.55, | |
| max_heavy_atom_delta: int = 3, | |
| ) -> tuple[list[dict[str, object]], dict[str, object]]: | |
| if not metadata_rows: | |
| return metadata_rows, {"analog_group_count": 0, "analog_grouped_ligands": 0, "analog_grouping_available": bool(RDKIT_AVAILABLE)} | |
| enriched: list[dict[str, object]] = [] | |
| representatives_by_scaffold: dict[str, list[int]] = {} | |
| groups: dict[str, list[int]] = {} | |
| group_parent: dict[str, str] = {} | |
| for idx, row in enumerate(metadata_rows): | |
| item = dict(row) | |
| ligand_id = str(item.get("ligand_id", f"lig_{idx:05d}")) | |
| smiles = str(item.get("smiles", "")).strip() | |
| mol = _mol_from_smiles(smiles) | |
| canonical = _canonical_smiles(smiles) | |
| scaffold = _scaffold_smiles(mol) or canonical | |
| heavy = int(mol.GetNumHeavyAtoms()) if mol is not None else 0 | |
| fp = _morgan_fp(mol) | |
| group_id = "" | |
| rule = "singleton" | |
| for rep_idx in representatives_by_scaffold.get(scaffold, []): | |
| rep = enriched[rep_idx] | |
| if canonical and canonical == str(rep.get("canonical_smiles", "")): | |
| group_id = str(rep["analog_group_id"]) | |
| rule = "canonical_duplicate" | |
| break | |
| rep_heavy = int(rep.get("heavy_atom_count_for_grouping", 0) or 0) | |
| rep_fp = rep.get("_analog_fp") | |
| if fp is None or rep_fp is None: | |
| continue | |
| if abs(heavy - rep_heavy) > max_heavy_atom_delta: | |
| continue | |
| try: | |
| sim = float(DataStructs.TanimotoSimilarity(fp, rep_fp)) | |
| except Exception: | |
| sim = 0.0 | |
| if sim >= tanimoto_threshold: | |
| group_id = str(rep["analog_group_id"]) | |
| rule = f"same_scaffold_tanimoto_{sim:.3f}" | |
| break | |
| if not group_id: | |
| group_id = f"analog_group_{len(groups) + 1:06d}" | |
| representatives_by_scaffold.setdefault(scaffold, []).append(idx) | |
| group_parent[group_id] = ligand_id | |
| item["canonical_smiles"] = canonical | |
| item["scaffold_core"] = scaffold | |
| item["heavy_atom_count_for_grouping"] = heavy | |
| item["analog_group_id"] = group_id | |
| item["analog_parent_id"] = group_parent.get(group_id, ligand_id) | |
| item["analog_group_rule"] = rule | |
| item["_analog_fp"] = fp | |
| groups.setdefault(group_id, []).append(idx) | |
| enriched.append(item) | |
| for group_id, indices in groups.items(): | |
| size = len(indices) | |
| parent_id = str(enriched[indices[0]].get("analog_parent_id", enriched[indices[0]].get("ligand_id", ""))) | |
| for variant_idx, row_idx in enumerate(indices, start=1): | |
| enriched[row_idx]["analog_group_size"] = size | |
| enriched[row_idx]["analog_variant_index"] = variant_idx | |
| enriched[row_idx]["analog_group_weight"] = 1.0 / max(1, size) | |
| enriched[row_idx]["analog_parent_id"] = parent_id | |
| enriched[row_idx].pop("_analog_fp", None) | |
| summary = { | |
| "analog_grouping_available": bool(RDKIT_AVAILABLE), | |
| "analog_group_count": len(groups), | |
| "analog_grouped_ligands": sum(len(indices) for indices in groups.values() if len(indices) > 1), | |
| "analog_largest_group_size": max((len(indices) for indices in groups.values()), default=0), | |
| "analog_tanimoto_threshold": float(tanimoto_threshold), | |
| "analog_max_heavy_atom_delta": int(max_heavy_atom_delta), | |
| } | |
| return enriched, summary | |
| def _dataset_uniqueness_summary(metadata_rows: list[dict[str, object]]) -> dict[str, object]: | |
| seen_smiles: set[str] = set() | |
| total = 0 | |
| for row in metadata_rows: | |
| smiles = str(row.get("smiles", "")).strip() | |
| if not smiles: | |
| continue | |
| total += 1 | |
| seen_smiles.add(smiles) | |
| duplicate_count = max(0, total - len(seen_smiles)) | |
| duplicate_fraction = (duplicate_count / total) if total else 0.0 | |
| warnings: list[str] = [] | |
| if duplicate_fraction > 0.01: | |
| warnings.append( | |
| f"duplicate parent fraction is {duplicate_fraction:.4f} (>1%); inspect ligand source and deduplication settings before scientific benchmarking" | |
| ) | |
| return { | |
| "n_input_smiles": total, | |
| "n_unique_parent_ligands": len(seen_smiles), | |
| "duplicate_parent_count": duplicate_count, | |
| "duplicate_parent_fraction": duplicate_fraction, | |
| "warnings": warnings, | |
| "deduplication_method": "exact_smiles", | |
| } | |
| def _infer_existing_dataset_manifest(out: Path, prepared_ligands: int, warnings: list[str] | None = None) -> dict[str, object]: | |
| warnings = list(warnings or []) | |
| raw_dir = out / "raw" | |
| pdb_candidates = sorted(list(raw_dir.glob("*.pdb")) + list(raw_dir.glob("*.cif")) + list(raw_dir.glob("*.mmcif"))) | |
| pdb_id = pdb_candidates[0].stem[:4].upper() if pdb_candidates else "" | |
| resolved = resolve_known_good_defaults(KNOWN_GOOD, pdb_id or "UNKN", None, None, None) | |
| ligand_source = "smiles_file" | |
| reference_smiles = "" | |
| pubchem_payload: dict[str, object] = {} | |
| pubchem_path = out / "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") | |
| reference_smiles = str(pubchem_payload.get("reference_smiles") or "") | |
| else: | |
| ref_smiles_log = out / "logs" / "reference_ligand_to_smiles.stdout.log" | |
| if ref_smiles_log.exists(): | |
| first = ref_smiles_log.read_text(encoding="utf-8", errors="ignore").splitlines() | |
| if first: | |
| reference_smiles = first[0].split()[0].strip() | |
| manifest = { | |
| "pdb_id": resolved["pdb_id"] or pdb_id, | |
| "receptor_chain": resolved["receptor_chain"], | |
| "reference_ligand_resname": resolved["reference_ligand_resname"], | |
| "reference_ligand_chain": resolved["reference_ligand_chain"], | |
| "n_ligands_requested": len(_read_all_smiles(require_file(out / "ligands" / "all_ligands.smi", "all_ligands.smi"))), | |
| "ligands_prepared": int(prepared_ligands), | |
| "paths": { | |
| "target_mol2": str(out / "target" / "target.mol2"), | |
| "reference_ligand_sdf": str(out / "target" / "reference_ligand.sdf"), | |
| "all_ligands_sdf": str(out / "ligands" / "all_ligands.sdf"), | |
| "all_ligands_smi": str(out / "ligands" / "all_ligands.smi"), | |
| "rdock_prm_dir": str(out / "target" / "rdock_prm"), | |
| "target_config_yaml": str(out / "target" / "rdock_prm" / "target_config.yaml"), | |
| }, | |
| "versions": { | |
| "obabel": probe_version(require_executable("obabel")) if shutil.which("obabel") else "", | |
| "rbdock": probe_version(require_executable("rbdock")) if shutil.which("rbdock") else "", | |
| "rbcavity": probe_version(require_executable("rbcavity")) if shutil.which("rbcavity") else "", | |
| }, | |
| "ligand_source": ligand_source, | |
| "reference_ligand_smiles": reference_smiles, | |
| "pubchem_threshold_ladder": pubchem_payload.get("thresholds_tried", []) if pubchem_payload else [], | |
| "pubchem_diagnostics": pubchem_payload, | |
| "rbcavity_status": "success" if (out / "target" / "rdock_prm").exists() else "unknown", | |
| "warnings": warnings, | |
| "available_hetero_ligands": [], | |
| "auto_reference_ligand": False, | |
| "auto_reference_candidates": [], | |
| "auto_reference_selected": {}, | |
| } | |
| return manifest | |
| def _ensure_dataset_metadata_files(out: Path, prepared_ligands: int, warnings: list[str] | None = None) -> None: | |
| manifest_path = out / "dataset_manifest.json" | |
| if manifest_path.exists(): | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| manifest["ligands_prepared"] = int(prepared_ligands) | |
| manifest.setdefault("paths", {}) | |
| manifest["paths"]["all_ligands_sdf"] = str(out / "ligands" / "all_ligands.sdf") | |
| manifest["paths"]["all_ligands_smi"] = str(out / "ligands" / "all_ligands.smi") | |
| if warnings: | |
| manifest["warnings"] = list(dict.fromkeys(list(manifest.get("warnings", [])) + list(warnings))) | |
| create_dataset_manifest(out, manifest) | |
| else: | |
| synth_warnings = ["dataset_manifest.json was missing and was reconstructed from existing dataset files"] | |
| if warnings: | |
| synth_warnings.extend(warnings) | |
| create_dataset_manifest(out, _infer_existing_dataset_manifest(out, prepared_ligands, warnings=synth_warnings)) | |
| report_path = out / "qc" / "preparation_report.md" | |
| if not report_path.exists(): | |
| report_lines = [ | |
| f"# Dataset Preparation Report: {out.name}", | |
| "", | |
| "- report_status: `reconstructed`", | |
| f"- ligands_prepared: `{prepared_ligands}`", | |
| f"- target_mol2: `{out / 'target' / 'target.mol2'}`", | |
| f"- reference_ligand_sdf: `{out / 'target' / 'reference_ligand.sdf'}`", | |
| f"- all_ligands_sdf: `{out / 'ligands' / 'all_ligands.sdf'}`", | |
| f"- all_ligands_smi: `{out / 'ligands' / 'all_ligands.smi'}`", | |
| ] | |
| if warnings: | |
| report_lines.extend(["", "## Warnings", *[f"- {item}" for item in warnings]]) | |
| report_path.parent.mkdir(parents=True, exist_ok=True) | |
| report_path.write_text("\n".join(report_lines) + "\n", encoding="utf-8") | |
| def _list_known_good() -> int: | |
| complexes = list_known_good_complexes(KNOWN_GOOD) | |
| print(json.dumps(complexes, indent=2)) | |
| return 0 | |
| def _list_hetero_for_pdb(args: argparse.Namespace) -> int: | |
| temp_root = Path(args.out) if args.out else ROOT / ".tmp_list_hetero" | |
| _mkdir_or_fail(temp_root) | |
| pdb_path = download_pdb_structure(str(args.pdb_id), temp_root / "raw", force=False) | |
| payload = { | |
| "pdb_id": str(args.pdb_id).upper(), | |
| "hetero_ligands": list_hetero_ligands(pdb_path, min_reference_ligand_atoms=args.min_reference_ligand_atoms), | |
| } | |
| print(json.dumps(payload, indent=2)) | |
| return 0 | |
| def _validate_only(dataset_dir: Path) -> int: | |
| print(json.dumps(validate_dataset_dir(dataset_dir, check_rdock_tools=False), indent=2)) | |
| return 0 | |
| def _plan(args: argparse.Namespace, resolved: dict[str, str], smiles_file: Path | None) -> dict[str, object]: | |
| if smiles_file is None: | |
| ligand_count = None | |
| smiles_repr = "" | |
| elif not smiles_file.exists(): | |
| ligand_count = 0 | |
| smiles_repr = str(smiles_file) | |
| else: | |
| ligand_count = len(_read_smiles(smiles_file, args.n_ligands)) | |
| smiles_repr = str(smiles_file) | |
| missing_tools = [tool for tool in ("obabel", "rbcavity", "rbdock") if shutil.which(tool) is None] | |
| return { | |
| "pdb_id": resolved["pdb_id"], | |
| "receptor_chain": resolved["receptor_chain"], | |
| "reference_ligand_resname": resolved["reference_ligand_resname"], | |
| "reference_ligand_chain": resolved["reference_ligand_chain"], | |
| "n_ligands_requested": args.n_ligands, | |
| "ligand_source": args.ligand_source, | |
| "auto_reference_ligand": bool(args.auto_reference_ligand), | |
| "min_reference_ligand_atoms": int(args.min_reference_ligand_atoms), | |
| "smiles_file": smiles_repr, | |
| "detected_smiles_rows": ligand_count, | |
| "out": str(args.out), | |
| "missing_dependencies": missing_tools, | |
| "commands": [ | |
| "download PDB structure if absent", | |
| "extract receptor chain and reference ligand from PDB", | |
| "convert reference ligand and receptor with OpenBabel", | |
| "resolve ligand source via smiles file or PubChem when --smiles-file is not provided", | |
| "prepare target with rbcavity", | |
| "convert SMILES to 3D SDF", | |
| "write dataset_manifest.json and qc/preparation_report.md", | |
| ], | |
| } | |
| def _reference_selection_error( | |
| exc: RDockPipelineError, | |
| pdb_id: str, | |
| receptor_chain: str, | |
| out: Path, | |
| ) -> RDockPipelineError: | |
| known = _known_good_entry(pdb_id) | |
| lines = [str(exc)] | |
| if known: | |
| lines.append( | |
| "Known-good suggestion: " | |
| f"--receptor-chain {known.get('receptor_chain')} " | |
| f"--reference-ligand-resname {known.get('reference_ligand_resname')} " | |
| f"--reference-ligand-chain {known.get('reference_ligand_chain')}" | |
| ) | |
| lines.append( | |
| "Recommended correction: " | |
| f"python scripts/prepare_pdb_ligand_dataset.py --pdb-id {pdb_id} --receptor-chain {receptor_chain} " | |
| f"--auto-reference-ligand --n-ligands 1000 --ligand-source smiles_file " | |
| f"--smiles-file data/examples/example_smiles_1000.smi --out {out} --force" | |
| ) | |
| lines.append( | |
| "You can inspect candidate hetero ligands with: " | |
| f"python scripts/prepare_pdb_ligand_dataset.py --list-hetero --pdb-id {pdb_id}" | |
| ) | |
| return RDockPipelineError("\n".join(lines)) | |
| def _select_reference_ligand(args: argparse.Namespace, resolved: dict[str, str], pdb_path: Path) -> tuple[dict[str, str], list[dict[str, object]], dict[str, object] | None]: | |
| if args.auto_reference_ligand or not resolved["reference_ligand_resname"]: | |
| selected, candidates = auto_detect_reference_ligand( | |
| pdb_path, | |
| resolved["receptor_chain"], | |
| min_reference_ligand_atoms=args.min_reference_ligand_atoms, | |
| ) | |
| resolved = dict(resolved) | |
| resolved["reference_ligand_resname"] = str(selected["resname"]) | |
| resolved["reference_ligand_chain"] = str(selected["chain"]) | |
| return resolved, candidates, selected | |
| return resolved, [], None | |
| def _resolve_ligand_rows( | |
| args: argparse.Namespace, | |
| resolved: dict[str, str], | |
| runner: CommandRunner, | |
| reference_sdf: Path, | |
| out: Path, | |
| ) -> tuple[list[tuple[str, str]], list[dict[str, object]], str, dict[str, object] | None, str, list[str]]: | |
| smiles_file = _resolve_smiles_source(args) | |
| source = args.ligand_source | |
| if args.smiles_file: | |
| source = "smiles_file" | |
| if source == "smiles_file" and smiles_file is None: | |
| raise RDockPipelineError("`--ligand-source smiles_file` requires --smiles-file /path/to/library.smi.") | |
| if source in {"pubchem_random_compounds", "zinc_file"}: | |
| raise RDockPipelineError( | |
| f"Ligand source `{source}` is not enabled in this portable bundle. " | |
| "Use --ligand-source smiles_file --smiles-file /path/to/real_library.smi." | |
| ) | |
| if source == "bundled_example": | |
| if args.n_ligands > 50: | |
| raise RDockPipelineError( | |
| f"`bundled_example` contains only 50 ligands. Requested {args.n_ligands}. " | |
| f"Use --ligand-source smiles_file --smiles-file data/examples/example_smiles_1000.smi or a larger real library." | |
| ) | |
| if args.n_ligands > 5000 and source not in {"smiles_file", "pubchem_similarity"}: | |
| raise RDockPipelineError( | |
| f"Requested {args.n_ligands} ligands with source `{source}`. For libraries larger than 5000 ligands, " | |
| "provide a real large library via --ligand-source smiles_file --smiles-file /path/to/library.smi." | |
| ) | |
| if smiles_file is not None: | |
| rows = _read_smiles(smiles_file, args.n_ligands) | |
| if len(rows) < args.n_ligands: | |
| raise RDockPipelineError( | |
| f"Requested {args.n_ligands} ligands but {smiles_file} contains only {len(rows)} usable rows. " | |
| f"Provide a larger --smiles-file. Example: --smiles-file /data/libraries/real_50k_library.smi" | |
| ) | |
| metadata_rows = [{"ligand_id": ligand_id, "smiles": smiles, "source": "smiles_file"} for smiles, ligand_id in rows] | |
| return rows, metadata_rows, "", None, source, [] | |
| reference_smiles = _reference_ligand_to_smiles(runner, reference_sdf, out) | |
| reference_sdf_block = _reference_ligand_sdf_block(reference_sdf) | |
| threshold_ladder = _resolve_threshold_ladder(args) | |
| diagnostics_errors: list[str] = [] | |
| combined_diagnostics: list[dict[str, object]] = [] | |
| warnings: list[str] = [] | |
| if source in {"auto", "pubchem_similarity"}: | |
| try: | |
| rows, metadata_rows, diagnostics, warning = _pubchem_similarity_rows( | |
| reference_smiles, | |
| reference_sdf_block, | |
| args.n_ligands, | |
| threshold_ladder, | |
| timeout=args.pubchem_timeout, | |
| allow_partial=bool(getattr(args, "allow_partial_ligand_set", False)), | |
| out=out, | |
| property_workers=int(getattr(args, "pubchem_property_workers", _default_pubchem_workers())), | |
| property_chunk_size=int(getattr(args, "pubchem_property_chunk_size", 200)), | |
| record_multiplier=int(getattr(args, "pubchem_record_multiplier", 8)), | |
| min_records_per_threshold=int(getattr(args, "pubchem_min_records_per_threshold", 1000)), | |
| max_records_per_threshold=int(getattr(args, "pubchem_max_records_per_threshold", 5000)), | |
| ) | |
| combined_diagnostics.extend(diagnostics) | |
| payload = _pubchem_diagnostics_payload("pubchem_similarity", reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors) | |
| payload["requested_ligands"] = args.n_ligands | |
| payload["collected_ligands"] = len(rows) | |
| if warning: | |
| warnings.append(warning) | |
| return rows, metadata_rows, reference_smiles, payload, "pubchem_similarity", warnings | |
| except RDockPipelineError as exc: | |
| diagnostics_errors.append(str(exc)) | |
| if source in {"auto", "pubchem_compound_search"}: | |
| queries = [ | |
| resolved["reference_ligand_resname"], | |
| f"{resolved['pdb_id']} {resolved['reference_ligand_resname']}", | |
| str((_known_good_entry(resolved["pdb_id"]) or {}).get("target_name", "")), | |
| ] | |
| rows, metadata_rows, diagnostics = _pubchem_name_rows(queries, args.n_ligands, timeout=args.pubchem_timeout) | |
| combined_diagnostics.extend(diagnostics) | |
| if len(rows) >= args.n_ligands: | |
| payload = _pubchem_diagnostics_payload("pubchem_compound_search", reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors) | |
| payload["requested_ligands"] = args.n_ligands | |
| payload["collected_ligands"] = len(rows) | |
| return rows, metadata_rows, reference_smiles, payload, "pubchem_compound_search", warnings | |
| diagnostics_errors.append( | |
| f"PubChem compound search collected only {len(rows)} ligands for queries {queries}. Requested {args.n_ligands}." | |
| ) | |
| if rows and bool(getattr(args, "allow_partial_ligand_set", False)): | |
| payload = _pubchem_diagnostics_payload("pubchem_compound_search", reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors) | |
| payload["requested_ligands"] = args.n_ligands | |
| payload["collected_ligands"] = len(rows) | |
| warnings.append( | |
| f"PubChem compound search collected {len(rows)} ligands for queries {queries}. Requested {args.n_ligands}." | |
| ) | |
| return rows, metadata_rows, reference_smiles, payload, "pubchem_compound_search", warnings | |
| payload = _pubchem_diagnostics_payload(source, reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors) | |
| payload["requested_ligands"] = args.n_ligands | |
| payload["collected_ligands"] = 0 | |
| _write_pubchem_diagnostics(out, payload) | |
| raise RDockPipelineError( | |
| f"Could not collect {args.n_ligands} ligands from source `{source}` for {resolved['pdb_id']}. " | |
| f"Diagnostics were written to {out / 'logs' / 'pubchem_diagnostics.json'}. " | |
| "Use --ligand-source smiles_file --smiles-file /path/to/real_library.smi for a stable large-library workflow." | |
| ) | |
| def run(args: argparse.Namespace) -> int: | |
| if args.list_known_good: | |
| return _list_known_good() | |
| if args.list_hetero: | |
| return _list_hetero_for_pdb(args) | |
| if args.validate_only: | |
| return _validate_only(Path(args.out)) | |
| if args.prepare_ligands_only: | |
| out = Path(args.out) | |
| _mkdir_or_fail(out) | |
| for name in ("ligands", "logs", "qc"): | |
| _mkdir_or_fail(out / name) | |
| runner = CommandRunner(out / "logs" / "commands.log") | |
| result = _prepare_ligands_from_existing_smi( | |
| out, | |
| runner, | |
| batch_size=int(args.ligand_batch_size), | |
| jobs=args.ligand_jobs, | |
| cpu_fraction=float(args.ligand_cpu_fraction), | |
| force_rebuild=bool(args.force), | |
| ) | |
| metadata_warnings: list[str] = [] | |
| if not (out / "dataset_manifest.json").exists(): | |
| metadata_warnings.append("dataset_manifest.json was missing before ligand resume") | |
| if not (out / "qc" / "preparation_report.md").exists(): | |
| metadata_warnings.append("qc/preparation_report.md was missing before ligand resume") | |
| _ensure_dataset_metadata_files(out, int(result["prepared_ligands"]), warnings=metadata_warnings) | |
| print(json.dumps(result, indent=2)) | |
| return 0 | |
| resolved = resolve_known_good_defaults( | |
| KNOWN_GOOD, | |
| args.pdb_id, | |
| args.receptor_chain, | |
| args.reference_ligand_resname, | |
| args.reference_ligand_chain, | |
| ) | |
| if not resolved["receptor_chain"] or (not resolved["reference_ligand_resname"] and not args.auto_reference_ligand): | |
| raise RDockPipelineError( | |
| "Missing receptor chain or reference ligand resname. Provide them explicitly, use --auto-reference-ligand, or use a known-good PDB entry." | |
| ) | |
| smiles_file = _resolve_smiles_source(args) | |
| plan = _plan(args, resolved, smiles_file) | |
| plan["ligand_source"] = args.ligand_source | |
| plan["pubchem_threshold_ladder"] = _resolve_threshold_ladder(args) | |
| plan["uses_pubchem_similarity"] = smiles_file is None | |
| out = Path(args.out) | |
| _mkdir_or_fail(out) | |
| if args.dry_run: | |
| (out / "dataset_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8") | |
| print(json.dumps(plan, indent=2)) | |
| return 0 | |
| if out.exists() and args.force: | |
| shutil.rmtree(out) | |
| _mkdir_or_fail(out) | |
| for name in ("raw", "target", "ligands", "logs", "qc"): | |
| _mkdir_or_fail(out / name) | |
| runner = CommandRunner(out / "logs" / "commands.log") | |
| pdb_path = download_pdb_structure(resolved["pdb_id"], out / "raw", force=args.force) | |
| resolved, auto_candidates, auto_selected = _select_reference_ligand(args, resolved, pdb_path) | |
| (out / "raw" / "download_metadata.json").write_text( | |
| json.dumps({"pdb_id": resolved["pdb_id"], "source": str(pdb_path), "status": "downloaded_or_reused"}, indent=2), | |
| encoding="utf-8", | |
| ) | |
| try: | |
| receptor_pdb, ligand_pdb, hetero = extract_receptor_and_reference_ligand( | |
| pdb_path, | |
| resolved["receptor_chain"], | |
| resolved["reference_ligand_resname"], | |
| resolved["reference_ligand_chain"], | |
| out / "target", | |
| min_reference_ligand_atoms=args.min_reference_ligand_atoms, | |
| ) | |
| except RDockPipelineError as exc: | |
| raise _reference_selection_error(exc, resolved["pdb_id"], resolved["receptor_chain"], out) from exc | |
| reference_raw_sdf = out / "target" / "reference_ligand_raw.sdf" | |
| reference_sdf = out / "target" / "reference_ligand.sdf" | |
| _obabel_convert(runner, "reference_ligand_raw_to_sdf", ligand_pdb, reference_raw_sdf, [], out) | |
| shutil.copy2(reference_raw_sdf, reference_sdf) | |
| rows, metadata_rows, reference_smiles, pubchem_payload, ligand_source_used, ligand_warnings = _resolve_ligand_rows(args, resolved, runner, reference_sdf, out) | |
| if pubchem_payload is not None: | |
| _write_pubchem_diagnostics(out, pubchem_payload) | |
| if ligand_warnings: | |
| for warning in ligand_warnings: | |
| print(f"WARNING: {warning}", file=sys.stderr) | |
| if not rows: | |
| diagnostics_path = out / "logs" / "pubchem_diagnostics.json" | |
| raise RDockPipelineError( | |
| f"PubChem returned zero usable ligands for {resolved['pdb_id']} with source `{ligand_source_used}` and thresholds " | |
| f"{_resolve_threshold_ladder(args)}. No docking dataset can be created from zero ligands. " | |
| f"See diagnostics: {diagnostics_path}. " | |
| "Lower --identity-threshold-stop, try a different reference complex, or provide --smiles-file with a real library." | |
| ) | |
| metadata_rows, analog_summary = _annotate_near_duplicate_analogs(metadata_rows) | |
| metadata_by_id = {str(row.get("ligand_id", "")): row for row in metadata_rows} | |
| rows = [(smiles, ligand_id) for smiles, ligand_id in rows if str(ligand_id) in metadata_by_id] | |
| target_prm_dir = out / "target" / "rdock_prm" | |
| prep = prepare_dataset_target_with_rdock(receptor_pdb, reference_sdf, target_prm_dir, jobs="auto", cpu_fraction=0.85) | |
| target_mol2 = require_file(target_prm_dir / "receptor.mol2", "prepared receptor mol2") | |
| shutil.copy2(target_mol2, out / "target" / "target.mol2") | |
| smi_path = _write_smi(rows, out / "ligands" / "all_ligands.smi") | |
| _write_csv(out / "ligands" / "ligand_metadata.csv", metadata_rows) | |
| _write_csv(out / "ligands" / "invalid_ligands.csv", []) | |
| if args.stop_after_ligand_collection: | |
| collection_summary = { | |
| "status": "ligand_collection_complete", | |
| "pdb_id": resolved["pdb_id"], | |
| "ligands_requested": args.n_ligands, | |
| "ligands_collected": len(rows), | |
| "reference_ligand_smiles": reference_smiles, | |
| "ligand_source": ligand_source_used, | |
| "all_ligands_smi": str(smi_path), | |
| "ligand_metadata_csv": str(out / "ligands" / "ligand_metadata.csv"), | |
| "analog_grouping": analog_summary, | |
| "pubchem_diagnostics_json": str(out / "logs" / "pubchem_diagnostics.json"), | |
| "next_stage": "openbabel_ligand_preparation", | |
| } | |
| (out / "qc" / "collection_summary.json").write_text(json.dumps(collection_summary, indent=2), encoding="utf-8") | |
| print( | |
| f"Collected {len(rows)}/{args.n_ligands} ligands and wrote {smi_path}. " | |
| "Stopping before OpenBabel ligand preparation as requested.", | |
| file=sys.stderr, | |
| ) | |
| print(json.dumps(collection_summary, indent=2)) | |
| return 0 | |
| ligand_prep = _prepare_ligands_from_existing_smi( | |
| out, | |
| runner, | |
| batch_size=int(args.ligand_batch_size), | |
| jobs=args.ligand_jobs, | |
| cpu_fraction=float(args.ligand_cpu_fraction), | |
| force_rebuild=bool(args.force), | |
| metadata_rows=metadata_rows, | |
| ) | |
| ligands_sdf = require_file(Path(str(ligand_prep["final_sdf"])), "prepared ligand sdf") | |
| uniqueness = _dataset_uniqueness_summary(metadata_rows) | |
| manifest_warnings = list(ligand_warnings) + [str(item) for item in uniqueness.get("warnings", [])] | |
| manifest = { | |
| "pdb_id": resolved["pdb_id"], | |
| "receptor_chain": resolved["receptor_chain"], | |
| "reference_ligand_resname": resolved["reference_ligand_resname"], | |
| "reference_ligand_chain": resolved["reference_ligand_chain"], | |
| "reference_ligand_pubchem_cid": (pubchem_payload or {}).get("reference_pubchem_cid", ""), | |
| "n_ligands_requested": args.n_ligands, | |
| "n_collected_raw": len(rows), | |
| "n_input_smiles": int(uniqueness["n_input_smiles"]), | |
| "n_unique_parent_ligands": int(uniqueness["n_unique_parent_ligands"]), | |
| "ligands_prepared": len(rows), | |
| "n_prepared_ligands": len(rows), | |
| "n_invalid": 0, | |
| "deduplication_method": str(uniqueness["deduplication_method"]), | |
| "source": ligand_source_used, | |
| "synthetic_expansion": False, | |
| "synthetic_stress_test_only": False, | |
| "similarity_thresholds": _resolve_threshold_ladder(args) if pubchem_payload is not None else [], | |
| "min_similarity": float(getattr(args, "min_similarity", 0.70)), | |
| "max_similarity": float(getattr(args, "max_similarity", 0.99)), | |
| "deduplicate_canonical_smiles": _bool_arg(getattr(args, "deduplicate_canonical_smiles", "true"), True), | |
| "deduplicate_inchikey": _bool_arg(getattr(args, "deduplicate_inchikey", "true"), True), | |
| "paths": { | |
| "target_mol2": str(out / "target" / "target.mol2"), | |
| "reference_ligand_sdf": str(reference_sdf), | |
| "all_ligands_sdf": str(ligands_sdf), | |
| "rdock_prm_dir": str(target_prm_dir), | |
| "target_config_yaml": str(target_prm_dir / "target_config.yaml"), | |
| }, | |
| "versions": { | |
| "obabel": probe_version(require_executable("obabel")), | |
| "rbdock": probe_version(require_executable("rbdock")), | |
| "rbcavity": probe_version(require_executable("rbcavity")), | |
| }, | |
| "ligand_source": ligand_source_used, | |
| "analog_grouping": analog_summary, | |
| "reference_ligand_smiles": reference_smiles, | |
| "pubchem_threshold_ladder": _resolve_threshold_ladder(args) if pubchem_payload is not None else [], | |
| "pubchem_diagnostics": pubchem_payload or {}, | |
| "rbcavity_status": "success", | |
| "warnings": manifest_warnings, | |
| "ligand_preparation": ligand_prep, | |
| "available_hetero_ligands": hetero[:50], | |
| "auto_reference_ligand": bool(args.auto_reference_ligand), | |
| "auto_reference_candidates": auto_candidates[:50], | |
| "auto_reference_selected": auto_selected or {}, | |
| "prepared_target": prep, | |
| "copied_target_bundle": {path.name: str(path) for path in target_prm_dir.iterdir() if path.is_file()}, | |
| } | |
| create_dataset_manifest(out, manifest) | |
| _write_csv( | |
| out / "qc" / "deduplication_report.tsv", | |
| [ | |
| { | |
| "n_input_smiles": int(uniqueness["n_input_smiles"]), | |
| "n_unique_parent_ligands": int(uniqueness["n_unique_parent_ligands"]), | |
| "duplicate_parent_fraction": float(uniqueness["duplicate_parent_fraction"]), | |
| "deduplication_method": str(uniqueness["deduplication_method"]), | |
| "synthetic_expansion": "false", | |
| } | |
| ], | |
| ) | |
| qc_report = [ | |
| f"# Dataset Preparation Report: {resolved['pdb_id']}", | |
| "", | |
| f"- receptor_chain: `{resolved['receptor_chain']}`", | |
| f"- reference_ligand: `{resolved['reference_ligand_resname']}` chain `{resolved['reference_ligand_chain']}`", | |
| f"- ligands_prepared: `{len(rows)}`", | |
| f"- ligands_requested: `{args.n_ligands}`", | |
| f"- ligand_source: `{ligand_source_used}`", | |
| f"- n_input_smiles: `{uniqueness['n_input_smiles']}`", | |
| f"- n_unique_parent_ligands: `{uniqueness['n_unique_parent_ligands']}`", | |
| f"- duplicate_parent_fraction: `{float(uniqueness['duplicate_parent_fraction']):.4f}`", | |
| f"- analog_group_count: `{analog_summary['analog_group_count']}`", | |
| f"- analog_grouped_ligands: `{analog_summary['analog_grouped_ligands']}`", | |
| f"- analog_largest_group_size: `{analog_summary['analog_largest_group_size']}`", | |
| f"- deduplication_method: `{uniqueness['deduplication_method']}`", | |
| "- synthetic_expansion: `false`", | |
| f"- reference_ligand_smiles: `{reference_smiles}`", | |
| f"- pubchem_threshold_ladder: `{_resolve_threshold_ladder(args) if pubchem_payload is not None else []}`", | |
| f"- target_mol2: `{out / 'target' / 'target.mol2'}`", | |
| f"- reference_ligand_sdf: `{reference_sdf}`", | |
| f"- all_ligands_sdf: `{ligands_sdf}`", | |
| f"- target_config_yaml: `{target_prm_dir / 'target_config.yaml'}`", | |
| ] | |
| if auto_selected: | |
| qc_report.extend( | |
| [ | |
| "", | |
| "## Auto reference ligand selection", | |
| f"- selected_resname: `{auto_selected.get('resname', '')}`", | |
| f"- selected_chain: `{auto_selected.get('chain', '')}`", | |
| f"- selected_residue_id: `{auto_selected.get('residue_id', '')}`", | |
| f"- heavy_atom_count: `{auto_selected.get('heavy_atom_count', '')}`", | |
| f"- min_distance_to_receptor: `{auto_selected.get('min_distance_to_receptor', '')}`", | |
| ] | |
| ) | |
| if manifest_warnings: | |
| qc_report.extend(["", "## Ligand Collection Warnings", *[f"- {warning}" for warning in manifest_warnings]]) | |
| (out / "qc" / "preparation_report.md").write_text("\n".join(qc_report) + "\n", encoding="utf-8") | |
| print(json.dumps(validate_dataset_dir(out, check_rdock_tools=False), indent=2)) | |
| return 0 | |
| def build_parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser(description="Prepare a portable PDB + ligand dataset for rDock production runs.") | |
| parser.add_argument("--pdb-id") | |
| parser.add_argument("--receptor-chain") | |
| parser.add_argument("--reference-ligand-resname") | |
| parser.add_argument("--reference-ligand-chain") | |
| parser.add_argument("--auto-reference-ligand", action="store_true") | |
| parser.add_argument("--min-reference-ligand-atoms", type=int, default=8) | |
| parser.add_argument("--n-ligands", type=int, default=1000) | |
| parser.add_argument( | |
| "--ligand-source", | |
| default="auto", | |
| choices=[ | |
| "auto", | |
| "smiles_file", | |
| "pubchem_similarity", | |
| "pubchem_compound_search", | |
| "pubchem_random_compounds", | |
| "zinc_file", | |
| "bundled_example", | |
| ], | |
| ) | |
| parser.add_argument("--source", dest="ligand_source") | |
| parser.add_argument("--smiles-file") | |
| parser.add_argument("--similarity-thresholds", default="") | |
| parser.add_argument("--min-similarity", type=float, default=0.70) | |
| parser.add_argument("--max-similarity", type=float, default=0.99) | |
| parser.add_argument("--deduplicate-canonical-smiles", default="true") | |
| parser.add_argument("--deduplicate-inchikey", default="true") | |
| parser.add_argument("--pubchem-threshold-ladder", default="95,90,85,80,75,70") | |
| parser.add_argument("--pubchem-threshold-start", "--identity-threshold-start", dest="pubchem_threshold_start", type=int, default=None) | |
| parser.add_argument("--pubchem-threshold-stop", "--identity-threshold-stop", dest="pubchem_threshold_stop", type=int, default=None) | |
| parser.add_argument("--pubchem-threshold-step", type=int, default=1) | |
| parser.add_argument("--pubchem-timeout", type=int, default=60) | |
| parser.add_argument("--pubchem-property-workers", type=int, default=_default_pubchem_workers()) | |
| parser.add_argument("--pubchem-property-chunk-size", type=int, default=200) | |
| parser.add_argument("--pubchem-record-multiplier", type=int, default=8) | |
| parser.add_argument("--pubchem-min-records-per-threshold", type=int, default=1000) | |
| parser.add_argument("--pubchem-max-records-per-threshold", type=int, default=5000) | |
| parser.add_argument("--allow-partial-ligand-set", action="store_true") | |
| parser.add_argument("--prepare-ligands-only", action="store_true") | |
| parser.add_argument("--stop-after-ligand-collection", action="store_true") | |
| parser.add_argument("--ligand-batch-size", type=int, default=250) | |
| parser.add_argument("--ligand-jobs", default=str(_default_ligand_jobs())) | |
| parser.add_argument("--ligand-cpu-fraction", type=float, default=0.85) | |
| parser.add_argument("--out") | |
| parser.add_argument("--ph", type=float, default=7.4) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--force", action="store_true") | |
| parser.add_argument("--dry-run", action="store_true") | |
| parser.add_argument("--list-known-good", action="store_true") | |
| parser.add_argument("--list-hetero", action="store_true") | |
| parser.add_argument("--validate-only", action="store_true") | |
| return parser | |
| def main() -> int: | |
| parser = build_parser() | |
| args = parser.parse_args() | |
| if not args.list_known_good and not args.validate_only and not args.list_hetero and not args.prepare_ligands_only and not args.pdb_id: | |
| parser.error("--pdb-id is required unless --list-known-good, --list-hetero, or --validate-only is used") | |
| if not args.list_known_good and not args.list_hetero and not args.out: | |
| parser.error("--out is required unless --list-known-good or --list-hetero is used") | |
| return run(args) | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |