File size: 6,743 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable

import numpy as np
import pandas as pd


REQUIRED_REFERENCE_DIAG_COLUMNS = [
    "dataset",
    "target_name",
    "reference_ligand_id",
    "reference_ligand_score",
    "reference_ligand_rank_percentile",
    "adaptive_best_score",
    "exhaustive_best_score",
]

REQUIRED_BACKEND_COMPARISON_COLUMNS = [
    "dataset",
    "backend",
    "analysis_scope",
    "available",
    "n_ligands",
    "runtime_seconds",
    "runtime_per_ligand",
    "reference_ligand_score",
    "reference_ligand_rank_percentile",
    "best_score",
    "score_gap_reference_vs_best",
    "reference_pose_centroid_distance_A",
    "reference_pose_in_expected_pocket",
]

REQUIRED_POCKET_PREP_COLUMNS = [
    "dataset",
    "backend",
    "pocket_variant",
    "prep_variant",
    "reference_ligand_score",
    "reference_pose_centroid_distance_A",
    "reference_pose_in_expected_pocket",
]


@dataclass(frozen=True)
class ManualAgentsCheck:
    exists: bool
    path: str
    manually_read: bool


def manual_agents_check(path: str | Path, manually_read: bool = True) -> ManualAgentsCheck:
    p = Path(path).expanduser().resolve()
    return ManualAgentsCheck(exists=p.exists(), path=str(p), manually_read=bool(manually_read and p.exists()))


def _safe_float(x: Any, default: float = np.nan) -> float:
    try:
        v = float(x)
        return float(v) if np.isfinite(v) else float(default)
    except Exception:
        return float(default)


def compute_rank_percentile(df: pd.DataFrame, ligand_id: str, score_col: str, lower_is_better: bool = True) -> float:
    if df.empty or score_col not in df.columns:
        return np.nan
    d = df[["ligand_id", score_col]].copy()
    d["ligand_id"] = d["ligand_id"].astype(str)
    d[score_col] = pd.to_numeric(d[score_col], errors="coerce")
    d = d.dropna(subset=[score_col]).copy()
    if d.empty:
        return np.nan
    d = d.sort_values(score_col, ascending=bool(lower_is_better)).reset_index(drop=True)
    hit = d.index[d["ligand_id"] == str(ligand_id)]
    if len(hit) == 0:
        return np.nan
    rank = int(hit[0]) + 1
    return float(100.0 * rank / max(1, d.shape[0]))


def select_suspicious_datasets(reference_diag_df: pd.DataFrame, threshold_pct: float = 25.0, max_deep: int = 2) -> list[str]:
    if reference_diag_df.empty:
        return []
    d = reference_diag_df.copy()
    d["reference_ligand_rank_percentile"] = pd.to_numeric(d["reference_ligand_rank_percentile"], errors="coerce")
    d = d.dropna(subset=["reference_ligand_rank_percentile"]).copy()
    d = d[d["reference_ligand_rank_percentile"] >= float(threshold_pct)].copy()
    if d.empty:
        return []
    d = d.sort_values("reference_ligand_rank_percentile", ascending=False)
    return d["dataset"].astype(str).head(int(max(1, max_deep))).tolist()


def validate_required_columns(df: pd.DataFrame, required_columns: Iterable[str]) -> list[str]:
    cols = set(df.columns)
    missing = [c for c in required_columns if c not in cols]
    return missing


def recommend_toolchain(
    backend_comparison_df: pd.DataFrame,
    pocket_prep_df: pd.DataFrame,
) -> dict[str, Any]:
    """
    Choose practical recommendation from diagnostic evidence.

    Policy:
    - Prefer backend with best median reference rank percentile under "subset_default" scope.
    - Penalize poor runtime-per-ligand if >2x best runtime.
    - Use pocket/prep gain to detect whether core issue is mostly preparation/pocket.
    """
    out: dict[str, Any] = {
        "recommended_main_backend": "rdock",
        "recommended_rescoring": "gnina_or_haddock_shortlist_optional",
        "keep_haddock": "optional_shortlist_only",
        "main_failure_source": "mixed",
        "evidence": [],
    }

    bdf = backend_comparison_df.copy()
    if not bdf.empty:
        bdf = bdf[bdf["analysis_scope"].astype(str) == "subset_default"].copy()
    if not bdf.empty:
        bdf["runtime_per_ligand"] = pd.to_numeric(bdf["runtime_per_ligand"], errors="coerce")
        bdf["reference_ligand_rank_percentile"] = pd.to_numeric(bdf["reference_ligand_rank_percentile"], errors="coerce")
        agg = (
            bdf.groupby("backend", as_index=False)
            .agg(
                median_ref_rank_pct=("reference_ligand_rank_percentile", "median"),
                median_runtime=("runtime_per_ligand", "median"),
                available_ratio=("available", "mean"),
            )
            .sort_values(["median_ref_rank_pct", "median_runtime"], ascending=[True, True])
        )
        if not agg.empty:
            best = agg.iloc[0]
            best_runtime = max(1e-9, _safe_float(best["median_runtime"], 1.0))
            candidate = str(best["backend"])
            if _safe_float(best["available_ratio"], 0.0) < 0.5:
                out["evidence"].append("best_rank_backend_not_reliably_available")
            else:
                out["recommended_main_backend"] = candidate

            rd = agg[agg["backend"].astype(str).str.lower() == "rdock"]
            if not rd.empty:
                rd_runtime = max(1e-9, _safe_float(rd.iloc[0]["median_runtime"], best_runtime))
                if best_runtime > 2.0 * rd_runtime and candidate != "rdock":
                    out["evidence"].append("candidate_backend_too_slow_vs_rdock")
                    out["recommended_main_backend"] = "rdock"

            out["evidence"].append(f"rank_runtime_table={agg.to_dict(orient='records')}")

    pdf = pocket_prep_df.copy()
    if not pdf.empty:
        pdf["reference_ligand_score"] = pd.to_numeric(pdf["reference_ligand_score"], errors="coerce")
        deltas: list[float] = []
        for (_, _), sub in pdf.groupby(["dataset", "backend"]):
            default = sub[(sub["pocket_variant"] == "default") & (sub["prep_variant"] == "default")]
            if default.empty:
                continue
            default_score = _safe_float(default.iloc[0]["reference_ligand_score"], np.nan)
            best_score = _safe_float(sub["reference_ligand_score"].min(), np.nan)
            if np.isfinite(default_score) and np.isfinite(best_score):
                deltas.append(default_score - best_score)
        mean_gain = float(np.mean(np.asarray(deltas, dtype=float))) if deltas else 0.0
        if mean_gain > 1.0:
            out["main_failure_source"] = "pocket_or_preparation"
        elif mean_gain > 0.2:
            out["main_failure_source"] = "mixed"
        else:
            out["main_failure_source"] = "backend_scoring_limitations"
        out["evidence"].append(f"mean_reference_gain_from_pocket_prep={mean_gain:.3f}")

    out["keep_haddock"] = "optional_shortlist_only"
    return out