from __future__ import annotations import math import re from pathlib import Path from typing import Any, Dict, List, Tuple import numpy as np from rdkit import Chem from rdkit.Chem import rdMolAlign TAG_RE = re.compile(r"^>\s*<\s*([^>]+?)\s*>", flags=re.IGNORECASE) def _safe_float(value: object) -> float | None: try: v = float(value) # type: ignore[arg-type] except Exception: return None if not np.isfinite(v): return None return float(v) def _split_sdf_blocks(text: str) -> List[str]: blocks = [] for part in text.split("$$$$"): block = part.strip() if block: blocks.append(block + "\n$$$$\n") return blocks def _parse_block_tags(block: str) -> Dict[str, str]: lines = block.splitlines() tags: Dict[str, str] = {} i = 0 while i < len(lines): m = TAG_RE.match(lines[i].strip()) if not m: i += 1 continue tag = m.group(1).strip() value = "" if i + 1 < len(lines): value = lines[i + 1].strip() tags[tag] = value i += 2 return tags def _pose_molecules(blocks: List[str]) -> List[Chem.Mol | None]: out: List[Chem.Mol | None] = [] for b in blocks: mol = None try: mol = Chem.MolFromMolBlock(b, sanitize=False, removeHs=False, strictParsing=False) except Exception: mol = None out.append(mol) return out def _pose_rmsd_stats(poses: List[Dict[str, Any]], mols: List[Chem.Mol | None], top_k: int = 5) -> Dict[str, float | None]: if not poses: return {"top_pose_rmsd_consistency": None, "geometry_similarity_top5": None} top = sorted(poses, key=lambda x: x["score"])[: max(1, min(top_k, len(poses)))] top_idx = [int(x["pose_idx"]) for x in top] if not top_idx: return {"top_pose_rmsd_consistency": None, "geometry_similarity_top5": None} ref_idx = int(top_idx[0]) ref_mol = mols[ref_idx] if 0 <= ref_idx < len(mols) else None if ref_mol is None: return {"top_pose_rmsd_consistency": None, "geometry_similarity_top5": None} rmsds: List[float] = [] for idx in top_idx[1:]: if idx < 0 or idx >= len(mols): continue mol = mols[idx] if mol is None: continue try: if ref_mol.GetNumAtoms() != mol.GetNumAtoms(): continue rmsd = float(rdMolAlign.GetBestRMS(ref_mol, mol)) if np.isfinite(rmsd): rmsds.append(rmsd) except Exception: continue if not rmsds: return {"top_pose_rmsd_consistency": None, "geometry_similarity_top5": None} mean_rmsd = float(np.mean(np.asarray(rmsds, dtype=float))) geom_sim = float(1.0 / (1.0 + mean_rmsd)) return {"top_pose_rmsd_consistency": mean_rmsd, "geometry_similarity_top5": geom_sim} def parse_rdock_output(path: str | Path) -> Dict[str, Any]: """ Parse real rDock SDF output and compute native + derived multi-pose features. Native features are direct tags parsed from rDock output (`SCORE*`). Derived features are computed from real generated poses and are explicitly marked as proxies where needed. """ source = Path(path) if not source.exists(): raise ValueError(f"rDock output file does not exist: {source}") if source.stat().st_size == 0: raise ValueError(f"rDock output file is empty: {source}") raw = source.read_text(encoding="utf-8", errors="ignore") blocks = _split_sdf_blocks(raw) if not blocks: raise ValueError(f"No molecule blocks found in real rDock output: {source}") poses: List[Dict[str, Any]] = [] for i, block in enumerate(blocks): tags = _parse_block_tags(block) score = _safe_float(tags.get("SCORE")) if score is None: continue poses.append({"pose_idx": i, "pose_rank": int(tags.get("RI", i) or i) + 1, "score": score, "tags": tags}) if not poses: raise ValueError(f"No SCORE fields found in real rDock output: {source}") poses = sorted(poses, key=lambda x: x["score"]) scores = [float(p["score"]) for p in poses] best = poses[0] top3 = scores[:3] top5 = scores[:5] native = { "rdock_total_score": float(best["score"]), "rdock_pose_rank": int(best.get("pose_rank", 1)), "n_generated_poses": int(len(scores)), "best_pose_score": float(best["score"]), "mean_top3_pose_score": float(np.mean(top3)), "mean_top5_pose_score": float(np.mean(top5)), "std_top5_pose_score": float(np.std(np.asarray(top5, dtype=float), ddof=0)), "pose_score_gap_1_2": float(scores[1] - scores[0]) if len(scores) > 1 else np.nan, "rdock_restraint_term": _safe_float(best["tags"].get("SCORE.RESTR")), "rdock_internal_ligand_term": _safe_float(best["tags"].get("SCORE.INTRA")), "rdock_polar_term": _safe_float(best["tags"].get("SCORE.INTER.POLAR")), "rdock_vdw_term": _safe_float(best["tags"].get("SCORE.INTER.VDW")), "rdock_inter_term": _safe_float(best["tags"].get("SCORE.INTER")), "rdock_intra_vdw_term": _safe_float(best["tags"].get("SCORE.INTRA.VDW")), "rdock_intra_dih_term": _safe_float(best["tags"].get("SCORE.INTRA.DIHEDRAL")), "rdock_norm_score": _safe_float(best["tags"].get("SCORE.norm")), "rdock_heavy_atoms": _safe_float(best["tags"].get("SCORE.heavy")), } mols = _pose_molecules(blocks) rmsd_stats = _pose_rmsd_stats(poses=poses, mols=mols, top_k=5) std5 = native["std_top5_pose_score"] if std5 is None or (isinstance(std5, float) and (not np.isfinite(std5))): pose_stability = None else: pose_stability = float(math.exp(-float(std5))) inter_scores: List[float] = [] for p in poses[:5]: v = _safe_float(p["tags"].get("SCORE.INTER")) if v is not None: inter_scores.append(float(v)) inter_std = float(np.std(np.asarray(inter_scores), ddof=0)) if inter_scores else np.nan # Explicitly proxy-derived (not directly reported by rDock tags). derived = { "n_valid_poses": int(len(scores)), "top_pose_rmsd_consistency": rmsd_stats["top_pose_rmsd_consistency"], "contact_overlap_consistency": (float(1.0 / (1.0 + inter_std)) if np.isfinite(inter_std) else np.nan), "hotspot_contact_frequency": ( float(np.mean([1.0 if (_safe_float(p["tags"].get("SCORE.INTER")) or 0.0) < 0.0 else 0.0 for p in poses[:5]])) if poses else np.nan ), "subpocket_match_score": pose_stability if pose_stability is not None else np.nan, "consensus_contact_score": (float(-np.mean(np.asarray(inter_scores, dtype=float))) if inter_scores else np.nan), "consensus_hotspot_coverage": ( float(np.mean([1.0 if (_safe_float(p["tags"].get("SCORE.INTER.VDW")) or 0.0) < 0.0 else 0.0 for p in poses[:5]])) if poses else np.nan ), "pose_stability_proxy": pose_stability, "geometry_similarity_top5": rmsd_stats["geometry_similarity_top5"], } feature_provenance: List[Dict[str, Any]] = [] for name, val in native.items(): feature_provenance.append( { "feature_name": name, "feature_source": "rdock_native", "pose_source": "best_pose" if name.startswith("rdock_") else "top5", "raw_output_file": str(source), "parsed_from": f"{source}::SDF_TAG", "feature_type": "exact" if val is not None and np.isfinite(float(val)) else "unavailable", "available": bool(val is not None and np.isfinite(float(val))), } ) for name, val in derived.items(): feature_provenance.append( { "feature_name": name, "feature_source": "rdock_derived", "pose_source": "top5" if ("top" in name or "consensus" in name) else "best_pose", "raw_output_file": str(source), "parsed_from": f"{source}::derived", "feature_type": "proxy" if val is not None and np.isfinite(float(val)) else "unavailable", "available": bool(val is not None and np.isfinite(float(val))), } ) return { "pose_path": str(source), "score": float(native["best_pose_score"]), "score_tag": "SCORE", "all_scores": scores, "pose_count": int(len(scores)), "poses": poses, "native_features": native, "derived_features": derived, "feature_provenance": feature_provenance, }