Docking_project / docking_pipeline /benchmark_adaptive.py
QPromaQ's picture
Reset repository and upload final project (part 29)
24f6204 verified
Raw
History Blame Contribute Delete
274 kB
from __future__ import annotations
import argparse
import csv
import json
import math
import os
import random
import shutil
import time
import traceback
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from .audit_benchmark import audit_benchmark_run
from .dataset import read_ligand_metadata, repair_dataset_dir, validate_dataset_dir
from .provenance import RDockPipelineError, probe_version, require_executable, require_file, sha256_file
from .rdock import RDockEngine, RDockRunConfig, TargetConfig, load_target_config
from .reports.plots import plot_multifidelity_outputs, plot_score_outputs
from .sdf import ligand_id_from_block, parse_tags, split_sdf_file, write_rows_csv, write_sdf_blocks
try:
from libs.adaptive.surrogate_model import SurrogateConfig, SurrogateModel
except Exception: # pragma: no cover
SurrogateConfig = None # type: ignore[assignment]
SurrogateModel = None # type: ignore[assignment]
try: # pragma: no cover
from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor, RandomForestRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import LogisticRegression, Ridge
SKLEARN_AVAILABLE = True
except Exception: # pragma: no cover
ExtraTreesClassifier = None # type: ignore[assignment]
ExtraTreesRegressor = None # type: ignore[assignment]
RandomForestRegressor = None # type: ignore[assignment]
HistGradientBoostingRegressor = None # type: ignore[assignment]
LogisticRegression = None # type: ignore[assignment]
Ridge = None # type: ignore[assignment]
SKLEARN_AVAILABLE = False
try: # pragma: no cover
from rdkit import Chem, DataStructs, RDLogger
from rdkit.Chem import AllChem, Descriptors, MACCSkeys, rdMolDescriptors
from rdkit.Chem.Scaffolds import MurckoScaffold
try:
from rdkit.Chem.EnumerateStereoisomers import EnumerateStereoisomers, StereoEnumerationOptions
except Exception: # pragma: no cover
EnumerateStereoisomers = None # type: ignore[assignment]
StereoEnumerationOptions = None # type: ignore[assignment]
try:
from rdkit.Chem.MolStandardize import rdMolStandardize # type: ignore
except Exception: # pragma: no cover
rdMolStandardize = None # type: ignore[assignment]
RDKit_AVAILABLE = True
RDLogger.DisableLog("rdApp.warning")
except Exception: # pragma: no cover
Chem = None # type: ignore[assignment]
DataStructs = None # type: ignore[assignment]
AllChem = None # type: ignore[assignment]
Descriptors = None # type: ignore[assignment]
MACCSkeys = None # type: ignore[assignment]
rdMolDescriptors = None # type: ignore[assignment]
MurckoScaffold = None # type: ignore[assignment]
EnumerateStereoisomers = None # type: ignore[assignment]
StereoEnumerationOptions = None # type: ignore[assignment]
rdMolStandardize = None # type: ignore[assignment]
RDKit_AVAILABLE = False
def _read_rows(path: str | Path) -> list[dict[str, str]]:
with Path(path).open("r", encoding="utf-8", newline="") as handle:
return list(csv.DictReader(handle))
def _write_json(path: str | Path, payload: dict[str, Any]) -> Path:
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(payload, indent=2), encoding="utf-8")
return target
def _load_json(path: str | Path) -> dict[str, Any]:
source = require_file(path, "JSON artifact")
payload = json.loads(source.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise RDockPipelineError(f"Expected JSON object in {source}")
return payload
def _float(value: object, default: float = 0.0) -> float:
try:
text = str(value).strip()
if not text:
return default
return float(text)
except Exception:
return default
def _bool_text(value: bool) -> str:
return "true" if value else "false"
def _parse_levels(text: str) -> list[int]:
try:
levels = [int(part.strip()) for part in text.split(",") if part.strip()]
except Exception as exc:
raise RDockPipelineError(f"Invalid --fidelity-levels value {text!r}: {exc}") from exc
if not levels or sorted(levels) != levels or min(levels) <= 0:
raise RDockPipelineError(f"Invalid fidelity levels: {levels}")
return levels
def _write_yaml_like(path: Path, payload: dict[str, Any]) -> None:
try:
import yaml
text = yaml.safe_dump(payload, sort_keys=False)
except Exception:
text = json.dumps(payload, indent=2)
path.write_text(text, encoding="utf-8")
def _bool_arg(value: object, default: bool = False) -> bool:
text = str(value).strip().lower()
if not text:
return default
return text in {"1", "true", "yes", "y", "on"}
def _count_sdf(path: Path) -> int:
return len(split_sdf_file(path))
def _load_input_block_map(sdf_path: Path) -> dict[str, str]:
block_map: dict[str, str] = {}
for idx, block in enumerate(split_sdf_file(sdf_path)):
tags = parse_tags(block)
ligand_id = ligand_id_from_block(block, tags, idx)
block_map[ligand_id] = block
return block_map
def _write_selected_sdf(block_map: dict[str, str], ligand_ids: list[str], out_path: Path) -> Path:
missing = [ligand_id for ligand_id in ligand_ids if ligand_id not in block_map]
if missing:
raise RDockPipelineError(f"Missing {len(missing)} ligand IDs in prepared SDF: {missing[:10]}")
write_sdf_blocks([block_map[ligand_id] for ligand_id in ligand_ids], out_path)
return out_path
def _mean(values: list[float]) -> float:
return sum(values) / len(values) if values else 0.0
def _stdev(values: list[float], center: float) -> float:
if not values:
return 1.0
var = sum((value - center) ** 2 for value in values) / max(1, len(values))
return math.sqrt(var) or 1.0
def _component_sane_score(row: dict[str, Any]) -> float | None:
for key in ("ranking_score", "final_score", "SCORE", "best_score"):
value = _float(row.get(key), float("inf"))
if math.isfinite(value):
return value
return None
def _score_target_value(row: dict[str, Any], target: str) -> float | None:
target_name = str(target or "component_sane_affinity_like").strip().lower()
raw_score = _float(row.get("SCORE"), float("inf"))
filtered_score = _component_sane_score(row)
score_inter = _float(row.get("SCORE.INTER"), float("inf"))
if target_name == "raw_score":
return raw_score if math.isfinite(raw_score) else None
if target_name in {"filtered_score", "downranked_score", "component_sane_score"}:
return filtered_score
if target_name == "score_inter":
return score_inter if math.isfinite(score_inter) else None
if target_name in {"affinity_like", "component_sane_affinity_like"}:
return (-filtered_score) if filtered_score is not None else None
return (-filtered_score) if filtered_score is not None else None
def _state_overrides_from_rows(rows: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
overrides: dict[str, dict[str, Any]] = {}
for row in rows:
ligand_id = str(row.get("ligand_id", ""))
if not ligand_id:
continue
score = _component_sane_score(row)
inter_val = _float(row.get("SCORE.INTER"), 0.0)
intra_val = _float(row.get("SCORE.INTRA"), 0.0)
intra_fraction = _float(row.get("intra_fraction"), 0.0)
selected_level = int(_float(row.get("selected_fidelity_runs"), 0.0) or 0)
overrides[ligand_id] = {
"selected_fidelity_runs": selected_level,
"current_best_score": score if score is not None else 0.0,
"score_mean_observed": score if score is not None else 0.0,
"score_std_observed": 0.0,
"best_inter_seen": inter_val,
"best_intra_seen": intra_val,
"best_intra_fraction_seen": intra_fraction,
"failed_observation_fraction": 0.0 if str(row.get("rdock_success", "true")).lower() in {"true", "1"} else 1.0,
"pose_count_seen": int(_float(row.get("n_poses"), 1.0) or 1),
}
return overrides
def _split_rows_for_validation(
rows: list[dict[str, Any]],
holdout_fraction: float,
seed: int,
mode: str,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
if len(rows) < 2:
return list(rows), []
holdout_size = max(1, min(len(rows) - 1, int(math.ceil(len(rows) * holdout_fraction))))
shuffled = list(rows)
rng = random.Random(seed)
mode_name = str(mode or "random").strip().lower()
if mode_name == "cluster":
clusters: dict[str, list[dict[str, Any]]] = {}
for row in shuffled:
clusters.setdefault(str(row.get("cluster_id", "")), []).append(row)
cluster_ids = list(clusters)
rng.shuffle(cluster_ids)
holdout_rows: list[dict[str, Any]] = []
for cluster_id in cluster_ids:
if len(holdout_rows) >= holdout_size:
break
holdout_rows.extend(clusters[cluster_id])
holdout_ids = {str(row["ligand_id"]) for row in holdout_rows[:holdout_size]}
holdout = [row for row in shuffled if str(row["ligand_id"]) in holdout_ids]
train = [row for row in shuffled if str(row["ligand_id"]) not in holdout_ids]
if not train or not holdout:
rng.shuffle(shuffled)
holdout = shuffled[:holdout_size]
train = shuffled[holdout_size:] or shuffled[:-1]
return train, holdout
rng.shuffle(shuffled)
holdout = shuffled[:holdout_size]
train = shuffled[holdout_size:] or shuffled[:-1]
return train, holdout
def _effective_uncertainty_weight(configured_weight: float, correlation: float | None) -> tuple[float, bool, str]:
corr = _float(correlation, None)
if corr is None:
return 0.0, False, "uncertainty_validation_unavailable"
if corr < 0.1:
return 0.0, False, "uncertainty_vs_error_correlation_too_low"
return min(float(configured_weight), 0.2), True, ""
def _clamp_unit_interval(value: Any) -> float | None:
numeric = _float(value, None)
if numeric is None:
return None
return max(0.0, min(1.0, float(numeric)))
def _regressor_status_from_metrics(metrics: dict[str, Any]) -> tuple[bool, str]:
spearman = _float(metrics.get("surrogate_affinity_like_spearman", metrics.get("surrogate_spearman")), None)
mae = _float(metrics.get("surrogate_mae"), None)
cluster_spearman = _float(metrics.get("cluster_validation_spearman"), None)
sign_ok = bool(metrics.get("regressor_sign_check_passed", False))
if not sign_ok:
return False, "regressor_sign_check_failed"
if spearman is None or spearman < 0.3:
return False, "surrogate_spearman_below_threshold"
if cluster_spearman is not None and cluster_spearman < 0.2:
return False, "cluster_aware_spearman_below_threshold"
if mae is not None and mae > 25.0:
return False, "surrogate_mae_above_threshold"
return True, ""
def _augment_full_rows(rows: list[dict[str, str]]) -> list[dict[str, Any]]:
ordered = sorted(rows, key=lambda row: (_float(row.get("SCORE"), float("inf")), str(row.get("ligand_id", ""))))
total = max(1, len(ordered))
enriched: list[dict[str, Any]] = []
for idx, row in enumerate(ordered, start=1):
item: dict[str, Any] = dict(row)
item["full_rank"] = idx
item["full_percentile"] = 100.0 if total == 1 else 100.0 * (1.0 - ((idx - 1) / (total - 1)))
enriched.append(item)
return enriched
def _percentile_from_rank(rank: int, total: int) -> float:
if total <= 1:
return 100.0
return 100.0 * (1.0 - ((rank - 1) / (total - 1)))
def _append_rank_metrics(rows: list[dict[str, Any]], full_rank_map: dict[str, int], total: int) -> list[dict[str, Any]]:
enriched: list[dict[str, Any]] = []
for row in rows:
item = dict(row)
ligand_id = str(item["ligand_id"])
rank = full_rank_map.get(ligand_id)
item["full_rank"] = rank if rank is not None else ""
item["full_percentile"] = _percentile_from_rank(rank, total) if rank is not None else ""
enriched.append(item)
return enriched
def _make_regressor_model(model_type: str) -> Any:
model_name = str(model_type or "extra_trees").strip().lower()
if model_name == "random_forest" and RandomForestRegressor is not None:
return RandomForestRegressor(
n_estimators=256,
random_state=42,
min_samples_leaf=2,
n_jobs=1,
)
if model_name == "hist_gradient_boosting" and HistGradientBoostingRegressor is not None:
return HistGradientBoostingRegressor(
random_state=42,
max_depth=8,
learning_rate=0.05,
)
if model_name == "ridge" and Ridge is not None:
return Ridge(alpha=1.0, random_state=42)
if ExtraTreesRegressor is not None:
return ExtraTreesRegressor(
n_estimators=256,
random_state=42,
min_samples_leaf=2,
n_jobs=1,
)
return None
def _sort_by_score(rows: list[dict[str, Any]], *keys: str) -> list[dict[str, Any]]:
def _row_score(row: dict[str, Any]) -> float:
for key in keys:
value = _float(row.get(key), None)
if value is not None and math.isfinite(value):
return value
return float("inf")
return sorted(rows, key=lambda row: (_row_score(row), str(row.get("ligand_id", ""))))
def _top_overlap(full_rows: list[dict[str, Any]], sample_rows: list[dict[str, Any]], n: int) -> int:
full_top = {str(row["ligand_id"]) for row in full_rows[:n]}
ranked = sorted(sample_rows, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf")))
sample_top = {str(row["ligand_id"]) for row in ranked[:n] if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}}
return len(full_top & sample_top)
def _infer_cluster_id(row: dict[str, str], index: int) -> str:
for key in ("cluster_id", "scaffold_id", "series_id"):
value = str(row.get(key, "")).strip()
if value:
return value
smiles = str(row.get("smiles", "")).strip()
if smiles:
return smiles[:12]
return f"cluster_{index:05d}"
def _rdkit_mol(smiles: str):
if not RDKit_AVAILABLE or not smiles:
return None
try:
return Chem.MolFromSmiles(smiles)
except Exception:
return None
def _rdkit_scaffold_id(mol) -> str:
if not RDKit_AVAILABLE or mol is None:
return ""
try:
scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=mol)
return str(scaffold or "")
except Exception:
return ""
def _rdkit_fingerprint_bits(mol, n_bits: int = 128) -> list[float]:
if not RDKit_AVAILABLE or mol is None:
return [0.0 for _ in range(n_bits)]
try:
fp = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=n_bits)
bits = [1.0 if int(fp.GetBit(i)) else 0.0 for i in range(n_bits)]
if any(bits):
return bits
except Exception:
pass
try:
counts = rdMolDescriptors.GetHashedMorganFingerprint(mol, 2, nBits=n_bits)
bits = [0.0 for _ in range(n_bits)]
for bit_id, count in counts.GetNonzeroElements().items():
if int(count) > 0:
bits[int(bit_id) % n_bits] = 1.0
return bits
except Exception:
return [0.0 for _ in range(n_bits)]
def _rdkit_morgan_count_sum(mol, n_bits: int = 128) -> float:
if not RDKit_AVAILABLE or mol is None:
return 0.0
try:
counts = rdMolDescriptors.GetHashedMorganFingerprint(mol, 2, nBits=n_bits)
return float(sum(max(0, int(count)) for count in counts.GetNonzeroElements().values()))
except Exception:
return 0.0
def _rdkit_maccs_bits(mol) -> list[float]:
if not RDKit_AVAILABLE or mol is None or MACCSkeys is None:
return [0.0 for _ in range(167)]
try:
fp = MACCSkeys.GenMACCSKeys(mol)
return [1.0 if int(fp.GetBit(i)) else 0.0 for i in range(fp.GetNumBits())]
except Exception:
return [0.0 for _ in range(167)]
def _rdkit_chiral_center_count(mol) -> float:
if not RDKit_AVAILABLE or mol is None:
return 0.0
try:
return float(len(Chem.FindMolChiralCenters(mol, includeUnassigned=True)))
except Exception:
return 0.0
def _activity_class(p_good: float, uncertainty: float, confidence: float) -> str:
if p_good >= 0.65 and confidence >= 0.35:
return "active"
if p_good <= 0.25 and uncertainty <= 0.75:
return "inactive"
return "uncertain"
def _build_model_rows(rows: list[dict[str, str]]) -> list[dict[str, Any]]:
numeric_keys = [
"molecular_weight",
"xlogp",
"tpsa",
"hbd",
"hba",
"rotatable_bonds",
"heavy_atom_count",
"formal_charge",
"ring_count",
"aromatic_ring_count",
"fraction_csp3",
"heteroatom_count",
"chiral_center_count",
"smiles_length",
"digit_count",
"branch_count",
"double_bond_count",
"triple_bond_count",
"halogen_count",
"hetero_fraction",
"rotor_heavy_ratio",
]
features: dict[str, list[float]] = {key: [] for key in numeric_keys}
parsed: list[dict[str, Any]] = []
for idx, row in enumerate(rows):
item: dict[str, Any] = dict(row)
smiles = str(row.get("smiles", "")).strip()
item["smiles"] = smiles
mol = _rdkit_mol(smiles)
rdkit_cluster = _rdkit_scaffold_id(mol)
analog_group_id = str(row.get("analog_group_id", "")).strip()
analog_group_size = max(1.0, _float(row.get("analog_group_size"), 1.0))
analog_group_weight = _float(row.get("analog_group_weight"), 1.0 / analog_group_size)
analog_group_weight = max(0.01, min(1.0, analog_group_weight))
item["analog_group_id"] = analog_group_id
item["analog_parent_id"] = str(row.get("analog_parent_id", row.get("ligand_id", "")))
item["analog_group_size"] = float(analog_group_size)
item["analog_group_weight"] = float(analog_group_weight)
item["analog_variant_index"] = _float(row.get("analog_variant_index"), 1.0)
item["analog_group_rule"] = str(row.get("analog_group_rule", "singleton"))
item["cluster_id"] = analog_group_id or rdkit_cluster or _infer_cluster_id(row, idx)
item["scaffold_id"] = rdkit_cluster or str(row.get("scaffold_id", ""))
scaffold_match = _bool_arg(row.get("scaffold_match"), False)
is_reference = _bool_arg(row.get("is_reference"), False)
item["scaffold_match_num"] = 1.0 if scaffold_match else 0.0
item["is_reference_num"] = 1.0 if is_reference else 0.0
if RDKit_AVAILABLE and mol is not None:
item["molecular_weight"] = _float(row.get("molecular_weight"), float(Descriptors.MolWt(mol)))
item["xlogp"] = _float(row.get("xlogp"), float(Descriptors.MolLogP(mol)))
item["tpsa"] = _float(row.get("tpsa"), float(rdMolDescriptors.CalcTPSA(mol)))
item["hbd"] = _float(row.get("hbd"), float(rdMolDescriptors.CalcNumHBD(mol)))
item["hba"] = _float(row.get("hba"), float(rdMolDescriptors.CalcNumHBA(mol)))
item["rotatable_bonds"] = _float(row.get("rotatable_bonds"), float(rdMolDescriptors.CalcNumRotatableBonds(mol)))
item["heavy_atom_count"] = _float(row.get("heavy_atom_count"), float(mol.GetNumHeavyAtoms()))
item["formal_charge"] = _float(row.get("formal_charge"), float(sum(atom.GetFormalCharge() for atom in mol.GetAtoms())))
item["ring_count"] = _float(row.get("ring_count"), float(rdMolDescriptors.CalcNumRings(mol)))
item["aromatic_ring_count"] = _float(row.get("aromatic_ring_count"), float(rdMolDescriptors.CalcNumAromaticRings(mol)))
item["fraction_csp3"] = _float(row.get("fraction_csp3"), float(rdMolDescriptors.CalcFractionCSP3(mol)))
item["heteroatom_count"] = _float(row.get("heteroatom_count"), float(sum(1 for atom in mol.GetAtoms() if atom.GetAtomicNum() not in {1, 6})))
item["chiral_center_count"] = _float(row.get("chiral_center_count"), _rdkit_chiral_center_count(mol))
fp_bits = _rdkit_fingerprint_bits(mol, 128)
morgan_count_sum = _rdkit_morgan_count_sum(mol, 128)
maccs_bits = _rdkit_maccs_bits(mol)
else:
item["molecular_weight"] = _float(row.get("molecular_weight"), 0.0)
item["xlogp"] = _float(row.get("xlogp"), 0.0)
item["tpsa"] = _float(row.get("tpsa"), 0.0)
item["hbd"] = _float(row.get("hbd"), 0.0)
item["hba"] = _float(row.get("hba"), 0.0)
item["rotatable_bonds"] = _float(row.get("rotatable_bonds"), 0.0)
item["heavy_atom_count"] = _float(row.get("heavy_atom_count"), 0.0)
item["formal_charge"] = _float(row.get("formal_charge"), 0.0)
item["ring_count"] = _float(row.get("ring_count"), smiles.count("1") + smiles.count("2") + smiles.count("3"))
item["aromatic_ring_count"] = _float(row.get("aromatic_ring_count"), max(0.0, smiles.count("c") / 6.0))
item["fraction_csp3"] = _float(row.get("fraction_csp3"), min(1.0, max(0.0, smiles.count("C") / max(1.0, float(smiles.count("C") + smiles.count("c"))))))
hetero_count = sum(smiles.count(token) for token in ("N", "O", "S", "P", "F", "Cl", "Br", "I", "n", "o", "s", "p"))
item["heteroatom_count"] = _float(row.get("heteroatom_count"), float(hetero_count))
item["chiral_center_count"] = _float(row.get("chiral_center_count"), 0.0)
fp_bits = [0.0 for _ in range(128)]
morgan_count_sum = 0.0
maccs_bits = [0.0 for _ in range(167)]
fp_bits = list(fp_bits or [])
maccs_bits = list(maccs_bits or [])
if len(fp_bits) != 128:
fp_bits = (fp_bits + [0.0 for _ in range(128)])[:128]
if len(maccs_bits) != 167:
maccs_bits = (maccs_bits + [0.0 for _ in range(167)])[:167]
item["smiles_length"] = float(len(smiles))
item["digit_count"] = float(sum(1 for ch in smiles if ch.isdigit()))
item["branch_count"] = float(smiles.count("("))
item["double_bond_count"] = float(smiles.count("="))
item["triple_bond_count"] = float(smiles.count("#"))
item["halogen_count"] = float(smiles.count("F") + smiles.count("Cl") + smiles.count("Br") + smiles.count("I"))
item["hetero_fraction"] = float(item["heteroatom_count"]) / max(1.0, float(item["heavy_atom_count"]))
item["rotor_heavy_ratio"] = float(item["rotatable_bonds"]) / max(1.0, float(item["heavy_atom_count"]))
item["morgan_nonzero_count"] = float(sum(1 for value in fp_bits if float(value) > 0.0))
item["morgan_density"] = item["morgan_nonzero_count"] / 128.0
item["morgan_count_sum"] = float(morgan_count_sum)
item["maccs_nonzero_count"] = float(sum(1 for value in maccs_bits if float(value) > 0.0))
sim = _float(row.get("reference_similarity"), 0.0)
item["reference_similarity"] = sim
item["reference_core_focus_score"] = float((0.65 * sim) + (0.25 * item["scaffold_match_num"]) + (0.10 * item["is_reference_num"]))
model_score = _float(
row.get("model_score"),
(
0.10 * sim
+ 0.08 * item["scaffold_match_num"]
+ 0.04 * item["is_reference_num"]
- 0.002 * float(item["molecular_weight"])
- 0.03 * float(item["rotatable_bonds"])
),
)
item["model_score"] = model_score
for key in numeric_keys:
value = _float(item.get(key), 0.0)
item[key] = value
features[key].append(value)
item["fingerprint_bits"] = fp_bits
item["maccs_bits"] = maccs_bits
parsed.append(item)
cluster_sizes: dict[str, int] = {}
for item in parsed:
cluster_id = str(item["cluster_id"])
cluster_sizes[cluster_id] = cluster_sizes.get(cluster_id, 0) + 1
means = {key: _mean(values) for key, values in features.items()}
stdevs = {key: _stdev(values, means[key]) for key, values in features.items()}
for item in parsed:
item["cluster_size"] = cluster_sizes.get(str(item["cluster_id"]), 1)
item["feature_vector"] = [
(_float(item[key]) - means[key]) / stdevs[key]
for key in numeric_keys
] + [
float(item["scaffold_match_num"]),
float(item["is_reference_num"]),
float(item["reference_similarity"]),
float(item["reference_core_focus_score"]),
float(item["morgan_nonzero_count"]),
float(item["morgan_density"]),
float(item["morgan_count_sum"]),
float(item["maccs_nonzero_count"]),
float(item["analog_group_size"]),
float(item["analog_group_weight"]),
float(item["analog_variant_index"]),
] + list(item.get("fingerprint_bits") or []) + list(item.get("maccs_bits") or [])
return parsed
MODEL_STRATEGIES = {
"reference_free_triage_bandit_v1",
"reference_free_active_learning_v2",
"reference_free_active_learning_v3_diverse_ranker",
"reference_free_active_learning_v3_lean",
}
TRIAGE_ROW_FIELDS = [
"ligand_id",
"smiles",
"cluster_id",
"scaffold_id",
"analog_group_id",
"analog_parent_id",
"analog_group_size",
"analog_group_weight",
"analog_variant_index",
"analog_group_rule",
"survived_triage",
"triage_score",
"keep_probability",
"p_good",
"regressor_activity_class",
"predicted_adjusted_score",
"predicted_affinity_like",
"predicted_uncertainty",
"regressor_confidence",
"outlier_risk",
"cluster_quality",
"diversity_bonus",
"interaction_quality",
"post_docking_confidence_score",
"biological_interaction_proxy_score",
"reference_similarity",
"reference_core_focus_score",
"scaffold_match_num",
"is_reference_num",
"morgan_nonzero_count",
"morgan_density",
"morgan_count_sum",
"maccs_nonzero_count",
"adaptive_policy",
"acquisition_mode",
"acquisition_classifier_component",
"acquisition_score_component",
"acquisition_uncertainty_component",
"acquisition_diversity_component",
"acquisition_cluster_component",
"acquisition_outlier_component",
"acquisition_interaction_component",
"effective_regressor_weight",
"effective_uncertainty_weight",
]
def _strategy_requires_rdkit(strategy: str) -> bool:
return strategy in MODEL_STRATEGIES or strategy in {"cluster_only_triage"}
def _variants_require_rdkit(enabled: bool, stage: str) -> bool:
return enabled and str(stage) in {"final_survivors", "posthoc_top_hits"}
def _feature_matrix(rows: list[dict[str, Any]]) -> list[list[float]]:
matrix: list[list[float]] = []
for row in rows:
vector = row.get("augmented_feature_vector", row.get("feature_vector", []))
matrix.append(_sanitize_model_features(vector))
return matrix
def _analog_sample_weights(rows: list[dict[str, Any]]) -> list[float]:
return [max(0.01, min(1.0, _float(row.get("analog_group_weight"), 1.0))) for row in rows]
def _fit_model(model: Any, x: list[list[float]], y: list[Any], sample_weight: list[float] | None = None) -> Any:
if sample_weight is not None:
try:
return model.fit(x, y, sample_weight=sample_weight)
except TypeError:
pass
return model.fit(x, y)
def _sanitize_model_feature(value: Any, default: float = 0.0, limit: float = 1.0e6) -> float:
try:
numeric = float(value)
except Exception:
return default
if not math.isfinite(numeric):
return default
return max(-limit, min(limit, numeric))
def _sanitize_model_features(values: Any) -> list[float]:
try:
iterator = list(values)
except Exception:
return []
return [_sanitize_model_feature(value) for value in iterator]
def _median(values: list[float]) -> float:
if not values:
return 0.0
ordered = sorted(values)
mid = len(ordered) // 2
if len(ordered) % 2:
return float(ordered[mid])
return float(0.5 * (ordered[mid - 1] + ordered[mid]))
def _ensemble_uncertainty(model: Any, matrix: list[list[float]], fallback: float = 1.0) -> list[float]:
if not matrix:
return []
estimators = list(getattr(model, "estimators_", []) or [])
if not estimators:
return [fallback for _ in matrix]
per_row: list[list[float]] = [[] for _ in matrix]
for estimator in estimators:
try:
preds = estimator.predict(matrix)
except Exception:
continue
for idx, pred in enumerate(preds):
per_row[idx].append(float(pred))
uncertainties: list[float] = []
for preds in per_row:
if not preds:
uncertainties.append(fallback)
continue
center = _mean(preds)
uncertainties.append(_stdev(preds, center))
return uncertainties
def _binary_positive_proba(model: Any, matrix: list[list[float]], default_positive: float = 0.0) -> list[float]:
if not matrix:
return []
classes_attr = getattr(model, "classes_", None)
classes = list(classes_attr) if classes_attr is not None else []
if len(classes) <= 1:
if classes and int(classes[0]) == 1:
return [1.0 for _ in matrix]
return [default_positive for _ in matrix]
probs = model.predict_proba(matrix)
positive_index = classes.index(1) if 1 in classes else len(classes) - 1
return [float(row[positive_index]) for row in probs]
def _spearman(xs: list[float], ys: list[float]) -> float | None:
if len(xs) < 2 or len(xs) != len(ys):
return None
def _ranks(values: list[float]) -> list[float]:
order = sorted(range(len(values)), key=lambda idx: values[idx])
ranks = [0.0] * len(values)
for rank, idx in enumerate(order, start=1):
ranks[idx] = float(rank)
return ranks
rx = _ranks(xs)
ry = _ranks(ys)
mx = _mean(rx)
my = _mean(ry)
num = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
denx = math.sqrt(sum((a - mx) ** 2 for a in rx))
deny = math.sqrt(sum((b - my) ** 2 for b in ry))
if denx == 0.0 or deny == 0.0:
return None
return num / (denx * deny)
def _distance(a: list[float], b: list[float]) -> float:
left = _sanitize_model_features(a)
right = _sanitize_model_features(b)
return math.sqrt(sum((x - y) ** 2 for x, y in zip(left, right)))
def _plan_level_counts(library_size: int, levels: list[int], budget_runs: int, promotion_fraction: float) -> list[int]:
if not 0.0 < promotion_fraction <= 1.0:
raise RDockPipelineError(f"promotion_fraction must be in (0, 1], got {promotion_fraction}")
if library_size <= 0:
return [0 for _ in levels]
best_counts = [0 for _ in levels]
for final_count in range(1, library_size + 1):
counts = [0 for _ in levels]
counts[-1] = final_count
for idx in range(len(levels) - 2, -1, -1):
counts[idx] = min(library_size, max(counts[idx + 1], int(math.ceil(counts[idx + 1] / promotion_fraction))))
cost = sum(count * level for count, level in zip(counts, levels))
if cost <= budget_runs:
best_counts = counts
else:
break
if not any(best_counts):
base = min(library_size, max(1, budget_runs // levels[0]))
best_counts[0] = base
for idx in range(1, len(levels)):
best_counts[idx] = 0
return best_counts
def _select_diverse(rows: list[dict[str, Any]], target_count: int, min_per_cluster: int, max_per_cluster: int) -> list[dict[str, Any]]:
if target_count <= 0 or not rows:
return []
def _cluster_key(row: dict[str, Any]) -> str:
for key in ("cluster_id", "scaffold_id", "canonical_smiles", "smiles", "ligand_id"):
value = row.get(key)
if value not in (None, ""):
return str(value)
return "__missing_cluster__"
cluster_counts: dict[str, int] = {}
selected: list[dict[str, Any]] = []
cluster_buckets: dict[str, list[dict[str, Any]]] = {}
for row in rows:
cluster_buckets.setdefault(_cluster_key(row), []).append(row)
for cluster_id in sorted(cluster_buckets):
bucket = cluster_buckets[cluster_id]
take = min(len(bucket), min_per_cluster, max_per_cluster, target_count - len(selected))
selected.extend(bucket[:take])
cluster_counts[cluster_id] = take
if len(selected) >= target_count:
return selected[:target_count]
for row in rows:
cluster_id = _cluster_key(row)
current = cluster_counts.get(cluster_id, 0)
if current >= max_per_cluster:
continue
if any(str(existing["ligand_id"]) == str(row["ligand_id"]) for existing in selected):
continue
selected.append(row)
cluster_counts[cluster_id] = current + 1
if len(selected) >= target_count:
break
return selected[:target_count]
def _sample_reference_rows(
rows: list[dict[str, Any]],
sample_size: int,
seed: int,
min_per_cluster: int,
max_per_cluster: int,
) -> list[dict[str, Any]]:
if sample_size <= 0 or sample_size >= len(rows):
return list(rows)
shuffled = list(rows)
random.Random(seed).shuffle(shuffled)
shuffled.sort(key=lambda row: (str(row.get("cluster_id", "")), str(row.get("ligand_id", ""))))
return _select_diverse(shuffled, sample_size, min_per_cluster, max_per_cluster)
def _top_ids_by_score(rows: list[dict[str, Any]], top_fraction: float, *keys: str) -> set[str]:
ranked = _sort_by_score(rows, *keys)
n_top = max(1, int(math.ceil(len(ranked) * top_fraction)))
return {str(row["ligand_id"]) for row in ranked[:n_top]}
def _evaluate_selection_against_reference(
reference_rows: list[dict[str, Any]],
selected_ids: set[str],
*,
top_fraction: float,
) -> dict[str, Any]:
total = len(reference_rows)
if total == 0:
return {
"survivor_count": len(selected_ids),
"reduction_fraction": 0.0,
"top1_recall": None,
"top5_recall": None,
"top10_recall": None,
"top1pct_recall": None,
"top5pct_recall": None,
"top10pct_recall": None,
"false_negative_rate": None,
"best_survivor_score": None,
"top10_survivor_mean_score": None,
}
full_top1 = {str(row["ligand_id"]) for row in reference_rows[:1]}
full_top5 = {str(row["ligand_id"]) for row in reference_rows[: min(5, total)]}
full_top10 = {str(row["ligand_id"]) for row in reference_rows[: min(10, total)]}
full_top1pct = _top_ids_by_score(reference_rows, 0.01, "SCORE", "best_score", "final_score")
full_top5pct = _top_ids_by_score(reference_rows, 0.05, "SCORE", "best_score", "final_score")
full_top10pct = _top_ids_by_score(reference_rows, 0.10, "SCORE", "best_score", "final_score")
survivor_rows = [row for row in reference_rows if str(row["ligand_id"]) in selected_ids]
top10_survivors = survivor_rows[: min(10, len(survivor_rows))]
top10_scores = [_float(row.get("SCORE", row.get("best_score", row.get("final_score"))), None) for row in top10_survivors]
top10_scores = [value for value in top10_scores if value is not None]
return {
"survivor_count": len(selected_ids),
"reduction_fraction": 1.0 - (len(selected_ids) / max(1, total)),
"top1_recall": len(full_top1 & selected_ids) / max(1, len(full_top1)),
"top5_recall": len(full_top5 & selected_ids) / max(1, len(full_top5)),
"top10_recall": len(full_top10 & selected_ids) / max(1, len(full_top10)),
"top1pct_recall": len(full_top1pct & selected_ids) / max(1, len(full_top1pct)),
"top5pct_recall": len(full_top5pct & selected_ids) / max(1, len(full_top5pct)),
"top10pct_recall": len(full_top10pct & selected_ids) / max(1, len(full_top10pct)),
"false_negative_rate": 1.0 - (len(full_top5pct & selected_ids) / max(1, len(full_top5pct))),
"best_survivor_score": _float(survivor_rows[0].get("SCORE", survivor_rows[0].get("best_score", survivor_rows[0].get("final_score"))), None) if survivor_rows else None,
"top10_survivor_mean_score": _mean(top10_scores) if top10_scores else None,
"best_full_ligand_survived": str(reference_rows[0]["ligand_id"]) in selected_ids,
}
def _requested_survivor_count(
total_rows: int,
retain_fraction: float,
min_survivors: int,
max_survivors: int,
) -> int:
requested = max(min_survivors, int(math.ceil(total_rows * retain_fraction)))
if max_survivors > 0:
requested = min(requested, max_survivors)
return min(total_rows, max(1, requested))
def _stable_json_hash(payload: dict[str, Any]) -> str:
import hashlib
return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
@dataclass
class MultiFidelityConfig:
strategy: str
fidelity_levels: list[int]
cost_budget_runs: int
adaptive_budget_ligands: int | None
promotion_fraction: float
min_per_cluster: int
max_per_cluster: int
outlier_intra_z_threshold: float
score_component_filter: str
final_fidelity_only_hits: bool
checkpoint_every: int
jobs: int | str
cpu_fraction: float
resume: bool
reference_mode: str
evaluation_pool_mode: str
balanced_baselines: bool
reference_sample_size: int
reference_sample_seed: int
posthoc_score_selected_hits: bool
posthoc_final_runs: int
force_resume_stale: bool
outlier_policy: str
intra_z_threshold: float
score_z_threshold: float
max_intra_fraction: float
max_intra_fraction_soft: float
max_intra_fraction_hard: float
exploration_fraction: float
diversity_weight: float
uncertainty_weight: float
outlier_risk_weight: float
cluster_min_coverage: int
use_reference_features: bool
production_reference_free_mode: bool
calibration_size: int
calibration_fraction: float
min_clusters_covered: int
calibration_random_fraction: float
calibration_diversity_weight: float
fidelity_validation_size: int
fidelity_validation_policy: str
promotion_policy: str
min_final_ligands: int
min_promotion_per_level: int
promotion_fraction_by_level: str
triage_retain_fraction: float
triage_target_recall: float
triage_min_survivors: int
triage_max_survivors: int
cluster_min_survivors: int
cluster_max_survivors: int
rescue_fraction: float
rare_cluster_rescue: int
uncertainty_rescue: int
allow_low_confidence_triage: bool
top_good_fraction: float
minimum_training_ligands: int
triage_controller: str
max_retain_fraction_before_not_useful: float
classifier_top_percentile: float
triage_model: str = "classifier"
classifier_threshold_mode: str = "recall_target"
classifier_min_positives: int = 10
classifier_holdout_fraction: float = 0.25
classifier_fallback: str = "cluster_only"
model_fallback_if_worse: str = "none"
survivor_combination_policy: str = "model_only"
adaptive_policy: str = "hybrid_rank"
regressor_contribution_mode: str = "linear"
classifier_weight: float = 1.0
regressor_weight: float = 0.35
cluster_quality_weight: float = 0.5
fixed_score_regressor_name: str = "fixed_score_regressor_v1"
fixed_score_regressor_target: str = "component_sane_affinity_like"
regressor_model_type: str = "extra_trees"
model_validation_split: str = "cluster"
cluster_quota: int = 0
promotion_temperature: float = 1.0
final_survivor_enumerate_variants: bool = False
variant_stage: str = "none"
enumerate_stereoisomers: str = "none"
max_stereoisomers_per_parent: int = 2
enumerate_tautomers: str = "none"
max_tautomers_per_parent: int = 1
enumerate_protonation: str = "none"
ph: float = 7.4
max_protomer_states_per_parent: int = 1
max_conformers_per_variant: int = 1
max_total_variants_per_parent: int = 1
posthoc_top_parents: int = 100
posthoc_max_total_variants_per_parent: int = 20
variant_fairness_policy: str = "cap"
allow_no_rdkit_parent_only: bool = False
diagnostics_level: str = "standard"
classifier_gate_fraction: float = 0.15
classifier_max_gate_fraction: float = 0.2
class MultiFidelityAdaptiveRunner:
def __init__(
self,
dataset_dir: str | Path,
out_dir: str | Path,
engine: RDockEngine,
config: MultiFidelityConfig,
) -> None:
self.dataset_dir = Path(dataset_dir)
self.out_dir = Path(out_dir)
self.engine = engine
self.config = config
self._prepare_runtime_dirs()
self._emit_progress("repair_dataset:start", {"dataset_dir": str(self.dataset_dir)})
self.dataset_repair = repair_dataset_dir(self.dataset_dir)
self._emit_progress("repair_dataset:done", self.dataset_repair)
self.dataset_validation = validate_dataset_dir(self.dataset_dir, check_rdock_tools=False)
self.manifest = self.dataset_validation["manifest"]
self.manifest.setdefault("pocket_definition_mode", "dataset_manifest")
self.manifest.setdefault("has_reference_ligand", bool(self.dataset_validation.get("reference_records", 0)))
self.manifest.setdefault("reference_features_enabled", bool(self.config.use_reference_features))
self.manifest.setdefault("production_reference_free_mode", bool(self.config.production_reference_free_mode))
self.synthetic_dataset = bool(self.manifest.get("synthetic_expansion") or self.manifest.get("synthetic_stress_test_only"))
self.target_config = load_target_config(self.dataset_dir / "target" / "rdock_prm" / "target_config.yaml")
self.ligands_sdf = require_file(self.dataset_dir / "ligands" / "all_ligands.sdf", "dataset ligand library")
metadata_path = self.dataset_dir / "ligands" / "ligand_metadata.csv"
if metadata_path.exists():
metadata_rows = read_ligand_metadata(metadata_path)
else:
metadata_rows = [{"ligand_id": ligand_id, "smiles": ""} for ligand_id in self._load_block_map()]
self.block_map = self._load_block_map()
raw_model_rows = _build_model_rows(metadata_rows)
self.model_rows, self.missing_prepared_model_rows = self._filter_prepared_model_rows(raw_model_rows)
self.model_by_id = {str(row["ligand_id"]): row for row in self.model_rows}
self.dataset_ligand_ids = [str(row["ligand_id"]) for row in self.model_rows]
self.reference_rows = self._build_reference_rows()
self.reference_ids = [str(row["ligand_id"]) for row in self.reference_rows]
self.reference_id_set = set(self.reference_ids)
self.candidate_rows = self._build_candidate_rows()
self.candidate_ids = [str(row["ligand_id"]) for row in self.candidate_rows]
self.candidate_id_set = set(self.candidate_ids)
self.final_level = self.config.fidelity_levels[-1]
self.trace_rows: list[dict[str, Any]] = []
self.promotion_rows: list[dict[str, Any]] = []
self.failed_chunk_rows: list[dict[str, Any]] = []
self.failed_ligand_rows: list[dict[str, Any]] = []
self.rdock_records_without_score_dropped = 0
self.state_by_id: dict[str, dict[str, Any]] = {}
self.training_time_total = 0.0
self.docking_time_total = 0.0
self.overhead_time_total = 0.0
self.parsing_time_total = 0.0
self.sdf_split_merge_time_total = 0.0
self.scheduler_time_total = 0.0
self.io_time_total = 0.0
self.reference_completion_fraction = 0.0
self.benchmark_status = "BENCHMARK COMPLETE"
self.reference_label = "full"
self.reference_free_mode = self.config.strategy in MODEL_STRATEGIES or self.config.production_reference_free_mode
self.trace_step_counter = 0
self.pre_docking_prediction_rows: list[dict[str, Any]] = []
self.acquisition_component_rows: list[dict[str, Any]] = []
self.cluster_quota_rows: list[dict[str, Any]] = []
self.exploration_split_rows: list[dict[str, Any]] = []
self.current_effective_uncertainty_weight = float(self.config.uncertainty_weight)
self.current_uncertainty_used_for_acquisition = True
self.current_uncertainty_disabled_reason = ""
self.current_regressor_used_for_ranking = self.config.regressor_contribution_mode != "none"
self.current_regressor_disabled_reason = ""
self.current_effective_regressor_weight = float(self.config.regressor_weight)
self.current_classifier_gate_warning = ""
self.run_started_at = time.time()
self._validate_runtime_dependencies()
self.signature = self._build_run_signature()
self._check_resume_signature()
self._write_json_artifact(self.out_dir / "checkpoints" / "run_signature.json", self.signature)
self._write_reference_artifacts()
self._init_state()
def _prepare_runtime_dirs(self) -> None:
for name in ("checkpoints", "metrics", "tables", "plots", "rdock", "poses", "target", "ligands"):
(self.out_dir / name).mkdir(parents=True, exist_ok=True)
def _diagnostics_rows(
self,
rows: list[dict[str, Any]],
*,
survivors: list[dict[str, Any]] | None = None,
final_hits: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
level = str(getattr(self.config, "diagnostics_level", "standard") or "standard").lower()
if level == "full":
return list(rows)
survivor_ids = {str(row.get("ligand_id", "")) for row in (survivors or []) if str(row.get("ligand_id", ""))}
final_ids = {str(row.get("ligand_id", "")) for row in (final_hits or []) if str(row.get("ligand_id", ""))}
keep_ids = survivor_ids | final_ids
if level == "minimal":
if keep_ids:
return [row for row in rows if str(row.get("ligand_id", "")) in keep_ids]
return rows[: min(10, len(rows))]
if keep_ids:
return [row for row in rows if str(row.get("ligand_id", "")) in keep_ids]
return rows[: min(250, len(rows))]
def _validate_runtime_dependencies(self) -> None:
if _strategy_requires_rdkit(self.config.strategy) and not RDKit_AVAILABLE:
raise RDockPipelineError("RDKit_REQUIRED_FOR_REFERENCE_FREE_MODEL")
if _variants_require_rdkit(self.config.final_survivor_enumerate_variants, self.config.variant_stage):
if not RDKit_AVAILABLE and not self.config.allow_no_rdkit_parent_only:
raise RDockPipelineError("RDKit_REQUIRED_FOR_VARIANT_ENUMERATION")
if not RDKit_AVAILABLE and self.config.allow_no_rdkit_parent_only:
warning = {
"warning": "RDKit unavailable; variant expansion downgraded to parent-only passthrough because --allow-no-rdkit-parent-only was set.",
"variant_stage": self.config.variant_stage,
}
_write_json(self.out_dir / "metrics" / "variant_rdkit_warning.json", warning)
def _write_json_artifact(self, path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
def _build_reference_rows(self) -> list[dict[str, Any]]:
mode = str(self.config.reference_mode).lower()
if mode == "none":
self.reference_label = "none"
return []
if mode == "sampled":
self.reference_label = "sampled_reference"
return _sample_reference_rows(
self.model_rows,
self.config.reference_sample_size,
self.config.reference_sample_seed,
self.config.min_per_cluster,
self.config.max_per_cluster,
)
self.reference_label = "full"
return list(self.model_rows)
def _build_candidate_rows(self) -> list[dict[str, Any]]:
if str(self.config.evaluation_pool_mode).lower() == "same_pool" and self.reference_rows:
return list(self.reference_rows)
return list(self.model_rows)
def _write_reference_artifacts(self) -> None:
if not self.reference_ids:
return
if self.reference_label == "sampled_reference":
sample_path = self.out_dir / "tables" / "reference_sample_ligand_ids.txt"
sample_path.write_text("\n".join(self.reference_ids) + "\n", encoding="utf-8")
def _build_run_signature(self) -> dict[str, Any]:
manifest_path = require_file(self.dataset_dir / "dataset_manifest.json", "dataset manifest")
target_config_path = require_file(self.dataset_dir / "target" / "rdock_prm" / "target_config.yaml", "dataset target_config")
return {
"run_id": self.out_dir.name,
"dataset_manifest_hash": sha256_file(manifest_path),
"ligand_file_hash": sha256_file(self.ligands_sdf),
"target_config_hash": sha256_file(target_config_path),
"strategy": self.config.strategy,
"reference_mode": self.config.reference_mode,
"evaluation_pool_mode": self.config.evaluation_pool_mode,
"reference_sample_seed": self.config.reference_sample_seed,
"reference_sample_size": self.config.reference_sample_size,
"fidelity_levels": self.config.fidelity_levels,
"cost_budget_runs": self.config.cost_budget_runs,
"final_fidelity_runs": self.final_level,
"rdock_version": probe_version(require_executable("rbdock")),
"command_args": {
"balanced_baselines": self.config.balanced_baselines,
"outlier_policy": self.config.outlier_policy,
"intra_z_threshold": self.config.intra_z_threshold,
"score_z_threshold": self.config.score_z_threshold,
"max_intra_fraction": self.config.max_intra_fraction,
"exploration_fraction": self.config.exploration_fraction,
"diversity_weight": self.config.diversity_weight,
"uncertainty_weight": self.config.uncertainty_weight,
"outlier_risk_weight": self.config.outlier_risk_weight,
"cluster_min_coverage": self.config.cluster_min_coverage,
"triage_retain_fraction": self.config.triage_retain_fraction,
"triage_target_recall": self.config.triage_target_recall,
"calibration_size": self.config.calibration_size,
"fidelity_validation_size": self.config.fidelity_validation_size,
"promotion_policy": self.config.promotion_policy,
"min_final_ligands": self.config.min_final_ligands,
"use_reference_features": self.config.use_reference_features,
"production_reference_free_mode": self.config.production_reference_free_mode,
},
}
def _check_resume_signature(self) -> None:
signature_path = self.out_dir / "checkpoints" / "run_signature.json"
if not self.config.resume or not signature_path.exists():
return
existing = _load_json(signature_path)
if existing == self.signature:
return
mismatch = {
"existing": existing,
"current": self.signature,
}
self._write_json_artifact(self.out_dir / "checkpoints" / "stale_signature.json", mismatch)
if not self.config.force_resume_stale:
raise RDockPipelineError(
f"Resume checkpoint signature mismatch for {self.out_dir}. "
f"Refusing to reuse stale cache without --force-resume-stale."
)
def _emit_progress(self, message: str, payload: dict[str, Any] | None = None) -> None:
line = f"[benchmark-adaptive] {message}"
print(line, flush=True)
progress_log = self.out_dir / "checkpoints" / "progress.log"
progress_log.parent.mkdir(parents=True, exist_ok=True)
with progress_log.open("a", encoding="utf-8") as handle:
handle.write(line + "\n")
if payload is not None:
_write_json(self.out_dir / "checkpoints" / "status.json", {"message": message, **payload})
def _load_block_map(self) -> dict[str, str]:
return _load_input_block_map(Path(self.ligands_sdf))
def _filter_prepared_model_rows(self, rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
prepared_ids = set(self.block_map)
kept: list[dict[str, Any]] = []
missing: list[dict[str, Any]] = []
for row in rows:
ligand_id = str(row["ligand_id"])
if ligand_id in prepared_ids:
kept.append(row)
else:
missing.append(
{
"ligand_id": ligand_id,
"cluster_id": str(row.get("cluster_id", "")),
"scaffold_id": str(row.get("scaffold_id", "")),
"smiles": str(row.get("smiles", "")),
"reason": "missing_from_prepared_sdf",
}
)
write_rows_csv(missing, self.out_dir / "tables" / "missing_prepared_ligands.csv")
_write_json(
self.out_dir / "metrics" / "prepared_sdf_consistency.json",
{
"metadata_rows": len(rows),
"prepared_sdf_rows": len(prepared_ids),
"usable_model_rows": len(kept),
"missing_prepared_ligands": len(missing),
},
)
if not kept:
raise RDockPipelineError("Prepared SDF contains no usable ligand IDs after metadata alignment")
return kept, missing
def _init_state(self) -> None:
for row in self.candidate_rows:
ligand_id = str(row["ligand_id"])
self.state_by_id[ligand_id] = {
"ligand_id": ligand_id,
"cluster_id": str(row["cluster_id"]),
"model_score": float(row["model_score"]),
"surrogate_score": float(row["model_score"]),
"selected_fidelity_runs": 0,
"current_best_score": "",
"current_best_score_level": "",
"final_score": "",
"is_final_fidelity": False,
"n_rdock_runs_total_spent": 0,
"promoted_from_level": "",
"promoted_to_level": "",
"promotion_reason": "",
"batch_id": "",
"rdock_success": False,
"failed_reason": "",
"timing_docking_seconds": 0.0,
"timing_training_seconds": 0.0,
"intra_outlier": False,
"score_outlier": False,
"component_warning": "",
"pre_docking_predicted_score": "",
"pre_docking_predicted_uncertainty": "",
"predicted_filtered_score": 0.0,
"predicted_uncertainty": 0.0,
"outlier_risk": 0.0,
"diversity_bonus": 0.0,
"p_good": 0.0,
"cluster_quality": 0.0,
"triage_score": 0.0,
"acquisition_classifier_component": 0.0,
"acquisition_score_component": 0.0,
"acquisition_uncertainty_component": 0.0,
"acquisition_diversity_component": 0.0,
"acquisition_cluster_component": 0.0,
"acquisition_outlier_component": 0.0,
"score_observation_count": 0,
"score_sum": 0.0,
"score_sq_sum": 0.0,
"score_mean_observed": 0.0,
"score_std_observed": 0.0,
"best_inter_seen": 0.0,
"best_intra_seen": 0.0,
"best_intra_fraction_seen": 0.0,
"failed_observation_count": 0,
"failed_observation_fraction": 0.0,
"pose_count_seen": 0,
}
def _write_checkpoint(self, name: str, payload: dict[str, Any]) -> None:
checkpoint_dir = self.out_dir / "checkpoints"
checkpoint_dir.mkdir(parents=True, exist_ok=True)
_write_json(checkpoint_dir / f"{name}.json", payload)
def _prepare_output_layout(self) -> None:
self._prepare_runtime_dirs()
target_dir = self.out_dir / "target"
shutil.copy2(require_file(self.dataset_dir / "target" / "target.mol2", "dataset target.mol2"), target_dir / "target.mol2")
reference_ligand = self.dataset_dir / "target" / "reference_ligand.sdf"
if reference_ligand.exists():
shutil.copy2(reference_ligand, target_dir / "reference_ligand.sdf")
prm_dir = target_dir / "rdock_prm"
prm_dir.mkdir(parents=True, exist_ok=True)
for path in (self.dataset_dir / "target" / "rdock_prm").iterdir():
if path.is_file():
shutil.copy2(path, prm_dir / path.name)
shutil.copy2(self.ligands_sdf, self.out_dir / "ligands" / "all_ligands.sdf")
def _materialize_reference_sdf(self, ligand_ids: list[str], out_path: Path) -> Path:
if not ligand_ids:
raise RDockPipelineError("Reference/evaluation pool is empty")
return _write_selected_sdf(self.block_map, ligand_ids, out_path)
def _complete_docking_rows(
self,
selected_ids: list[str],
observed_rows: list[dict[str, Any]],
n_runs_requested: int,
source_label: str,
) -> list[dict[str, Any]]:
observed_map = {str(row["ligand_id"]): dict(row) for row in observed_rows}
completed: list[dict[str, Any]] = []
for ligand_id in selected_ids:
row = observed_map.get(ligand_id)
if row is None:
row = {
"ligand_id": ligand_id,
"attempted": True,
"rdock_success": False,
"failed_reason": "missing_best_pose",
"best_score": "",
"SCORE": "",
"n_poses": 0,
"n_runs_requested": n_runs_requested,
"n_runs_completed": 0,
"source_chunk": source_label,
"score_outlier": False,
"intra_outlier": False,
}
else:
score = row.get("final_score", row.get("SCORE", ""))
row["attempted"] = True
row["rdock_success"] = _bool_text(str(row.get("rdock_success", True)).lower() in {"true", "1"})
row["failed_reason"] = row.get("failed_reason", "")
row["best_score"] = score
row["n_runs_requested"] = n_runs_requested
row["n_runs_completed"] = n_runs_requested if str(row.get("rdock_success", "")).lower() in {"true", "1"} else 0
row["source_chunk"] = row.get("source_chunk", source_label)
row.setdefault("n_poses", 1 if str(row.get("rdock_success", "")).lower() in {"true", "1"} else 0)
completed.append(row)
return completed
def _run_full_docking(self) -> tuple[list[dict[str, Any]], dict[str, Any]]:
if not self.reference_ids:
return [], {
"reference_mode": self.config.reference_mode,
"reference_completion_fraction": 0.0,
"reference_ligand_count": 0,
"full_docking_seconds": 0.0,
"n_runs": self.final_level,
"benchmark_status": "BENCHMARK PARTIAL / NOT COMPARABLE",
}
full_dir = self.out_dir / "full_docking"
full_dir.mkdir(parents=True, exist_ok=True)
self._emit_progress("full_docking:start", {"run_dir": str(full_dir), "n_runs": self.final_level, "jobs": self.config.jobs})
reference_sdf = self.out_dir / "ligands" / f"{self.reference_label}.sdf"
self._materialize_reference_sdf(self.reference_ids, reference_sdf)
start = time.time()
artifacts = self.engine.dock_sdf(
self.target_config,
reference_sdf,
full_dir,
n_runs=self.final_level,
jobs=self.config.jobs,
run_id=f"{self.out_dir.name}_full",
resume=self.config.resume,
)
elapsed = time.time() - start
observed_rows = [dict(row) for row in _read_rows(artifacts.best_per_ligand_csv)]
complete_rows = self._complete_docking_rows(self.reference_ids, observed_rows, self.final_level, "reference")
success_rows = [row for row in complete_rows if str(row.get("rdock_success", "")).lower() in {"true", "1"} and _float(row.get("best_score"), None) is not None]
for row in success_rows:
row["SCORE"] = row.get("best_score", row.get("SCORE", ""))
rows = _augment_full_rows(success_rows)
full_rank_map = {str(row["ligand_id"]): row for row in rows}
full_table_rows: list[dict[str, Any]] = []
for row in complete_rows:
item = dict(row)
item.update({k: v for k, v in full_rank_map.get(str(row["ligand_id"]), {}).items() if k not in item or item[k] in {"", None}})
full_table_rows.append(item)
self.reference_completion_fraction = len(full_table_rows) / max(1, len(self.reference_ids))
if self.config.reference_mode == "full" and self.reference_completion_fraction < 0.99:
self.benchmark_status = "BENCHMARK PARTIAL / NOT COMPARABLE"
elif self.config.reference_mode == "sampled":
self.benchmark_status = "BENCHMARK SAMPLED REFERENCE"
write_rows_csv(full_table_rows, self.out_dir / "tables" / "full_docking_scores.csv")
write_rows_csv(full_table_rows, self.out_dir / "tables" / "reference_scores.csv")
metrics = {
"library_size": len(self.reference_ids),
"successful_ligands": len(rows),
"failed_ligands": max(0, len(self.reference_ids) - len(rows)),
"pose_count": _count_sdf(Path(artifacts.all_poses_sdf)),
"best_SCORE": _float(rows[0]["SCORE"]) if rows else None,
"full_docking_seconds": elapsed,
"n_runs": self.final_level,
"best_ligand_id": rows[0]["ligand_id"] if rows else None,
"reference_mode": self.config.reference_mode,
"reference_completion_fraction": self.reference_completion_fraction,
"reference_ligand_count": len(self.reference_ids),
"benchmark_status": self.benchmark_status,
}
_write_json(self.out_dir / "metrics" / "rdock_metrics.json", metrics)
self._write_checkpoint("full_docking", metrics)
self._emit_progress("full_docking:done", metrics)
return rows, metrics
def _run_single_fidelity_adaptive(self, count: int) -> tuple[list[dict[str, Any]], float]:
if count <= 0:
return [], 0.0
ordered = sorted(
self.candidate_rows,
key=lambda row: (-float(row["model_score"]), str(row["cluster_id"]), str(row["ligand_id"])),
)
selected = _select_diverse(ordered, count, self.config.min_per_cluster, self.config.max_per_cluster)
selected_ids = [str(row["ligand_id"]) for row in selected]
run_dir = self.out_dir / "single_fidelity_adaptive"
run_dir.mkdir(parents=True, exist_ok=True)
sdf_path = self.out_dir / "ligands" / "single_fidelity_adaptive.sdf"
_write_selected_sdf(self.block_map, selected_ids, sdf_path)
self._emit_progress("single_fidelity:start", {"count": len(selected_ids), "run_dir": str(run_dir)})
start = time.time()
self.engine.dock_sdf(
self.target_config,
sdf_path,
run_dir,
n_runs=self.final_level,
jobs=self.config.jobs,
run_id=f"{self.out_dir.name}_single",
resume=self.config.resume,
)
elapsed = time.time() - start
observed = [dict(row) for row in _read_rows(run_dir / "tables" / "best_per_ligand.csv")]
rows = self._complete_docking_rows(selected_ids, observed, self.final_level, "single_fidelity")
for row in rows:
row["is_final_fidelity"] = str(row.get("rdock_success", "")).lower() in {"true", "1"}
row["final_score"] = row.get("best_score", row.get("SCORE", ""))
write_rows_csv(rows, self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv")
self._write_checkpoint("single_fidelity", {"count": len(rows), "seconds": elapsed})
self._emit_progress("single_fidelity:done", {"count": len(rows), "seconds": elapsed})
return rows, elapsed
def _run_random_baseline(self, cost_budget_runs: int, diverse: bool = False) -> tuple[list[dict[str, Any]], float]:
count = max(1, cost_budget_runs // self.final_level)
population_rows = list(self.candidate_rows)
rng = random.Random(42 if not diverse else 43)
if diverse:
rng.shuffle(population_rows)
selected_rows = _select_diverse(population_rows, min(len(population_rows), count), self.config.min_per_cluster, self.config.max_per_cluster)
selected_ids = [str(row["ligand_id"]) for row in selected_rows]
else:
population = [str(row["ligand_id"]) for row in population_rows]
selected_ids = rng.sample(population, min(len(population), count))
run_dir = self.out_dir / "random_baseline"
if diverse:
run_dir = self.out_dir / "diverse_random_baseline"
run_dir.mkdir(parents=True, exist_ok=True)
sdf_path = self.out_dir / "ligands" / ("diverse_random_baseline.sdf" if diverse else "random_baseline.sdf")
_write_selected_sdf(self.block_map, selected_ids, sdf_path)
phase = "diverse_random_baseline" if diverse else "random_baseline"
self._emit_progress(f"{phase}:start", {"count": len(selected_ids), "run_dir": str(run_dir)})
start = time.time()
self.engine.dock_sdf(
self.target_config,
sdf_path,
run_dir,
n_runs=self.final_level,
jobs=self.config.jobs,
run_id=f"{self.out_dir.name}_{'diverse_random' if diverse else 'random'}",
resume=self.config.resume,
)
elapsed = time.time() - start
observed = [dict(row) for row in _read_rows(run_dir / "tables" / "best_per_ligand.csv")]
rows = self._complete_docking_rows(selected_ids, observed, self.final_level, phase)
for row in rows:
row["is_final_fidelity"] = str(row.get("rdock_success", "")).lower() in {"true", "1"}
row["final_score"] = row.get("best_score", row.get("SCORE", ""))
row["n_rdock_runs_total_spent"] = self.final_level
write_rows_csv(rows, self.out_dir / "tables" / ("diverse_random_baseline_scores.csv" if diverse else "random_baseline_scores.csv"))
self._write_checkpoint(phase, {"count": len(rows), "seconds": elapsed})
self._emit_progress(f"{phase}:done", {"count": len(rows), "seconds": elapsed})
return rows, elapsed
def _penalize_rows(self, rows: list[dict[str, Any]], level: int) -> list[dict[str, Any]]:
score_values = [_float(row.get("SCORE"), float("nan")) for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}]
intra_values = [_float(row.get("SCORE.INTRA"), float("nan")) for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}]
score_mean = _mean(score_values)
intra_mean = _mean(intra_values)
score_sd = _stdev(score_values, score_mean)
intra_sd = _stdev(intra_values, intra_mean)
output: list[dict[str, Any]] = []
for row in rows:
item = dict(row)
score = _float(item.get("SCORE"), float("inf"))
intra = _float(item.get("SCORE.INTRA"), 0.0)
score_z = (score - score_mean) / score_sd if math.isfinite(score) else 0.0
intra_z = (intra - intra_mean) / intra_sd if math.isfinite(intra) else 0.0
intra_fraction = abs(intra) / max(abs(score), 1e-6) if math.isfinite(intra) and math.isfinite(score) else 0.0
dominant_intra_soft = intra_fraction >= self.config.max_intra_fraction_soft
dominant_intra_hard = intra_fraction >= self.config.max_intra_fraction_hard
intra_outlier = intra_z < (-abs(self.config.intra_z_threshold)) or dominant_intra_soft
score_outlier = score_z < -abs(self.config.score_z_threshold)
penalty = 0.0
warnings: list[str] = []
severe_pattern = (score_outlier and intra_outlier) or dominant_intra_hard
if intra_outlier:
penalty += min(12.0, abs(intra_z) * 1.25 if math.isfinite(intra_z) else 6.0)
warnings.append("intra_outlier")
if score_outlier:
penalty += 3.0
warnings.append("score_outlier")
if dominant_intra_soft:
warnings.append("intra_dominance")
penalty += 2.0 if not dominant_intra_hard else 6.0
item["intra_outlier"] = intra_outlier
item["score_outlier"] = score_outlier
item["score_z"] = score_z
item["intra_z"] = intra_z
item["intra_fraction"] = intra_fraction
item["component_warning"] = ",".join(warnings)
if severe_pattern and len(warnings) >= 2:
penalty += 6.0
if self.config.outlier_policy == "exclude" and severe_pattern and len(warnings) >= 2:
item["ranking_score"] = float("inf")
elif self.config.outlier_policy == "flag":
item["ranking_score"] = score
else:
item["ranking_score"] = score + penalty
item["selected_fidelity_runs"] = level
output.append(item)
return output
def _promotion_priority(self, row: dict[str, Any]) -> float:
classifier_probability = _float(row.get("p_good"), 0.0)
predicted_score = _float(row.get("predicted_filtered_score"), _float(row.get("ranking_score"), float("inf")))
uncertainty = _float(row.get("predicted_uncertainty"), 0.0)
outlier_risk = _float(row.get("outlier_risk"), 0.0)
diversity_bonus = _float(row.get("diversity_bonus"), 0.0)
cluster_quality = _float(row.get("cluster_quality"), 0.0)
acquisition = -(self.config.classifier_weight * classifier_probability)
if self.current_regressor_used_for_ranking:
acquisition += self.config.regressor_weight * predicted_score
acquisition -= self.current_effective_uncertainty_weight * uncertainty
acquisition -= self.config.diversity_weight * diversity_bonus
acquisition -= self.config.cluster_quality_weight * cluster_quality
acquisition += self.config.outlier_risk_weight * outlier_risk
return acquisition
def _update_surrogate(self, observed_rows: list[dict[str, Any]]) -> float:
start = time.time()
observed = []
for row in observed_rows:
ligand_id = str(row["ligand_id"])
target_score = _float(row.get("ranking_score"), float("inf"))
outlier_flag = 1.0 if str(row.get("component_warning", "")).strip() else 0.0
observed.append((ligand_id, target_score, outlier_flag))
if not observed:
return 0.0
observed_ids = [ligand_id for ligand_id, _, _ in observed]
if SurrogateModel is not None and SurrogateConfig is not None and len(observed) >= 8:
feature_names = [f"f{i}" for i in range(len(self.model_rows[0]["feature_vector"]))]
train_features = []
train_masks = []
train_targets = []
for ligand_id, target_score, _ in observed:
feat = [float(x) for x in self.model_by_id[ligand_id]["feature_vector"]]
train_features.append(feat)
train_masks.append([1.0 for _ in feat])
train_targets.append(float(target_score))
surrogate = SurrogateModel(SurrogateConfig(prefer_xgboost=False, random_state=42, n_estimators=120))
surrogate.fit(
features=__import__("numpy").asarray(train_features, dtype=float),
masks=__import__("numpy").asarray(train_masks, dtype=float),
y=__import__("numpy").asarray(train_targets, dtype=float),
feature_names=feature_names,
mask_names=[f"m{i}" for i in range(len(feature_names))],
)
all_features = []
all_masks = []
for row in self.candidate_rows:
feat = [float(x) for x in row["feature_vector"]]
all_features.append(feat)
all_masks.append([1.0 for _ in feat])
bundle = surrogate.predict_bundle(
features=__import__("numpy").asarray(all_features, dtype=float),
masks=__import__("numpy").asarray(all_masks, dtype=float),
)
for row, pred, unc in zip(self.candidate_rows, bundle["expected_score"], bundle["uncertainty"]):
row["predicted_filtered_score"] = float(pred)
row["predicted_uncertainty"] = float(unc)
if str(row["ligand_id"]) in observed_ids:
matching = next(item for item in observed if item[0] == str(row["ligand_id"]))
row["predicted_filtered_score"] = float(matching[1])
row["predicted_uncertainty"] = 0.0
observed_outlier_rate = sum(outlier for _, _, outlier in observed) / max(1, len(observed))
for row in self.candidate_rows:
row["outlier_risk"] = observed_outlier_rate if str(row["ligand_id"]) not in observed_ids else next(item[2] for item in observed if item[0] == str(row["ligand_id"]))
else:
for row in self.candidate_rows:
ligand_id = str(row["ligand_id"])
if ligand_id in observed_ids:
target = next(item[1] for item in observed if item[0] == ligand_id)
row["predicted_filtered_score"] = float(target)
row["predicted_uncertainty"] = 0.0
row["outlier_risk"] = next(item[2] for item in observed if item[0] == ligand_id)
continue
neighbors: list[tuple[float, float, float]] = []
for observed_id, ranking_score, outlier_flag in observed:
ref = self.model_by_id[observed_id]
dist = _distance(row["feature_vector"], ref["feature_vector"])
neighbors.append((dist, ranking_score, outlier_flag))
neighbors.sort(key=lambda item: item[0])
top = neighbors[: min(16, len(neighbors))]
weights = [1.0 / (1.0 + dist) for dist, _, _ in top]
total_weight = sum(weights) or 1.0
predicted = sum(weight * score for weight, (_, score, _) in zip(weights, top)) / total_weight
row["predicted_filtered_score"] = float(predicted)
row["predicted_uncertainty"] = float(_stdev([score for _, score, _ in top], predicted))
row["outlier_risk"] = float(sum(weight * outlier for weight, (_, _, outlier) in zip(weights, top)) / total_weight)
cluster_counts: dict[str, int] = {}
for row in observed_rows:
cluster_counts[str(row.get("cluster_id", ""))] = cluster_counts.get(str(row.get("cluster_id", "")), 0) + 1
for row in self.candidate_rows:
cluster_id = str(row.get("cluster_id", ""))
coverage = cluster_counts.get(cluster_id, 0)
row["diversity_bonus"] = 1.0 / (1.0 + coverage)
state = self.state_by_id.get(str(row["ligand_id"]))
if state is not None:
state["surrogate_score"] = float(-_float(row.get("predicted_filtered_score"), 0.0))
state["predicted_uncertainty"] = float(_float(row.get("predicted_uncertainty"), 0.0))
state["outlier_risk"] = float(_float(row.get("outlier_risk"), 0.0))
for row in self.model_rows:
ligand_id = str(row["ligand_id"])
source = self.model_by_id.get(ligand_id, row)
row["surrogate_score"] = source.get("surrogate_score", row.get("surrogate_score", 0.0))
row["predicted_filtered_score"] = source.get("predicted_filtered_score", row.get("predicted_filtered_score", 0.0))
row["predicted_uncertainty"] = source.get("predicted_uncertainty", row.get("predicted_uncertainty", 0.0))
row["outlier_risk"] = source.get("outlier_risk", row.get("outlier_risk", 0.0))
row["diversity_bonus"] = source.get("diversity_bonus", row.get("diversity_bonus", 0.0))
return time.time() - start
def _record_level_rows(self, level: int, batch_id: int, rows: list[dict[str, Any]], level_seconds: float, training_seconds: float) -> None:
level_rows: list[dict[str, Any]] = []
for row in rows:
ligand_id = str(row["ligand_id"])
state = self.state_by_id[ligand_id]
raw_score = row.get("SCORE", "")
score_value = _float(raw_score, None)
current_best = state["current_best_score"]
if current_best == "" or _float(raw_score, float("inf")) < _float(current_best, float("inf")):
state["current_best_score"] = raw_score
state["current_best_score_level"] = level
state["selected_fidelity_runs"] = level
state["surrogate_score"] = self.model_by_id[ligand_id].get("surrogate_score", state["surrogate_score"])
state["predicted_filtered_score"] = self.model_by_id[ligand_id].get("predicted_filtered_score", state.get("predicted_filtered_score", 0.0))
state["n_rdock_runs_total_spent"] = int(state["n_rdock_runs_total_spent"]) + level
state["batch_id"] = batch_id
state["rdock_success"] = str(row.get("rdock_success", True)).lower() in {"true", "1"}
state["failed_reason"] = row.get("failed_reason", "")
state["timing_docking_seconds"] = _float(state["timing_docking_seconds"]) + level_seconds / max(1, len(rows))
state["timing_training_seconds"] = _float(state["timing_training_seconds"]) + training_seconds / max(1, len(rows))
state["intra_outlier"] = row.get("intra_outlier", False)
state["score_outlier"] = row.get("score_outlier", False)
state["component_warning"] = row.get("component_warning", "")
state["predicted_uncertainty"] = self.model_by_id[ligand_id].get("predicted_uncertainty", state.get("predicted_uncertainty", 0.0))
state["outlier_risk"] = self.model_by_id[ligand_id].get("outlier_risk", state.get("outlier_risk", 0.0))
state["diversity_bonus"] = self.model_by_id[ligand_id].get("diversity_bonus", state.get("diversity_bonus", 0.0))
state["p_good"] = self.model_by_id[ligand_id].get("p_good", state.get("p_good", 0.0))
state["cluster_quality"] = self.model_by_id[ligand_id].get("cluster_quality", state.get("cluster_quality", 0.0))
state["triage_score"] = self.model_by_id[ligand_id].get("triage_score", state.get("triage_score", 0.0))
state["acquisition_classifier_component"] = self.model_by_id[ligand_id].get("acquisition_classifier_component", state.get("acquisition_classifier_component", 0.0))
state["acquisition_score_component"] = self.model_by_id[ligand_id].get("acquisition_score_component", state.get("acquisition_score_component", 0.0))
state["acquisition_uncertainty_component"] = self.model_by_id[ligand_id].get("acquisition_uncertainty_component", state.get("acquisition_uncertainty_component", 0.0))
state["acquisition_diversity_component"] = self.model_by_id[ligand_id].get("acquisition_diversity_component", state.get("acquisition_diversity_component", 0.0))
state["acquisition_cluster_component"] = self.model_by_id[ligand_id].get("acquisition_cluster_component", state.get("acquisition_cluster_component", 0.0))
state["acquisition_outlier_component"] = self.model_by_id[ligand_id].get("acquisition_outlier_component", state.get("acquisition_outlier_component", 0.0))
if score_value is not None and math.isfinite(score_value):
state["score_observation_count"] = int(_float(state.get("score_observation_count"), 0.0) or 0) + 1
state["score_sum"] = _float(state.get("score_sum"), 0.0) + score_value
state["score_sq_sum"] = _float(state.get("score_sq_sum"), 0.0) + (score_value * score_value)
count = max(1, int(_float(state.get("score_observation_count"), 1.0) or 1))
mean_score = _float(state.get("score_sum"), 0.0) / count
variance = max(0.0, (_float(state.get("score_sq_sum"), 0.0) / count) - (mean_score * mean_score))
state["score_mean_observed"] = mean_score
state["score_std_observed"] = math.sqrt(variance)
inter_val = _float(row.get("SCORE.INTER"), 0.0)
intra_val = _float(row.get("SCORE.INTRA"), 0.0)
state["best_inter_seen"] = inter_val if count == 1 or inter_val < _float(state.get("best_inter_seen"), float("inf")) else state.get("best_inter_seen", 0.0)
state["best_intra_seen"] = intra_val if count == 1 or intra_val < _float(state.get("best_intra_seen"), float("inf")) else state.get("best_intra_seen", 0.0)
state["best_intra_fraction_seen"] = _float(row.get("intra_fraction"), state.get("best_intra_fraction_seen", 0.0))
if str(row.get("rdock_success", "")).lower() not in {"true", "1"}:
state["failed_observation_count"] = int(_float(state.get("failed_observation_count"), 0.0) or 0) + 1
total_obs = max(1, int(_float(state.get("score_observation_count"), 0.0) or 0) + int(_float(state.get("failed_observation_count"), 0.0) or 0))
state["failed_observation_fraction"] = int(_float(state.get("failed_observation_count"), 0.0) or 0) / total_obs
state["pose_count_seen"] = int(_float(state.get("pose_count_seen"), 0.0) or 0) + int(_float(row.get("n_poses"), 1.0) or 0)
if level == self.final_level and state["rdock_success"]:
state["final_score"] = raw_score
state["is_final_fidelity"] = True
merged = dict(state)
merged.update(row)
self.trace_step_counter += 1
merged["trace_step"] = self.trace_step_counter
merged["trace_walltime_seconds"] = time.time() - self.run_started_at
merged["strategy"] = self.config.strategy
merged["adaptive_policy"] = getattr(self.config, "adaptive_policy", "")
self.trace_rows.append(merged)
level_rows.append(merged)
write_rows_csv(level_rows, self.out_dir / "tables" / f"fidelity_level_{level}_scores.csv")
def _run_level(self, level: int, level_index: int, selected_ids: list[str]) -> list[dict[str, Any]]:
level_dir = self.out_dir / "rdock" / f"fidelity_{level:03d}"
selection_path = level_dir / "selection.json"
level_dir.mkdir(parents=True, exist_ok=True)
if not (self.config.resume and selection_path.exists()):
_write_json(
selection_path,
{
"level": level,
"level_index": level_index,
"ligand_ids": selected_ids,
},
)
sdf_path = self.out_dir / "ligands" / f"fidelity_{level:03d}.sdf"
if not (self.config.resume and sdf_path.exists() and _count_sdf(sdf_path) == len(selected_ids)):
_write_selected_sdf(self.block_map, selected_ids, sdf_path)
self._emit_progress("fidelity:start", {"level": level, "selected_ligands": len(selected_ids), "run_dir": str(level_dir)})
pre_docking_predictions = {
ligand_id: {
"pre_docking_predicted_score": self.model_by_id[ligand_id].get("predicted_filtered_score", self.model_by_id[ligand_id].get("model_score", 0.0)),
"pre_docking_predicted_uncertainty": self.model_by_id[ligand_id].get("predicted_uncertainty", 0.0),
}
for ligand_id in selected_ids
}
for ligand_id in selected_ids:
self.pre_docking_prediction_rows.append(
{
"ligand_id": ligand_id,
"cluster_id": str(self.model_by_id.get(ligand_id, {}).get("cluster_id", "")),
"fidelity_level": level,
"prediction_stage": f"before_fidelity_{level:03d}",
"predicted_score": pre_docking_predictions[ligand_id]["pre_docking_predicted_score"],
"predicted_uncertainty": pre_docking_predictions[ligand_id]["pre_docking_predicted_uncertainty"],
"observed_score_available_before_prediction": "false",
"leakage_flag": "false",
}
)
start = time.time()
artifacts = self.engine.dock_sdf(
self.target_config,
sdf_path,
level_dir,
n_runs=level,
jobs=self.config.jobs,
run_id=f"{self.out_dir.name}_fidelity_{level:03d}",
resume=self.config.resume,
)
level_seconds = time.time() - start
self.docking_time_total += level_seconds
failed_chunks_path = level_dir / "tables" / "failed_chunks.csv"
failed_ligands_path = level_dir / "tables" / "failed_ligands.csv"
failure_summary_path = level_dir / "metrics" / "rdock_failure_summary.json"
if failed_chunks_path.exists():
for row in _read_rows(failed_chunks_path):
item = dict(row)
item["fidelity_level"] = level
self.failed_chunk_rows.append(item)
if failed_ligands_path.exists():
for row in _read_rows(failed_ligands_path):
item = dict(row)
item["fidelity_level"] = level
self.failed_ligand_rows.append(item)
if failure_summary_path.exists():
failure_payload = _load_json(failure_summary_path)
self.rdock_records_without_score_dropped += int(failure_payload.get("records_without_score_dropped", 0) or 0)
best_rows = []
success_rows = {str(row["ligand_id"]): dict(row) for row in _read_rows(level_dir / "tables" / "best_per_ligand.csv")}
for ligand_id in selected_ids:
row = success_rows.get(ligand_id, {"ligand_id": ligand_id, "rdock_success": False, "failed_reason": "missing_best_pose"})
row.setdefault("model_score", self.model_by_id[ligand_id]["model_score"])
row.setdefault("cluster_id", self.model_by_id[ligand_id]["cluster_id"])
row.setdefault("surrogate_score", self.model_by_id[ligand_id].get("surrogate_score", self.model_by_id[ligand_id]["model_score"]))
row.update(pre_docking_predictions.get(ligand_id, {}))
row["rdock_success"] = bool(success_rows.get(ligand_id))
best_rows.append(row)
penalized = self._penalize_rows(best_rows, level)
training_seconds = self._update_surrogate(penalized)
self.training_time_total += training_seconds
self._record_level_rows(level, level_index, penalized, level_seconds, training_seconds)
self._emit_progress(
"fidelity:done",
{
"level": level,
"selected_ligands": len(selected_ids),
"successful_ligands": sum(1 for row in penalized if str(row.get("rdock_success", "")).lower() in {"true", "1"}),
"seconds_docking": level_seconds,
"seconds_training": training_seconds,
},
)
return penalized
def _promotion_reason(self, row: dict[str, Any]) -> str:
reasons = [f"ranking_score={row.get('ranking_score')}", f"cluster={row.get('cluster_id')}"]
if row.get("component_warning"):
reasons.append(str(row["component_warning"]))
return ";".join(reasons)
def _promote(
self,
rows: list[dict[str, Any]],
current_level: int,
next_level: int,
target_count: int,
) -> list[str]:
successful = [row for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}]
promotion_policy = str(self.config.promotion_policy).lower()
def _policy_priority(item: dict[str, Any]) -> tuple[float, float, float, str, str]:
base = self._promotion_priority(item) / max(0.1, float(getattr(self.config, "promotion_temperature", 1.0) or 1.0))
uncertainty = _float(item.get("predicted_uncertainty"), 0.0)
cluster_quality = _float(item.get("cluster_quality"), 0.0)
classifier_probability = _float(item.get("p_good"), 0.0)
diversity_bonus = _float(item.get("diversity_bonus"), 0.0)
if promotion_policy == "quota_ladder":
return (
base,
-classifier_probability,
-cluster_quality,
-diversity_bonus,
str(item.get("cluster_id", "")),
)
if promotion_policy == "exploit_heavy":
return (base, -cluster_quality, -_float(item.get("p_good"), 0.0), str(item.get("cluster_id", "")), str(item.get("ligand_id", "")))
if promotion_policy == "explore_heavy":
return (base - (0.75 * uncertainty), -uncertainty, -cluster_quality, str(item.get("cluster_id", "")), str(item.get("ligand_id", "")))
return (base - (0.25 * uncertainty), -cluster_quality, -_float(item.get("p_good"), 0.0), str(item.get("cluster_id", "")), str(item.get("ligand_id", "")))
ordered = sorted(successful, key=_policy_priority)
chosen_rows = _select_diverse(ordered, target_count, self.config.min_per_cluster, self.config.max_per_cluster)
promoted_ids = [str(row["ligand_id"]) for row in chosen_rows]
for row in ordered:
ligand_id = str(row["ligand_id"])
decision = {
"ligand_id": ligand_id,
"cluster_id": row.get("cluster_id", ""),
"from_level": current_level,
"to_level": next_level if ligand_id in promoted_ids else "",
"promoted": ligand_id in promoted_ids,
"promotion_reason": self._promotion_reason(row) if ligand_id in promoted_ids else "not selected",
"ranking_score": row.get("ranking_score", ""),
"SCORE": row.get("SCORE", ""),
"SCORE.INTER": row.get("SCORE.INTER", ""),
"SCORE.INTRA": row.get("SCORE.INTRA", ""),
"component_warning": row.get("component_warning", ""),
}
self.promotion_rows.append(decision)
state = self.state_by_id[ligand_id]
if ligand_id in promoted_ids:
state["promoted_from_level"] = current_level
state["promoted_to_level"] = next_level
state["promotion_reason"] = decision["promotion_reason"]
return promoted_ids
def _initial_selection(self, target_count: int) -> list[str]:
if target_count <= 0:
return []
ordered = sorted(
self.candidate_rows,
key=lambda row: (-float(row["model_score"]), str(row["cluster_id"]), str(row["ligand_id"])),
)
explore_count = max(self.config.cluster_min_coverage, int(math.ceil(target_count * self.config.exploration_fraction)))
explore_seed_rows = _select_diverse(ordered, min(target_count, explore_count), max(self.config.min_per_cluster, self.config.cluster_min_coverage), self.config.max_per_cluster)
selected_ids = [str(row["ligand_id"]) for row in explore_seed_rows]
if len(selected_ids) >= target_count:
return selected_ids[:target_count]
for row in ordered:
ligand_id = str(row["ligand_id"])
if ligand_id in selected_ids:
continue
selected_ids.append(ligand_id)
if len(selected_ids) >= target_count:
break
return selected_ids[:target_count]
def _prefilter_candidate_rows(self) -> list[dict[str, Any]]:
decisions: list[dict[str, Any]] = []
screenable: list[dict[str, Any]] = []
for row in self.candidate_rows:
item = dict(row)
reasons: list[str] = []
low_priority = False
smiles = str(item.get("smiles", "")).strip()
mw = _float(item.get("molecular_weight"), 0.0)
charge = abs(_float(item.get("formal_charge"), 0.0))
rotors = _float(item.get("rotatable_bonds"), 0.0)
heavy = _float(item.get("heavy_atom_count"), 0.0)
if not smiles:
reasons.append("missing_smiles")
if mw <= 0.0 and heavy <= 0.0:
reasons.append("missing_descriptor_support")
if charge > 3.0:
reasons.append("high_formal_charge")
low_priority = True
if rotors > 18:
reasons.append("high_rotatable_bonds")
low_priority = True
if mw > 900:
reasons.append("large_molecule")
low_priority = True
if heavy < 8 and mw < 120:
reasons.append("very_small_molecule")
low_priority = True
keep = "missing_smiles" not in reasons
decision = {
"ligand_id": str(item["ligand_id"]),
"cluster_id": str(item["cluster_id"]),
"keep_for_screening": _bool_text(keep),
"low_priority": _bool_text(low_priority),
"reason": ",".join(reasons),
"molecular_weight": item.get("molecular_weight", ""),
"rotatable_bonds": item.get("rotatable_bonds", ""),
"formal_charge": item.get("formal_charge", ""),
"heavy_atom_count": item.get("heavy_atom_count", ""),
"smiles_length": item.get("smiles_length", ""),
}
decisions.append(decision)
if keep:
item["prefilter_low_priority"] = low_priority
item["prefilter_reason"] = decision["reason"]
screenable.append(item)
write_rows_csv(decisions, self.out_dir / "tables" / "initial_prefilter_decisions.csv")
return screenable
def _policy_level_counts(self, library_size: int, levels: list[int], budget_runs: int) -> list[int]:
if library_size <= 0:
return [0 for _ in levels]
if not self.reference_free_mode:
counts = _plan_level_counts(
library_size=library_size,
levels=levels,
budget_runs=budget_runs,
promotion_fraction=self.config.promotion_fraction,
)
if self.config.adaptive_budget_ligands is not None and counts:
counts[0] = min(counts[0], int(self.config.adaptive_budget_ligands))
return counts
policy = str(self.config.promotion_policy).lower()
step_expansion_caps = {
"aggressive": 1.30,
"adaptive": 1.45,
"conservative": 1.55,
"exploit_heavy": 1.35,
"balanced": 1.55,
"explore_heavy": 1.80,
}
max_step_expansion = step_expansion_caps.get(policy, step_expansion_caps["conservative"])
explicit_multipliers: list[float] = []
if str(self.config.promotion_fraction_by_level).strip():
try:
parsed = [float(part.strip()) for part in str(self.config.promotion_fraction_by_level).split(",") if part.strip()]
if len(parsed) == len(levels):
explicit_multipliers = [max(1.0, float(value)) for value in parsed]
except Exception:
explicit_multipliers = []
def _counts_from_final(final_count: int) -> list[int]:
counts = [0 for _ in levels]
counts[-1] = min(library_size, max(0, final_count))
for idx in range(len(levels) - 2, -1, -1):
if explicit_multipliers:
proposed = int(math.ceil(counts[-1] * explicit_multipliers[idx]))
else:
proposed = int(math.ceil(counts[idx + 1] * max_step_expansion))
counts[idx] = min(
library_size,
max(counts[idx + 1], self.config.min_promotion_per_level, proposed),
)
return counts
def _cost(counts: list[int]) -> int:
return sum(level * count for level, count in zip(levels, counts))
max_final_by_budget = max(0, budget_runs // max(1, sum(levels)))
if max_final_by_budget <= 0:
base = min(library_size, max(1, budget_runs // max(1, levels[0])))
counts = [0 for _ in levels]
counts[0] = base
return counts
high = min(library_size, max_final_by_budget)
low = 1
best_counts = _counts_from_final(1)
if _cost(best_counts) > budget_runs:
counts = [0 for _ in levels]
counts[0] = min(library_size, max(1, budget_runs // max(1, levels[0])))
return counts
while low <= high:
mid = (low + high) // 2
counts = _counts_from_final(mid)
total_cost = _cost(counts)
if total_cost <= budget_runs:
best_counts = counts
low = mid + 1
else:
high = mid - 1
counts = best_counts
if self.config.adaptive_budget_ligands is not None and counts:
counts[0] = min(counts[0], int(self.config.adaptive_budget_ligands))
for idx in range(1, len(counts)):
counts[idx] = min(counts[idx], counts[idx - 1])
return counts
def _select_calibration_rows(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
if not rows:
return []
requested = self.config.calibration_size
if requested <= 0:
requested = int(math.ceil(len(rows) * self.config.calibration_fraction))
requested = max(self.config.min_clusters_covered, min(len(rows), requested))
ordered = sorted(
rows,
key=lambda row: (
_bool_arg(row.get("prefilter_low_priority"), False),
-float(row.get("diversity_bonus", 0.0)),
str(row.get("cluster_id", "")),
str(row.get("ligand_id", "")),
),
)
selected = _select_diverse(ordered, requested, max(self.config.min_clusters_covered, 1), max(self.config.max_per_cluster, 1))
if self.config.calibration_random_fraction > 0.0 and len(selected) < requested:
rng = random.Random(self.config.reference_sample_seed)
remaining = [row for row in rows if str(row["ligand_id"]) not in {str(item["ligand_id"]) for item in selected}]
rng.shuffle(remaining)
random_take = max(1, int(math.ceil(requested * self.config.calibration_random_fraction)))
selected.extend(remaining[: max(0, min(random_take, requested - len(selected)))])
return selected[:requested]
def _cluster_only_selection(self, rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
requested = _requested_survivor_count(
len(rows),
self.config.triage_retain_fraction,
self.config.triage_min_survivors,
self.config.triage_max_survivors,
)
ordered = sorted(
rows,
key=lambda row: (
_bool_arg(row.get("prefilter_low_priority"), False),
float(row.get("cluster_size", 1)),
-float(row.get("diversity_bonus", 0.0)),
str(row.get("cluster_id", "")),
str(row.get("ligand_id", "")),
),
)
selected = _select_diverse(ordered, requested, max(1, self.config.cluster_min_survivors), self.config.cluster_max_survivors or max(1, self.config.max_per_cluster))
selected_ids = {str(row["ligand_id"]) for row in selected}
if self.config.rare_cluster_rescue > 0:
rare_candidates = [
row for row in ordered
if str(row["ligand_id"]) not in selected_ids and int(_float(row.get("cluster_size"), 1.0) or 1) <= 2
]
for row in rare_candidates[: self.config.rare_cluster_rescue]:
selected.append(row)
selected_ids.add(str(row["ligand_id"]))
selected.sort(key=lambda row: (float(row.get("cluster_size", 1)), str(row.get("cluster_id", "")), str(row.get("ligand_id", ""))))
return selected, {
"requested_survivor_count": requested,
"final_survivor_count": len(selected),
}
def _descriptor_filter_selection(self, rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
decisions: list[dict[str, Any]] = []
retained: list[dict[str, Any]] = []
for row in rows:
reasons: list[str] = []
keep = True
mw = _float(row.get("molecular_weight"), 0.0)
charge = abs(_float(row.get("formal_charge"), 0.0))
rotors = _float(row.get("rotatable_bonds"), 0.0)
heavy = _float(row.get("heavy_atom_count"), 0.0)
if str(row.get("smiles", "")).strip() == "":
keep = False
reasons.append("missing_smiles")
if charge > 4.0:
keep = False
reasons.append("extreme_charge")
if rotors > 20:
keep = False
reasons.append("too_many_rotors")
if mw > 1000:
keep = False
reasons.append("too_large")
if heavy < 6 and mw < 100:
keep = False
reasons.append("too_small")
decisions.append(
{
"ligand_id": str(row["ligand_id"]),
"cluster_id": str(row.get("cluster_id", "")),
"keep_for_screening": _bool_text(keep),
"reason": ",".join(reasons),
"molecular_weight": row.get("molecular_weight", ""),
"formal_charge": row.get("formal_charge", ""),
"rotatable_bonds": row.get("rotatable_bonds", ""),
"heavy_atom_count": row.get("heavy_atom_count", ""),
}
)
if keep:
retained.append(dict(row))
write_rows_csv(decisions, self.out_dir / "tables" / "descriptor_filter_decisions.csv")
requested = _requested_survivor_count(
len(retained),
self.config.triage_retain_fraction,
min(self.config.triage_min_survivors, max(1, len(retained))),
self.config.triage_max_survivors,
) if retained else 0
ordered = sorted(
retained,
key=lambda row: (
float(row.get("rotatable_bonds", 0.0)),
abs(float(row.get("formal_charge", 0.0))),
float(row.get("cluster_size", 1)),
str(row.get("ligand_id", "")),
),
)
selected = _select_diverse(ordered, requested, max(1, self.config.cluster_min_survivors), self.config.cluster_max_survivors or max(1, self.config.max_per_cluster)) if requested > 0 else []
selected.sort(key=lambda row: (float(row.get("rotatable_bonds", 0.0)), abs(float(row.get("formal_charge", 0.0))), str(row.get("ligand_id", ""))))
return selected, {
"prefilter_retained_count": len(retained),
"requested_survivor_count": requested,
"final_survivor_count": len(selected),
}
def _classifier_metrics(self, labeled_rows: list[dict[str, Any]], top_fraction: float) -> dict[str, Any]:
if len(labeled_rows) < 3:
return {
"classifier_precision": None,
"classifier_recall": None,
"classifier_f1": None,
"classifier_auc_pr": None,
"top_k_recall": None,
"selected_threshold": None,
"calibration_sample_size": len(labeled_rows),
"positive_count": 0,
"positives_in_train": 0,
"positives_in_holdout": 0,
"threshold_confidence": "low",
"insufficient_positive_examples_for_classifier": True,
}
ranked = _sort_by_score(labeled_rows, "final_score", "ranking_score", "SCORE")
positive_ids = {str(row["ligand_id"]) for row in ranked[: max(1, int(math.ceil(len(ranked) * top_fraction)))]}
if len(positive_ids) < self.config.classifier_min_positives:
return {
"classifier_precision": None,
"classifier_recall": None,
"classifier_f1": None,
"classifier_auc_pr": None,
"top_k_recall": None,
"selected_threshold": None,
"calibration_sample_size": len(labeled_rows),
"positive_count": len(positive_ids),
"positives_in_train": 0,
"positives_in_holdout": len(positive_ids),
"threshold_confidence": "low",
"insufficient_positive_examples_for_classifier": True,
}
def _run_split(split_name: str) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
train_rows, holdout_rows = _split_rows_for_validation(
labeled_rows,
self.config.classifier_holdout_fraction,
self.config.reference_sample_seed,
split_name,
)
holdout_positive_ids = {str(row["ligand_id"]) for row in holdout_rows if str(row["ligand_id"]) in positive_ids}
predicted_rows = self._build_knn_predictions(
train_rows,
holdout_rows,
top_fraction=top_fraction,
state_overrides=_state_overrides_from_rows(train_rows),
)
scored = [(str(row["ligand_id"]), float(row["p_good"])) for row in predicted_rows]
ordered = sorted(scored, key=lambda item: item[1], reverse=True)
unique_thresholds = sorted({score for _, score in ordered}, reverse=True)
curve_rows: list[dict[str, Any]] = []
best_metrics = None
precision_points: list[tuple[float, float]] = []
for candidate_threshold in unique_thresholds:
selected_ids = {ligand_id for ligand_id, score in ordered if score >= candidate_threshold}
tp = len(selected_ids & holdout_positive_ids)
recall = tp / max(1, len(holdout_positive_ids))
precision = tp / max(1, len(selected_ids))
f1 = 0.0 if (precision + recall) == 0.0 else (2.0 * precision * recall) / (precision + recall)
curve_rows.append(
{
"validation_split": split_name,
"threshold": candidate_threshold,
"selected_count": len(selected_ids),
"recall": recall,
"precision": precision,
"f1": f1,
}
)
precision_points.append((recall, precision))
if recall >= self.config.triage_target_recall:
if best_metrics is None or len(selected_ids) < int(best_metrics["selected_count"]):
best_metrics = {
"classifier_precision": precision,
"classifier_recall": recall,
"classifier_f1": f1,
"top_k_recall": recall,
"selected_threshold": candidate_threshold,
"calibration_sample_size": len(labeled_rows),
"positive_count": len(positive_ids),
"positives_in_train": len({str(row['ligand_id']) for row in train_rows if str(row['ligand_id']) in positive_ids}),
"positives_in_holdout": len(holdout_positive_ids),
"threshold_confidence": "high",
"selected_count": len(selected_ids),
"insufficient_positive_examples_for_classifier": False,
"validation_split": split_name,
}
auc_pr = None
if precision_points:
ordered_curve = sorted(precision_points, key=lambda item: item[0])
auc = 0.0
prev_recall, prev_precision = ordered_curve[0]
for recall, precision in ordered_curve[1:]:
auc += max(0.0, recall - prev_recall) * ((precision + prev_precision) * 0.5)
prev_recall, prev_precision = recall, precision
auc_pr = auc
if best_metrics is None:
fallback_threshold = unique_thresholds[-1] if unique_thresholds else 0.0
selected_ids = {ligand_id for ligand_id, score in ordered if score >= fallback_threshold}
tp = len(selected_ids & holdout_positive_ids)
recall = tp / max(1, len(holdout_positive_ids))
precision = tp / max(1, len(selected_ids))
f1 = 0.0 if (precision + recall) == 0.0 else (2.0 * precision * recall) / (precision + recall)
best_metrics = {
"classifier_precision": precision,
"classifier_recall": recall,
"classifier_f1": f1,
"top_k_recall": recall,
"selected_threshold": fallback_threshold,
"calibration_sample_size": len(labeled_rows),
"positive_count": len(positive_ids),
"positives_in_train": len({str(row['ligand_id']) for row in train_rows if str(row['ligand_id']) in positive_ids}),
"positives_in_holdout": len(holdout_positive_ids),
"threshold_confidence": "low",
"selected_count": len(selected_ids),
"insufficient_positive_examples_for_classifier": False,
"validation_split": split_name,
}
best_metrics["classifier_auc_pr"] = auc_pr
return best_metrics, curve_rows, train_rows, holdout_rows
random_metrics, random_curve_rows, random_train, random_holdout = _run_split("random")
cluster_metrics, cluster_curve_rows, cluster_train, cluster_holdout = _run_split("cluster")
active_split = str(getattr(self.config, "model_validation_split", "cluster") or "cluster").lower()
active = cluster_metrics if active_split == "cluster" else random_metrics
active_train = cluster_train if active_split == "cluster" else random_train
active_holdout = cluster_holdout if active_split == "cluster" else random_holdout
write_rows_csv(random_curve_rows + cluster_curve_rows, self.out_dir / "tables" / "threshold_calibration_curve.csv")
write_rows_csv(
[
{
"split": active_split,
"role": "train",
"ligand_id": str(row.get("ligand_id", "")),
"cluster_id": str(row.get("cluster_id", "")),
"canonical_smiles": str(row.get("smiles", "")),
"is_positive": _bool_text(str(row.get("ligand_id", "")) in positive_ids),
}
for row in active_train
],
self.out_dir / "tables" / "model_training_rows.csv",
)
write_rows_csv(
[
{
"split": active_split,
"role": "holdout",
"ligand_id": str(row.get("ligand_id", "")),
"cluster_id": str(row.get("cluster_id", "")),
"canonical_smiles": str(row.get("smiles", "")),
"is_positive": _bool_text(str(row.get("ligand_id", "")) in positive_ids),
}
for row in active_holdout
],
self.out_dir / "tables" / "model_holdout_rows.csv",
)
active.update(
{
"classifier_precision_random": random_metrics.get("classifier_precision"),
"classifier_recall_random": random_metrics.get("classifier_recall"),
"classifier_auc_pr_random": random_metrics.get("classifier_auc_pr"),
"classifier_precision_cluster": cluster_metrics.get("classifier_precision"),
"classifier_recall_cluster": cluster_metrics.get("classifier_recall"),
"classifier_auc_pr_cluster": cluster_metrics.get("classifier_auc_pr"),
"model_validation_split": active_split,
}
)
random_auc = _float(random_metrics.get("classifier_auc_pr"), None)
cluster_auc = _float(cluster_metrics.get("classifier_auc_pr"), None)
active["MODEL_GENERALIZATION_WEAK_ACROSS_CLUSTERS"] = bool(
random_auc is not None and cluster_auc is not None and random_auc > 0.15 and cluster_auc < (0.7 * random_auc)
)
_write_json(self.out_dir / "metrics" / "classifier_threshold_metrics.json", active)
return active
def _regressor_audit_metrics(self, labeled_rows: list[dict[str, Any]], top_fraction: float) -> dict[str, Any]:
if len(labeled_rows) < max(12, self.config.classifier_min_positives * 2):
payload = {
"fixed_score_regressor_name": self.config.fixed_score_regressor_name,
"fixed_score_regressor_target": self.config.fixed_score_regressor_target,
"regressor_model_type": self.config.regressor_model_type,
"surrogate_mae": None,
"surrogate_spearman": None,
"surrogate_spearman_neg_pred_vs_obs": None,
"surrogate_spearman_pred_vs_neg_obs": None,
"surrogate_affinity_like_spearman": None,
"n_regressor_points": 0,
"regressor_prediction_direction": "higher_is_better",
"uncertainty_vs_error_spearman": None,
"regressor_sign_check_passed": False,
"cluster_validation_spearman": None,
"REGRESSOR_NOT_PROVEN_USEFUL": True,
"predicted_score_sd": None,
"observed_score_sd": None,
"predicted_observed_sd_ratio": None,
"REGRESSOR_MEDIAN_COLLAPSE_RISK": True,
}
_write_json(self.out_dir / "metrics" / "regressor_audit_metrics.json", payload)
write_rows_csv([], self.out_dir / "tables" / "regressor_validation_predictions.csv")
write_rows_csv([], self.out_dir / "tables" / "regressor_sign_check.csv")
write_rows_csv([], self.out_dir / "tables" / "regressor_target_comparison.csv")
write_rows_csv([], self.out_dir / "tables" / "regressor_distribution_audit.csv")
write_rows_csv([], self.out_dir / "tables" / "leakage_audit.csv")
return payload
validation_rows: list[dict[str, Any]] = []
target_rows: list[dict[str, Any]] = []
leakage_rows: list[dict[str, Any]] = []
split_payloads: dict[str, dict[str, Any]] = {}
for split_name in ("random", "cluster"):
train_rows, holdout_rows = _split_rows_for_validation(
labeled_rows,
self.config.classifier_holdout_fraction,
self.config.reference_sample_seed,
split_name,
)
predicted_rows = self._build_knn_predictions(
train_rows,
holdout_rows,
top_fraction=top_fraction,
state_overrides=_state_overrides_from_rows(train_rows),
)
pred_rows_by_id = {str(row.get("ligand_id", "")): row for row in predicted_rows}
pred_score: list[float] = []
obs_score: list[float] = []
pred_affinity: list[float] = []
obs_affinity: list[float] = []
unc_values: list[float] = []
unc_errors: list[float] = []
split_validation_rows: list[dict[str, Any]] = []
for row in holdout_rows:
ligand_id = str(row.get("ligand_id", ""))
pred_row = pred_rows_by_id.get(ligand_id)
if pred_row is None:
continue
predicted_adjusted_score = _float(pred_row.get("predicted_adjusted_score"), None)
predicted_affinity_like = _float(pred_row.get("predicted_affinity_like"), None)
observed_component_sane = _component_sane_score(row)
observed_raw = _float(row.get("SCORE"), None)
observed_inter = _float(row.get("SCORE.INTER"), None)
if predicted_adjusted_score is None or predicted_affinity_like is None or observed_component_sane is None:
continue
pred_score.append(predicted_adjusted_score)
obs_score.append(observed_component_sane)
pred_affinity.append(predicted_affinity_like)
obs_affinity.append(-observed_component_sane)
unc_val = _float(pred_row.get("predicted_uncertainty"), None)
if unc_val is not None:
unc_values.append(unc_val)
unc_errors.append(abs(predicted_adjusted_score - observed_component_sane))
split_validation_rows.append(
{
"validation_split": split_name,
"ligand_id": ligand_id,
"cluster_id": str(row.get("cluster_id", "")),
"predicted_activity_class": str(pred_row.get("regressor_activity_class", "uncertain")),
"predicted_score": predicted_adjusted_score,
"predicted_affinity_like": predicted_affinity_like,
"prediction_uncertainty": unc_val,
"observed_component_sane_score": observed_component_sane,
"observed_raw_score": observed_raw,
"observed_score_inter": observed_inter,
"observed_affinity_like": -observed_component_sane,
"regressor_rank_score": _float(pred_row.get("regressor_rank_score"), None),
"regressor_confidence": _float(pred_row.get("regressor_confidence"), None),
}
)
leakage_rows.append(
{
"ligand_id": ligand_id,
"split": split_name,
"cluster_id": str(row.get("cluster_id", "")),
"fidelity_level": str(row.get("selected_fidelity_runs", "")),
"prediction_timestamp_stage": f"{split_name}_holdout_validation",
"observed_score_available_before_prediction": "false",
"leakage_flag": "false",
}
)
for target_name in ("raw_score", "component_sane_score", "score_inter", "affinity_like"):
observed_target = _score_target_value(row, target_name)
target_rows.append(
{
"validation_split": split_name,
"ligand_id": ligand_id,
"target_name": target_name,
"predicted_score": predicted_adjusted_score,
"predicted_affinity_like": predicted_affinity_like,
"observed_target": observed_target,
}
)
split_payloads[split_name] = {
"surrogate_mae": _mean([abs(a - b) for a, b in zip(pred_score, obs_score)]) if pred_score else None,
"surrogate_spearman": _spearman(pred_score, obs_score),
"surrogate_affinity_like_spearman": _spearman(pred_affinity, obs_affinity),
"uncertainty_vs_error_spearman": _spearman(unc_values, unc_errors) if unc_values else None,
"validation_rows": split_validation_rows,
"sign_rows": [
{"comparison": "spearman(predicted_score, observed_score)", "value": _spearman(pred_score, obs_score), "validation_split": split_name},
{"comparison": "spearman(-predicted_score, observed_score)", "value": _spearman([-value for value in pred_score], obs_score), "validation_split": split_name},
{"comparison": "spearman(predicted_score, -observed_score)", "value": _spearman(pred_score, [-value for value in obs_score]), "validation_split": split_name},
{"comparison": "spearman(predicted_affinity_like, observed_affinity_like)", "value": _spearman(pred_affinity, obs_affinity), "validation_split": split_name},
],
"n_points": len(split_validation_rows),
}
validation_rows.extend(split_validation_rows)
grouped_targets: dict[tuple[str, str], list[tuple[float, float]]] = {}
for row in target_rows:
predicted_affinity_like = _float(row.get("predicted_affinity_like"), None)
observed_target = _float(row.get("observed_target"), None)
if predicted_affinity_like is None or observed_target is None:
continue
grouped_targets.setdefault((str(row["validation_split"]), str(row["target_name"])), []).append((predicted_affinity_like, observed_target))
target_comparison_rows: list[dict[str, Any]] = []
for (split_name, target_name), pairs in grouped_targets.items():
target_comparison_rows.append(
{
"validation_split": split_name,
"target_name": target_name,
"spearman_predicted_affinity_vs_target": _spearman([x for x, _ in pairs], [y for _, y in pairs]),
"n_points": len(pairs),
}
)
active_split = str(getattr(self.config, "model_validation_split", "cluster") or "cluster").lower()
active = split_payloads.get(active_split, split_payloads["cluster"])
sign_lookup = {str(row["comparison"]): row.get("value") for row in active["sign_rows"]}
active_validation = list(active.get("validation_rows", []))
active_pred_scores_raw = [_float(row.get("predicted_score"), None) for row in active_validation]
active_obs_scores_raw = [_float(row.get("observed_component_sane_score"), None) for row in active_validation]
active_pred_scores = [float(value) for value in active_pred_scores_raw if value is not None]
active_obs_scores = [float(value) for value in active_obs_scores_raw if value is not None]
pred_sd = _stdev(active_pred_scores, _mean(active_pred_scores)) if active_pred_scores else None
obs_sd = _stdev(active_obs_scores, _mean(active_obs_scores)) if active_obs_scores else None
sd_ratio = (float(pred_sd) / float(obs_sd)) if pred_sd is not None and obs_sd not in {None, 0.0} else None
median_collapse = bool(sd_ratio is not None and sd_ratio < 0.25 and int(active.get("n_points", 0) or 0) >= 8)
distribution_rows = [
{
"validation_split": active_split,
"n_points": active.get("n_points", 0),
"predicted_score_mean": _mean(active_pred_scores) if active_pred_scores else None,
"predicted_score_median": _median(active_pred_scores) if active_pred_scores else None,
"predicted_score_sd": pred_sd,
"observed_score_mean": _mean(active_obs_scores) if active_obs_scores else None,
"observed_score_median": _median(active_obs_scores) if active_obs_scores else None,
"observed_score_sd": obs_sd,
"predicted_observed_sd_ratio": sd_ratio,
"median_collapse_risk": median_collapse,
}
]
raw_target_spearman = next(
(
_float(row.get("spearman_predicted_affinity_vs_target"), None)
for row in target_comparison_rows
if str(row.get("validation_split")) == active_split and str(row.get("target_name")) == "raw_score"
),
None,
)
component_sane_spearman = next(
(
_float(row.get("spearman_predicted_affinity_vs_target"), None)
for row in target_comparison_rows
if str(row.get("validation_split")) == active_split and str(row.get("target_name")) == "component_sane_score"
),
None,
)
inter_component_spearman = next(
(
_float(row.get("spearman_predicted_affinity_vs_target"), None)
for row in target_comparison_rows
if str(row.get("validation_split")) == active_split and str(row.get("target_name")) == "score_inter"
),
None,
)
sign_passed = (_float(sign_lookup.get("spearman(predicted_affinity_like, observed_affinity_like)"), -1.0) or -1.0) > 0.0
payload = {
"fixed_score_regressor_name": self.config.fixed_score_regressor_name,
"fixed_score_regressor_target": self.config.fixed_score_regressor_target,
"regressor_model_type": self.config.regressor_model_type,
"surrogate_mae": active.get("surrogate_mae"),
"surrogate_spearman": active.get("surrogate_spearman"),
"surrogate_spearman_neg_pred_vs_obs": sign_lookup.get("spearman(-predicted_score, observed_score)"),
"surrogate_spearman_pred_vs_neg_obs": sign_lookup.get("spearman(predicted_score, -observed_score)"),
"surrogate_affinity_like_spearman": active.get("surrogate_affinity_like_spearman"),
"uncertainty_vs_error_spearman": active.get("uncertainty_vs_error_spearman"),
"n_regressor_points": active.get("n_points"),
"regressor_prediction_direction": "higher_is_better",
"model_validation_split": active_split,
"random_validation_spearman": split_payloads["random"].get("surrogate_affinity_like_spearman"),
"cluster_validation_spearman": split_payloads["cluster"].get("surrogate_affinity_like_spearman"),
"random_validation_mae": split_payloads["random"].get("surrogate_mae"),
"cluster_validation_mae": split_payloads["cluster"].get("surrogate_mae"),
"raw_score_spearman": raw_target_spearman,
"component_sane_spearman": component_sane_spearman,
"inter_component_spearman": inter_component_spearman,
"regressor_sign_check_passed": sign_passed,
"MODEL_GENERALIZATION_WEAK_ACROSS_CLUSTERS": bool(
_float(split_payloads["random"].get("surrogate_affinity_like_spearman"), None) is not None
and _float(split_payloads["cluster"].get("surrogate_affinity_like_spearman"), None) is not None
and float(split_payloads["random"]["surrogate_affinity_like_spearman"]) > 0.3
and float(split_payloads["cluster"]["surrogate_affinity_like_spearman"]) < 0.2
),
"intra_fraction_outlier_rate": _mean(
[
1.0 if _float(row.get("intra_fraction"), 0.0) >= self.config.max_intra_fraction_soft else 0.0
for row in labeled_rows
]
),
"target_outlier_rate": _mean(
[
1.0 if str(row.get("component_warning", "")).strip() else 0.0
for row in labeled_rows
]
),
"predicted_score_sd": pred_sd,
"observed_score_sd": obs_sd,
"predicted_observed_sd_ratio": sd_ratio,
"REGRESSOR_MEDIAN_COLLAPSE_RISK": median_collapse,
}
regressor_ok, disabled_reason = _regressor_status_from_metrics(payload)
payload["REGRESSOR_NOT_PROVEN_USEFUL"] = not regressor_ok
payload["regressor_disabled_reason"] = disabled_reason
_write_json(self.out_dir / "metrics" / "regressor_audit_metrics.json", payload)
write_rows_csv(validation_rows, self.out_dir / "tables" / "regressor_validation_predictions.csv")
write_rows_csv(split_payloads["random"]["sign_rows"] + split_payloads["cluster"]["sign_rows"], self.out_dir / "tables" / "regressor_sign_check.csv")
write_rows_csv(target_comparison_rows, self.out_dir / "tables" / "regressor_target_comparison.csv")
write_rows_csv(distribution_rows, self.out_dir / "tables" / "regressor_distribution_audit.csv")
write_rows_csv(leakage_rows, self.out_dir / "tables" / "leakage_audit.csv")
return payload
def _build_knn_predictions(
self,
labeled_rows: list[dict[str, Any]],
universe_rows: list[dict[str, Any]],
*,
top_fraction: float,
state_overrides: dict[str, dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
usable_labeled_rows = [
dict(row)
for row in labeled_rows
if _score_target_value(row, self.config.fixed_score_regressor_target) is not None
]
if not usable_labeled_rows:
return [
dict(
row,
p_good=0.5,
predicted_adjusted_score=_float(row.get("model_score"), 0.0),
predicted_affinity_like=-_float(row.get("model_score"), 0.0),
predicted_uncertainty=1.0,
outlier_risk=0.0,
regressor_confidence=0.5,
regressor_activity_class="uncertain",
regressor_prediction_direction="higher_is_better",
)
for row in universe_rows
]
ranked = _sort_by_score(usable_labeled_rows, "final_score", "ranking_score", "SCORE")
n_good = max(1, int(math.ceil(len(ranked) * top_fraction)))
good_ids = {str(row["ligand_id"]) for row in ranked[:n_good]}
cluster_scores: dict[str, list[float]] = {}
cluster_hits: dict[str, list[float]] = {}
for row in usable_labeled_rows:
cluster_id = str(row.get("cluster_id", ""))
cluster_scores.setdefault(cluster_id, []).append(_float(row.get("final_score", row.get("ranking_score", row.get("SCORE"))), 0.0))
cluster_hits.setdefault(cluster_id, []).append(1.0 if str(row.get("ligand_id")) in good_ids else 0.0)
def _augment_row(row: dict[str, Any]) -> dict[str, Any]:
item = dict(row)
ligand_id = str(item.get("ligand_id", ""))
cluster_id = str(item.get("cluster_id", ""))
if state_overrides is None:
state = self.state_by_id.get(ligand_id, {})
else:
state = state_overrides.get(ligand_id, {})
scores = cluster_scores.get(cluster_id, [])
hits = cluster_hits.get(cluster_id, [])
item["best_cluster_score_seen_so_far"] = min(scores) if scores else 0.0
item["median_cluster_score_seen_so_far"] = _median(scores) if scores else 0.0
item["n_cluster_labeled"] = len(scores)
item["cluster_uncertainty"] = _stdev(scores, _mean(scores)) if scores else 1.0
item["cluster_hit_rate"] = _mean(hits) if hits else 0.0
item["interaction_quality"] = max(
_float(state.get("biological_interaction_proxy_score"), 0.0),
_float(item.get("biological_interaction_proxy_score"), 0.0),
)
item["post_docking_confidence_score"] = max(
_float(state.get("post_docking_confidence_score"), 0.0),
_float(item.get("post_docking_confidence_score"), 0.0),
)
dynamic = [
_float(state.get("selected_fidelity_runs"), 0.0),
_float(state.get("current_best_score"), 0.0),
_float(state.get("score_mean_observed"), 0.0),
_float(state.get("score_std_observed"), 0.0),
_float(state.get("best_inter_seen"), 0.0),
_float(state.get("best_intra_seen"), 0.0),
_float(state.get("best_intra_fraction_seen"), 0.0),
_float(state.get("failed_observation_fraction"), 0.0),
_float(state.get("pose_count_seen"), 0.0),
_float(item.get("best_cluster_score_seen_so_far"), 0.0),
_float(item.get("median_cluster_score_seen_so_far"), 0.0),
_float(item.get("n_cluster_labeled"), 0.0),
_float(item.get("cluster_uncertainty"), 0.0),
_float(item.get("cluster_hit_rate"), 0.0),
_float(item.get("interaction_quality"), 0.0),
_float(item.get("post_docking_confidence_score"), 0.0),
]
item["augmented_feature_vector"] = [float(value) for value in item.get("feature_vector", [])] + dynamic
return item
usable_labeled_rows = [_augment_row(row) for row in usable_labeled_rows]
prepared_universe_rows = [_augment_row(row) for row in universe_rows]
if SKLEARN_AVAILABLE and len(usable_labeled_rows) >= max(12, self.config.classifier_min_positives * 2):
train_x = _feature_matrix(usable_labeled_rows)
pred_x = _feature_matrix(prepared_universe_rows)
y_good = [1 if str(row["ligand_id"]) in good_ids else 0 for row in usable_labeled_rows]
y_score = [_score_target_value(row, self.config.fixed_score_regressor_target) or 0.0 for row in usable_labeled_rows]
y_outlier = [1 if str(row.get("component_warning", "")).strip() else 0 for row in usable_labeled_rows]
sample_weight = _analog_sample_weights(usable_labeled_rows)
classifier_name = str(self.config.triage_model).lower()
if classifier_name == "logistic_regression" and LogisticRegression is not None:
classifier = LogisticRegression(max_iter=500, class_weight="balanced", random_state=42)
else:
classifier = ExtraTreesClassifier(
n_estimators=256,
random_state=42,
class_weight="balanced",
min_samples_leaf=2,
n_jobs=1,
)
_fit_model(classifier, train_x, y_good, sample_weight)
regressor = _make_regressor_model(self.config.regressor_model_type)
if regressor is None:
raise RDockPipelineError("No regressor backend available")
_fit_model(regressor, train_x, y_score, sample_weight)
outlier_model = ExtraTreesClassifier(
n_estimators=128,
random_state=17,
class_weight="balanced",
min_samples_leaf=2,
n_jobs=1,
)
_fit_model(outlier_model, train_x, y_outlier, sample_weight)
predicted_good = _binary_positive_proba(classifier, pred_x, default_positive=0.0)
predicted_affinity = regressor.predict(pred_x)
uncertainties = _ensemble_uncertainty(regressor, pred_x, fallback=1.0)
outlier_probs = _binary_positive_proba(outlier_model, pred_x, default_positive=0.0)
cluster_positive_rate: dict[str, float] = {}
cluster_totals: dict[str, int] = {}
for row, label in zip(usable_labeled_rows, y_good):
cluster_id = str(row["cluster_id"])
cluster_positive_rate[cluster_id] = cluster_positive_rate.get(cluster_id, 0.0) + float(label)
cluster_totals[cluster_id] = cluster_totals.get(cluster_id, 0) + 1
for cluster_id, total in cluster_totals.items():
cluster_positive_rate[cluster_id] = cluster_positive_rate[cluster_id] / max(1, total)
out: list[dict[str, Any]] = []
for row, p_good, pred_affinity, unc, outlier_prob in zip(prepared_universe_rows, predicted_good, predicted_affinity, uncertainties, outlier_probs):
item = dict(row)
item["p_good"] = float(p_good)
item["predicted_affinity_like"] = float(pred_affinity)
item["predicted_adjusted_score"] = float(-pred_affinity)
item["predicted_uncertainty"] = float(unc)
item["outlier_risk"] = float(outlier_prob)
item["cluster_quality"] = float(cluster_positive_rate.get(str(row["cluster_id"]), _mean(list(cluster_positive_rate.values())) if cluster_positive_rate else 0.5))
item["regressor_rank_score"] = float(pred_affinity)
item["regressor_confidence"] = 1.0 / (1.0 + max(0.0, float(unc)))
item["regressor_activity_class"] = _activity_class(float(p_good), float(unc), float(item["regressor_confidence"]))
item["regressor_prediction_direction"] = "higher_is_better"
out.append(item)
return out
out: list[dict[str, Any]] = []
for row in prepared_universe_rows:
item = dict(row)
neighbors: list[tuple[float, dict[str, Any]]] = []
for ref in usable_labeled_rows:
dist = _distance(item["augmented_feature_vector"], ref["augmented_feature_vector"])
neighbors.append((dist, ref))
neighbors.sort(key=lambda pair: pair[0])
top_neighbors = neighbors[: min(16, len(neighbors))]
weights = [(1.0 / (1.0 + dist)) * max(0.01, min(1.0, _float(ref.get("analog_group_weight"), 1.0))) for dist, ref in top_neighbors]
total_weight = sum(weights) or 1.0
predicted_affinity = sum(weight * ((_score_target_value(ref, self.config.fixed_score_regressor_target) or 0.0)) for weight, (_, ref) in zip(weights, top_neighbors)) / total_weight
p_good = sum(weight * (1.0 if str(ref["ligand_id"]) in good_ids else 0.0) for weight, (_, ref) in zip(weights, top_neighbors)) / total_weight
outlier_risk = sum(weight * (1.0 if str(ref.get("component_warning", "")).strip() else 0.0) for weight, (_, ref) in zip(weights, top_neighbors)) / total_weight
uncertainty = _stdev([(_score_target_value(ref, self.config.fixed_score_regressor_target) or 0.0) for _, ref in top_neighbors], predicted_affinity)
item["p_good"] = p_good
item["predicted_affinity_like"] = predicted_affinity
item["predicted_adjusted_score"] = -predicted_affinity
item["predicted_uncertainty"] = uncertainty
item["outlier_risk"] = outlier_risk
item["cluster_quality"] = p_good
item["regressor_rank_score"] = predicted_affinity
item["regressor_confidence"] = 1.0 / (1.0 + max(0.0, uncertainty))
item["regressor_activity_class"] = _activity_class(float(p_good), float(uncertainty), float(item["regressor_confidence"]))
item["regressor_prediction_direction"] = "higher_is_better"
out.append(item)
return out
def _triage_survivors(
self,
universe_rows: list[dict[str, Any]],
labeled_rows: list[dict[str, Any]],
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
predictions = self._build_knn_predictions(labeled_rows, universe_rows, top_fraction=self.config.classifier_top_percentile)
classifier_metrics = self._classifier_metrics(labeled_rows, self.config.classifier_top_percentile)
regressor_metrics = self._regressor_audit_metrics(labeled_rows, self.config.classifier_top_percentile)
effective_uncertainty_weight, uncertainty_used_for_acquisition, uncertainty_disabled_reason = _effective_uncertainty_weight(
self.config.uncertainty_weight,
regressor_metrics.get("uncertainty_vs_error_spearman"),
)
regressor_allowed = (
str(getattr(self.config, "regressor_contribution_mode", "linear") or "linear").lower() != "none"
and not bool(regressor_metrics.get("REGRESSOR_NOT_PROVEN_USEFUL"))
)
effective_regressor_weight = float(self.config.regressor_weight) if regressor_allowed else 0.0
self.current_effective_uncertainty_weight = effective_uncertainty_weight
self.current_uncertainty_used_for_acquisition = uncertainty_used_for_acquisition
self.current_uncertainty_disabled_reason = uncertainty_disabled_reason
self.current_regressor_used_for_ranking = regressor_allowed
self.current_regressor_disabled_reason = "" if regressor_allowed else str(regressor_metrics.get("regressor_disabled_reason", "regressor_disabled"))
self.current_effective_regressor_weight = effective_regressor_weight
self.current_classifier_gate_warning = ""
cluster_good_counts: dict[str, float] = {}
for row in predictions:
cluster_good_counts[str(row["cluster_id"])] = cluster_good_counts.get(str(row["cluster_id"]), 0.0) + float(row["p_good"])
policy = str(getattr(self.config, "adaptive_policy", "hybrid_rank") or "hybrid_rank").lower()
regressor_mode = str(getattr(self.config, "regressor_contribution_mode", "linear") or "linear").lower()
scored_rows: list[dict[str, Any]] = []
v3_strategies = {"reference_free_active_learning_v3_diverse_ranker", "reference_free_active_learning_v3_lean"}
if self.config.strategy in {"reference_free_active_learning_v2", *v3_strategies}:
score_order = sorted(predictions, key=lambda row: (_float(row.get("predicted_adjusted_score"), float("inf")), str(row["ligand_id"])))
pgood_order = sorted(predictions, key=lambda row: (-_float(row.get("p_good"), 0.0), str(row["ligand_id"])))
uncertainty_order = sorted(predictions, key=lambda row: (-_float(row.get("predicted_uncertainty"), 0.0), str(row["ligand_id"])))
cluster_order = sorted(predictions, key=lambda row: (-_float(row.get("cluster_quality"), 0.0), str(row["ligand_id"])))
diversity_order = sorted(predictions, key=lambda row: (_float(cluster_good_counts.get(str(row["cluster_id"]), 0.0), 0.0), str(row["ligand_id"])))
score_rank = {str(row["ligand_id"]): idx for idx, row in enumerate(score_order, start=1)}
pgood_rank = {str(row["ligand_id"]): idx for idx, row in enumerate(pgood_order, start=1)}
uncertainty_rank = {str(row["ligand_id"]): idx for idx, row in enumerate(uncertainty_order, start=1)}
cluster_rank = {str(row["ligand_id"]): idx for idx, row in enumerate(cluster_order, start=1)}
diversity_rank = {str(row["ligand_id"]): idx for idx, row in enumerate(diversity_order, start=1)}
else:
score_rank = {}
pgood_rank = {}
uncertainty_rank = {}
cluster_rank = {}
diversity_rank = {}
for row in predictions:
cluster_id = str(row["cluster_id"])
diversity_bonus = 1.0 / max(1.0, cluster_good_counts.get(cluster_id, 1.0))
ligand_id = str(row["ligand_id"])
interaction_component = -0.35 * float(row.get("interaction_quality", row.get("biological_interaction_proxy_score", 0.0)))
if self.config.strategy in {"reference_free_active_learning_v2", *v3_strategies}:
classifier_component = -float(row.get("p_good", 0.0))
score_component = float(row.get("predicted_adjusted_score", float("inf")))
uncertainty_component = -effective_uncertainty_weight * float(row.get("predicted_uncertainty", 0.0))
diversity_component = -self.config.diversity_weight * diversity_bonus
cluster_component = -self.config.cluster_quality_weight * float(row.get("cluster_quality", 0.0))
outlier_component = self.config.outlier_risk_weight * float(row.get("outlier_risk", 0.0))
use_regressor = regressor_allowed
if self.config.strategy in v3_strategies:
classifier_rank_weight = 0.35 if self.config.strategy == "reference_free_active_learning_v3_diverse_ranker" else 0.25
gate_bonus = -classifier_rank_weight * self.config.classifier_weight * float(row.get("p_good", 0.0))
novelty_component = -(max(0.4, self.config.exploration_fraction) * diversity_bonus)
cluster_quota_component = -(0.5 * float(row.get("cluster_quality", 0.0)))
triage_score = (
gate_bonus
+ diversity_component
+ cluster_quota_component
+ cluster_component
+ novelty_component
+ outlier_component
)
if use_regressor:
triage_score += max(0.0, min(0.15, effective_regressor_weight)) * score_component
elif policy == "classifier_only":
triage_score = self.config.classifier_weight * classifier_component
if regressor_mode in {"linear", "gate"}:
triage_score += effective_regressor_weight * score_component
elif policy == "classifier_uncertainty":
triage_score = self.config.classifier_weight * classifier_component + uncertainty_component
if regressor_mode in {"linear", "gate"}:
triage_score += effective_regressor_weight * score_component
elif policy == "classifier_uncertainty_diversity":
triage_score = self.config.classifier_weight * classifier_component + uncertainty_component + diversity_component
if regressor_mode in {"linear", "gate"}:
triage_score += effective_regressor_weight * score_component
elif policy == "ucb_like":
triage_score = (
(effective_regressor_weight * score_component if use_regressor else 0.0)
- (8.0 * self.config.classifier_weight * float(row.get("p_good", 0.0)))
+ uncertainty_component
+ outlier_component
)
elif policy == "cluster_bandit":
triage_score = (
-3.0 * float(row.get("cluster_quality", 0.0))
- (2.5 * self.config.classifier_weight * float(row.get("p_good", 0.0)))
+ ((0.5 * effective_regressor_weight * score_component) if use_regressor else 0.0)
+ diversity_component
+ outlier_component
)
elif policy == "classifier_plus_regressor_plus_cluster_quality":
triage_score = (self.config.classifier_weight * classifier_component) + (effective_regressor_weight * score_component if use_regressor else 0.0) + cluster_component + outlier_component
else:
triage_score = (
(float(score_rank.get(ligand_id, len(predictions))) if use_regressor else 0.0)
+ (0.8 * self.config.classifier_weight * float(pgood_rank.get(ligand_id, len(predictions))))
- effective_uncertainty_weight * float(len(predictions) - uncertainty_rank.get(ligand_id, len(predictions)))
- self.config.diversity_weight * float(len(predictions) - diversity_rank.get(ligand_id, len(predictions)))
- self.config.cluster_quality_weight * float(len(predictions) - cluster_rank.get(ligand_id, len(predictions)))
+ self.config.outlier_risk_weight * float(row.get("outlier_risk", 0.0)) * len(predictions)
)
else:
classifier_component = -12.0 * float(row.get("p_good", 0.0))
score_component = float(row["predicted_adjusted_score"])
uncertainty_component = -effective_uncertainty_weight * float(row["predicted_uncertainty"])
diversity_component = -self.config.diversity_weight * diversity_bonus
cluster_component = -0.5 * float(row.get("cluster_quality", 0.0))
outlier_component = self.config.outlier_risk_weight * float(row["outlier_risk"])
triage_score = (
score_component
+ classifier_component
+ uncertainty_component
+ diversity_component
+ outlier_component
)
triage_score += interaction_component
row["diversity_bonus"] = diversity_bonus
row["triage_score"] = triage_score
row["keep_probability"] = row["p_good"]
row["adaptive_policy"] = policy
row["acquisition_mode"] = (
"diverse_ranker_v1"
if self.config.strategy == "reference_free_active_learning_v3_diverse_ranker"
else "lean_production_v1"
if self.config.strategy == "reference_free_active_learning_v3_lean"
else policy
)
row["acquisition_classifier_component"] = classifier_component
row["acquisition_score_component"] = score_component
row["acquisition_uncertainty_component"] = uncertainty_component
row["acquisition_diversity_component"] = diversity_component
row["acquisition_cluster_component"] = cluster_component
row["acquisition_outlier_component"] = outlier_component
row["acquisition_interaction_component"] = interaction_component
row["effective_regressor_weight"] = effective_regressor_weight
row["effective_uncertainty_weight"] = effective_uncertainty_weight
scored_rows.append(row)
state = self.state_by_id.get(ligand_id)
model_row = self.model_by_id.get(ligand_id)
if state is not None:
state["p_good"] = float(row.get("p_good", 0.0))
state["cluster_quality"] = float(row.get("cluster_quality", 0.0))
state["triage_score"] = float(triage_score)
state["predicted_filtered_score"] = float(row.get("predicted_adjusted_score", 0.0))
state["predicted_affinity_like"] = float(row.get("predicted_affinity_like", 0.0))
state["predicted_uncertainty"] = float(row.get("predicted_uncertainty", 0.0))
state["outlier_risk"] = float(row.get("outlier_risk", 0.0))
state["diversity_bonus"] = float(diversity_bonus)
state["acquisition_classifier_component"] = float(classifier_component)
state["acquisition_score_component"] = float(score_component)
state["acquisition_uncertainty_component"] = float(uncertainty_component)
state["acquisition_diversity_component"] = float(diversity_component)
state["acquisition_cluster_component"] = float(cluster_component)
state["acquisition_outlier_component"] = float(outlier_component)
state["acquisition_interaction_component"] = float(interaction_component)
state["interaction_quality"] = float(row.get("interaction_quality", 0.0))
if model_row is not None:
model_row["p_good"] = float(row.get("p_good", 0.0))
model_row["cluster_quality"] = float(row.get("cluster_quality", 0.0))
model_row["triage_score"] = float(triage_score)
model_row["predicted_filtered_score"] = float(row.get("predicted_adjusted_score", 0.0))
model_row["predicted_affinity_like"] = float(row.get("predicted_affinity_like", 0.0))
model_row["predicted_uncertainty"] = float(row.get("predicted_uncertainty", 0.0))
model_row["outlier_risk"] = float(row.get("outlier_risk", 0.0))
model_row["diversity_bonus"] = float(diversity_bonus)
model_row["acquisition_classifier_component"] = float(classifier_component)
model_row["acquisition_score_component"] = float(score_component)
model_row["acquisition_uncertainty_component"] = float(uncertainty_component)
model_row["acquisition_diversity_component"] = float(diversity_component)
model_row["acquisition_cluster_component"] = float(cluster_component)
model_row["acquisition_outlier_component"] = float(outlier_component)
model_row["acquisition_interaction_component"] = float(interaction_component)
model_row["interaction_quality"] = float(row.get("interaction_quality", 0.0))
scored_rows.sort(key=lambda row: (float(row["triage_score"]), str(row["cluster_id"]), str(row["ligand_id"])))
labeled_good_ids = {
str(row["ligand_id"])
for row in _sort_by_score(labeled_rows, "final_score", "ranking_score", "SCORE")[: max(1, int(math.ceil(len(labeled_rows) * self.config.classifier_top_percentile)))]
}
controller_rows: list[dict[str, Any]] = []
threshold_rows: list[dict[str, Any]] = []
requested_fraction = self.config.triage_retain_fraction
requested = _requested_survivor_count(
len(scored_rows),
requested_fraction,
self.config.triage_min_survivors,
self.config.triage_max_survivors,
)
step_fraction = max(0.01, requested_fraction * 0.5)
final_selected: list[dict[str, Any]] = []
final_selected_ids: set[str] = set()
final_recall_estimate = 0.0 if labeled_good_ids else 1.0
iterations = 0
selected_threshold = classifier_metrics.get("selected_threshold")
gate_retained_count = 0
def _select_for_requested(requested_count: int) -> tuple[list[dict[str, Any]], set[str]]:
nonlocal gate_retained_count
cluster_selected: dict[str, int] = {}
selected: list[dict[str, Any]] = []
selected_ids: set[str] = set()
hard_cap = requested_count
if self.config.triage_max_survivors > 0:
hard_cap = min(hard_cap, self.config.triage_max_survivors)
hard_cap = max(1, hard_cap)
candidate_rows = scored_rows
if self.config.triage_model == "classifier" and selected_threshold is not None:
classifier_rows = [row for row in scored_rows if float(row.get("keep_probability", 0.0)) >= float(selected_threshold)]
if classifier_rows:
candidate_rows = classifier_rows
if self.config.strategy in v3_strategies:
gate_fraction = max(0.10, min(float(getattr(self.config, "classifier_gate_fraction", 0.15)), 0.20))
max_gate_fraction = max(gate_fraction, min(0.30, float(getattr(self.config, "classifier_max_gate_fraction", 0.20))))
requested_gate_pool = max(hard_cap, int(math.ceil(len(scored_rows) * gate_fraction)))
max_gate_pool = max(hard_cap, int(math.ceil(len(scored_rows) * max_gate_fraction)))
if len(candidate_rows) > max_gate_pool:
candidate_rows = sorted(
candidate_rows,
key=lambda row: (-float(row.get("keep_probability", 0.0)), float(row.get("triage_score", float("inf")))),
)[:max_gate_pool]
self.current_classifier_gate_warning = "classifier_gate_capped_to_max_gate_fraction"
min_candidate_pool = max(
hard_cap,
min(len(candidate_rows), max(self.config.min_final_ligands, requested_gate_pool)),
)
candidate_rows = sorted(
candidate_rows,
key=lambda row: (-float(row.get("keep_probability", 0.0)), float(row.get("triage_score", float("inf")))),
)[:min_candidate_pool]
gate_retained_count = len(candidate_rows)
if self.config.strategy == "reference_free_active_learning_v3_lean":
exploit_fraction = 0.60
explore_fraction = 0.40
else:
exploit_fraction = max(0.6, 1.0 - self.config.exploration_fraction)
explore_fraction = self.config.exploration_fraction
exploit_target = min(hard_cap, max(1, int(math.ceil(hard_cap * exploit_fraction))))
explore_target = max(0, hard_cap - exploit_target)
self.exploration_split_rows.append(
{
"requested_count": requested_count,
"candidate_pool": len(candidate_rows),
"exploit_target": exploit_target,
"explore_target": explore_target,
"exploration_fraction": explore_fraction,
"strategy": self.config.strategy,
}
)
exploit_rows = sorted(candidate_rows, key=lambda row: (float(row.get("triage_score", float("inf"))), str(row.get("cluster_id", "")), str(row.get("ligand_id", ""))))
explore_rows = sorted(
[row for row in candidate_rows if str(row.get("ligand_id", "")) not in {str(item.get("ligand_id", "")) for item in exploit_rows[:exploit_target]}],
key=lambda row: (
-float(row.get("diversity_bonus", 0.0)),
-float(row.get("cluster_quality", 0.0)),
float(row.get("triage_score", float("inf"))),
),
)
selected = _select_diverse(exploit_rows, exploit_target, max(1, self.config.min_per_cluster), max(1, self.config.max_per_cluster))
selected_ids = {str(row["ligand_id"]) for row in selected}
for row in explore_rows:
if len(selected) >= hard_cap or explore_target <= 0:
break
ligand_id = str(row["ligand_id"])
cluster_id = str(row["cluster_id"])
if ligand_id in selected_ids:
continue
if cluster_selected.get(cluster_id, 0) >= self.config.max_per_cluster > 0:
self.cluster_quota_rows.append({"ligand_id": ligand_id, "cluster_id": cluster_id, "decision": "rejected_cluster_cap", "phase": "explore"})
continue
selected.append(row)
selected_ids.add(ligand_id)
explore_target -= 1
self.cluster_quota_rows.append({"ligand_id": ligand_id, "cluster_id": cluster_id, "decision": "selected_explore", "phase": "explore"})
cluster_selected = {}
for row in selected:
cluster_id = str(row["cluster_id"])
cluster_selected[cluster_id] = cluster_selected.get(cluster_id, 0) + 1
for row in selected:
self.cluster_quota_rows.append(
{
"ligand_id": str(row["ligand_id"]),
"cluster_id": str(row["cluster_id"]),
"decision": "selected",
"phase": "exploit" if row in exploit_rows[:exploit_target] else "explore",
}
)
selected = _sort_by_score(selected, "triage_score", "predicted_adjusted_score")[:hard_cap]
selected_ids = {str(row["ligand_id"]) for row in selected}
return selected, selected_ids
for row in candidate_rows:
cluster_id = str(row["cluster_id"])
if cluster_selected.get(cluster_id, 0) >= self.config.cluster_max_survivors > 0:
continue
selected.append(row)
selected_ids.add(str(row["ligand_id"]))
cluster_selected[cluster_id] = cluster_selected.get(cluster_id, 0) + 1
if len(selected) >= hard_cap:
break
if self.config.cluster_min_survivors > 0:
for cluster_id in sorted({str(row["cluster_id"]) for row in scored_rows}):
if len(selected) >= hard_cap:
break
current = cluster_selected.get(cluster_id, 0)
if current >= self.config.cluster_min_survivors:
continue
for row in scored_rows:
if len(selected) >= hard_cap:
break
if str(row["cluster_id"]) != cluster_id or str(row["ligand_id"]) in selected_ids:
continue
selected.append(row)
selected_ids.add(str(row["ligand_id"]))
cluster_selected[cluster_id] = cluster_selected.get(cluster_id, 0) + 1
current += 1
if current >= self.config.cluster_min_survivors:
break
if self.config.rare_cluster_rescue > 0:
rare_rows = [row for row in scored_rows if cluster_good_counts.get(str(row["cluster_id"]), 0.0) <= 1.0 and str(row["ligand_id"]) not in selected_ids]
for row in rare_rows[: self.config.rare_cluster_rescue]:
if len(selected) >= hard_cap:
break
selected.append(row)
selected_ids.add(str(row["ligand_id"]))
if self.config.uncertainty_rescue > 0:
uncertain_rows = sorted(
[row for row in scored_rows if str(row["ligand_id"]) not in selected_ids],
key=lambda row: (-float(row["predicted_uncertainty"]), float(row["triage_score"])),
)
for row in uncertain_rows[: self.config.uncertainty_rescue]:
if len(selected) >= hard_cap:
break
selected.append(row)
selected_ids.add(str(row["ligand_id"]))
if regressor_mode == "rescue":
rescue_cap = max(1, int(math.ceil(requested_count * max(0.01, self.config.rescue_fraction))))
regressor_rows = sorted(
[row for row in scored_rows if str(row["ligand_id"]) not in selected_ids],
key=lambda row: (
-float(row.get("predicted_affinity_like", 0.0)),
float(row.get("triage_score", float("inf"))),
),
)
for row in regressor_rows[:rescue_cap]:
if len(selected) >= hard_cap:
break
selected.append(row)
selected_ids.add(str(row["ligand_id"]))
selected = _sort_by_score(selected, "triage_score", "predicted_adjusted_score")[:hard_cap]
selected_ids = {str(row["ligand_id"]) for row in selected}
return selected, selected_ids
def _cluster_only_ids() -> set[str]:
cluster_rows, _ = self._cluster_only_selection(universe_rows)
return {str(row["ligand_id"]) for row in cluster_rows}
max_fraction = max(requested_fraction, self.config.max_retain_fraction_before_not_useful)
while True:
iterations += 1
selected, selected_ids = _select_for_requested(requested)
recall_estimate = len(labeled_good_ids & selected_ids) / max(1, len(labeled_good_ids)) if labeled_good_ids else 1.0
threshold_rows.append(
{
"retain_fraction": requested_fraction,
"requested_survivors": requested,
"estimated_recall": recall_estimate,
"estimated_cost_saved_fraction": max(0.0, 1.0 - (len(selected_ids) / max(1, len(scored_rows)))),
}
)
controller_rows.append(
{
"iteration": iterations,
"requested_retain_fraction": requested_fraction,
"requested_survivors": requested,
"achieved_recall_estimate": recall_estimate,
"survivor_count": len(selected_ids),
}
)
final_selected, final_selected_ids, final_recall_estimate = selected, selected_ids, recall_estimate
if self.config.triage_controller != "auto_recall":
break
if recall_estimate >= self.config.triage_target_recall:
break
if requested_fraction >= max_fraction:
break
requested_fraction = min(max_fraction, requested_fraction + step_fraction)
requested = _requested_survivor_count(
len(scored_rows),
requested_fraction,
self.config.triage_min_survivors,
self.config.triage_max_survivors,
)
self.config.uncertainty_rescue = max(self.config.uncertainty_rescue, int(math.ceil(requested * 0.02)))
self.config.rare_cluster_rescue = max(self.config.rare_cluster_rescue, int(math.ceil(requested * 0.01)))
selected = final_selected
selected_ids = final_selected_ids
recall_estimate = final_recall_estimate
final_requested_survivors = _requested_survivor_count(
len(scored_rows),
requested_fraction,
self.config.triage_min_survivors,
self.config.triage_max_survivors,
)
fallback_used = ""
if classifier_metrics.get("insufficient_positive_examples_for_classifier") and self.config.classifier_fallback == "cluster_only":
selected_ids = _cluster_only_ids()
selected = [row for row in scored_rows if str(row["ligand_id"]) in selected_ids]
recall_estimate = len(labeled_good_ids & selected_ids) / max(1, len(labeled_good_ids)) if labeled_good_ids else 1.0
fallback_used = "cluster_only_insufficient_positives"
if self.config.model_fallback_if_worse in {"cluster_only", "union_with_cluster_only"}:
cluster_ids = _cluster_only_ids()
cluster_recall = len(labeled_good_ids & cluster_ids) / max(1, len(labeled_good_ids)) if labeled_good_ids else 1.0
if self.config.model_fallback_if_worse == "union_with_cluster_only" or cluster_recall > recall_estimate:
fallback_used = self.config.model_fallback_if_worse
if self.config.survivor_combination_policy == "cluster_only" and self.config.model_fallback_if_worse == "cluster_only":
selected_ids = cluster_ids
elif self.config.survivor_combination_policy == "intersection":
selected_ids = selected_ids & cluster_ids
else:
selected_ids = selected_ids | cluster_ids
selected = [row for row in scored_rows if str(row["ligand_id"]) in selected_ids]
recall_estimate = len(labeled_good_ids & selected_ids) / max(1, len(labeled_good_ids)) if labeled_good_ids else 1.0
capped_survivor_limit = max(1, final_requested_survivors)
if len(selected_ids) > capped_survivor_limit:
selected = _sort_by_score(selected, "triage_score", "predicted_adjusted_score")[:capped_survivor_limit]
selected_ids = {str(row["ligand_id"]) for row in selected}
recall_estimate = len(labeled_good_ids & selected_ids) / max(1, len(labeled_good_ids)) if labeled_good_ids else 1.0
survivors = _sort_by_score(selected, "triage_score", "predicted_adjusted_score")
rejected = [row for row in scored_rows if str(row["ligand_id"]) not in selected_ids]
for row in survivors:
row["survived_triage"] = True
for row in rejected:
row["survived_triage"] = False
write_rows_csv(scored_rows, self.out_dir / "tables" / "triage_scores.csv", fieldnames=TRIAGE_ROW_FIELDS)
write_rows_csv(survivors, self.out_dir / "tables" / "triage_survivors.csv", fieldnames=TRIAGE_ROW_FIELDS)
write_rows_csv(rejected, self.out_dir / "tables" / "triage_rejected.csv", fieldnames=TRIAGE_ROW_FIELDS)
write_rows_csv(controller_rows, self.out_dir / "tables" / "triage_controller_iterations.csv")
write_rows_csv(threshold_rows, self.out_dir / "tables" / "threshold_calibration_curve.csv")
acquisition_component_rows = [
{
"ligand_id": str(row.get("ligand_id", "")),
"cluster_id": str(row.get("cluster_id", "")),
"classifier_probability": row.get("p_good", ""),
"regressor_score": row.get("predicted_adjusted_score", ""),
"predicted_affinity_like": row.get("predicted_affinity_like", ""),
"diversity_bonus": row.get("diversity_bonus", ""),
"cluster_quality": row.get("cluster_quality", ""),
"uncertainty": row.get("predicted_uncertainty", ""),
"outlier_risk": row.get("outlier_risk", ""),
"interaction_quality": row.get("interaction_quality", ""),
"effective_regressor_weight": effective_regressor_weight,
"effective_uncertainty_weight": effective_uncertainty_weight,
"regressor_used_for_ranking": self.current_regressor_used_for_ranking,
"uncertainty_used_for_acquisition": uncertainty_used_for_acquisition,
"final_acquisition_score": row.get("triage_score", ""),
"adaptive_policy": row.get("adaptive_policy", ""),
"acquisition_mode": row.get("acquisition_mode", ""),
}
for row in scored_rows
]
write_rows_csv(
self._diagnostics_rows(acquisition_component_rows, survivors=survivors),
self.out_dir / "tables" / "acquisition_components.csv",
)
write_rows_csv(self._diagnostics_rows(self.cluster_quota_rows, survivors=survivors), self.out_dir / "tables" / "cluster_quota_decisions.csv")
write_rows_csv(self._diagnostics_rows(self.exploration_split_rows, survivors=survivors), self.out_dir / "tables" / "exploration_exploitation_split.csv")
reduction_fraction = 1.0 - (len(survivors) / max(1, len(scored_rows)))
triage_metrics = {
"adaptive_policy": policy,
"initial_ligands": len(scored_rows),
"triage_survivor_count": len(survivors),
"triage_reduction_fraction": reduction_fraction,
"triage_recall_estimate": recall_estimate,
"triage_false_negative_estimate": max(0.0, 1.0 - recall_estimate),
"triage_target_recall": self.config.triage_target_recall,
"safe_to_reduce_95_percent": recall_estimate >= self.config.triage_target_recall and reduction_fraction >= 0.95,
"safe_to_reduce_99_percent": recall_estimate >= self.config.triage_target_recall and reduction_fraction >= 0.99,
"confidence_level": "high" if recall_estimate >= self.config.triage_target_recall and len(labeled_rows) >= self.config.minimum_training_ligands else "medium" if recall_estimate >= max(0.9, self.config.triage_target_recall - 0.05) else "low",
"requested_retain_fraction": self.config.triage_retain_fraction,
"final_requested_survivors": final_requested_survivors,
"final_retain_fraction": len(survivors) / max(1, len(scored_rows)),
"iterations": iterations,
"model_useful_for_target_recall": recall_estimate >= self.config.triage_target_recall and reduction_fraction >= 0.5,
"safe_to_reduce_any_meaningfully": recall_estimate >= self.config.triage_target_recall and reduction_fraction >= 0.25,
"fallback_used": fallback_used,
}
triage_metrics.update(classifier_metrics)
triage_metrics.update(
{
"surrogate_mae": regressor_metrics.get("surrogate_mae"),
"surrogate_spearman": regressor_metrics.get("surrogate_spearman"),
"surrogate_affinity_like_spearman": regressor_metrics.get("surrogate_affinity_like_spearman"),
"cluster_validation_spearman": regressor_metrics.get("cluster_validation_spearman"),
"raw_score_spearman": regressor_metrics.get("raw_score_spearman"),
"component_sane_spearman": regressor_metrics.get("component_sane_spearman"),
"inter_component_spearman": regressor_metrics.get("inter_component_spearman"),
"regressor_prediction_direction": regressor_metrics.get("regressor_prediction_direction"),
"fixed_score_regressor_name": regressor_metrics.get("fixed_score_regressor_name"),
"fixed_score_regressor_target": regressor_metrics.get("fixed_score_regressor_target"),
"regressor_model_type": regressor_metrics.get("regressor_model_type"),
"REGRESSOR_NOT_PROVEN_USEFUL": regressor_metrics.get("REGRESSOR_NOT_PROVEN_USEFUL"),
"regressor_used_for_ranking": self.current_regressor_used_for_ranking,
"fallback_to_classifier_only": not self.current_regressor_used_for_ranking,
"regressor_disabled_reason": self.current_regressor_disabled_reason,
"effective_regressor_weight": effective_regressor_weight,
"uncertainty_vs_error_spearman": regressor_metrics.get("uncertainty_vs_error_spearman"),
"effective_uncertainty_weight": effective_uncertainty_weight,
"uncertainty_used_for_acquisition": uncertainty_used_for_acquisition,
"uncertainty_disabled_reason": uncertainty_disabled_reason,
"acquisition_mode": (
"diverse_ranker_v1"
if self.config.strategy == "reference_free_active_learning_v3_diverse_ranker"
else "lean_production_v1"
if self.config.strategy == "reference_free_active_learning_v3_lean"
else policy
),
"classifier_gate_retained": gate_retained_count if self.config.strategy in v3_strategies else None,
"classifier_gate_fraction": (gate_retained_count / max(1, len(scored_rows))) if self.config.strategy in v3_strategies else None,
"classifier_gate_warning": self.current_classifier_gate_warning if self.config.strategy in v3_strategies else None,
"exploration_budget_fraction": (0.40 if self.config.strategy == "reference_free_active_learning_v3_lean" else self.config.exploration_fraction) if self.config.strategy in v3_strategies else None,
"exploitation_budget_fraction": (0.60 if self.config.strategy == "reference_free_active_learning_v3_lean" else (1.0 - self.config.exploration_fraction)) if self.config.strategy in v3_strategies else None,
"cluster_coverage_fraction": (len({str(row.get('cluster_id','')) for row in survivors}) / max(1, len({str(row.get('cluster_id','')) for row in scored_rows}))) if self.config.strategy in v3_strategies else None,
"max_cluster_occupancy": max(([sum(1 for row in survivors if str(row.get('cluster_id','')) == cluster_id) for cluster_id in {str(row.get('cluster_id','')) for row in survivors}] or [0])) if self.config.strategy in v3_strategies else None,
"outlier_risk_penalty_applied": True,
"interaction_weight_applied": 0.35,
"acquisition_component_summary": {
"classifier_weight": self.config.classifier_weight,
"effective_regressor_weight": effective_regressor_weight,
"effective_uncertainty_weight": effective_uncertainty_weight,
"diversity_weight": self.config.diversity_weight,
"cluster_quality_weight": self.config.cluster_quality_weight,
"outlier_risk_weight": self.config.outlier_risk_weight,
"interaction_weight": 0.35,
},
"MODEL_GENERALIZATION_WEAK_ACROSS_CLUSTERS": regressor_metrics.get("MODEL_GENERALIZATION_WEAK_ACROSS_CLUSTERS")
or classifier_metrics.get("MODEL_GENERALIZATION_WEAK_ACROSS_CLUSTERS"),
}
)
triage_metrics["model_signal_too_weak"] = bool(
classifier_metrics.get("classifier_recall") is not None
and (
_float(classifier_metrics.get("classifier_auc_pr"), 0.0) < 0.1
or _float(classifier_metrics.get("classifier_precision"), 0.0) < 0.1
)
)
if regressor_metrics.get("REGRESSOR_NOT_PROVEN_USEFUL"):
triage_metrics.setdefault("warnings", []).append("REGRESSOR_NOT_PROVEN_USEFUL")
if triage_metrics.get("MODEL_GENERALIZATION_WEAK_ACROSS_CLUSTERS"):
triage_metrics.setdefault("warnings", []).append("MODEL_GENERALIZATION_WEAK_ACROSS_CLUSTERS")
_write_json(self.out_dir / "metrics" / "triage_metrics.json", triage_metrics)
_write_json(
self.out_dir / "metrics" / "triage_controller_metrics.json",
{
"triage_controller": self.config.triage_controller,
"requested_retain_fraction": self.config.triage_retain_fraction,
"final_retain_fraction": triage_metrics["final_retain_fraction"],
"target_recall": self.config.triage_target_recall,
"achieved_recall_estimate": recall_estimate,
"iterations": iterations,
"safe_to_reduce_95_percent": triage_metrics["safe_to_reduce_95_percent"],
"safe_to_reduce_99_percent": triage_metrics["safe_to_reduce_99_percent"],
"reason": "model cannot safely reduce this dataset enough to be useful"
if recall_estimate < self.config.triage_target_recall and triage_metrics["final_retain_fraction"] >= self.config.max_retain_fraction_before_not_useful
else "",
},
)
return survivors, triage_metrics
def _fidelity_reliability_payload(self, ligand_ids: list[str]) -> dict[str, Any]:
per_ligand: dict[str, dict[int, float]] = {}
for row in self.trace_rows:
ligand_id = str(row.get("ligand_id", ""))
if ligand_ids and ligand_id not in set(ligand_ids):
continue
level = int(_float(row.get("selected_fidelity_runs"), 0.0) or 0)
score = _float(row.get("SCORE"), None)
if score is None:
continue
per_ligand.setdefault(ligand_id, {})[level] = score
final_level = self.final_level
final_pairs = {ligand_id: levels for ligand_id, levels in per_ligand.items() if final_level in levels}
correlations: dict[str, float | None] = {}
recovery: dict[str, float] = {}
final_scores = {ligand_id: levels[final_level] for ligand_id, levels in final_pairs.items()}
final_ranked = sorted(final_scores.items(), key=lambda item: item[1])
final_top_10 = {ligand_id for ligand_id, _ in final_ranked[: max(1, int(math.ceil(len(final_ranked) * 0.1)))]}
for level in self.config.fidelity_levels[:-1]:
xs: list[float] = []
ys: list[float] = []
level_scores: dict[str, float] = {}
for ligand_id, levels in final_pairs.items():
if level not in levels:
continue
xs.append(levels[level])
ys.append(levels[final_level])
level_scores[ligand_id] = levels[level]
correlations[f"spearman_{level}_vs_{final_level}"] = _spearman(xs, ys)
ranked = sorted(level_scores.items(), key=lambda item: item[1])
level_top_10 = {ligand_id for ligand_id, _ in ranked[: max(1, int(math.ceil(len(ranked) * 0.1)))]}
recovery[f"top10pct_recovery_{level}_vs_{final_level}"] = len(level_top_10 & final_top_10) / max(1, len(final_top_10))
payload = {
"final_level": final_level,
"n_multilevel_ligands": len(final_pairs),
"correlations": correlations,
"rank_recovery": recovery,
"low_fidelity_reliable": all((value or -1.0) >= 0.35 for key, value in correlations.items() if key.startswith("spearman_5") or key.startswith("spearman_10")),
}
_write_json(self.out_dir / "metrics" / "fidelity_reliability.json", payload)
return payload
def _latest_trace_rows(self, ligand_ids: list[str], min_level: int = 0, max_level_exclusive: int | None = None) -> list[dict[str, Any]]:
wanted = set(str(ligand_id) for ligand_id in ligand_ids)
latest: dict[str, dict[str, Any]] = {}
for row in self.trace_rows:
ligand_id = str(row.get("ligand_id", ""))
if ligand_id not in wanted:
continue
level = int(_float(row.get("selected_fidelity_runs"), 0.0) or 0)
if level < min_level:
continue
if max_level_exclusive is not None and level >= max_level_exclusive:
continue
latest[ligand_id] = dict(row)
return [latest[ligand_id] for ligand_id in ligand_ids if ligand_id in latest]
def _variant_parent_candidates(self) -> list[dict[str, Any]]:
level_rows = [dict(state) for state in self.state_by_id.values() if int(_float(state.get("selected_fidelity_runs"), 0.0) or 0) > 0]
if not level_rows:
return []
highest_level = max(int(_float(row.get("selected_fidelity_runs"), 0.0) or 0) for row in level_rows)
candidates = [row for row in level_rows if int(_float(row.get("selected_fidelity_runs"), 0.0) or 0) == highest_level]
return _sort_by_score(candidates, "final_score", "current_best_score", "SCORE")
def _enumerate_final_survivor_variants(self, parent_rows: list[dict[str, Any]]) -> dict[str, Any]:
variant_rows: list[dict[str, Any]] = []
best_parent_rows: list[dict[str, Any]] = []
total_variants = 0
total_variant_runs = 0
if not parent_rows:
write_rows_csv([], self.out_dir / "tables" / "variant_scores_long.csv")
write_rows_csv([], self.out_dir / "tables" / "best_variant_per_parent.csv")
return {"variant_generation_backend": "none", "n_parent_ligands": 0, "n_variants_generated": 0, "expansion_factor": 0.0, "added_rDock_runs_due_to_variants": 0, "variant_advantage_warning": False}
if not RDKit_AVAILABLE and not self.config.allow_no_rdkit_parent_only:
raise RDockPipelineError("RDKit_REQUIRED_FOR_VARIANT_ENUMERATION")
backend = "rdkit_variant_enumeration"
if not RDKit_AVAILABLE and self.config.allow_no_rdkit_parent_only:
backend = "parent_only_no_rdkit_allowed"
for row in parent_rows:
parent_id = str(row.get("ligand_id", ""))
smiles = str(self.model_by_id.get(parent_id, {}).get("smiles", ""))
warning = ""
variant_smiles_list = [smiles] if smiles else [""]
if RDKit_AVAILABLE and smiles:
mol = _rdkit_mol(smiles)
if mol is None:
warning = "rdkit_failed_to_parse_smiles"
else:
variant_smiles_list = [Chem.MolToSmiles(mol, isomericSmiles=True)]
if self.config.enumerate_stereoisomers != "none" and EnumerateStereoisomers is not None and StereoEnumerationOptions is not None:
try:
opts = StereoEnumerationOptions(tryEmbedding=False, unique=True, maxIsomers=max(1, self.config.max_stereoisomers_per_parent))
stereo_mols = list(EnumerateStereoisomers(mol, options=opts))
for stereo_mol in stereo_mols[: max(0, self.config.max_stereoisomers_per_parent - 1)]:
variant_smiles_list.append(Chem.MolToSmiles(stereo_mol, isomericSmiles=True))
except Exception:
warning = "stereoisomer_enumeration_failed"
if self.config.enumerate_tautomers != "none":
if rdMolStandardize is None:
warning = ",".join(filter(None, [warning, "tautomer_module_unavailable"]))
else:
try:
tautomer_enum = rdMolStandardize.TautomerEnumerator()
taut = tautomer_enum.Canonicalize(mol)
taut_smiles = Chem.MolToSmiles(taut, isomericSmiles=True)
variant_smiles_list.append(taut_smiles)
except Exception:
warning = ",".join(filter(None, [warning, "tautomer_enumeration_failed"]))
variant_smiles_list = list(dict.fromkeys([text for text in variant_smiles_list if text]))[: max(1, self.config.max_total_variants_per_parent)]
n_variants = len(variant_smiles_list)
score = _float(row.get("final_score", row.get("current_best_score", row.get("SCORE"))), None)
base_runs = int(_float(row.get("selected_fidelity_runs"), 0.0) or 0)
for idx, variant_smiles in enumerate(variant_smiles_list):
variant_rows.append(
{
"parent_ligand_id": parent_id,
"variant_id": f"{parent_id}__v{idx+1:02d}",
"canonical_smiles": smiles,
"variant_smiles": variant_smiles,
"variant_type": "parent_identity" if idx == 0 and variant_smiles == smiles else "stereoisomer_or_standardized_variant",
"stereo_index": idx,
"tautomer_index": 0,
"protomer_index": 0,
"conformer_id": 0,
"total_variants_for_parent": n_variants,
"variant_generation_warnings": warning,
"variant_score": score if idx == 0 and score is not None else "",
"variant_cost_runs": 0,
"selected_fidelity_runs": base_runs,
}
)
total_variants += 1
best_parent_rows.append(
{
"parent_ligand_id": parent_id,
"best_variant_id": f"{parent_id}__v01",
"best_variant_score": score if score is not None else "",
"n_variants_generated": n_variants,
"n_variants_docked": 0,
"variant_score_spread": 0.0,
"variant_cost_runs": 0,
"parent_total_cost_runs": int(_float(row.get("n_rdock_runs_total_spent"), 0.0) or 0),
}
)
write_rows_csv(variant_rows, self.out_dir / "tables" / "variant_scores_long.csv")
write_rows_csv(best_parent_rows, self.out_dir / "tables" / "best_variant_per_parent.csv")
parent_level_rows = []
for row in parent_rows:
parent_id = str(row.get("ligand_id", ""))
best = next((item for item in best_parent_rows if str(item["parent_ligand_id"]) == parent_id), None)
parent_level = dict(row)
parent_level["parent_ligand_id"] = parent_id
parent_level["best_variant_id"] = best.get("best_variant_id", "") if best else ""
parent_level["best_variant_score"] = best.get("best_variant_score", "") if best else ""
parent_level["n_variants_generated"] = best.get("n_variants_generated", 0) if best else 0
parent_level["variant_cost_runs"] = best.get("variant_cost_runs", 0) if best else 0
parent_level["parent_total_cost_runs"] = best.get("parent_total_cost_runs", 0) if best else 0
parent_level_rows.append(parent_level)
sorted_parent_level = _sort_by_score(parent_level_rows, "best_variant_score", "final_score", "current_best_score", "SCORE")
write_rows_csv(sorted_parent_level, self.out_dir / "tables" / "final_hits_parent_level_raw.csv")
write_rows_csv(sorted_parent_level, self.out_dir / "tables" / "final_hits_parent_level_downranked.csv")
write_rows_csv(sorted_parent_level, self.out_dir / "tables" / "final_hits_parent_level_filtered.csv")
variant_metrics = {
"variant_generation_backend": backend,
"n_parent_ligands": len(parent_rows),
"n_variants_generated": total_variants,
"n_variants_docked": 0,
"variants_per_parent_distribution": [int(row["n_variants_generated"]) for row in best_parent_rows],
"expansion_factor": total_variants / max(1, len(parent_rows)),
"added_rDock_runs_due_to_variants": total_variant_runs,
"variant_advantage_warning": False,
}
_write_json(self.out_dir / "metrics" / "variant_expansion_metrics.json", variant_metrics)
return variant_metrics
def _run_reference_free_triage_strategy(self, full_rows: list[dict[str, Any]], full_metrics: dict[str, Any]) -> dict[str, Any]:
screenable_rows = self._prefilter_candidate_rows()
self.candidate_rows = screenable_rows
self.candidate_ids = [str(row["ligand_id"]) for row in self.candidate_rows]
self.candidate_id_set = set(self.candidate_ids)
self.state_by_id = {ligand_id: state for ligand_id, state in self.state_by_id.items() if ligand_id in self.candidate_id_set}
survivors: list[dict[str, Any]] = []
triage_metrics: dict[str, Any] = {}
calibration_rows: list[dict[str, Any]] = []
calibration_ids: list[str] = []
calibration_observed: list[dict[str, Any]] = []
validation_ids: list[str] = []
fidelity_payload = {"final_level": self.final_level, "n_multilevel_ligands": 0, "correlations": {}, "rank_recovery": {}, "low_fidelity_reliable": False}
if self.config.strategy == "cluster_only_triage":
selected_rows, selection_metrics = self._cluster_only_selection(screenable_rows)
write_rows_csv(selected_rows, self.out_dir / "tables" / "cluster_only_survivors.csv")
rejected_rows = [row for row in screenable_rows if str(row["ligand_id"]) not in {str(item["ligand_id"]) for item in selected_rows}]
write_rows_csv(rejected_rows, self.out_dir / "tables" / "cluster_only_rejected.csv")
write_rows_csv(selected_rows + rejected_rows, self.out_dir / "tables" / "cluster_only_triage_scores.csv")
if full_rows:
selection_metrics.update(_evaluate_selection_against_reference(full_rows, {str(row["ligand_id"]) for row in selected_rows}, top_fraction=self.config.classifier_top_percentile))
_write_json(self.out_dir / "metrics" / "cluster_only_triage_metrics.json", selection_metrics)
survivors = selected_rows
triage_metrics = {
"initial_ligands": len(screenable_rows),
"triage_survivor_count": len(selected_rows),
"triage_reduction_fraction": 1.0 - (len(selected_rows) / max(1, len(screenable_rows))),
"triage_recall_estimate": selection_metrics.get("top5pct_recall", 1.0 if not full_rows else None),
"triage_false_negative_estimate": (1.0 - float(selection_metrics.get("top5pct_recall", 1.0))) if full_rows and selection_metrics.get("top5pct_recall") is not None else None,
"triage_target_recall": self.config.triage_target_recall,
"safe_to_reduce_95_percent": False,
"safe_to_reduce_99_percent": False,
"confidence_level": "medium" if not full_rows else "high",
"requested_retain_fraction": self.config.triage_retain_fraction,
"final_retain_fraction": len(selected_rows) / max(1, len(screenable_rows)),
"iterations": 1,
"model_useful_for_target_recall": False,
"safe_to_reduce_any_meaningfully": selection_metrics.get("top5pct_recall", 0.0) is not None and float(selection_metrics.get("top5pct_recall", 0.0) or 0.0) >= self.config.triage_target_recall,
}
_write_json(self.out_dir / "metrics" / "triage_metrics.json", triage_metrics)
_write_json(self.out_dir / "metrics" / "triage_controller_metrics.json", {"triage_controller": "none", "iterations": 1})
elif self.config.strategy == "cheap_descriptor_filter_only":
selected_rows, selection_metrics = self._descriptor_filter_selection(screenable_rows)
rejected_rows = [row for row in screenable_rows if str(row["ligand_id"]) not in {str(item["ligand_id"]) for item in selected_rows}]
write_rows_csv(selected_rows, self.out_dir / "tables" / "descriptor_filter_survivors.csv")
write_rows_csv(rejected_rows, self.out_dir / "tables" / "descriptor_filter_rejected.csv")
if full_rows:
selection_metrics.update(_evaluate_selection_against_reference(full_rows, {str(row["ligand_id"]) for row in selected_rows}, top_fraction=self.config.classifier_top_percentile))
_write_json(self.out_dir / "metrics" / "descriptor_filter_metrics.json", selection_metrics)
survivors = selected_rows
triage_metrics = {
"initial_ligands": len(screenable_rows),
"triage_survivor_count": len(selected_rows),
"triage_reduction_fraction": 1.0 - (len(selected_rows) / max(1, len(screenable_rows))),
"triage_recall_estimate": selection_metrics.get("top5pct_recall", 1.0 if not full_rows else None),
"triage_false_negative_estimate": (1.0 - float(selection_metrics.get("top5pct_recall", 1.0))) if full_rows and selection_metrics.get("top5pct_recall") is not None else None,
"triage_target_recall": self.config.triage_target_recall,
"safe_to_reduce_95_percent": False,
"safe_to_reduce_99_percent": False,
"confidence_level": "medium" if not full_rows else "high",
"requested_retain_fraction": self.config.triage_retain_fraction,
"final_retain_fraction": len(selected_rows) / max(1, len(screenable_rows)),
"iterations": 1,
"model_useful_for_target_recall": False,
"safe_to_reduce_any_meaningfully": selection_metrics.get("top5pct_recall", 0.0) is not None and float(selection_metrics.get("top5pct_recall", 0.0) or 0.0) >= self.config.triage_target_recall,
}
_write_json(self.out_dir / "metrics" / "triage_metrics.json", triage_metrics)
_write_json(self.out_dir / "metrics" / "triage_controller_metrics.json", {"triage_controller": "none", "iterations": 1})
else:
calibration_rows = self._select_calibration_rows(screenable_rows)
calibration_level = self.config.fidelity_levels[0]
if calibration_rows:
future_levels = self.config.fidelity_levels[1:]
reserve_for_min_final = self.config.min_final_ligands * sum(future_levels)
reserve_for_validation = max(0, self.config.fidelity_validation_size) * sum(future_levels)
reserved_budget = min(
max(0, self.config.cost_budget_runs - calibration_level),
reserve_for_min_final + reserve_for_validation,
)
max_calibration_affordable = max(
1,
max(1, (self.config.cost_budget_runs - reserved_budget) // max(1, calibration_level)),
)
calibration_rows = calibration_rows[: min(len(calibration_rows), max_calibration_affordable)]
calibration_ids = [str(row["ligand_id"]) for row in calibration_rows]
if not calibration_ids:
raise RDockPipelineError("reference_free_triage_bandit_v1 selected no calibration ligands")
self._emit_progress("triage_calibration:start", {"calibration_size": len(calibration_ids)})
calibration_observed = self._run_level(calibration_level, 0, calibration_ids)
extra_validation_cost = sum(self.config.fidelity_levels[1:])
remaining_after_calibration = max(
0,
self.config.cost_budget_runs - len(calibration_ids) * calibration_level,
)
if extra_validation_cost > 0:
max_validation_affordable = remaining_after_calibration // extra_validation_cost
else:
max_validation_affordable = 0
validation_count = min(
len(calibration_ids),
max(0, self.config.fidelity_validation_size),
max_validation_affordable,
)
validation_ids = [str(row["ligand_id"]) for row in _sort_by_score(calibration_observed, "ranking_score", "SCORE")[:validation_count]]
validation_observed = list(calibration_observed)
if validation_ids:
for idx, level in enumerate(self.config.fidelity_levels[1:], start=1):
validation_observed.extend(self._run_level(level, idx, validation_ids))
labeled_lookup: dict[str, dict[str, Any]] = {}
for row in calibration_observed:
labeled_lookup[str(row["ligand_id"])] = dict(row)
for row in validation_observed:
ligand_id = str(row["ligand_id"])
labeled_lookup.setdefault(ligand_id, {}).update(dict(row))
labeled_rows = [dict(self.model_by_id[ligand_id], **row) for ligand_id, row in labeled_lookup.items()]
write_rows_csv(labeled_rows, self.out_dir / "tables" / "calibration_scores.csv")
fidelity_payload = self._fidelity_reliability_payload(validation_ids)
if not fidelity_payload.get("low_fidelity_reliable", False):
self.config.promotion_policy = "conservative"
self.config.rescue_fraction = max(self.config.rescue_fraction, 0.1)
self.config.uncertainty_rescue = max(self.config.uncertainty_rescue, 10)
survivors, triage_metrics = self._triage_survivors(screenable_rows, labeled_rows)
if full_rows:
cluster_rows, _ = self._cluster_only_selection(screenable_rows)
model_eval = _evaluate_selection_against_reference(full_rows, {str(row["ligand_id"]) for row in survivors}, top_fraction=self.config.classifier_top_percentile)
cluster_eval = _evaluate_selection_against_reference(full_rows, {str(row["ligand_id"]) for row in cluster_rows}, top_fraction=self.config.classifier_top_percentile)
model_beats_cluster_only = False
model_recall = _float(model_eval.get("top5pct_recall"), 0.0) or 0.0
cluster_recall = _float(cluster_eval.get("top5pct_recall"), 0.0) or 0.0
model_reduction = _float(model_eval.get("reduction_fraction"), 0.0) or 0.0
cluster_reduction = _float(cluster_eval.get("reduction_fraction"), 0.0) or 0.0
if model_recall > cluster_recall:
model_beats_cluster_only = True
elif abs(model_recall - cluster_recall) < 1e-9 and model_reduction > cluster_reduction:
model_beats_cluster_only = True
triage_metrics["model_beats_cluster_only"] = model_beats_cluster_only
if not survivors:
raise RDockPipelineError(f"{self.config.strategy} produced no survivors for refinement")
survivor_ids = [str(row["ligand_id"]) for row in survivors]
level_counts = self._policy_level_counts(len(survivor_ids), self.config.fidelity_levels, self.config.cost_budget_runs)
remaining_budget = max(0, self.config.cost_budget_runs - sum(int(_float(state.get("n_rdock_runs_total_spent"), 0.0)) for state in self.state_by_id.values()))
per_level_summary: list[dict[str, Any]] = []
if calibration_ids:
per_level_summary.append(
{
"fidelity_level": calibration_level,
"screened_ligands": len(calibration_ids),
"successful_ligands": sum(1 for row in calibration_observed if int(_float(row.get("selected_fidelity_runs"), calibration_level) or calibration_level) == calibration_level and str(row.get("rdock_success", "")).lower() in {"true", "1"}),
"failed_ligands": sum(1 for row in calibration_observed if int(_float(row.get("selected_fidelity_runs"), calibration_level) or calibration_level) == calibration_level and str(row.get("rdock_success", "")).lower() not in {"true", "1"}),
"outlier_count": sum(1 for row in calibration_observed if int(_float(row.get("selected_fidelity_runs"), calibration_level) or calibration_level) == calibration_level and str(row.get("component_warning", "")).strip()),
}
)
self._emit_progress(
"triage_refinement:start",
{
"survivors": len(survivor_ids),
"remaining_budget_runs": remaining_budget,
"level_counts": level_counts,
},
)
first_level_target = level_counts[0] if level_counts else len(calibration_ids)
already_first_level = {
ligand_id
for ligand_id in survivor_ids
if int(_float(self.state_by_id.get(ligand_id, {}).get("selected_fidelity_runs"), 0.0) or 0) >= calibration_level
}
need_first_level = max(0, min(len(survivor_ids), first_level_target) - len(already_first_level))
if need_first_level > 0 and remaining_budget >= calibration_level:
triage_order = [str(row["ligand_id"]) for row in survivors if str(row["ligand_id"]) not in already_first_level]
max_affordable_first = min(need_first_level, remaining_budget // max(1, calibration_level))
new_first_level_ids = triage_order[:max_affordable_first]
if new_first_level_ids:
new_first_level_rows = self._run_level(calibration_level, len(self.config.fidelity_levels) + 1, new_first_level_ids)
if not per_level_summary:
per_level_summary.append(
{
"fidelity_level": calibration_level,
"screened_ligands": 0,
"successful_ligands": 0,
"failed_ligands": 0,
"outlier_count": 0,
}
)
per_level_summary[0]["screened_ligands"] = int(per_level_summary[0]["screened_ligands"]) + len(new_first_level_ids)
per_level_summary[0]["successful_ligands"] = int(per_level_summary[0]["successful_ligands"]) + sum(
1 for row in new_first_level_rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}
)
per_level_summary[0]["failed_ligands"] = int(per_level_summary[0]["failed_ligands"]) + sum(
1 for row in new_first_level_rows if str(row.get("rdock_success", "")).lower() not in {"true", "1"}
)
per_level_summary[0]["outlier_count"] = int(per_level_summary[0]["outlier_count"]) + sum(
1 for row in new_first_level_rows if str(row.get("component_warning", "")).strip()
)
remaining_budget = max(
0,
self.config.cost_budget_runs - sum(int(_float(state.get("n_rdock_runs_total_spent"), 0.0)) for state in self.state_by_id.values()),
)
for idx, level in enumerate(self.config.fidelity_levels[1:], start=1):
if remaining_budget < level:
break
target_total = level_counts[idx] if idx < len(level_counts) else 0
already_at_level = {
ligand_id
for ligand_id in survivor_ids
if int(_float(self.state_by_id.get(ligand_id, {}).get("selected_fidelity_runs"), 0.0) or 0) >= level
}
need_level = max(0, target_total - len(already_at_level))
if need_level <= 0:
continue
previous_level = self.config.fidelity_levels[idx - 1]
promotion_candidates = self._latest_trace_rows(survivor_ids, min_level=previous_level, max_level_exclusive=level)
if not promotion_candidates:
continue
candidate_ids = [str(row["ligand_id"]) for row in promotion_candidates]
target_affordable = min(need_level, remaining_budget // max(1, level))
if target_affordable <= 0:
break
promoted_ids = self._promote(promotion_candidates, previous_level, level, max(target_affordable, self.config.min_promotion_per_level))
promoted_ids = [ligand_id for ligand_id in promoted_ids if ligand_id in candidate_ids][:target_affordable]
if not promoted_ids:
continue
level_rows = self._run_level(level, 100 + idx, promoted_ids)
successful_count = sum(1 for row in level_rows if str(row.get("rdock_success", "")).lower() in {"true", "1"})
per_level_summary.append(
{
"fidelity_level": level,
"screened_ligands": len(promoted_ids),
"successful_ligands": successful_count,
"failed_ligands": len(promoted_ids) - successful_count,
"outlier_count": sum(1 for row in level_rows if str(row.get("component_warning", "")).strip()),
}
)
remaining_budget = max(
0,
self.config.cost_budget_runs - sum(int(_float(state.get("n_rdock_runs_total_spent"), 0.0)) for state in self.state_by_id.values()),
)
final_promoted = [
ligand_id
for ligand_id in survivor_ids
if int(_float(self.state_by_id.get(ligand_id, {}).get("selected_fidelity_runs"), 0.0) or 0) >= self.final_level
and bool(self.state_by_id.get(ligand_id, {}).get("rdock_success"))
]
if len(final_promoted) < self.config.min_final_ligands and remaining_budget >= self.final_level:
candidate_rows = self._latest_trace_rows(survivor_ids, min_level=self.config.fidelity_levels[0], max_level_exclusive=self.final_level)
candidate_rows = [
row for row in candidate_rows
if str(row.get("rdock_success", "")).lower() in {"true", "1"}
and int(_float(row.get("selected_fidelity_runs"), 0.0) or 0) < self.final_level
]
fallback_target_affordable = min(
max(0, self.config.min_final_ligands - len(final_promoted)),
remaining_budget // max(1, self.final_level),
)
if fallback_target_affordable > 0 and candidate_rows:
promotion_request = max(
fallback_target_affordable,
min(self.config.min_promotion_per_level, len(candidate_rows)),
)
promoted_ids = self._promote(
candidate_rows,
max(int(_float(row.get("selected_fidelity_runs"), 0.0) or 0) for row in candidate_rows),
self.final_level,
promotion_request,
)
if promoted_ids:
promoted_ids = promoted_ids[:fallback_target_affordable]
level_rows = self._run_level(self.final_level, 999, promoted_ids)
successful_count = sum(1 for row in level_rows if str(row.get("rdock_success", "")).lower() in {"true", "1"})
per_level_summary.append(
{
"fidelity_level": self.final_level,
"screened_ligands": len(promoted_ids),
"successful_ligands": successful_count,
"failed_ligands": len(promoted_ids) - successful_count,
"outlier_count": sum(1 for row in level_rows if str(row.get("component_warning", "")).strip()),
"promotion_source": "forced_min_final_ligands",
}
)
return {
"per_level_summary": per_level_summary,
"triage_metrics": triage_metrics,
"fidelity_reliability": fidelity_payload,
}
def run_multifidelity(self) -> dict[str, Any]:
try:
benchmark_started_at = time.time()
self._prepare_output_layout()
observed_rows: list[dict[str, Any]] = []
per_level_summary: list[dict[str, Any]] = []
full_rows, full_metrics = ([], {
"reference_mode": self.config.reference_mode,
"reference_completion_fraction": 0.0,
"reference_ligand_count": 0,
"full_docking_seconds": 0.0,
"n_runs": self.final_level,
"benchmark_status": "BENCHMARK PARTIAL / NOT COMPARABLE" if self.config.reference_mode == "none" else "BENCHMARK COMPLETE",
})
if not self.config.production_reference_free_mode:
full_rows, full_metrics = self._run_full_docking()
if self.reference_free_mode:
triage_payload = self._run_reference_free_triage_strategy(full_rows, full_metrics)
per_level_summary = list(triage_payload["per_level_summary"])
else:
level_counts = self._policy_level_counts(
library_size=len(self.candidate_ids),
levels=self.config.fidelity_levels,
budget_runs=self.config.cost_budget_runs,
)
selected_ids = self._initial_selection(level_counts[0] if level_counts else 0)
self._emit_progress("multifidelity:start", {"level_counts": level_counts, "final_level": self.final_level})
for idx, level in enumerate(self.config.fidelity_levels):
if not selected_ids:
break
level_rows = self._run_level(level, idx, selected_ids)
observed_rows.extend(level_rows)
outlier_count = sum(1 for row in level_rows if str(row.get("intra_outlier", "")).lower() in {"true", "1"})
successful_count = sum(1 for row in level_rows if str(row.get("rdock_success", "")).lower() in {"true", "1"})
per_level_summary.append(
{
"fidelity_level": level,
"screened_ligands": len(selected_ids),
"successful_ligands": successful_count,
"failed_ligands": len(selected_ids) - successful_count,
"outlier_count": outlier_count,
}
)
if idx + 1 < len(self.config.fidelity_levels):
selected_ids = self._promote(level_rows, level, self.config.fidelity_levels[idx + 1], level_counts[idx + 1])
if idx % max(1, self.config.checkpoint_every) == 0:
self._write_checkpoint(
f"level_{level:03d}",
{
"level": level,
"selected_ids": selected_ids,
"summary": per_level_summary[-1],
},
)
else:
selected_ids = []
write_rows_csv(self.trace_rows, self.out_dir / "tables" / "multifidelity_trace.csv")
write_rows_csv(self.trace_rows, self.out_dir / "tables" / "adaptive_queue_trace.csv")
write_rows_csv(self.pre_docking_prediction_rows, self.out_dir / "tables" / "regressor_predictions_pre_docking.csv")
write_rows_csv(self.promotion_rows, self.out_dir / "tables" / "promotion_decisions.csv")
write_rows_csv(self.failed_chunk_rows, self.out_dir / "tables" / "failed_chunks.csv")
write_rows_csv(self.failed_ligand_rows, self.out_dir / "tables" / "failed_ligands.csv")
final_rows = [dict(state) for state in self.state_by_id.values() if not self.config.final_fidelity_only_hits or bool(state["is_final_fidelity"])]
final_rows = [row for row in final_rows if row.get("final_score", "") != "" or not self.config.final_fidelity_only_hits]
final_rows.sort(key=lambda row: (_float(row.get("final_score", row.get("current_best_score")), float("inf")), str(row.get("ligand_id", ""))))
write_rows_csv(final_rows, self.out_dir / "tables" / "final_hits.csv")
final_raw_rows = _sort_by_score([dict(row) for row in final_rows], "final_score", "SCORE", "current_best_score")
for idx, row in enumerate(final_raw_rows, start=1):
row["raw_rank"] = idx
final_downranked_rows = _sort_by_score([dict(row) for row in final_raw_rows], "ranking_score", "final_score", "SCORE")
for idx, row in enumerate(final_downranked_rows, start=1):
row["downranked_rank"] = idx
final_filtered_rows = [
dict(row)
for row in final_downranked_rows
if str(row.get("rdock_success", "")).lower() in {"true", "1"}
and _float(row.get("ranking_score"), float("inf")) < float("inf")
and str(row.get("failed_reason", "")).strip() == ""
]
for idx, row in enumerate(final_filtered_rows, start=1):
row["filtered_rank"] = idx
write_rows_csv(final_raw_rows, self.out_dir / "tables" / "final_hits_raw.csv")
write_rows_csv(final_downranked_rows, self.out_dir / "tables" / "final_hits_downranked.csv")
write_rows_csv(final_filtered_rows, self.out_dir / "tables" / "final_hits_filtered.csv")
outlier_flag_rows: list[dict[str, Any]] = []
raw_rank_by_id = {str(row.get("ligand_id", "")): row.get("raw_rank", "") for row in final_raw_rows}
downranked_rank_by_id = {str(row.get("ligand_id", "")): row.get("downranked_rank", "") for row in final_downranked_rows}
filtered_rank_by_id = {str(row.get("ligand_id", "")): row.get("filtered_rank", "") for row in final_filtered_rows}
for row in final_raw_rows:
ligand_id = str(row.get("ligand_id", ""))
outlier_flag_rows.append(
{
"ligand_id": ligand_id,
"SCORE": row.get("SCORE", row.get("final_score", "")),
"SCORE.INTER": row.get("SCORE.INTER", ""),
"SCORE.INTRA": row.get("SCORE.INTRA", ""),
"SCORE.RESTR": row.get("SCORE.RESTR", ""),
"intra_fraction": row.get("intra_fraction", ""),
"intra_dominance_flag": _bool_text("intra_dominance" in str(row.get("component_warning", ""))),
"component_warning": row.get("component_warning", ""),
"raw_rank": raw_rank_by_id.get(ligand_id, ""),
"downranked_rank": downranked_rank_by_id.get(ligand_id, ""),
"filtered_rank": filtered_rank_by_id.get(ligand_id, ""),
}
)
write_rows_csv(
self._diagnostics_rows(outlier_flag_rows, survivors=final_rows, final_hits=final_filtered_rows),
self.out_dir / "tables" / "outlier_component_flags.csv",
)
variant_metrics = {}
if self.config.final_survivor_enumerate_variants and self.config.variant_stage in {"final_survivors", "posthoc_top_hits"}:
variant_parent_rows = final_rows if final_rows else self._variant_parent_candidates()
variant_metrics = self._enumerate_final_survivor_variants(variant_parent_rows)
total_runs_spent = sum(int(_float(row.get("n_rdock_runs_total_spent"), 0.0)) for row in self.state_by_id.values())
baseline_budget_runs = total_runs_spent if self.config.balanced_baselines else self.config.cost_budget_runs
single_rows: list[dict[str, Any]] = []
random_rows: list[dict[str, Any]] = []
diverse_random_rows: list[dict[str, Any]] = []
single_seconds = 0.0
random_seconds = 0.0
diverse_random_seconds = 0.0
if not self.config.production_reference_free_mode:
single_count = max(1, baseline_budget_runs // self.final_level)
single_rows, single_seconds = self._run_single_fidelity_adaptive(single_count)
random_rows, random_seconds = self._run_random_baseline(baseline_budget_runs, diverse=False)
diverse_random_rows, diverse_random_seconds = self._run_random_baseline(baseline_budget_runs, diverse=True)
full_rank_map = {str(row["ligand_id"]): int(row["full_rank"]) for row in full_rows}
random_ranked = _append_rank_metrics(random_rows, full_rank_map, len(full_rows))
single_ranked = _append_rank_metrics(single_rows, full_rank_map, len(full_rows))
final_ranked = _append_rank_metrics(final_rows, full_rank_map, len(full_rows))
diverse_random_ranked = _append_rank_metrics(diverse_random_rows, full_rank_map, len(full_rows))
write_rows_csv(random_ranked, self.out_dir / "tables" / "random_baseline_scores.csv")
write_rows_csv(single_ranked, self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv")
write_rows_csv(final_ranked, self.out_dir / "tables" / "multifidelity_final_hits_ranked.csv")
write_rows_csv(diverse_random_ranked, self.out_dir / "tables" / "diverse_random_baseline_scores.csv")
full_best = full_rows[0] if full_rows else None
final_only_rows = [row for row in final_ranked if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}]
mf_best = final_only_rows[0] if final_only_rows else None
random_best = min(random_ranked, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf"))) if random_ranked else None
single_best = min(single_ranked, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf"))) if single_ranked else None
diverse_random_best = min(diverse_random_ranked, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf"))) if diverse_random_ranked else None
random_total_runs = sum(int(_float(row.get("n_rdock_runs_total_spent"), self.final_level)) for row in random_ranked)
single_total_runs = sum(int(_float(row.get("n_rdock_runs_total_spent"), self.final_level)) for row in single_ranked)
metrics = {
"strategy": self.config.strategy,
"dataset_dir": str(self.dataset_dir),
"target_id": str(self.manifest.get("pdb_id", self.out_dir.name)).lower(),
"fidelity_levels": self.config.fidelity_levels,
"cost_budget_runs": self.config.cost_budget_runs,
"reference_mode": self.config.reference_mode,
"evaluation_pool_mode": self.config.evaluation_pool_mode,
"benchmark_status": self.benchmark_status,
"best_final_SCORE_found_by_multifidelity": _float(mf_best.get("final_score")) if mf_best else None,
"best_final_SCORE_found_by_random_at_same_cost": _float(random_best.get("final_score", random_best.get("SCORE"))) if random_best else None,
"best_final_SCORE_found_by_diverse_random_at_same_cost": _float(diverse_random_best.get("final_score", diverse_random_best.get("SCORE"))) if diverse_random_best else None,
"best_SCORE_in_full_docking": _float(full_best.get("SCORE")) if full_best else None,
"best_final_SCORE_found_by_single_fidelity": _float(single_best.get("final_score", single_best.get("SCORE"))) if single_best else None,
"multifidelity_percentile_vs_full": _float(mf_best.get("full_percentile")) if mf_best and self.config.reference_mode == "full" and self.reference_completion_fraction >= 0.99 else None,
"random_percentile_vs_full": _float(random_best.get("full_percentile")) if random_best and self.config.reference_mode == "full" and self.reference_completion_fraction >= 0.99 else None,
"single_fidelity_percentile_vs_full": _float(single_best.get("full_percentile")) if single_best and self.config.reference_mode == "full" and self.reference_completion_fraction >= 0.99 else None,
"top1_overlap_vs_full": _top_overlap(full_rows, final_ranked, 1),
"top5_overlap_vs_full": _top_overlap(full_rows, final_ranked, 5),
"top10_overlap_vs_full": _top_overlap(full_rows, final_ranked, 10),
"total_rdock_runs_spent": total_runs_spent,
"multifidelity_total_runs_spent": total_runs_spent,
"random_total_runs_spent": random_total_runs,
"single_fidelity_total_runs_spent": single_total_runs,
"cost_ratio_random_vs_multifidelity": (random_total_runs / total_runs_spent) if total_runs_spent else None,
"cost_ratio_single_vs_multifidelity": (single_total_runs / total_runs_spent) if total_runs_spent else None,
"reference_completion_fraction": self.reference_completion_fraction,
"walltime_total_seconds": time.time() - benchmark_started_at,
"docking_time_seconds": full_metrics["full_docking_seconds"] + self.docking_time_total + single_seconds + random_seconds + diverse_random_seconds,
"training_time_seconds": self.training_time_total,
"parsing_time_seconds": self.parsing_time_total,
"sdf_split_merge_time_seconds": self.sdf_split_merge_time_total,
"scheduler_time_seconds": self.scheduler_time_total,
"io_time_seconds": self.io_time_total,
"overhead_time_seconds": self.overhead_time_total,
"number_of_ligands_screened_at_each_fidelity": per_level_summary,
"number_promoted_between_levels": {
f"{current}->{next_level}": sum(1 for row in self.promotion_rows if row.get("promoted") and row.get("from_level") == current and row.get("to_level") == next_level)
for current, next_level in zip(self.config.fidelity_levels[:-1], self.config.fidelity_levels[1:])
},
"promoted_5_to_10": sum(1 for row in self.promotion_rows if row.get("promoted") and row.get("from_level") == 5 and row.get("to_level") == 10),
"promoted_10_to_15": sum(1 for row in self.promotion_rows if row.get("promoted") and row.get("from_level") == 10 and row.get("to_level") == 15),
"promoted_15_to_30": sum(1 for row in self.promotion_rows if row.get("promoted") and row.get("from_level") == 15 and row.get("to_level") == 30),
"promoted_30_to_50": sum(1 for row in self.promotion_rows if row.get("promoted") and row.get("from_level") == 30 and row.get("to_level") == 50),
"final_fidelity_ligands": len(final_only_rows),
"success_failure_rate_per_fidelity": per_level_summary,
"outlier_count_per_fidelity": {str(row["fidelity_level"]): row["outlier_count"] for row in per_level_summary},
"adaptive_gain_over_random": (
_float(random_best.get("final_score", random_best.get("SCORE"))) - _float(mf_best.get("final_score", mf_best.get("SCORE")))
if mf_best and random_best
else None
),
"final_hits_count": len(final_only_rows),
"raw_final_hits_count": len(final_raw_rows),
"downranked_final_hits_count": len(final_downranked_rows),
"filtered_final_hits_count": len(final_filtered_rows),
"full_docking_success_count": len(full_rows),
"random_final_count": len(random_ranked),
"single_fidelity_final_count": len(single_ranked),
"production_reference_free_mode": self.config.production_reference_free_mode,
"use_reference_features": self.config.use_reference_features,
"variant_expansion_enabled": self.config.final_survivor_enumerate_variants,
"variant_expansion_metrics": variant_metrics,
"production_run_success": True,
"missing_prepared_ligands": len(getattr(self, "missing_prepared_model_rows", [])),
"failed_chunks": len(self.failed_chunk_rows),
"failed_ligands": len(self.failed_ligand_rows),
"records_without_score_dropped": self.rdock_records_without_score_dropped,
}
triage_metrics_path = self.out_dir / "metrics" / "triage_metrics.json"
if triage_metrics_path.exists():
metrics.update(_load_json(triage_metrics_path))
fidelity_metrics_path = self.out_dir / "metrics" / "fidelity_reliability.json"
if fidelity_metrics_path.exists():
fidelity_payload = _load_json(fidelity_metrics_path)
metrics["fidelity_reliability"] = fidelity_payload
metrics["best_raw_hit_score"] = _float(final_raw_rows[0].get("final_score", final_raw_rows[0].get("SCORE")), None) if final_raw_rows else None
metrics["best_filtered_hit_score"] = _float(final_filtered_rows[0].get("final_score", final_filtered_rows[0].get("SCORE")), None) if final_filtered_rows else None
metrics["regressor_used_for_ranking"] = bool(self.current_regressor_used_for_ranking)
metrics["regressor_fallback_reason"] = "" if metrics["regressor_used_for_ranking"] else (
"regressor_validation_weak" if self.config.regressor_contribution_mode != "none" else "regressor_disabled"
)
metrics["effective_regressor_weight"] = self.current_effective_regressor_weight
production_failure_reason = ""
if self.config.production_reference_free_mode:
if not self.promotion_rows:
metrics["production_run_success"] = False
metrics["benchmark_status"] = "PRODUCTION_FAILED_NO_PROMOTIONS"
production_failure_reason = "PRODUCTION_FAILED_NO_FINAL_HITS: no promotion decisions were recorded"
metrics["promotion_failure_reason"] = "no_promotion_decisions"
elif len(final_only_rows) == 0 and self.config.cost_budget_runs > self.final_level:
metrics["production_run_success"] = False
metrics["benchmark_status"] = "PRODUCTION_FAILED_NO_FINAL_HITS"
production_failure_reason = "PRODUCTION_FAILED_NO_FINAL_HITS"
metrics["promotion_failure_reason"] = "no_final_hits"
_write_json(self.out_dir / "metrics" / "adaptive_benchmark_metrics.json", metrics)
_write_json(self.out_dir / "metrics" / "adaptive_benchmark_metrics_raw.json", metrics)
_write_json(self.out_dir / "metrics" / "validation_metrics.json", metrics)
_write_json(self.out_dir / "metrics" / "production_model_metrics.json", metrics)
_write_json(
self.out_dir / "metrics" / "rdock_failure_summary.json",
{
"failure_policy": os.environ.get("RDOCK_CHUNK_FAILURE_POLICY", "mark_failed"),
"failed_chunks": len(self.failed_chunk_rows),
"failed_ligands": len(self.failed_ligand_rows),
"records_without_score_dropped": self.rdock_records_without_score_dropped,
},
)
if self.config.production_reference_free_mode:
triage_scores = self.out_dir / "tables" / "triage_scores.csv"
triage_survivors = self.out_dir / "tables" / "triage_survivors.csv"
triage_rejected = self.out_dir / "tables" / "triage_rejected.csv"
threshold_curve = self.out_dir / "tables" / "threshold_calibration_curve.csv"
if triage_scores.exists():
shutil.copy2(triage_scores, self.out_dir / "tables" / "production_triage_scores.csv")
if triage_survivors.exists():
shutil.copy2(triage_survivors, self.out_dir / "tables" / "production_survivors.csv")
if triage_rejected.exists():
shutil.copy2(triage_rejected, self.out_dir / "tables" / "production_rejected.csv")
if threshold_curve.exists():
shutil.copy2(threshold_curve, self.out_dir / "tables" / "classifier_threshold_curve.csv")
plots = []
full_scores_csv = self.out_dir / "tables" / "full_docking_scores.csv"
if full_scores_csv.exists():
plots.extend(plot_score_outputs(full_scores_csv, self.out_dir / "plots", title_prefix="full docking"))
plots.extend(
plot_multifidelity_outputs(
self.out_dir / "tables" / "multifidelity_trace.csv",
self.out_dir / "tables" / "final_hits.csv",
self.out_dir / "tables" / "random_baseline_scores.csv",
self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv",
full_scores_csv,
self.out_dir / "metrics" / "adaptive_benchmark_metrics.json",
self.out_dir / "plots",
)
)
report_lines = [
f"# {'screen-production-adaptive' if self.config.production_reference_free_mode else 'benchmark-adaptive'}: {self.manifest.get('pdb_id', self.out_dir.name)}",
"",
"## Executive Summary",
f"- benchmark_status: `{metrics.get('benchmark_status')}`",
f"- production_run_success: `{metrics.get('production_run_success')}`",
f"- comparable: `{metrics.get('comparable', 'n/a')}`",
f"- best_filtered_multifidelity: `{metrics.get('best_filtered_hit_score', metrics.get('best_final_SCORE_found_by_multifidelity'))}`",
f"- best_random: `{metrics.get('best_random_filtered_hit_score', metrics.get('best_final_SCORE_found_by_random_at_same_cost'))}`",
"",
"## Input",
f"- dataset_dir: `{self.dataset_dir}`",
f"- strategy: `{self.config.strategy}`",
f"- fidelity_levels: `{','.join(str(v) for v in self.config.fidelity_levels)}`",
f"- cost_budget_runs: `{self.config.cost_budget_runs}`",
f"- jobs: `{self.config.jobs}`",
f"- cpu_fraction: `{self.config.cpu_fraction}`",
"",
"## Triage Safety",
]
for key in [
"initial_ligands",
"triage_survivor_count",
"triage_reduction_fraction",
"triage_recall_estimate",
"triage_false_negative_estimate",
"safe_to_reduce_95_percent",
"safe_to_reduce_99_percent",
"confidence_level",
]:
if key in metrics:
report_lines.append(f"- {key}: `{metrics.get(key)}`")
report_lines.extend([
"",
"## Computational Value",
])
for key in [
"multifidelity_total_runs_spent",
"random_total_runs_spent",
"single_fidelity_total_runs_spent",
"cost_ratio_random_vs_multifidelity",
"cost_ratio_single_vs_multifidelity",
"walltime_total_seconds",
"docking_time_seconds",
"training_time_seconds",
]:
report_lines.append(f"- {key}: `{metrics.get(key)}`")
report_lines.extend([
"",
"## Final Hit Quality",
])
for key in [
"best_final_SCORE_found_by_multifidelity",
"best_final_SCORE_found_by_random_at_same_cost",
"best_final_SCORE_found_by_single_fidelity",
"best_SCORE_in_full_docking",
"multifidelity_percentile_vs_full",
"random_percentile_vs_full",
"single_fidelity_percentile_vs_full",
"adaptive_gain_over_random",
]:
report_lines.append(f"- {key}: `{metrics.get(key)}`")
report_lines.extend([
"",
"## Production Status",
f"- promotion_decisions_count: `{len(self.promotion_rows)}`",
f"- raw_final_hits_count: `{len(final_raw_rows)}`",
f"- filtered_final_hits_count: `{len(final_filtered_rows)}`",
f"- missing_prepared_ligands: `{metrics.get('missing_prepared_ligands')}`",
f"- regressor_used_for_ranking: `{metrics.get('regressor_used_for_ranking')}`",
f"- regressor_fallback_reason: `{metrics.get('regressor_fallback_reason')}`",
])
report_lines.extend([
"",
"## Model operational status",
f"- classifier_status: `{'ok' if not metrics.get('model_signal_too_weak') else 'weak_signal'}`",
f"- regressor_status: `{'enabled' if metrics.get('regressor_used_for_ranking') else 'disabled'}`",
f"- uncertainty_status: `{'enabled' if metrics.get('uncertainty_used_for_acquisition') else 'disabled'}`",
f"- promotion_status: `{'ok' if len(self.promotion_rows) > 0 else 'failed'}`",
f"- final_hit_status: `{'ok' if len(final_filtered_rows) > 0 else 'failed'}`",
f"- comparability_status: `{metrics.get('benchmark_status')}`",
])
report_lines.extend(["", "## Plots"])
report_lines.extend([f"- `{path}`" for path in plots] or ["- No plots generated"])
report_lines.extend(["", "## Top Final Hits"])
for row in final_only_rows[:20]:
report_lines.append(
f"- `{row.get('ligand_id')}` final_score `{row.get('final_score')}` "
f"cluster `{row.get('cluster_id')}` runs_spent `{row.get('n_rdock_runs_total_spent')}` "
f"warning `{row.get('component_warning', '')}`"
)
(self.out_dir / "report.md").write_text("\n".join(report_lines) + "\n", encoding="utf-8")
manifest = {
"engine": "benchmark-adaptive",
"strategy": self.config.strategy,
"dataset_dir": str(self.dataset_dir),
"artifacts": {
"target_dir": str(self.out_dir / "target"),
"ligands_sdf": str(self.out_dir / "ligands" / "all_ligands.sdf"),
"full_docking_scores": str(self.out_dir / "tables" / "full_docking_scores.csv"),
"random_baseline_scores": str(self.out_dir / "tables" / "random_baseline_scores.csv"),
"single_fidelity_scores": str(self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv"),
"multifidelity_trace": str(self.out_dir / "tables" / "multifidelity_trace.csv"),
"promotion_decisions": str(self.out_dir / "tables" / "promotion_decisions.csv"),
"final_hits": str(self.out_dir / "tables" / "final_hits.csv"),
"metrics_json": str(self.out_dir / "metrics" / "adaptive_benchmark_metrics.json"),
"report": str(self.out_dir / "report.md"),
},
"executables": {
"rbdock": probe_version(require_executable("rbdock")),
"rbcavity": probe_version(require_executable("rbcavity")),
"obabel": probe_version(require_executable("obabel")),
},
"metrics": metrics,
}
_write_json(self.out_dir / "manifest.json", manifest)
_write_yaml_like(
self.out_dir / "config.yaml",
{
"dataset_dir": str(self.dataset_dir),
"strategy": self.config.strategy,
"fidelity_levels": self.config.fidelity_levels,
"cost_budget_runs": self.config.cost_budget_runs,
"promotion_fraction": self.config.promotion_fraction,
"min_per_cluster": self.config.min_per_cluster,
"max_per_cluster": self.config.max_per_cluster,
"outlier_intra_z_threshold": self.config.outlier_intra_z_threshold,
"score_component_filter": self.config.score_component_filter,
"final_fidelity_only_hits": self.config.final_fidelity_only_hits,
"jobs": self.config.jobs,
"cpu_fraction": self.config.cpu_fraction,
"resume": self.config.resume,
},
)
audit_payload = audit_benchmark_run(self.out_dir)
validation_payload = None
try:
from .validate_benchmark_model import validate_benchmark_model
validation_payload = validate_benchmark_model(self.out_dir)
except Exception:
validation_payload = None
self._write_checkpoint("completed", {"metrics": metrics})
if production_failure_reason:
self._write_checkpoint("failure", {"error": production_failure_reason, "metrics": metrics})
raise RDockPipelineError(production_failure_reason)
self._emit_progress("benchmark:done", {"run_dir": str(self.out_dir), "metrics_path": str(self.out_dir / "metrics" / "adaptive_benchmark_metrics.json")})
return {"run_dir": str(self.out_dir), "metrics": metrics, "audit": audit_payload, "validation": validation_payload}
except Exception as exc:
failure = {
"error": str(exc),
"traceback": traceback.format_exc(),
"dataset_dir": str(self.dataset_dir),
"out_dir": str(self.out_dir),
}
self._write_checkpoint("failure", failure)
self._emit_progress("benchmark:failed", {"error": str(exc), "failure_checkpoint": str(self.out_dir / "checkpoints" / "failure.json")})
raise
def build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Run adaptive rDock benchmark from a prepared dataset directory.")
parser.add_argument("--dataset-dir", required=True)
parser.add_argument("--strategy", default="cost_balanced_diverse_multifidelity_surrogate", choices=["multifidelity_adaptive_rdock", "single_fidelity_adaptive_rdock", "cost_balanced_diverse_multifidelity_surrogate", "reference_free_triage_bandit_v1", "reference_free_active_learning_v2", "reference_free_active_learning_v3_diverse_ranker", "reference_free_active_learning_v3_lean", "random_cost_balanced", "diverse_random_cost_balanced", "cluster_only_triage", "single_fidelity_cost_balanced", "cheap_descriptor_filter_only"])
parser.add_argument("--fidelity-levels", default="5,10,15,30,50")
parser.add_argument("--cost-budget-runs", type=int, required=True)
parser.add_argument("--adaptive-budget-ligands", type=int)
parser.add_argument("--promotion-fraction", type=float, default=0.5)
parser.add_argument("--min-per-cluster", type=int, default=1)
parser.add_argument("--max-per-cluster", type=int, default=50)
parser.add_argument("--outlier-intra-z-threshold", type=float, default=3.0)
parser.add_argument("--score-component-filter", default="warn")
parser.add_argument("--final-fidelity-only-hits", default="true")
parser.add_argument("--reference-mode", default="full", choices=["full", "sampled", "none"])
parser.add_argument("--evaluation-pool-mode", default="same_pool", choices=["same_pool", "candidate_pool"])
parser.add_argument("--reference-sample-size", type=int, default=5000)
parser.add_argument("--reference-sample-seed", type=int, default=42)
parser.add_argument("--balanced-baselines", default="true")
parser.add_argument("--posthoc-score-selected-hits", default="false")
parser.add_argument("--posthoc-final-runs", type=int, default=50)
parser.add_argument("--force-resume-stale", action="store_true")
parser.add_argument("--outlier-policy", default="downrank", choices=["flag", "downrank", "exclude"])
parser.add_argument("--intra-z-threshold", type=float, default=4.0)
parser.add_argument("--score-z-threshold", type=float, default=5.0)
parser.add_argument("--max-intra-fraction", type=float, default=0.75)
parser.add_argument("--max-intra-fraction-soft", type=float, default=0.75)
parser.add_argument("--max-intra-fraction-hard", type=float, default=0.9)
parser.add_argument("--exploration-fraction", type=float, default=0.35)
parser.add_argument("--diversity-weight", type=float, default=0.75)
parser.add_argument("--uncertainty-weight", type=float, default=0.35)
parser.add_argument("--outlier-risk-weight", type=float, default=2.0)
parser.add_argument("--cluster-min-coverage", type=int, default=1)
parser.add_argument("--use-reference-features", default="false")
parser.add_argument("--production-reference-free", default="false")
parser.add_argument("--calibration-size", type=int, default=0)
parser.add_argument("--calibration-fraction", type=float, default=0.2)
parser.add_argument("--min-clusters-covered", type=int, default=8)
parser.add_argument("--calibration-random-fraction", type=float, default=0.15)
parser.add_argument("--calibration-diversity-weight", type=float, default=1.0)
parser.add_argument("--fidelity-validation-size", type=int, default=50)
parser.add_argument("--fidelity-validation-policy", default="cluster_stratified", choices=["diverse", "random", "cluster_stratified"])
parser.add_argument("--promotion-policy", default="conservative", choices=["conservative", "adaptive", "aggressive", "exploit_heavy", "balanced", "explore_heavy", "quota_ladder"])
parser.add_argument("--min-final-ligands", type=int, default=20)
parser.add_argument("--min-promotion-per-level", type=int, default=8)
parser.add_argument("--promotion-fraction-by-level", default="")
parser.add_argument("--triage-retain-fraction", type=float, default=0.05)
parser.add_argument("--triage-target-recall", type=float, default=0.98)
parser.add_argument("--triage-min-survivors", type=int, default=50)
parser.add_argument("--triage-max-survivors", type=int, default=0)
parser.add_argument("--cluster-min-survivors", type=int, default=1)
parser.add_argument("--cluster-max-survivors", type=int, default=0)
parser.add_argument("--rescue-fraction", type=float, default=0.05)
parser.add_argument("--rare-cluster-rescue", type=int, default=20)
parser.add_argument("--uncertainty-rescue", type=int, default=20)
parser.add_argument("--allow-low-confidence-triage", action="store_true")
parser.add_argument("--top-good-fraction", type=float, default=0.1)
parser.add_argument("--minimum-training-ligands", type=int, default=50)
parser.add_argument("--triage-controller", default="auto_recall", choices=["auto_recall", "fixed"])
parser.add_argument("--max-retain-fraction-before-not-useful", type=float, default=0.5)
parser.add_argument("--classifier-top-percentile", type=float, default=0.1)
parser.add_argument("--triage-model", default="classifier")
parser.add_argument("--classifier-threshold-mode", default="recall_target")
parser.add_argument("--classifier-min-positives", type=int, default=10)
parser.add_argument("--classifier-holdout-fraction", type=float, default=0.25)
parser.add_argument("--classifier-fallback", default="cluster_only")
parser.add_argument("--model-fallback-if-worse", default="none")
parser.add_argument("--survivor-combination-policy", default="model_only")
parser.add_argument("--adaptive-policy", default="hybrid_rank", choices=["classifier_only", "classifier_uncertainty", "classifier_uncertainty_diversity", "classifier_plus_regressor_plus_cluster_quality", "hybrid_rank", "ucb_like", "cluster_bandit"])
parser.add_argument("--regressor-contribution-mode", default="linear", choices=["none", "linear", "gate", "rescue"])
parser.add_argument("--classifier-weight", type=float, default=1.0)
parser.add_argument("--regressor-weight", type=float, default=0.35)
parser.add_argument("--cluster-quality-weight", type=float, default=0.5)
parser.add_argument("--fixed-score-regressor-name", default="fixed_score_regressor_v1")
parser.add_argument("--fixed-score-regressor-target", default="component_sane_affinity_like")
parser.add_argument("--regressor-model-type", default="extra_trees", choices=["extra_trees", "random_forest", "hist_gradient_boosting", "ridge"])
parser.add_argument("--model-validation-split", default="cluster", choices=["random", "cluster"])
parser.add_argument("--cluster-quota", type=int, default=0)
parser.add_argument("--promotion-temperature", type=float, default=1.0)
parser.add_argument("--diagnostics-level", default="standard", choices=["minimal", "standard", "full"])
parser.add_argument("--classifier-gate-fraction", type=float, default=0.15)
parser.add_argument("--classifier-max-gate-fraction", type=float, default=0.2)
parser.add_argument("--final-survivor-enumerate-variants", default="false")
parser.add_argument("--variant-stage", default="none")
parser.add_argument("--enumerate-stereoisomers", default="none")
parser.add_argument("--max-stereoisomers-per-parent", type=int, default=2)
parser.add_argument("--enumerate-tautomers", default="none")
parser.add_argument("--max-tautomers-per-parent", type=int, default=1)
parser.add_argument("--enumerate-protonation", default="none")
parser.add_argument("--ph", type=float, default=7.4)
parser.add_argument("--max-protomer-states-per-parent", type=int, default=1)
parser.add_argument("--max-conformers-per-variant", type=int, default=1)
parser.add_argument("--max-total-variants-per-parent", type=int, default=1)
parser.add_argument("--posthoc-top-parents", type=int, default=100)
parser.add_argument("--posthoc-max-total-variants-per-parent", type=int, default=20)
parser.add_argument("--variant-fairness-policy", default="cap")
parser.add_argument("--allow-no-rdkit-parent-only", action="store_true")
parser.add_argument("--chunk-size", type=int, default=50)
parser.add_argument("--rdock-timeout-seconds", type=int, default=3600)
parser.add_argument("--resume", action="store_true")
parser.add_argument("--checkpoint-every", type=int, default=1)
parser.add_argument("--jobs", default="auto")
parser.add_argument("--cpu-fraction", type=float, default=0.85)
parser.add_argument("--out", required=True)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--plan-only", action="store_true")
return parser
def run_from_args(args: argparse.Namespace) -> dict[str, Any]:
levels = _parse_levels(args.fidelity_levels)
dataset_summary = validate_dataset_dir(args.dataset_dir, check_rdock_tools=False)
plan = {
"dataset_dir": args.dataset_dir,
"strategy": args.strategy,
"fidelity_levels": levels,
"cost_budget_runs": int(args.cost_budget_runs),
"adaptive_budget_ligands": args.adaptive_budget_ligands,
"promotion_fraction": float(args.promotion_fraction),
"min_per_cluster": int(args.min_per_cluster),
"max_per_cluster": int(args.max_per_cluster),
"outlier_intra_z_threshold": float(args.outlier_intra_z_threshold),
"score_component_filter": args.score_component_filter,
"final_fidelity_only_hits": str(args.final_fidelity_only_hits).lower() in {"1", "true", "yes", "y"},
"reference_mode": args.reference_mode,
"evaluation_pool_mode": args.evaluation_pool_mode,
"reference_sample_size": int(args.reference_sample_size),
"reference_sample_seed": int(args.reference_sample_seed),
"balanced_baselines": str(args.balanced_baselines).lower() in {"1", "true", "yes", "y"},
"posthoc_score_selected_hits": str(args.posthoc_score_selected_hits).lower() in {"1", "true", "yes", "y"},
"posthoc_final_runs": int(args.posthoc_final_runs),
"force_resume_stale": bool(args.force_resume_stale),
"outlier_policy": args.outlier_policy,
"intra_z_threshold": float(args.intra_z_threshold),
"score_z_threshold": float(args.score_z_threshold),
"max_intra_fraction": float(args.max_intra_fraction),
"max_intra_fraction_soft": float(args.max_intra_fraction_soft),
"max_intra_fraction_hard": float(args.max_intra_fraction_hard),
"exploration_fraction": float(args.exploration_fraction),
"diversity_weight": float(args.diversity_weight),
"uncertainty_weight": float(args.uncertainty_weight),
"outlier_risk_weight": float(args.outlier_risk_weight),
"cluster_min_coverage": int(args.cluster_min_coverage),
"use_reference_features": _bool_arg(args.use_reference_features, False),
"production_reference_free_mode": _bool_arg(args.production_reference_free, False),
"calibration_size": int(args.calibration_size),
"calibration_fraction": float(args.calibration_fraction),
"min_clusters_covered": int(args.min_clusters_covered),
"calibration_random_fraction": float(args.calibration_random_fraction),
"calibration_diversity_weight": float(args.calibration_diversity_weight),
"fidelity_validation_size": int(args.fidelity_validation_size),
"fidelity_validation_policy": str(args.fidelity_validation_policy),
"promotion_policy": str(args.promotion_policy),
"min_final_ligands": int(args.min_final_ligands),
"min_promotion_per_level": int(args.min_promotion_per_level),
"promotion_fraction_by_level": str(args.promotion_fraction_by_level),
"triage_retain_fraction": float(args.triage_retain_fraction),
"triage_target_recall": float(args.triage_target_recall),
"triage_min_survivors": int(args.triage_min_survivors),
"triage_max_survivors": int(args.triage_max_survivors),
"cluster_min_survivors": int(args.cluster_min_survivors),
"cluster_max_survivors": int(args.cluster_max_survivors),
"rescue_fraction": float(args.rescue_fraction),
"rare_cluster_rescue": int(args.rare_cluster_rescue),
"uncertainty_rescue": int(args.uncertainty_rescue),
"allow_low_confidence_triage": bool(args.allow_low_confidence_triage),
"top_good_fraction": float(args.top_good_fraction),
"minimum_training_ligands": int(args.minimum_training_ligands),
"triage_controller": str(getattr(args, "triage_controller", "auto_recall")),
"max_retain_fraction_before_not_useful": float(getattr(args, "max_retain_fraction_before_not_useful", 0.5)),
"classifier_top_percentile": float(getattr(args, "classifier_top_percentile", 0.1)),
"triage_model": str(getattr(args, "triage_model", "classifier")),
"classifier_threshold_mode": str(getattr(args, "classifier_threshold_mode", "recall_target")),
"classifier_min_positives": int(getattr(args, "classifier_min_positives", 10)),
"classifier_holdout_fraction": float(getattr(args, "classifier_holdout_fraction", 0.25)),
"classifier_fallback": str(getattr(args, "classifier_fallback", "cluster_only")),
"model_fallback_if_worse": str(getattr(args, "model_fallback_if_worse", "none")),
"survivor_combination_policy": str(getattr(args, "survivor_combination_policy", "model_only")),
"adaptive_policy": str(getattr(args, "adaptive_policy", "hybrid_rank")),
"regressor_contribution_mode": str(getattr(args, "regressor_contribution_mode", "linear")),
"classifier_weight": float(getattr(args, "classifier_weight", 1.0)),
"regressor_weight": float(getattr(args, "regressor_weight", 0.35)),
"cluster_quality_weight": float(getattr(args, "cluster_quality_weight", 0.5)),
"fixed_score_regressor_name": str(getattr(args, "fixed_score_regressor_name", "fixed_score_regressor_v1")),
"fixed_score_regressor_target": str(getattr(args, "fixed_score_regressor_target", "component_sane_affinity_like")),
"regressor_model_type": str(getattr(args, "regressor_model_type", "extra_trees")),
"model_validation_split": str(getattr(args, "model_validation_split", "cluster")),
"cluster_quota": int(getattr(args, "cluster_quota", 0)),
"promotion_temperature": float(getattr(args, "promotion_temperature", 1.0)),
"final_survivor_enumerate_variants": _bool_arg(getattr(args, "final_survivor_enumerate_variants", "false"), False),
"variant_stage": str(getattr(args, "variant_stage", "none")),
"enumerate_stereoisomers": str(getattr(args, "enumerate_stereoisomers", "none")),
"max_stereoisomers_per_parent": int(getattr(args, "max_stereoisomers_per_parent", 2)),
"enumerate_tautomers": str(getattr(args, "enumerate_tautomers", "none")),
"max_tautomers_per_parent": int(getattr(args, "max_tautomers_per_parent", 1)),
"enumerate_protonation": str(getattr(args, "enumerate_protonation", "none")),
"ph": float(getattr(args, "ph", 7.4)),
"max_protomer_states_per_parent": int(getattr(args, "max_protomer_states_per_parent", 1)),
"max_conformers_per_variant": int(getattr(args, "max_conformers_per_variant", 1)),
"max_total_variants_per_parent": int(getattr(args, "max_total_variants_per_parent", 1)),
"posthoc_top_parents": int(getattr(args, "posthoc_top_parents", 100)),
"posthoc_max_total_variants_per_parent": int(getattr(args, "posthoc_max_total_variants_per_parent", 20)),
"variant_fairness_policy": str(getattr(args, "variant_fairness_policy", "cap")),
"allow_no_rdkit_parent_only": bool(getattr(args, "allow_no_rdkit_parent_only", False)),
"diagnostics_level": str(getattr(args, "diagnostics_level", "standard")),
"classifier_gate_fraction": float(getattr(args, "classifier_gate_fraction", 0.15)),
"classifier_max_gate_fraction": float(getattr(args, "classifier_max_gate_fraction", 0.2)),
"rdock_timeout_seconds": int(getattr(args, "rdock_timeout_seconds", 3600)),
"jobs": args.jobs,
"cpu_fraction": float(args.cpu_fraction),
"dataset_summary": dataset_summary,
}
out_dir = Path(args.out)
out_dir.mkdir(parents=True, exist_ok=True)
if args.dry_run or args.plan_only:
_write_json(out_dir / "benchmark_adaptive_plan.json", plan)
return plan
config = MultiFidelityConfig(
strategy=args.strategy,
fidelity_levels=levels,
cost_budget_runs=int(args.cost_budget_runs),
adaptive_budget_ligands=args.adaptive_budget_ligands,
promotion_fraction=float(args.promotion_fraction),
min_per_cluster=int(args.min_per_cluster),
max_per_cluster=int(args.max_per_cluster),
outlier_intra_z_threshold=float(args.outlier_intra_z_threshold),
score_component_filter=str(args.score_component_filter),
final_fidelity_only_hits=str(args.final_fidelity_only_hits).lower() in {"1", "true", "yes", "y"},
checkpoint_every=int(args.checkpoint_every),
jobs=args.jobs,
cpu_fraction=float(args.cpu_fraction),
resume=bool(args.resume),
reference_mode=str(args.reference_mode),
evaluation_pool_mode=str(args.evaluation_pool_mode),
balanced_baselines=str(args.balanced_baselines).lower() in {"1", "true", "yes", "y"},
reference_sample_size=int(args.reference_sample_size),
reference_sample_seed=int(args.reference_sample_seed),
posthoc_score_selected_hits=str(args.posthoc_score_selected_hits).lower() in {"1", "true", "yes", "y"},
posthoc_final_runs=int(args.posthoc_final_runs),
force_resume_stale=bool(args.force_resume_stale),
outlier_policy=str(args.outlier_policy),
intra_z_threshold=float(args.intra_z_threshold),
score_z_threshold=float(args.score_z_threshold),
max_intra_fraction=float(args.max_intra_fraction),
max_intra_fraction_soft=float(args.max_intra_fraction_soft),
max_intra_fraction_hard=float(args.max_intra_fraction_hard),
exploration_fraction=float(args.exploration_fraction),
diversity_weight=float(args.diversity_weight),
uncertainty_weight=float(args.uncertainty_weight),
outlier_risk_weight=float(args.outlier_risk_weight),
cluster_min_coverage=int(args.cluster_min_coverage),
use_reference_features=_bool_arg(args.use_reference_features, False),
production_reference_free_mode=_bool_arg(args.production_reference_free, False),
calibration_size=int(args.calibration_size),
calibration_fraction=float(args.calibration_fraction),
min_clusters_covered=int(args.min_clusters_covered),
calibration_random_fraction=float(args.calibration_random_fraction),
calibration_diversity_weight=float(args.calibration_diversity_weight),
fidelity_validation_size=int(args.fidelity_validation_size),
fidelity_validation_policy=str(args.fidelity_validation_policy),
promotion_policy=str(args.promotion_policy),
min_final_ligands=int(args.min_final_ligands),
min_promotion_per_level=int(args.min_promotion_per_level),
promotion_fraction_by_level=str(args.promotion_fraction_by_level),
triage_retain_fraction=float(args.triage_retain_fraction),
triage_target_recall=float(args.triage_target_recall),
triage_min_survivors=int(args.triage_min_survivors),
triage_max_survivors=int(args.triage_max_survivors),
cluster_min_survivors=int(args.cluster_min_survivors),
cluster_max_survivors=int(args.cluster_max_survivors),
rescue_fraction=float(args.rescue_fraction),
rare_cluster_rescue=int(args.rare_cluster_rescue),
uncertainty_rescue=int(args.uncertainty_rescue),
allow_low_confidence_triage=bool(args.allow_low_confidence_triage),
top_good_fraction=float(args.top_good_fraction),
minimum_training_ligands=int(args.minimum_training_ligands),
triage_controller=str(getattr(args, "triage_controller", "auto_recall")),
max_retain_fraction_before_not_useful=float(getattr(args, "max_retain_fraction_before_not_useful", 0.5)),
classifier_top_percentile=float(getattr(args, "classifier_top_percentile", 0.1)),
triage_model=str(getattr(args, "triage_model", "classifier")),
classifier_threshold_mode=str(getattr(args, "classifier_threshold_mode", "recall_target")),
classifier_min_positives=int(getattr(args, "classifier_min_positives", 10)),
classifier_holdout_fraction=float(getattr(args, "classifier_holdout_fraction", 0.25)),
classifier_fallback=str(getattr(args, "classifier_fallback", "cluster_only")),
model_fallback_if_worse=str(getattr(args, "model_fallback_if_worse", "none")),
survivor_combination_policy=str(getattr(args, "survivor_combination_policy", "model_only")),
adaptive_policy=str(getattr(args, "adaptive_policy", "hybrid_rank")),
regressor_contribution_mode=str(getattr(args, "regressor_contribution_mode", "linear")),
classifier_weight=float(getattr(args, "classifier_weight", 1.0)),
regressor_weight=float(getattr(args, "regressor_weight", 0.35)),
cluster_quality_weight=float(getattr(args, "cluster_quality_weight", 0.5)),
fixed_score_regressor_name=str(getattr(args, "fixed_score_regressor_name", "fixed_score_regressor_v1")),
fixed_score_regressor_target=str(getattr(args, "fixed_score_regressor_target", "component_sane_affinity_like")),
regressor_model_type=str(getattr(args, "regressor_model_type", "extra_trees")),
model_validation_split=str(getattr(args, "model_validation_split", "cluster")),
cluster_quota=int(getattr(args, "cluster_quota", 0)),
promotion_temperature=float(getattr(args, "promotion_temperature", 1.0)),
final_survivor_enumerate_variants=_bool_arg(getattr(args, "final_survivor_enumerate_variants", "false"), False),
variant_stage=str(getattr(args, "variant_stage", "none")),
enumerate_stereoisomers=str(getattr(args, "enumerate_stereoisomers", "none")),
max_stereoisomers_per_parent=int(getattr(args, "max_stereoisomers_per_parent", 2)),
enumerate_tautomers=str(getattr(args, "enumerate_tautomers", "none")),
max_tautomers_per_parent=int(getattr(args, "max_tautomers_per_parent", 1)),
enumerate_protonation=str(getattr(args, "enumerate_protonation", "none")),
ph=float(getattr(args, "ph", 7.4)),
max_protomer_states_per_parent=int(getattr(args, "max_protomer_states_per_parent", 1)),
max_conformers_per_variant=int(getattr(args, "max_conformers_per_variant", 1)),
max_total_variants_per_parent=int(getattr(args, "max_total_variants_per_parent", 1)),
posthoc_top_parents=int(getattr(args, "posthoc_top_parents", 100)),
posthoc_max_total_variants_per_parent=int(getattr(args, "posthoc_max_total_variants_per_parent", 20)),
variant_fairness_policy=str(getattr(args, "variant_fairness_policy", "cap")),
allow_no_rdkit_parent_only=bool(getattr(args, "allow_no_rdkit_parent_only", False)),
diagnostics_level=str(getattr(args, "diagnostics_level", "standard")),
classifier_gate_fraction=float(getattr(args, "classifier_gate_fraction", 0.15)),
classifier_max_gate_fraction=float(getattr(args, "classifier_max_gate_fraction", 0.2)),
)
engine = RDockEngine(
RDockRunConfig(
n_runs=levels[-1],
jobs=args.jobs,
cpu_fraction=float(args.cpu_fraction),
timeout_seconds=int(getattr(args, "rdock_timeout_seconds", 3600)),
chunk_size=int(getattr(args, "chunk_size", 0) or 0) or None,
)
)
runner = MultiFidelityAdaptiveRunner(args.dataset_dir, args.out, engine, config)
return runner.run_multifidelity()
def run_reference_free_from_args(args: argparse.Namespace) -> dict[str, Any]:
if not getattr(args, "dataset_dir", None):
raise RDockPipelineError("screen-reference-free currently requires --dataset-dir")
defaults = {
"strategy": "reference_free_triage_bandit_v1",
"reference_mode": "none",
"evaluation_pool_mode": "same_pool",
"balanced_baselines": "false",
"production_reference_free": "true",
"adaptive_budget_ligands": None,
"promotion_fraction": 0.5,
"min_per_cluster": 1,
"max_per_cluster": 50,
"outlier_intra_z_threshold": 3.0,
"score_component_filter": "warn",
"final_fidelity_only_hits": "true",
"reference_sample_size": 0,
"reference_sample_seed": 42,
"posthoc_score_selected_hits": "false",
"posthoc_final_runs": 50,
"force_resume_stale": False,
"outlier_policy": "downrank",
"intra_z_threshold": 4.0,
"score_z_threshold": 5.0,
"max_intra_fraction": 0.75,
"max_intra_fraction_soft": 0.75,
"max_intra_fraction_hard": 0.9,
"exploration_fraction": 0.35,
"cluster_min_coverage": 1,
"calibration_fraction": 0.2,
"min_clusters_covered": 8,
"calibration_random_fraction": 0.15,
"calibration_diversity_weight": 1.0,
"fidelity_validation_size": 200,
"fidelity_validation_policy": "cluster_stratified",
"promotion_fraction_by_level": "",
"triage_min_survivors": 50,
"triage_max_survivors": 0,
"cluster_min_survivors": 1,
"cluster_max_survivors": 0,
"rescue_fraction": 0.05,
"rare_cluster_rescue": 20,
"uncertainty_rescue": 20,
"allow_low_confidence_triage": False,
"top_good_fraction": 0.1,
"minimum_training_ligands": 50,
"use_reference_features": "false",
"triage_controller": "auto_recall",
"max_retain_fraction_before_not_useful": 0.5,
"classifier_top_percentile": 0.1,
"triage_model": "classifier",
"classifier_threshold_mode": "recall_target",
"classifier_min_positives": 10,
"classifier_holdout_fraction": 0.25,
"classifier_fallback": "cluster_only",
"model_fallback_if_worse": "none",
"survivor_combination_policy": "model_only",
"adaptive_policy": "hybrid_rank",
"regressor_contribution_mode": "linear",
"classifier_weight": 1.0,
"regressor_weight": 0.35,
"cluster_quality_weight": 0.5,
"fixed_score_regressor_name": "fixed_score_regressor_v1",
"fixed_score_regressor_target": "component_sane_affinity_like",
"regressor_model_type": "extra_trees",
"cluster_quota": 0,
"promotion_temperature": 1.0,
"final_survivor_enumerate_variants": "false",
"variant_stage": "none",
"enumerate_stereoisomers": "none",
"max_stereoisomers_per_parent": 2,
"enumerate_tautomers": "none",
"max_tautomers_per_parent": 1,
"enumerate_protonation": "none",
"ph": 7.4,
"max_protomer_states_per_parent": 1,
"max_conformers_per_variant": 1,
"max_total_variants_per_parent": 1,
"posthoc_top_parents": 100,
"posthoc_max_total_variants_per_parent": 20,
"variant_fairness_policy": "cap",
"allow_no_rdkit_parent_only": False,
"checkpoint_every": 1,
}
for key, value in defaults.items():
if not hasattr(args, key):
setattr(args, key, value)
return run_from_args(args)
def run_production_from_args(args: argparse.Namespace) -> dict[str, Any]:
if not getattr(args, "dataset_dir", None):
raise RDockPipelineError("screen-production-adaptive currently requires --dataset-dir")
defaults = {
"strategy": "reference_free_active_learning_v2",
"reference_mode": "none",
"evaluation_pool_mode": "same_pool",
"balanced_baselines": "false",
"production_reference_free": "true",
"adaptive_budget_ligands": None,
"promotion_fraction": 0.5,
"min_per_cluster": 1,
"max_per_cluster": 50,
"outlier_intra_z_threshold": 3.0,
"score_component_filter": "warn",
"final_fidelity_only_hits": "true",
"reference_sample_size": 0,
"reference_sample_seed": 42,
"posthoc_score_selected_hits": "false",
"posthoc_final_runs": 50,
"force_resume_stale": False,
"outlier_policy": "downrank",
"intra_z_threshold": 4.0,
"score_z_threshold": 5.0,
"max_intra_fraction": 0.75,
"max_intra_fraction_soft": 0.75,
"max_intra_fraction_hard": 0.9,
"exploration_fraction": 0.35,
"cluster_min_coverage": 1,
"calibration_fraction": 0.2,
"min_clusters_covered": 8,
"calibration_random_fraction": 0.15,
"calibration_diversity_weight": 1.0,
"fidelity_validation_size": 200,
"fidelity_validation_policy": "cluster_stratified",
"promotion_fraction_by_level": "",
"triage_min_survivors": 50,
"triage_max_survivors": 0,
"cluster_min_survivors": 1,
"cluster_max_survivors": 0,
"rescue_fraction": 0.05,
"rare_cluster_rescue": 20,
"uncertainty_rescue": 20,
"allow_low_confidence_triage": False,
"top_good_fraction": 0.1,
"minimum_training_ligands": 50,
"use_reference_features": "false",
"triage_controller": "auto_recall",
"max_retain_fraction_before_not_useful": 0.5,
"classifier_top_percentile": 0.05,
"triage_model": "classifier",
"classifier_threshold_mode": "recall_target",
"classifier_min_positives": 10,
"classifier_holdout_fraction": 0.25,
"classifier_fallback": "cluster_only",
"model_fallback_if_worse": "none",
"survivor_combination_policy": "model_only",
"adaptive_policy": "cluster_bandit",
"regressor_contribution_mode": "gate",
"classifier_weight": 1.0,
"regressor_weight": 0.2,
"cluster_quality_weight": 0.5,
"fixed_score_regressor_name": "fixed_score_regressor_v1",
"fixed_score_regressor_target": "component_sane_affinity_like",
"regressor_model_type": "extra_trees",
"cluster_quota": 0,
"promotion_temperature": 1.0,
"calibration_size": 12000,
"triage_target_recall": 0.95,
"diversity_weight": 0.75,
"uncertainty_weight": 0.35,
"outlier_risk_weight": 2.0,
"final_survivor_enumerate_variants": "false",
"variant_stage": "none",
"enumerate_stereoisomers": "none",
"max_stereoisomers_per_parent": 2,
"enumerate_tautomers": "none",
"max_tautomers_per_parent": 1,
"enumerate_protonation": "none",
"ph": 7.4,
"max_protomer_states_per_parent": 1,
"max_conformers_per_variant": 1,
"max_total_variants_per_parent": 1,
"posthoc_top_parents": 100,
"posthoc_max_total_variants_per_parent": 20,
"variant_fairness_policy": "cap",
"allow_no_rdkit_parent_only": False,
"checkpoint_every": 1,
}
for key, value in defaults.items():
if not hasattr(args, key):
setattr(args, key, value)
return run_from_args(args)
def clean_run_cache(run_dir: str | Path) -> dict[str, Any]:
root = Path(run_dir)
removed: list[str] = []
for name in ("checkpoints", "full_docking", "single_fidelity_adaptive", "random_baseline", "diverse_random_baseline", "rdock", "tables", "metrics", "plots", "poses", "ligands", "target"):
candidate = root / name
if candidate.exists():
shutil.rmtree(candidate)
removed.append(str(candidate))
return {"run_dir": str(root), "removed": removed}