| from __future__ import annotations |
|
|
| import json |
| import shutil |
| from dataclasses import dataclass |
| from pathlib import Path |
|
|
| from .provenance import RDockPipelineError, require_file |
| from .rdock import RDockEngine, TargetConfig |
| from .sdf import best_per_ligand, parse_rdock_sdf_records, records_to_rows, split_sdf_file, write_rows_csv, write_sdf_blocks, write_sdf_records |
|
|
|
|
| @dataclass |
| class ScheduledBatch: |
| batch_index: int |
| ligand_ids: list[str] |
|
|
|
|
| class RealDockingScheduler: |
| """Simple explicit scheduler: model ranks candidates, rDock produces ground truth.""" |
|
|
| def __init__(self, ligands: object, budget: int, batch_size: int) -> None: |
| if hasattr(ligands, "to_dict"): |
| rows = ligands.to_dict(orient="records") |
| else: |
| rows = list(ligands) |
| if not rows or "ligand_id" not in rows[0] or "smiles" not in rows[0]: |
| raise RDockPipelineError("Adaptive ligand CSV must contain ligand_id and smiles columns") |
| self.rows: list[dict[str, object]] = [dict(r) for r in rows] |
| self.budget = int(budget) |
| self.batch_size = int(batch_size) |
| self.completed: set[str] = set() |
| for row in self.rows: |
| model_score = _float_or_zero(row.get("model_score", 0.0)) |
| row["model_score"] = model_score |
| row["adaptive_priority"] = -model_score |
| row["actually_docked"] = False |
|
|
| def next_batch(self) -> ScheduledBatch | None: |
| remaining_budget = self.budget - len(self.completed) |
| if remaining_budget <= 0: |
| return None |
| active = [row for row in self.rows if str(row["ligand_id"]) not in self.completed] |
| if not active: |
| return None |
| active = sorted(active, key=lambda r: (-float(r["adaptive_priority"]), str(r["ligand_id"]))) |
| ids = [str(row["ligand_id"]) for row in active[: min(self.batch_size, remaining_budget)]] |
| return ScheduledBatch(batch_index=len(self.completed) // max(1, self.batch_size), ligand_ids=ids) |
|
|
| def update(self, docked_scores: object) -> None: |
| if hasattr(docked_scores, "to_dict"): |
| score_rows = docked_scores.to_dict(orient="records") |
| else: |
| score_rows = list(docked_scores) |
| for ligand_id in [str(row["ligand_id"]) for row in score_rows]: |
| self.completed.add(ligand_id) |
| for row in self.rows: |
| if str(row["ligand_id"]) == ligand_id: |
| row["actually_docked"] = True |
| if not score_rows: |
| return |
| scores = sorted(_float_or_zero(row.get("SCORE", 0.0)) for row in score_rows) |
| median_score = scores[len(scores) // 2] |
| for row in self.rows: |
| if str(row["ligand_id"]) not in self.completed: |
| row["adaptive_priority"] = float(row["adaptive_priority"]) + (0.001 * -median_score) |
|
|
| def to_dataframe(self): |
| import pandas as pd |
|
|
| return pd.DataFrame(self.rows) |
|
|
|
|
| def _float_or_zero(value: object) -> float: |
| try: |
| return float(value) |
| except Exception: |
| return 0.0 |
|
|
|
|
| def _prepare_batch_sdf(ligands: pd.DataFrame, ligand_ids: list[str], out_sdf: Path) -> Path: |
| from libs.docking.prep import prepare_ligand_sdf |
|
|
| tmp = out_sdf.parent / "prepared" |
| tmp.mkdir(parents=True, exist_ok=True) |
| blocks: list[str] = [] |
| by_id = ligands.set_index("ligand_id") |
| for ligand_id in ligand_ids: |
| smiles = str(by_id.loc[ligand_id, "smiles"]) |
| sdf = prepare_ligand_sdf(ligand_id, smiles, tmp / f"{ligand_id}.sdf") |
| blocks.extend(split_sdf_file(sdf)) |
| write_sdf_blocks(blocks, out_sdf) |
| return out_sdf |
|
|
|
|
| def run_adaptive( |
| target_config: TargetConfig, |
| ligands_csv: str | Path, |
| out_dir: str | Path, |
| budget: int, |
| batch_size: int, |
| engine: RDockEngine, |
| n_runs: int | None = None, |
| ) -> Path: |
| import pandas as pd |
|
|
| ligands = pd.read_csv(require_file(ligands_csv, "adaptive ligand CSV")) |
| scheduler = RealDockingScheduler(ligands, budget=budget, batch_size=batch_size) |
| root = Path(out_dir) |
| for name in ("target", "ligands", "rdock", "poses", "tables", "metrics"): |
| (root / name).mkdir(parents=True, exist_ok=True) |
| shutil.copy2(target_config.receptor, root / "target" / Path(target_config.receptor).name) |
| shutil.copy2(target_config.reference_ligand, root / "target" / Path(target_config.reference_ligand).name) |
|
|
| batch_records = [] |
| all_blocks: list[str] = [] |
| while True: |
| batch = scheduler.next_batch() |
| if batch is None: |
| break |
| batch_dir = root / "rdock" / f"batch_{batch.batch_index:03d}" |
| batch_sdf = _prepare_batch_sdf(ligands, batch.ligand_ids, root / "ligands" / f"batch_{batch.batch_index:03d}.sdf") |
| artifacts = engine.dock_sdf(target_config, batch_sdf, batch_dir, n_runs=n_runs, jobs=engine.config.jobs, run_id=f"{root.name}_batch_{batch.batch_index:03d}") |
| best_df = pd.read_csv(artifacts.best_per_ligand_csv) |
| scheduler.update(best_df) |
| all_blocks.extend(split_sdf_file(artifacts.all_poses_sdf)) |
| for ligand_id in batch.ligand_ids: |
| batch_records.append({"batch": batch.batch_index, "ligand_id": ligand_id}) |
|
|
| all_poses = root / "poses" / "all_poses.sdf" |
| write_sdf_blocks(all_blocks, all_poses) |
| if all_blocks: |
| records = parse_rdock_sdf_records(all_poses) |
| best = best_per_ligand(records) |
| write_sdf_records(best, root / "poses" / "best_per_ligand.sdf") |
| score_rows = records_to_rows(records) |
| best_rows = records_to_rows(best) |
| else: |
| score_rows = [] |
| best_rows = [] |
| (root / "poses" / "best_per_ligand.sdf").write_text("", encoding="utf-8") |
| scheduler_df = scheduler.to_dataframe() |
| model_cols = scheduler_df[["ligand_id", "model_score", "adaptive_priority", "actually_docked"]] |
| if best_rows: |
| model_map = model_cols.set_index("ligand_id").to_dict(orient="index") |
| for row in best_rows: |
| row.update(model_map.get(str(row["ligand_id"]), {})) |
| write_rows_csv(score_rows, root / "tables" / "scores_long.csv") |
| write_rows_csv(best_rows, root / "tables" / "best_per_ligand.csv") |
| scheduler_df.to_csv(root / "tables" / "scheduler_all_ligands.csv", index=False) |
| pd.DataFrame(batch_records).to_csv(root / "tables" / "adaptive_batches.csv", index=False) |
| (root / "metrics" / "validation_metrics.json").write_text("{}", encoding="utf-8") |
| pd.DataFrame().to_csv(root / "metrics" / "enrichment.csv", index=False) |
| manifest = { |
| "engine": "real-rdock-adaptive", |
| "budget": int(budget), |
| "batch_size": int(batch_size), |
| "docked_ligand_count": int(scheduler_df["actually_docked"].sum()), |
| "undocked_ligands_are_hits": False, |
| "artifacts": { |
| "all_poses_sdf": str(all_poses), |
| "best_per_ligand_csv": str(root / "tables" / "best_per_ligand.csv"), |
| "scheduler_all_ligands_csv": str(root / "tables" / "scheduler_all_ligands.csv"), |
| }, |
| } |
| (root / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") |
| (root / "config.yaml").write_text(f"budget: {budget}\nbatch_size: {batch_size}\n", encoding="utf-8") |
| (root / "commands.log").write_text("", encoding="utf-8") |
| for batch_log in sorted((root / "rdock").glob("batch_*/commands.log")): |
| with (root / "commands.log").open("a", encoding="utf-8") as dst: |
| dst.write(batch_log.read_text(encoding="utf-8")) |
| (root / "report.md").write_text( |
| "# Adaptive rDock Run\n\n" |
| "Model scores only schedule ligands. `best_per_ligand.csv` is built exclusively from real rDock SDF records with SCORE fields.\n", |
| encoding="utf-8", |
| ) |
| return root |
|
|