#!/usr/bin/env python3 """Materialize Docking Base PDB outputs into GNNCP's flat pose layout. The operation is intentionally non-destructive: it reads canonical common outputs and creates hard links in a new directory. It neither rewrites nor moves a docking result. The resulting layout is accepted by ``gnncp/system_split_code/build_compact_v1_direct.py``. """ from __future__ import annotations import argparse import csv import json import os import re import shutil import tempfile from datetime import datetime, timezone from pathlib import Path from typing import Any, Iterable METHODS = ("diffdock", "autodock_vina", "medusagraph", "protenix") TARGET_RE = re.compile(r"[A-Za-z0-9_.-]+\Z") class MaterializeError(RuntimeError): pass def _utc_now() -> str: return datetime.now(timezone.utc).isoformat() def _write_json(path: Path, value: dict[str, Any]) -> None: path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8") def _read_manifest(path: Path) -> dict[str, Any]: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise MaterializeError(f"cannot read manifest {path}: {exc}") from exc if not isinstance(value, dict): raise MaterializeError(f"manifest is not an object: {path}") return value def _inside(path: Path, root: Path) -> Path: resolved = path.resolve() try: resolved.relative_to(root.resolve()) except ValueError as exc: raise MaterializeError(f"path escapes native output directory: {path}") from exc return resolved def _pose_paths(native: Path) -> list[Path]: csv_path = native / "poses.csv" try: with csv_path.open("r", newline="", encoding="utf-8") as handle: rows = list(csv.DictReader(handle)) except OSError as exc: raise MaterializeError(f"cannot read {csv_path}: {exc}") from exc if not rows: raise MaterializeError(f"no emitted poses in {csv_path}") poses: list[tuple[int, str, Path]] = [] for ordinal, row in enumerate(rows, start=1): raw_path = row.get("pose_file") if not raw_path: raise MaterializeError(f"{csv_path}: pose row {ordinal} has no pose_file") candidate = Path(raw_path) source = candidate if candidate.is_absolute() else native / candidate source = _inside(source, native) if source.suffix.lower() != ".pdb" or not source.is_file(): raise MaterializeError(f"{csv_path}: unsupported or missing PDB pose {source}") rank_text = row.get("rank", "") try: rank = int(rank_text) except ValueError: rank = ordinal poses.append((rank, source.name, source)) poses.sort(key=lambda item: (item[0], item[1])) return [item[2] for item in poses] def _discover(source_roots: Iterable[Path], method: str) -> dict[str, dict[str, Any]]: """Discover eligible outputs; later source roots deliberately take precedence.""" selected: dict[str, dict[str, Any]] = {} for source_root in source_roots: if not source_root.is_dir(): raise MaterializeError(f"source root is not a directory: {source_root}") # Do not use a recursive glob here: a bulk run's work tree includes # multi-gigabyte raw model artifacts. These are the only published # Docking Base layouts produced by the normal/sharded/bulk launchers. patterns = ( f"output/{method}/*/native/manifest.json", f"shards/*/{method}/output/{method}/*/native/manifest.json", f"workers/*/units/*/{method}/output/{method}/*/native/manifest.json", f"*/{method}/output/{method}/*/native/manifest.json", ) manifest_paths = { path for pattern in patterns for path in source_root.glob(pattern) } for manifest_path in sorted(manifest_paths, key=lambda value: str(value)): native = manifest_path.parent target = native.parent.name if not TARGET_RE.fullmatch(target): raise MaterializeError(f"unsafe target name {target!r} in {native}") manifest = _read_manifest(manifest_path) if manifest.get("status") not in {"success", "partial"}: continue selected[target] = { "native": native.resolve(), "manifest": manifest_path.resolve(), "source_root": source_root.resolve(), } return selected def _link(source: Path, destination: Path) -> None: if destination.exists() or destination.is_symlink(): raise MaterializeError(f"unexpected existing materialized file: {destination}") try: os.link(source, destination) except OSError as exc: raise MaterializeError( f"hard-link failed ({source} -> {destination}); source and output must share a filesystem: {exc}" ) from exc def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--method", choices=METHODS, required=True) parser.add_argument( "--source-root", action="append", type=Path, required=True, help="run root to scan; repeatable, later roots take target precedence", ) parser.add_argument("--output-root", type=Path, required=True) parser.add_argument("--max-systems", type=int, help="materialize this many ordered systems") parser.add_argument("--max-poses-per-system", type=int, default=20) return parser def main() -> int: args = build_parser().parse_args() if args.max_systems is not None and args.max_systems <= 0: raise MaterializeError("--max-systems must be positive") if args.max_poses_per_system <= 0: raise MaterializeError("--max-poses-per-system must be positive") output_root = args.output_root.expanduser().resolve() if output_root.exists(): raise MaterializeError(f"output root already exists; refusing to replace it: {output_root}") source_roots = [path.expanduser().resolve() for path in args.source_root] selected = _discover(source_roots, args.method) ordered_targets = sorted(selected, key=str.casefold) if args.max_systems is not None: ordered_targets = ordered_targets[: args.max_systems] if not ordered_targets: raise MaterializeError("no success/partial common outputs discovered") output_root.parent.mkdir(parents=True, exist_ok=True) staging = Path(tempfile.mkdtemp(prefix=f".{output_root.name}.building-", dir=output_root.parent)) records: dict[str, Any] = {} skipped: dict[str, str] = {} try: for target in ordered_targets: source = selected[target] native = Path(source["native"]) try: protein = _inside(native / "protein.pdb", native) ligand = _inside(native / "ligand.pdb", native) if not protein.is_file() or not ligand.is_file(): raise MaterializeError("missing protein.pdb or ligand.pdb") poses = _pose_paths(native)[: args.max_poses_per_system] if not poses: raise MaterializeError("no usable PDB poses") destination = staging / target destination.mkdir() _link(protein, destination / "protein.pdb") _link(ligand, destination / "ligand.pdb") names: list[str] = [] for ordinal, pose in enumerate(poses, start=1): name = f"{target}_pose_{ordinal:03d}.pdb" _link(pose, destination / name) names.append(name) records[target] = { "source_root": str(source["source_root"]), "source_native": str(native), "source_manifest": str(source["manifest"]), "pose_count": len(names), "materialized_poses": names, } except MaterializeError as exc: shutil.rmtree(staging / target, ignore_errors=True) skipped[target] = str(exc) if not records: raise MaterializeError("all selected systems were unusable") source_index = { "kind": "docking_base_common_output_to_gnncp_flat_index", "method": args.method, "records": records, "skipped": skipped, } _write_json(staging / "source_index.json", source_index) _write_json( staging / "materialization_manifest.json", { "kind": "docking_base_gnncp_materialization", "created_utc": _utc_now(), "method": args.method, "link_mode": "hardlink", "source_roots": [str(path) for path in source_roots], "requested_system_count": len(ordered_targets), "materialized_system_count": len(records), "materialized_pose_count": sum(item["pose_count"] for item in records.values()), "skipped_system_count": len(skipped), "max_poses_per_system": args.max_poses_per_system, }, ) os.replace(staging, output_root) except Exception: shutil.rmtree(staging, ignore_errors=True) raise print(json.dumps({"output_root": str(output_root), **json.loads((output_root / "materialization_manifest.json").read_text())}, sort_keys=True)) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except MaterializeError as exc: print(f"error: {exc}") raise SystemExit(2)