copuladock / code /compact_v2_pooled /materialize_protenix_usable_v2.py
liofoil's picture
Add files using upload-large-folder tool
8c74f19 verified
Raw
History Blame Contribute Delete
16.3 kB
#!/usr/bin/env python3
"""Materialize auditable HiQBind Protenix poses for pooled-v2 construction.
This program is intentionally independent of Docking Base's generic
``materialize_hiqbind_gnncp.py``. It has the same non-destructive materialization
model (validate published common output, then hard-link into a new flat tree),
but makes one Protenix policy explicit:
* ``success`` and ``partial`` result manifests are eligible by default;
* a ``failed`` result is eligible *only* when ``--include-failed-with-poses`` is
supplied and its published ``poses.csv`` points to one or more real PDB files.
The latter is needed for Protenix's protein-alignment quality gate: some
terminal ``failed`` manifests deliberately retain chemically valid ligand poses.
Those poses must never be silently mixed into an all-success dataset. Each
materialized record therefore retains the source result status and provenance in
``source_index.json``.
The script never modifies its source roots and refuses to reuse an output path.
It writes only to a private staging directory under the requested output parent,
then atomically publishes the completed directory.
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import re
import shutil
import sys
import tempfile
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Mapping
TARGET_RE = re.compile(r"[A-Za-z0-9_.-]+\Z")
NORMAL_STATUSES = frozenset({"success", "partial"})
FAILED_STATUS = "failed"
class MaterializeError(RuntimeError):
"""A source/output safety or eligibility error."""
def _utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def _read_json(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 JSON {path}: {exc}") from exc
if not isinstance(value, dict):
raise MaterializeError(f"JSON object expected in {path}")
return value
def _write_json(path: Path, value: Mapping[str, Any]) -> None:
"""Write a small metadata file inside the not-yet-published staging tree."""
path.write_text(
json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
encoding="utf-8",
)
def _inside(path: Path, root: Path) -> Path:
"""Resolve a source reference and ensure it cannot escape its native directory."""
resolved = path.resolve()
try:
resolved.relative_to(root.resolve())
except ValueError as exc:
raise MaterializeError(f"path escapes published native output: {path}") from exc
return resolved
def _pose_rows(native: Path) -> list[dict[str, Any]]:
"""Read usable published PDB poses in deterministic rank/name order."""
csv_path = native / "poses.csv"
try:
with csv_path.open("r", newline="", encoding="utf-8") as handle:
raw_rows = list(csv.DictReader(handle))
except OSError as exc:
raise MaterializeError(f"cannot read {csv_path}: {exc}") from exc
if not raw_rows:
raise MaterializeError(f"no emitted poses in {csv_path}")
rows: list[dict[str, Any]] = []
seen_paths: set[Path] = set()
for ordinal, row in enumerate(raw_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}"
)
if source in seen_paths:
raise MaterializeError(f"{csv_path}: duplicate pose file {source}")
seen_paths.add(source)
rank_text = row.get("rank", "")
try:
rank = int(rank_text)
except ValueError:
rank = ordinal
rows.append(
{
"rank": rank,
"row_ordinal": ordinal,
"source": source,
"source_relative_path": str(source.relative_to(native.resolve())),
"pose_id": row.get("pose_id", ""),
"score": row.get("score", ""),
"score_type": row.get("score_type", ""),
"seed": row.get("seed", ""),
"sample": row.get("sample", ""),
}
)
rows.sort(key=lambda item: (int(item["rank"]), str(item["source"].name)))
return rows
def _source_patterns() -> tuple[str, ...]:
"""Published output layouts produced by the HiQBind launchers."""
return (
"output/protenix/*/native/manifest.json",
"shards/*/protenix/output/protenix/*/native/manifest.json",
"workers/*/units/*/protenix/output/protenix/*/native/manifest.json",
"*/protenix/output/protenix/*/native/manifest.json",
)
def _is_eligible(status: str, include_failed_with_poses: bool) -> bool:
return status in NORMAL_STATUSES or (
include_failed_with_poses and status == FAILED_STATUS
)
def _discover(
source_roots: Iterable[Path],
*,
include_failed_with_poses: bool,
) -> dict[str, dict[str, Any]]:
"""Discover eligible published targets; later roots take target 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}")
manifest_paths = {
path
for pattern in _source_patterns()
for path in source_root.glob(pattern)
}
for manifest_path in sorted(manifest_paths, key=lambda value: str(value)):
native = manifest_path.parent.resolve()
target = native.parent.name
if not TARGET_RE.fullmatch(target):
raise MaterializeError(f"unsafe target name {target!r} in {native}")
manifest = _read_json(manifest_path)
status = manifest.get("status")
if not isinstance(status, str) or not _is_eligible(
status, include_failed_with_poses
):
continue
if status == FAILED_STATUS:
# A terminal failure is eligible only when its *published*
# pose table really resolves to usable PDB files. Do this
# before it is allowed to take precedence over an earlier
# source root for the same target.
try:
if not _pose_rows(native):
continue
except MaterializeError:
continue
selected[target] = {
"native": native,
"manifest_path": manifest_path.resolve(),
"manifest": manifest,
"source_root": source_root.resolve(),
"status": status,
}
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(
"hard-link failed "
f"({source} -> {destination}); source and output must share a filesystem: {exc}"
) from exc
def _check_output_is_safe(output_root: Path, source_roots: Iterable[Path]) -> None:
if output_root.exists() or output_root.is_symlink():
raise MaterializeError(f"output root already exists; refusing to replace it: {output_root}")
for source_root in source_roots:
try:
output_root.relative_to(source_root)
except ValueError:
continue
raise MaterializeError(
f"output root must not be inside source root: {output_root} inside {source_root}"
)
def _materialize_record(
*,
target: str,
source: Mapping[str, Any],
staging: Path,
max_poses: int,
include_failed_with_poses: bool,
) -> dict[str, Any]:
native = Path(source["native"])
status = str(source["status"])
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")
rows = _pose_rows(native)
if status == FAILED_STATUS and not include_failed_with_poses:
# Defensive redundancy: _discover already rejects this case.
raise MaterializeError("failed result requires --include-failed-with-poses")
if not rows:
raise MaterializeError("no usable PDB poses")
rows = rows[:max_poses]
destination = staging / target
destination.mkdir()
try:
_link(protein, destination / "protein.pdb")
_link(ligand, destination / "ligand.pdb")
materialized_names: list[str] = []
pose_provenance: list[dict[str, Any]] = []
for ordinal, row in enumerate(rows, start=1):
name = f"{target}_pose_{ordinal:03d}.pdb"
_link(Path(row["source"]), destination / name)
materialized_names.append(name)
pose_provenance.append(
{
"materialized_name": name,
"source_relative_path": row["source_relative_path"],
"source_rank": int(row["rank"]),
"source_row_ordinal": int(row["row_ordinal"]),
"source_pose_id": row["pose_id"],
"score": row["score"],
"score_type": row["score_type"],
"seed": row["seed"],
"sample": row["sample"],
}
)
except Exception:
shutil.rmtree(destination, ignore_errors=True)
raise
manifest = source["manifest"]
return {
"source_root": str(source["source_root"]),
"source_native": str(native),
"source_manifest": str(source["manifest_path"]),
"source_result_status": status,
"source_emitted_pose_count": manifest.get("emitted_pose_count"),
"accepted_by_policy": (
"success_or_partial"
if status in NORMAL_STATUSES
else "failed_with_published_poses_explicitly_included"
),
"pose_count": len(materialized_names),
"materialized_poses": materialized_names,
"pose_provenance": pose_provenance,
}
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--source-root",
action="append",
type=Path,
required=True,
help="published HiQBind run root; repeatable, later roots take precedence",
)
parser.add_argument("--output-root", type=Path, required=True)
parser.add_argument(
"--include-failed-with-poses",
action="store_true",
help=(
"explicitly include only failed manifests whose published poses.csv "
"contains usable PDB poses; source_result_status remains failed in metadata"
),
)
parser.add_argument(
"--target",
action="append",
default=[],
help="repeatable exact target filter (useful for a smoke materialization)",
)
parser.add_argument("--max-systems", type=int)
parser.add_argument("--max-poses-per-system", type=int, default=20)
return parser
def main(argv: list[str] | None = None) -> int:
args = _parser().parse_args(argv)
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")
source_roots = [path.expanduser().resolve() for path in args.source_root]
output_root = args.output_root.expanduser().resolve()
_check_output_is_safe(output_root, source_roots)
selected = _discover(
source_roots,
include_failed_with_poses=bool(args.include_failed_with_poses),
)
requested_targets = set(args.target)
if requested_targets:
selected = {key: value for key, value in selected.items() if key in requested_targets}
absent = sorted(requested_targets.difference(selected), key=str.casefold)
if absent:
raise MaterializeError(
"requested targets were not eligible/published: " + ", ".join(absent)
)
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 eligible Protenix systems 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]
try:
records[target] = _materialize_record(
target=target,
source=source,
staging=staging,
max_poses=int(args.max_poses_per_system),
include_failed_with_poses=bool(args.include_failed_with_poses),
)
except MaterializeError as exc:
shutil.rmtree(staging / target, ignore_errors=True)
skipped[target] = str(exc)
if not records:
raise MaterializeError("all selected Protenix systems were unusable")
status_counts = Counter(
record["source_result_status"] for record in records.values()
)
source_index: dict[str, Any] = {
"kind": "hiqbind_protenix_usable_pose_materialization_v2",
"method": "protenix",
"policy": {
"normal_eligible_statuses": sorted(NORMAL_STATUSES),
"include_failed_with_poses": bool(args.include_failed_with_poses),
"failed_inclusion_rule": (
"only a failed manifest with a non-empty poses.csv whose every "
"selected pose resolves to an existing PDB within the native output"
),
},
"records": records,
"skipped": skipped,
}
_write_json(staging / "source_index.json", source_index)
_write_json(
staging / "materialization_manifest.json",
{
"kind": "hiqbind_protenix_usable_pose_materialization_v2",
"created_utc": _utc_now(),
"method": "protenix",
"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(
int(record["pose_count"]) for record in records.values()
),
"materialized_systems_by_source_status": dict(sorted(status_counts.items())),
"skipped_system_count": len(skipped),
"max_poses_per_system": int(args.max_poses_per_system),
"include_failed_with_poses": bool(args.include_failed_with_poses),
"target_filter": sorted(requested_targets, key=str.casefold),
},
)
os.replace(staging, output_root)
except Exception:
shutil.rmtree(staging, ignore_errors=True)
raise
result = {
"output_root": str(output_root),
**_read_json(output_root / "materialization_manifest.json"),
}
print(json.dumps(result, sort_keys=True))
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except MaterializeError as exc:
print(f"error: {exc}", file=sys.stderr)
raise SystemExit(2)