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