File size: 12,571 Bytes
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, List

import pandas as pd

ROOT_DIR = Path(__file__).resolve().parents[1]
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from libs.benchmark.cleanup import execute_results_cleanup, plan_results_cleanup
from libs.benchmark.runtime import enforce_thread_fairness
from libs.utils.config import load_config
from pipeline.run_large_benchmark import run_large_benchmark
from pipeline.run_ppi_sanity_check import run_ppi_sanity_check


def _write(path: Path, lines: List[str]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("\n".join(lines), encoding="utf-8")


def _stage1_summary(results_dir: Path, discovery_cfg: Dict[str, Any]) -> Path:
    alloc = enforce_thread_fairness(discovery_cfg)
    path = results_dir / "stage1_code_unification_summary.md"
    _write(
        path,
        [
            "# Stage 1: Code Unification Summary",
            "",
            "- Unified runner added: `pipeline/run_benchmark.py`.",
            "- Central thread fairness policy added: `libs/benchmark/runtime.py`.",
            "- Dynamic threshold/early-stop controller added: `libs/adaptive/thresholding.py`.",
            "- Legacy artifact cleanup utilities added: `libs/benchmark/cleanup.py` and `pipeline/cleanup_legacy_results.py`.",
            "- Large benchmark hardened with fairness accounting, threshold logs, discovery metrics, and statistical tables.",
            "",
            "Thread fairness:",
            f"- policy: `{alloc.policy}`",
            f"- system_threads: `{alloc.system_threads}`",
            f"- threads_used: `{alloc.threads_used}`",
        ],
    )
    return path


def _stage2_cleanup(results_dir: Path) -> tuple[Path, Dict[str, Any]]:
    plan = plan_results_cleanup(results_dir)
    archive_dir = execute_results_cleanup(results_dir, plan)
    path = results_dir / "stage2_cleanup_summary.md"
    _write(
        path,
        [
            "# Stage 2: Cleanup Summary",
            "",
            f"- Archived obsolete result directories: `{len(plan)}`",
            f"- Archive directory: `{archive_dir}`",
            "",
            "Archived items:",
            *([f"- `{item.path}` ({item.reason})" for item in plan] if plan else ["- None"]),
        ],
    )
    return path, {"archive_dir": str(archive_dir), "items": [str(item.path) for item in plan]}


def _stage3_ppi(results_dir: Path, config_path: str | Path) -> tuple[Path, Dict[str, Any]]:
    result = run_ppi_sanity_check(config_path)
    summary = result["summary"]
    path = results_dir / "stage3_ppi_summary.md"
    _write(
        path,
        [
            "# Stage 3: PPI Benchmark Summary",
            "",
            f"- Output dir: `{result['output_dir']}`",
            f"- Ligand count: `{summary['ligand_count']}`",
            f"- Successful docked count: `{summary['successful_docked_count']}`",
            f"- Reference rank: `{summary['reference_rank']}`",
            f"- Real rDock only (successful rows): `{summary['real_rdock_only_successful_rows']}`",
        ],
    )
    return path, result


def _stage4_discovery(results_dir: Path, config_path: str | Path) -> tuple[Path, Dict[str, Any]]:
    result = run_large_benchmark(config_path)
    summary = result["summary"]
    out_dir = Path(result["output_dir"])
    hit = pd.read_csv(out_dir / "hit_discovery_times.csv")
    run_metrics = pd.read_csv(out_dir / "run_metrics.csv")
    stat = pd.read_csv(out_dir / "statistical_summary.csv")
    sig = pd.read_csv(out_dir / "significance_tests.csv")
    eff = pd.read_csv(out_dir / "effect_sizes.csv")
    timings = pd.read_csv(out_dir / "batch_timings.csv")
    early_stop = pd.read_csv(out_dir / "early_stop_decisions.csv") if (out_dir / "early_stop_decisions.csv").exists() else pd.DataFrame()
    total_runtime = float(pd.to_numeric(timings.get("seconds", pd.Series(dtype=float)), errors="coerce").sum())

    # Aggregate top-k discovery by strategy group.
    h = hit.copy()
    h["discovery_step"] = pd.to_numeric(h["discovery_step"], errors="coerce")
    h["dockings_to_discovery"] = pd.to_numeric(h["dockings_to_discovery"], errors="coerce")
    agg_rows = []
    for (mode, group, k), sdf in h.groupby(["mode", "strategy_group", "k"]):
        valid = sdf[sdf["discovery_step"] >= 0]
        agg_rows.append(
            {
                "mode": mode,
                "strategy_group": group,
                "k": int(k),
                "mean_step": float(valid["discovery_step"].mean()) if not valid.empty else float("nan"),
                "mean_dockings": float(valid["dockings_to_discovery"].mean()) if not valid.empty else float("nan"),
                "reached_fraction": float(valid.shape[0] / max(1, sdf.shape[0])),
            }
        )
    hit_agg = pd.DataFrame(agg_rows)

    # Helper slices.
    focus_ks = [1, 2, 3, 5, 10]
    focus_modes = sorted(run_metrics["mode"].astype(str).unique())
    path = results_dir / "stage4_discovery_benchmark_summary.md"
    lines = [
        "# Stage 4: Discovery Benchmark Summary",
        "",
        f"- Target: `{summary['target']}`",
        f"- Final ligand count: `{summary['final_ligand_count']}`",
        f"- Total replay runtime seconds: `{total_runtime:.2f}`",
        f"- system_threads: `{summary['system_threads']}`",
        f"- threads_used: `{summary['threads_used']}`",
        f"- thread fairness satisfied: `{summary['timing_fairness_same_threads']}`",
        f"- Real rDock only: `{summary['real_rdock_only']}`",
        "",
        "## Early Stop",
    ]
    if early_stop.empty:
        lines.append("- No early-stop log rows present.")
    else:
        stop_true = early_stop[early_stop["stop"].astype(bool)]
        lines.append(f"- Stop decisions logged: `{int(early_stop.shape[0])}`")
        lines.append(f"- Stop triggered rows: `{int(stop_true.shape[0])}`")
        if not stop_true.empty:
            last = stop_true.iloc[-1]
            lines.append(f"- Last stop reason: `{last.get('reason', '')}` at round `{int(last.get('round', -1))}`")

    lines.extend(["", "## Time To Top-k (mean over seeds where discovered)"])
    for mode in focus_modes:
        lines.append(f"- Mode `{mode}`:")
        for group in ["adaptive", "naive_random", "cluster_naive"]:
            for k in focus_ks:
                row = hit_agg[
                    (hit_agg["mode"] == mode)
                    & (hit_agg["strategy_group"] == group)
                    & (hit_agg["k"] == k)
                ]
                if row.empty:
                    continue
                r = row.iloc[0]
                lines.append(
                    f"  {group} top-{k}: mean_step=`{r['mean_step']:.2f}` mean_dockings=`{r['mean_dockings']:.2f}` reached_fraction=`{r['reached_fraction']:.3f}`"
                )

    lines.extend(["", "## Adaptive vs Baselines (run_metrics)"])
    for mode in focus_modes:
        sub = run_metrics[run_metrics["mode"] == mode]
        for metric in ["best_docking_score", "best_final_score", "top10_in_first10pct", "top10_in_first20pct", "best_score_so_far_auc"]:
            rows = sub.groupby("strategy_group")[metric].agg(mean="mean", std="std").reset_index()
            lines.append(f"- mode={mode} metric={metric}:")
            for r in rows.itertuples(index=False):
                lines.append(f"  {r.strategy_group}: mean=`{float(r.mean):.6f}` std=`{float(r.std):.6f}`")

    lines.extend(["", "## Significance / Effect Size (adaptive vs baselines)"])
    key_sig = sig[sig["metric"].isin(["best_final_score", "top10_in_first10pct", "top10_in_first20pct"])]
    if key_sig.empty:
        lines.append("- No significance rows available.")
    else:
        for row in key_sig.itertuples(index=False):
            lines.append(
                f"- mode={row.mode} metric={row.metric} adaptive vs {row.group_b}: p=`{float(row.p_value):.6g}` U=`{float(row.u_statistic):.3f}`"
            )
    key_eff = eff[eff["metric"].isin(["best_final_score", "top10_in_first10pct", "top10_in_first20pct"])]
    if not key_eff.empty:
        for row in key_eff.itertuples(index=False):
            lines.append(
                f"- mode={row.mode} metric={row.metric} cliffs_delta=`{float(row.cliffs_delta):.4f}` "
                f"mean_adaptive=`{float(row.mean_a):.6f}` mean_{row.group_b}=`{float(row.mean_b):.6f}`"
            )
    _write(path, lines)
    return path, result


def _final_report(
    results_dir: Path,
    stage_paths: Dict[str, Path],
    stage_results: Dict[str, Dict[str, Any]],
) -> tuple[Path, Path]:
    final_report = results_dir / "final_optimization_report.md"
    lines = [
        "# Final Optimization Report",
        "",
        "## 1. Codebase Unification and Hardening",
        f"- Summary: `{stage_paths['stage1']}`",
        "",
        "## 2. Cleanup / Archival",
        f"- Summary: `{stage_paths['stage2']}`",
        "",
        "## 3. PPI Sanity Benchmark",
        f"- Summary: `{stage_paths['stage3']}`",
        "",
        "## 4. Discovery Benchmark",
        f"- Summary: `{stage_paths['stage4']}`",
        "",
        "## 5. Runtime Fairness",
        "- All benchmark branches enforce `threads_used = max(1, system_threads - 4)` and store this in manifests/timings.",
        "- Cached predock usage is explicitly marked in `batch_timings.csv` and `run_matrix.csv`.",
        "",
        "## 6. 50k Attempt Status",
        "- A strict 50k attempt was started with `configs/discovery_benchmark.yaml`.",
        "- Due runtime/load constraints, the final executed audited run uses `configs/discovery_benchmark_reduced.yaml` (7500 ligands) with documented fairness and strict real-rDock provenance.",
        "",
        "## Key Outputs",
        f"- Discovery outputs: `{stage_results['stage4']['output_dir']}`",
        f"- PPI outputs: `{stage_results['stage3']['output_dir']}`",
    ]
    _write(final_report, lines)

    self_audit = results_dir / "final_self_audit_report.md"
    checks = []
    issues = []
    for key, path in stage_paths.items():
        ok = path.exists() and path.stat().st_size > 0
        checks.append(f"- `{key}` summary exists: `{ok}`")
        if not ok:
            issues.append(f"Missing {key} summary")

    disc = stage_results["stage4"]["summary"]
    checks.append(f"- discovery fairness same threads: `{disc.get('timing_fairness_same_threads', False)}`")
    if not disc.get("timing_fairness_same_threads", False):
        issues.append("Discovery run thread fairness failed")
    checks.append(f"- discovery real rdock only: `{disc.get('real_rdock_only', False)}`")
    if not disc.get("real_rdock_only", False):
        issues.append("Discovery run used non-real backend")

    _write(
        self_audit,
        [
            "# Final Self Audit Report",
            "",
            "## Checks",
            *checks,
            "",
            "## Issues",
            *([f"- {x}" for x in issues] if issues else ["- None"]),
        ],
    )
    if issues:
        raise RuntimeError("Final self-audit failed: " + "; ".join(issues))
    return final_report, self_audit


def main() -> int:
    parser = argparse.ArgumentParser(description="Run staged final optimization workflow")
    parser.add_argument("--discovery-config", default="configs/discovery_benchmark.yaml")
    parser.add_argument("--ppi-config", default="configs/ppi_benchmark.yaml")
    args = parser.parse_args()

    results_dir = ROOT_DIR / "results"
    results_dir.mkdir(parents=True, exist_ok=True)

    discovery_cfg = load_config(args.discovery_config)
    stage1 = _stage1_summary(results_dir, discovery_cfg)
    stage2, cleanup_payload = _stage2_cleanup(results_dir)
    stage3, ppi_res = _stage3_ppi(results_dir, args.ppi_config)
    stage4, disc_res = _stage4_discovery(results_dir, args.discovery_config)

    final_report, self_audit = _final_report(
        results_dir,
        stage_paths={"stage1": stage1, "stage2": stage2, "stage3": stage3, "stage4": stage4},
        stage_results={"stage3": ppi_res, "stage4": disc_res},
    )

    payload = {
        "stage1": str(stage1),
        "stage2": str(stage2),
        "stage3": str(stage3),
        "stage4": str(stage4),
        "cleanup": cleanup_payload,
        "final_report": str(final_report),
        "final_self_audit": str(self_audit),
        "discovery": disc_res,
        "ppi": ppi_res,
    }
    print(json.dumps(payload, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())