from __future__ import annotations import csv import math import re from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable from .provenance import RDockPipelineError, require_file TAG_RE = re.compile(r"^>\s*<\s*([^>]+?)\s*>", flags=re.IGNORECASE) @dataclass(frozen=True) class SDFRecord: block: str index: int ligand_id: str score: float | None tags: dict[str, str] numeric_tags: dict[str, float] def split_sdf_text(text: str) -> list[str]: blocks: list[str] = [] for part in text.split("$$$$"): body = part.strip() if body: blocks.append(body + "\n$$$$\n") return blocks def split_sdf_file(path: str | Path) -> list[str]: source = require_file(path, "SDF file") blocks = split_sdf_text(source.read_text(encoding="utf-8", errors="ignore")) if not blocks: raise RDockPipelineError(f"No SDF records found in {source}") return blocks def parse_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 key = m.group(1).strip() values: list[str] = [] j = i + 1 while j < len(lines) and lines[j].strip() and lines[j].strip() != "$$$$" and not TAG_RE.match(lines[j].strip()): values.append(lines[j].strip()) j += 1 tags[key] = "\n".join(values).strip() i = j return tags def _safe_float(value: Any) -> float | None: try: out = float(str(value).strip()) except Exception: return None if not math.isfinite(out): return None return out def _record_name(block: str, fallback: str) -> str: first = block.splitlines()[0].strip() if block.splitlines() else "" return first or fallback def ligand_id_from_block(block: str, tags: dict[str, str], index: int) -> str: for key in ("ligand_id", "LigandID", "LIGAND_ID", "ID", "Name", "_Name"): value = tags.get(key) if value: return value.split()[0].strip() return _record_name(block, f"ligand_{index:06d}").split()[0].strip() def parse_rdock_sdf_records(path: str | Path, require_score: bool = True) -> list[SDFRecord]: records: list[SDFRecord] = [] for idx, block in enumerate(split_sdf_file(path)): tags = parse_tags(block) numeric = {k: v for k, raw in tags.items() if (v := _safe_float(raw)) is not None} score = numeric.get("SCORE") if require_score and score is None: raise RDockPipelineError(f"Missing required rDock SCORE field in SDF record {idx} of {path}") records.append( SDFRecord( block=block, index=idx, ligand_id=ligand_id_from_block(block, tags, idx), score=score, tags=tags, numeric_tags=numeric, ) ) return records def write_sdf_records(records: Iterable[SDFRecord], path: str | Path) -> Path: target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) target.write_text("".join(rec.block for rec in records), encoding="utf-8") return target def write_sdf_blocks(blocks: Iterable[str], path: str | Path) -> Path: target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) target.write_text("".join(blocks), encoding="utf-8") return target def best_per_ligand(records: Iterable[SDFRecord]) -> list[SDFRecord]: best: dict[str, SDFRecord] = {} for rec in records: if rec.score is None: raise RDockPipelineError(f"Cannot rank ligand {rec.ligand_id}: missing SCORE") prev = best.get(rec.ligand_id) if prev is None or float(rec.score) < float(prev.score): best[rec.ligand_id] = rec return sorted(best.values(), key=lambda r: (float(r.score), r.ligand_id, r.index)) def records_to_rows(records: Iterable[SDFRecord]) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] for rec in records: row: dict[str, object] = { "pose_index": rec.index, "ligand_id": rec.ligand_id, "SCORE": rec.score, } for key, value in sorted(rec.numeric_tags.items()): row[key] = value rows.append(row) return rows def write_rows_csv(rows: list[dict[str, object]], path: str | Path, fieldnames: list[str] | None = None) -> Path: target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) fields: list[str] = list(fieldnames or []) if not fields: for row in rows: for key in row: if key not in fields: fields.append(key) with target.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fields, extrasaction="ignore") writer.writeheader() writer.writerows(rows) return target