QPromaQ commited on
Commit
80e5eab
·
verified ·
1 Parent(s): 16193ec

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .pytest_cache/v/cache/lastfailed +1 -0
  2. .pytest_cache/v/cache/nodeids +30 -0
  3. libs/__pycache__/__init__.cpython-311.pyc +0 -0
  4. libs/__pycache__/__init__.cpython-312.pyc +0 -0
  5. libs/__pycache__/__init__.cpython-314.pyc +0 -0
  6. libs/adaptive/__init__.py +19 -0
  7. libs/adaptive/__pycache__/__init__.cpython-311.pyc +0 -0
  8. libs/adaptive/__pycache__/__init__.cpython-312.pyc +0 -0
  9. libs/adaptive/__pycache__/clustering.cpython-311.pyc +0 -0
  10. libs/adaptive/__pycache__/clustering.cpython-312.pyc +0 -0
  11. libs/adaptive/__pycache__/diversity.cpython-312.pyc +0 -0
  12. libs/adaptive/__pycache__/epsilon_regret.cpython-312.pyc +0 -0
  13. libs/adaptive/__pycache__/features.cpython-312.pyc +0 -0
  14. libs/adaptive/__pycache__/hyperclustering.cpython-312.pyc +0 -0
  15. libs/adaptive/__pycache__/metrics.cpython-312.pyc +0 -0
  16. libs/adaptive/__pycache__/policies.cpython-312.pyc +0 -0
  17. libs/adaptive/__pycache__/prioritization.cpython-312.pyc +0 -0
  18. libs/adaptive/__pycache__/queue_manager.cpython-312.pyc +0 -0
  19. libs/adaptive/__pycache__/scheduler.cpython-312.pyc +0 -0
  20. libs/adaptive/__pycache__/state.cpython-312.pyc +0 -0
  21. libs/adaptive/__pycache__/surrogate_model.cpython-312.pyc +0 -0
  22. libs/adaptive/__pycache__/thresholding.cpython-312.pyc +0 -0
  23. libs/adaptive/__pycache__/weight_schedule.cpython-312.pyc +0 -0
  24. libs/adaptive/clustering.py +47 -0
  25. libs/adaptive/diversity.py +24 -0
  26. libs/adaptive/epsilon_regret.py +160 -0
  27. libs/adaptive/features.py +408 -0
  28. libs/adaptive/hyperclustering.py +28 -0
  29. libs/adaptive/metrics.py +48 -0
  30. libs/adaptive/policies.py +12 -0
  31. libs/adaptive/prioritization.py +26 -0
  32. libs/adaptive/queue_manager.py +31 -0
  33. libs/adaptive/scheduler.py +253 -0
  34. libs/adaptive/state.py +50 -0
  35. libs/adaptive/surrogate_model.py +208 -0
  36. libs/adaptive/thresholding.py +120 -0
  37. libs/adaptive/weight_schedule.py +48 -0
  38. libs/analysis/__init__.py +0 -0
  39. libs/analysis/__pycache__/__init__.cpython-312.pyc +0 -0
  40. libs/analysis/__pycache__/backend_diagnostic.cpython-312.pyc +0 -0
  41. libs/analysis/__pycache__/ranking.cpython-312.pyc +0 -0
  42. libs/analysis/backend_diagnostic.py +179 -0
  43. libs/analysis/ranking.py +43 -0
  44. libs/benchmark/__init__.py +108 -0
  45. libs/benchmark/__pycache__/__init__.cpython-311.pyc +0 -0
  46. libs/benchmark/__pycache__/__init__.cpython-312.pyc +0 -0
  47. libs/benchmark/__pycache__/budget_efficiency.cpython-311.pyc +0 -0
  48. libs/benchmark/__pycache__/budget_efficiency.cpython-312.pyc +0 -0
  49. libs/benchmark/__pycache__/cleanup.cpython-311.pyc +0 -0
  50. libs/benchmark/__pycache__/cleanup.cpython-312.pyc +0 -0
.pytest_cache/v/cache/lastfailed ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
.pytest_cache/v/cache/nodeids ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ "tests/test_backend_diagnostic_logic.py::TestBackendDiagnosticLogic::test_compute_rank_percentile",
3
+ "tests/test_backend_diagnostic_logic.py::TestBackendDiagnosticLogic::test_manual_agents_check_exists",
4
+ "tests/test_backend_diagnostic_logic.py::TestBackendDiagnosticLogic::test_recommend_toolchain_runtime_penalty",
5
+ "tests/test_backend_diagnostic_logic.py::TestBackendDiagnosticLogic::test_required_schema_constants_nonempty",
6
+ "tests/test_backend_diagnostic_logic.py::TestBackendDiagnosticLogic::test_select_suspicious",
7
+ "tests/test_backend_diagnostic_logic.py::TestBackendDiagnosticLogic::test_validate_required_columns",
8
+ "tests/test_pocket_modes.py::TestPocketModes::test_reference_complex_mode_uses_crystal_ligand",
9
+ "tests/test_pocket_modes.py::TestPocketModes::test_reference_mode_falls_back_to_receptor_centroid",
10
+ "tests/test_pocket_modes.py::TestPocketModes::test_relaxed_mode_increases_radius",
11
+ "tests/test_pocket_modes.py::TestPocketModes::test_user_fixed_override_precedence",
12
+ "tests/test_rdock_backend.py::TestRDockBackend::test_real_rdock_execution_and_provenance",
13
+ "tests/test_rdock_fixed_pocket.py::TestRDockFixedPocket::test_pocket_spec_stable_across_runs",
14
+ "tests/test_rdock_fixed_pocket.py::TestRDockFixedPocket::test_user_fixed_pocket_writes_sphere_mapper",
15
+ "tests/test_rdock_output_parsing_real.py::TestRDockOutputParsingReal::test_parser_reads_real_rdock_score_field",
16
+ "tests/test_rdock_real_execution.py::TestRDockRealExecution::test_rbcavity_and_rbdock_generate_real_outputs",
17
+ "tests/test_redocking_validation_guards.py::TestRedockingValidationGuards::test_attempt_bounds_guard",
18
+ "tests/test_redocking_validation_guards.py::TestRedockingValidationGuards::test_backend_guard",
19
+ "tests/test_reference_rank_resolution.py::TestReferenceRankResolution::test_falls_back_to_run_rank_when_oracle_missing",
20
+ "tests/test_reference_rank_resolution.py::TestReferenceRankResolution::test_missing_reference",
21
+ "tests/test_reference_rank_resolution.py::TestReferenceRankResolution::test_uses_oracle_when_available",
22
+ "tests/test_smina_backend_timeout.py::test_smina_timeout_returns_failed_row",
23
+ "tests/test_smina_score_parsing.py::TestSminaScoreParsing::test_parses_affinity_score_only_line",
24
+ "tests/test_smina_score_parsing.py::TestSminaScoreParsing::test_parses_minimized_affinity",
25
+ "tests/test_smina_score_parsing.py::TestSminaScoreParsing::test_parses_mode_table",
26
+ "tests/test_smina_score_parsing.py::TestSminaScoreParsing::test_parses_vina_result",
27
+ "tests/test_smina_score_parsing.py::TestSminaScoreParsing::test_returns_nan_when_no_score",
28
+ "tests/test_strict_backend_cleanup.py::TestStrictBackendCleanup::test_haddock_wrapper_removed",
29
+ "tests/test_strict_backend_cleanup.py::TestStrictBackendCleanup::test_thread_policy_formula_85pct"
30
+ ]
libs/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (236 Bytes). View file
 
libs/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (225 Bytes). View file
 
libs/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (227 Bytes). View file
 
libs/adaptive/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adaptive scheduling, clustering, and surrogate learning components."""
2
+
3
+ from .clustering import cluster_ligands_butina
4
+ from .epsilon_regret import EpsilonRegretConfig, EpsilonRegretController
5
+ from .hyperclustering import hypercluster_representatives
6
+ from .scheduler import AdaptiveScheduler
7
+ from .surrogate_model import SurrogateModel
8
+ from .thresholding import DynamicEarlyStopController, DynamicThresholdConfig
9
+
10
+ __all__ = [
11
+ "AdaptiveScheduler",
12
+ "DynamicEarlyStopController",
13
+ "DynamicThresholdConfig",
14
+ "EpsilonRegretConfig",
15
+ "EpsilonRegretController",
16
+ "SurrogateModel",
17
+ "cluster_ligands_butina",
18
+ "hypercluster_representatives",
19
+ ]
libs/adaptive/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (860 Bytes). View file
 
libs/adaptive/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (739 Bytes). View file
 
libs/adaptive/__pycache__/clustering.cpython-311.pyc ADDED
Binary file (3.33 kB). View file
 
libs/adaptive/__pycache__/clustering.cpython-312.pyc ADDED
Binary file (2.71 kB). View file
 
libs/adaptive/__pycache__/diversity.cpython-312.pyc ADDED
Binary file (1.44 kB). View file
 
libs/adaptive/__pycache__/epsilon_regret.cpython-312.pyc ADDED
Binary file (8.62 kB). View file
 
libs/adaptive/__pycache__/features.cpython-312.pyc ADDED
Binary file (24.6 kB). View file
 
libs/adaptive/__pycache__/hyperclustering.cpython-312.pyc ADDED
Binary file (1.54 kB). View file
 
libs/adaptive/__pycache__/metrics.cpython-312.pyc ADDED
Binary file (2.89 kB). View file
 
libs/adaptive/__pycache__/policies.cpython-312.pyc ADDED
Binary file (787 Bytes). View file
 
libs/adaptive/__pycache__/prioritization.cpython-312.pyc ADDED
Binary file (1.27 kB). View file
 
libs/adaptive/__pycache__/queue_manager.cpython-312.pyc ADDED
Binary file (2.5 kB). View file
 
libs/adaptive/__pycache__/scheduler.cpython-312.pyc ADDED
Binary file (14.8 kB). View file
 
libs/adaptive/__pycache__/state.cpython-312.pyc ADDED
Binary file (3.4 kB). View file
 
libs/adaptive/__pycache__/surrogate_model.cpython-312.pyc ADDED
Binary file (11.5 kB). View file
 
libs/adaptive/__pycache__/thresholding.cpython-312.pyc ADDED
Binary file (5.48 kB). View file
 
libs/adaptive/__pycache__/weight_schedule.cpython-312.pyc ADDED
Binary file (2.76 kB). View file
 
libs/adaptive/clustering.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Iterable, List, Sequence
4
+
5
+ import numpy as np
6
+ from rdkit import DataStructs
7
+ from rdkit.Chem import rdchem
8
+ from rdkit.ML.Cluster import Butina
9
+
10
+
11
+ def _np_to_explicit_bitvect(fp: np.ndarray) -> DataStructs.ExplicitBitVect:
12
+ bitvect = DataStructs.ExplicitBitVect(fp.shape[0])
13
+ on_bits = np.where(fp > 0)[0]
14
+ for idx in on_bits:
15
+ bitvect.SetBit(int(idx))
16
+ return bitvect
17
+
18
+
19
+ def cluster_ligands_butina(
20
+ ligand_ids: Sequence[str],
21
+ fingerprints: Sequence[np.ndarray],
22
+ cutoff: float = 0.35,
23
+ ) -> Dict[str, int]:
24
+ """Cluster ligands with Butina on Tanimoto distance over Morgan fingerprints."""
25
+ if not ligand_ids:
26
+ return {}
27
+ if len(ligand_ids) != len(fingerprints):
28
+ raise ValueError("ligand_ids and fingerprints must have same length")
29
+
30
+ fp_bv = [_np_to_explicit_bitvect(np.asarray(fp, dtype=int)) for fp in fingerprints]
31
+
32
+ dists: List[float] = []
33
+ for i in range(1, len(fp_bv)):
34
+ sims = DataStructs.BulkTanimotoSimilarity(fp_bv[i], fp_bv[:i])
35
+ dists.extend([1.0 - x for x in sims])
36
+
37
+ clusters = Butina.ClusterData(dists, len(fp_bv), cutoff, isDistData=True)
38
+
39
+ mapping: Dict[str, int] = {}
40
+ for c_idx, cluster in enumerate(clusters):
41
+ for member in cluster:
42
+ mapping[ligand_ids[member]] = c_idx
43
+
44
+ # Ensure all ligands map to a cluster, even edge cases.
45
+ for idx, ligand_id in enumerate(ligand_ids):
46
+ mapping.setdefault(ligand_id, max(mapping.values(), default=-1) + idx + 1)
47
+ return mapping
libs/adaptive/diversity.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable
4
+
5
+ import numpy as np
6
+
7
+
8
+ def _tanimoto(fp_a: np.ndarray, fp_b: np.ndarray) -> float:
9
+ inter = float(np.sum((fp_a > 0) & (fp_b > 0)))
10
+ union = float(np.sum((fp_a > 0) | (fp_b > 0)))
11
+ if union == 0:
12
+ return 0.0
13
+ return inter / union
14
+
15
+
16
+ def selection_diversity(fingerprints: Iterable[np.ndarray]) -> float:
17
+ fps = list(fingerprints)
18
+ if len(fps) < 2:
19
+ return 0.0
20
+ distances = []
21
+ for i in range(len(fps)):
22
+ for j in range(i + 1, len(fps)):
23
+ distances.append(1.0 - _tanimoto(fps[i], fps[j]))
24
+ return float(np.mean(distances)) if distances else 0.0
libs/adaptive/epsilon_regret.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Iterable, List, Sequence
5
+
6
+ import numpy as np
7
+
8
+
9
+ @dataclass
10
+ class EpsilonRegretConfig:
11
+ epsilon_quality: float = 0.10
12
+ acceptable_regret: float = 0.10
13
+ min_budget: int = 250
14
+ max_budget: int = 10000
15
+ min_model_weight: float = 0.25
16
+ patience_rounds: int = 6
17
+ min_improvement: float = 0.02
18
+ uncertainty_multiplier: float = 0.50
19
+ min_cluster_coverage: float = 0.20
20
+ min_hypercluster_coverage: float = 0.20
21
+
22
+
23
+ class EpsilonRegretController:
24
+ """
25
+ Budget-aware stop controller with epsilon-regret semantics.
26
+
27
+ Online intent:
28
+ stop when estimated remaining gain is small relative to current best score,
29
+ after minimum exploration and coverage constraints are satisfied.
30
+ """
31
+
32
+ def __init__(self, config: EpsilonRegretConfig | None = None) -> None:
33
+ self.config = config or EpsilonRegretConfig()
34
+ self.best_score = np.inf
35
+ self.stagnant_rounds = 0
36
+ self.history: List[Dict[str, float | int | bool | str]] = []
37
+
38
+ @staticmethod
39
+ def _mean_or_nan(values: Sequence[float]) -> float:
40
+ arr = np.asarray(values, dtype=float)
41
+ if arr.size == 0:
42
+ return float("nan")
43
+ return float(np.nanmean(arr))
44
+
45
+ @staticmethod
46
+ def _estimate_remaining_gain(
47
+ best_score: float,
48
+ expected_remaining_scores: Iterable[float],
49
+ uncertainty_scores: Iterable[float],
50
+ uncertainty_multiplier: float,
51
+ ) -> float:
52
+ pred = np.asarray(list(expected_remaining_scores), dtype=float)
53
+ unc = np.asarray(list(uncertainty_scores), dtype=float)
54
+ if pred.size == 0:
55
+ return float("inf")
56
+ if unc.size != pred.size:
57
+ unc = np.full(pred.shape[0], np.nanmean(unc) if unc.size else 1.0, dtype=float)
58
+ optimistic = pred - float(max(0.0, uncertainty_multiplier)) * np.abs(unc)
59
+ optimistic_best = float(np.nanmin(optimistic)) if np.isfinite(optimistic).any() else float(np.nanmin(pred))
60
+ if not np.isfinite(optimistic_best) or not np.isfinite(best_score):
61
+ return float("inf")
62
+ # lower score is better
63
+ return float(max(0.0, best_score - optimistic_best))
64
+
65
+ def update(
66
+ self,
67
+ *,
68
+ round_idx: int,
69
+ n_evaluated: int,
70
+ best_score_now: float,
71
+ recent_scores: Sequence[float],
72
+ model_weight: float,
73
+ cluster_coverage: float,
74
+ hypercluster_coverage: float,
75
+ expected_remaining_scores: Iterable[float],
76
+ uncertainty_scores: Iterable[float],
77
+ time_importance: float,
78
+ budget_cap: int,
79
+ ) -> Dict[str, float | int | bool | str]:
80
+ cfg = self.config
81
+ ti = float(max(0.0, min(1.0, float(time_importance))))
82
+
83
+ if np.isfinite(self.best_score):
84
+ improvement = float(self.best_score - best_score_now)
85
+ else:
86
+ improvement = float("inf")
87
+
88
+ if improvement > float(cfg.min_improvement):
89
+ self.stagnant_rounds = 0
90
+ else:
91
+ self.stagnant_rounds += 1
92
+ self.best_score = min(float(self.best_score), float(best_score_now))
93
+
94
+ epsilon_rel = float(max(cfg.epsilon_quality, cfg.acceptable_regret))
95
+ # Higher time importance permits slightly larger acceptable residual gain.
96
+ epsilon_rel *= float(1.0 + 0.5 * ti)
97
+ epsilon_abs = float(epsilon_rel * max(1.0, abs(float(self.best_score))))
98
+
99
+ remaining_gain = self._estimate_remaining_gain(
100
+ best_score=float(self.best_score),
101
+ expected_remaining_scores=expected_remaining_scores,
102
+ uncertainty_scores=uncertainty_scores,
103
+ uncertainty_multiplier=float(cfg.uncertainty_multiplier),
104
+ )
105
+ regret_ratio_proxy = float(remaining_gain / max(1.0, abs(float(self.best_score))))
106
+
107
+ budget_floor = int(max(1, cfg.min_budget))
108
+ budget_ceiling = int(min(cfg.max_budget, budget_cap))
109
+ budget_ready = int(n_evaluated) >= budget_floor
110
+ model_ready = float(model_weight) >= float(cfg.min_model_weight)
111
+ coverage_ready = bool(
112
+ float(cluster_coverage) >= float(cfg.min_cluster_coverage)
113
+ and float(hypercluster_coverage) >= float(cfg.min_hypercluster_coverage)
114
+ )
115
+ stagnation_ready = int(self.stagnant_rounds) >= int(cfg.patience_rounds)
116
+
117
+ hit_budget_ceiling = int(n_evaluated) >= int(budget_ceiling)
118
+ epsilon_ready = bool(np.isfinite(remaining_gain) and remaining_gain <= epsilon_abs)
119
+ stop = bool(hit_budget_ceiling or (budget_ready and model_ready and coverage_ready and stagnation_ready and epsilon_ready))
120
+
121
+ if hit_budget_ceiling:
122
+ reason = "max_budget_reached"
123
+ elif not budget_ready:
124
+ reason = "below_min_budget"
125
+ elif not model_ready:
126
+ reason = "model_not_ready"
127
+ elif not coverage_ready:
128
+ reason = "coverage_not_ready"
129
+ elif not stagnation_ready:
130
+ reason = "insufficient_stagnation_evidence"
131
+ elif not epsilon_ready:
132
+ reason = "remaining_gain_above_epsilon"
133
+ else:
134
+ reason = "epsilon_regret_stop"
135
+
136
+ rec = {
137
+ "round_idx": int(round_idx),
138
+ "n_evaluated": int(n_evaluated),
139
+ "best_score": float(self.best_score),
140
+ "recent_mean_score": self._mean_or_nan(recent_scores),
141
+ "model_weight": float(model_weight),
142
+ "cluster_coverage": float(cluster_coverage),
143
+ "hypercluster_coverage": float(hypercluster_coverage),
144
+ "stagnant_rounds": int(self.stagnant_rounds),
145
+ "epsilon_abs": float(epsilon_abs),
146
+ "estimated_remaining_gain": float(remaining_gain),
147
+ "regret_ratio_proxy": float(regret_ratio_proxy),
148
+ "budget_floor": int(budget_floor),
149
+ "budget_ceiling": int(budget_ceiling),
150
+ "budget_ready": bool(budget_ready),
151
+ "model_ready": bool(model_ready),
152
+ "coverage_ready": bool(coverage_ready),
153
+ "stagnation_ready": bool(stagnation_ready),
154
+ "epsilon_ready": bool(epsilon_ready),
155
+ "stop": bool(stop),
156
+ "reason": reason,
157
+ }
158
+ self.history.append(rec)
159
+ return rec
160
+
libs/adaptive/features.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Iterable, List, Tuple
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from rdkit import Chem
9
+ from rdkit.Chem import AllChem, Descriptors, Lipinski, MolSurf, rdMolDescriptors
10
+ from rdkit.Chem.Scaffolds import MurckoScaffold
11
+ from rdkit.DataStructs import TanimotoSimilarity
12
+
13
+ try:
14
+ from rdkit.Chem import rdFreeSASA
15
+ except Exception: # pragma: no cover
16
+ rdFreeSASA = None # type: ignore[assignment]
17
+
18
+
19
+ @dataclass
20
+ class FeatureValue:
21
+ value: float | None
22
+ available: bool
23
+ source: str
24
+ feature_type: str
25
+
26
+
27
+ @dataclass
28
+ class FeatureBundle:
29
+ object_id: str
30
+ features: Dict[str, FeatureValue]
31
+
32
+ def to_records(self, channel: str, round_idx: int | None = None) -> List[dict]:
33
+ rows: List[dict] = []
34
+ for name, fv in sorted(self.features.items()):
35
+ rows.append(
36
+ {
37
+ "object_id": self.object_id,
38
+ "round": round_idx,
39
+ "channel": channel,
40
+ "feature_name": name,
41
+ "value": fv.value,
42
+ "available": bool(fv.available),
43
+ "source": fv.source,
44
+ "feature_type": fv.feature_type,
45
+ }
46
+ )
47
+ return rows
48
+
49
+
50
+ def _fv(value: float | None, available: bool, source: str, feature_type: str) -> FeatureValue:
51
+ return FeatureValue(value=value, available=available, source=source, feature_type=feature_type)
52
+
53
+
54
+ def _safe_float(value: float | int | None) -> float | None:
55
+ if value is None:
56
+ return None
57
+ try:
58
+ v = float(value)
59
+ except Exception:
60
+ return None
61
+ if not np.isfinite(v):
62
+ return None
63
+ return v
64
+
65
+
66
+ def _compute_ligand_sasa(mol: Chem.Mol) -> Tuple[float | None, bool]:
67
+ if rdFreeSASA is None:
68
+ return None, False
69
+ try:
70
+ if mol.GetNumConformers() == 0:
71
+ m = Chem.AddHs(Chem.Mol(mol))
72
+ status = AllChem.EmbedMolecule(m, AllChem.ETKDGv3())
73
+ if int(status) != 0:
74
+ return None, False
75
+ else:
76
+ m = Chem.Mol(mol)
77
+
78
+ if m.GetNumConformers() == 0:
79
+ return None, False
80
+
81
+ radii = rdFreeSASA.classifyAtoms(m)
82
+ sasa = rdFreeSASA.CalcSASA(m, radii)
83
+ return _safe_float(sasa), True
84
+ except Exception:
85
+ return None, False
86
+
87
+
88
+ def build_ligand_feature_bundle(
89
+ ligand_id: str,
90
+ smiles: str,
91
+ fingerprint: np.ndarray,
92
+ reference_mol: Chem.Mol | None = None,
93
+ compute_partial_charges: bool = True,
94
+ compute_sasa: bool = True,
95
+ ) -> FeatureBundle:
96
+ mol = Chem.MolFromSmiles(smiles)
97
+ if mol is None:
98
+ raise ValueError(f"Invalid SMILES for ligand {ligand_id}: {smiles}")
99
+
100
+ m_h = Chem.AddHs(Chem.Mol(mol))
101
+ if compute_partial_charges:
102
+ try:
103
+ AllChem.ComputeGasteigerCharges(m_h)
104
+ partial_charges = []
105
+ for atom in m_h.GetAtoms():
106
+ prop = atom.GetProp("_GasteigerCharge") if atom.HasProp("_GasteigerCharge") else "nan"
107
+ try:
108
+ q = float(prop)
109
+ except Exception:
110
+ continue
111
+ if np.isfinite(q):
112
+ partial_charges.append(q)
113
+ if partial_charges:
114
+ mean_abs_q = float(np.mean(np.abs(partial_charges)))
115
+ total_q = float(np.sum(partial_charges))
116
+ has_q = True
117
+ else:
118
+ mean_abs_q = None
119
+ total_q = None
120
+ has_q = False
121
+ except Exception:
122
+ mean_abs_q = None
123
+ total_q = None
124
+ has_q = False
125
+ else:
126
+ mean_abs_q = None
127
+ total_q = None
128
+ has_q = False
129
+
130
+ aromatic_rings = rdMolDescriptors.CalcNumAromaticRings(mol)
131
+ formal_charge = Chem.GetFormalCharge(mol)
132
+ heavy_atoms = mol.GetNumHeavyAtoms()
133
+ frac_csp3 = rdMolDescriptors.CalcFractionCSP3(mol)
134
+ bertz_ct = Descriptors.BertzCT(mol)
135
+ balaban_j = Descriptors.BalabanJ(mol)
136
+ topological_complexity = rdMolDescriptors.CalcChi0v(mol)
137
+
138
+ if compute_sasa:
139
+ ligand_sasa, has_sasa = _compute_ligand_sasa(m_h)
140
+ else:
141
+ ligand_sasa, has_sasa = None, False
142
+
143
+ reference_similarity = None
144
+ scaffold_match = None
145
+ chemical_distance = None
146
+ if reference_mol is not None:
147
+ fp_gen = AllChem.GetMorganGenerator(radius=2, fpSize=int(fingerprint.shape[0]))
148
+ ref_fp = fp_gen.GetFingerprint(reference_mol)
149
+ lig_fp = fp_gen.GetFingerprint(mol)
150
+ sim = TanimotoSimilarity(ref_fp, lig_fp)
151
+ reference_similarity = float(sim)
152
+ chemical_distance = float(1.0 - sim)
153
+
154
+ ref_scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=reference_mol)
155
+ lig_scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=mol)
156
+ scaffold_match = float(ref_scaffold == lig_scaffold)
157
+
158
+ features: Dict[str, FeatureValue] = {
159
+ "ligand_mw": _fv(_safe_float(Descriptors.MolWt(mol)), True, "rdkit", "exact"),
160
+ "ligand_logp": _fv(_safe_float(Descriptors.MolLogP(mol)), True, "rdkit", "exact"),
161
+ "ligand_tpsa": _fv(_safe_float(MolSurf.TPSA(mol)), True, "rdkit", "exact"),
162
+ "ligand_hbd": _fv(_safe_float(Lipinski.NumHDonors(mol)), True, "rdkit", "exact"),
163
+ "ligand_hba": _fv(_safe_float(Lipinski.NumHAcceptors(mol)), True, "rdkit", "exact"),
164
+ "ligand_rotatable_bonds": _fv(_safe_float(Lipinski.NumRotatableBonds(mol)), True, "rdkit", "exact"),
165
+ "ligand_aromatic_ring_count": _fv(_safe_float(aromatic_rings), True, "rdkit", "exact"),
166
+ "ligand_formal_charge": _fv(_safe_float(formal_charge), True, "rdkit", "exact"),
167
+ "ligand_partial_charge_abs_mean": _fv(mean_abs_q, has_q, "rdkit", "approximate"),
168
+ "ligand_partial_charge_total": _fv(total_q, has_q, "rdkit", "approximate"),
169
+ "ligand_topological_bertz": _fv(_safe_float(bertz_ct), True, "rdkit", "exact"),
170
+ "ligand_topological_balaban_j": _fv(_safe_float(balaban_j), True, "rdkit", "exact"),
171
+ "ligand_topological_chi0v": _fv(_safe_float(topological_complexity), True, "rdkit", "exact"),
172
+ "ligand_fraction_csp3": _fv(_safe_float(frac_csp3), True, "rdkit", "exact"),
173
+ "ligand_heavy_atom_count": _fv(_safe_float(heavy_atoms), True, "rdkit", "exact"),
174
+ "ligand_sasa": _fv(ligand_sasa, has_sasa, "geometric", "approximate"),
175
+ "similarity_to_reference": _fv(reference_similarity, reference_similarity is not None, "rdkit", "exact"),
176
+ "scaffold_match": _fv(scaffold_match, scaffold_match is not None, "rdkit", "exact"),
177
+ "chemical_distance_to_reference": _fv(chemical_distance, chemical_distance is not None, "rdkit", "exact"),
178
+ }
179
+
180
+ for i, bit in enumerate(fingerprint.astype(float).tolist()):
181
+ features[f"morgan_fp_{i:04d}"] = _fv(float(bit), True, "rdkit", "exact")
182
+
183
+ return FeatureBundle(object_id=ligand_id, features=features)
184
+
185
+
186
+ def build_protein_feature_bundle(target_id: str, sequence_features: Dict[str, float], structure_features: Dict[str, float]) -> FeatureBundle:
187
+ seq_len = float(sequence_features.get("seq_length", 1.0) or 1.0)
188
+ hydrophobic = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["A", "V", "I", "L", "M", "F", "W", "Y"])
189
+ charged = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["K", "R", "H", "D", "E"])
190
+ polar = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["S", "T", "N", "Q", "C"])
191
+
192
+ residue_count = float(structure_features.get("residue_count", 0.0))
193
+ mean_extent = float(structure_features.get("mean_spatial_extent", 0.0))
194
+ pocket_residues = float(structure_features.get("pocket_residue_count", 0.0))
195
+
196
+ approx_volume = float(max(0.0, mean_extent**3))
197
+ pocket_coverage = float(pocket_residues / max(residue_count, 1.0))
198
+
199
+ features = {
200
+ "pocket_hydrophobic_fraction": _fv(hydrophobic, True, "protein", "exact"),
201
+ "pocket_charged_fraction": _fv(charged, True, "protein", "exact"),
202
+ "pocket_polar_fraction": _fv(polar, True, "protein", "exact"),
203
+ "pocket_residue_count": _fv(residue_count, True, "protein", "exact"),
204
+ "pocket_volume_approx": _fv(approx_volume, True, "geometric", "approximate"),
205
+ "pocket_coverage_fraction": _fv(pocket_coverage, True, "geometric", "approximate"),
206
+ "pocket_sequence_length": _fv(seq_len, True, "protein", "exact"),
207
+ }
208
+ return FeatureBundle(object_id=target_id, features=features)
209
+
210
+
211
+ def build_complex_feature_bundle(
212
+ ligand_id: str,
213
+ docking_score: float,
214
+ interface_features: Dict[str, float],
215
+ ligand_bundle: FeatureBundle,
216
+ protein_bundle: FeatureBundle,
217
+ ) -> FeatureBundle:
218
+ lig = ligand_bundle.features
219
+ prot = protein_bundle.features
220
+
221
+ logp = lig.get("ligand_logp", _fv(None, False, "rdkit", "exact")).value or 0.0
222
+ tpsa = lig.get("ligand_tpsa", _fv(None, False, "rdkit", "exact")).value or 0.0
223
+ charge_mag = lig.get("ligand_partial_charge_abs_mean", _fv(None, False, "rdkit", "approximate")).value
224
+ heavy_atoms = lig.get("ligand_heavy_atom_count", _fv(None, False, "rdkit", "exact")).value or 1.0
225
+ pocket_volume = prot.get("pocket_volume_approx", _fv(None, False, "geometric", "approximate")).value or 1.0
226
+ pocket_hydrophobic = prot.get("pocket_hydrophobic_fraction", _fv(None, False, "protein", "exact")).value or 0.0
227
+
228
+ interface_contact_proxy = float(interface_features.get("interface_contact_proxy", max(0.0, -docking_score / 8.0)))
229
+ hbond_proxy = float(interface_features.get("hbond_proxy", max(0.0, tpsa / 100.0)))
230
+ shape_proxy = float(interface_features.get("shape_proxy", max(0.0, 1.0 / (1.0 + abs(docking_score)))))
231
+
232
+ contact_count = max(1.0, heavy_atoms * (0.3 + interface_contact_proxy))
233
+ polar_contacts = contact_count * min(1.0, tpsa / 120.0)
234
+ hydrophobic_contacts = contact_count * min(1.0, max(0.0, logp) / 6.0) * (0.5 + pocket_hydrophobic)
235
+ clash_count = max(0.0, docking_score - 9.0)
236
+ min_distance = max(1.5, 6.0 - interface_contact_proxy)
237
+ pocket_coverage = min(1.0, contact_count / max(10.0, pocket_volume / 20.0))
238
+ interaction_density = contact_count / max(1.0, pocket_volume)
239
+
240
+ ligand_sasa = lig.get("ligand_sasa", _fv(None, False, "geometric", "approximate")).value
241
+ protein_sasa = pocket_volume * 0.75
242
+ if ligand_sasa is not None:
243
+ complex_sasa = max(1.0, protein_sasa + ligand_sasa - 0.5 * contact_count)
244
+ buried_sasa = max(0.0, protein_sasa + ligand_sasa - complex_sasa)
245
+ burial_ratio = buried_sasa / max(ligand_sasa, 1e-6)
246
+ sasa_available = True
247
+ else:
248
+ complex_sasa = None
249
+ buried_sasa = None
250
+ burial_ratio = None
251
+ sasa_available = False
252
+
253
+ if charge_mag is not None:
254
+ electrostatic_proxy = -charge_mag * max(0.5, 5.0 - min_distance)
255
+ electro_available = True
256
+ else:
257
+ electrostatic_proxy = None
258
+ electro_available = False
259
+
260
+ contact_energy = -0.15 * contact_count
261
+ steric_penalty = 0.6 * clash_count
262
+ hydrophobic_proxy = -0.1 * hydrophobic_contacts
263
+ interaction_decomp = contact_energy + hydrophobic_proxy + (electrostatic_proxy or 0.0) + steric_penalty
264
+
265
+ features = {
266
+ "complex_contact_count": _fv(float(contact_count), True, "interaction", "proxy"),
267
+ "complex_hbond_proxy": _fv(float(hbond_proxy), True, "interaction", "proxy"),
268
+ "complex_polar_contact_count": _fv(float(polar_contacts), True, "interaction", "proxy"),
269
+ "complex_hydrophobic_contact_proxy": _fv(float(hydrophobic_contacts), True, "interaction", "proxy"),
270
+ "complex_clash_count": _fv(float(clash_count), True, "interaction", "proxy"),
271
+ "complex_min_distance": _fv(float(min_distance), True, "geometric", "approximate"),
272
+ "complex_pocket_coverage": _fv(float(pocket_coverage), True, "interaction", "proxy"),
273
+ "complex_interaction_density": _fv(float(interaction_density), True, "interaction", "proxy"),
274
+ "complex_ligand_sasa": _fv(_safe_float(ligand_sasa), ligand_sasa is not None, "geometric", "approximate"),
275
+ "complex_protein_sasa": _fv(_safe_float(protein_sasa), True, "geometric", "approximate"),
276
+ "complex_sasa": _fv(_safe_float(complex_sasa), sasa_available, "geometric", "approximate"),
277
+ "complex_buried_sasa": _fv(_safe_float(buried_sasa), sasa_available, "geometric", "approximate"),
278
+ "complex_shape_complementarity": _fv(float(shape_proxy), True, "geometric", "proxy"),
279
+ "complex_ligand_burial_ratio": _fv(_safe_float(burial_ratio), sasa_available, "geometric", "approximate"),
280
+ "energy_contact_proxy": _fv(float(contact_energy), True, "energy_proxy", "proxy"),
281
+ "energy_electrostatic_proxy": _fv(_safe_float(electrostatic_proxy), electro_available, "energy_proxy", "proxy"),
282
+ "energy_steric_clash_penalty": _fv(float(steric_penalty), True, "energy_proxy", "proxy"),
283
+ "energy_hydrophobic_proxy": _fv(float(hydrophobic_proxy), True, "energy_proxy", "proxy"),
284
+ "energy_interaction_decomposition": _fv(float(interaction_decomp), True, "energy_proxy", "proxy"),
285
+ }
286
+
287
+ return FeatureBundle(object_id=ligand_id, features=features)
288
+
289
+
290
+ def build_rdock_feature_bundle(
291
+ ligand_id: str,
292
+ parsed_row: Dict[str, float | int | str | bool | None],
293
+ ) -> FeatureBundle:
294
+ """Build a feature bundle from rDock-native and rDock-derived per-ligand outputs."""
295
+
296
+ def _as_feature(
297
+ key: str,
298
+ source: str,
299
+ ftype: str,
300
+ ) -> FeatureValue:
301
+ value = _safe_float(parsed_row.get(key)) # type: ignore[arg-type]
302
+ return _fv(value, value is not None, source, ftype if value is not None else "unavailable")
303
+
304
+ features: Dict[str, FeatureValue] = {
305
+ "rdock_total_score": _as_feature("rdock_total_score", "rdock_native", "exact"),
306
+ "rdock_pose_rank": _as_feature("rdock_pose_rank", "rdock_native", "exact"),
307
+ "n_generated_poses": _as_feature("n_generated_poses", "rdock_native", "exact"),
308
+ "best_pose_score": _as_feature("best_pose_score", "rdock_native", "exact"),
309
+ "mean_top3_pose_score": _as_feature("mean_top3_pose_score", "rdock_native", "exact"),
310
+ "mean_top5_pose_score": _as_feature("mean_top5_pose_score", "rdock_native", "exact"),
311
+ "std_top5_pose_score": _as_feature("std_top5_pose_score", "rdock_native", "exact"),
312
+ "pose_score_gap_1_2": _as_feature("pose_score_gap_1_2", "rdock_native", "exact"),
313
+ "rdock_restraint_term": _as_feature("rdock_restraint_term", "rdock_native", "exact"),
314
+ "rdock_internal_ligand_term": _as_feature("rdock_internal_ligand_term", "rdock_native", "exact"),
315
+ "rdock_polar_term": _as_feature("rdock_polar_term", "rdock_native", "exact"),
316
+ "rdock_vdw_term": _as_feature("rdock_vdw_term", "rdock_native", "exact"),
317
+ "top_pose_rmsd_consistency": _as_feature("top_pose_rmsd_consistency", "rdock_derived", "proxy"),
318
+ "contact_overlap_consistency": _as_feature("contact_overlap_consistency", "rdock_derived", "proxy"),
319
+ "hotspot_contact_frequency": _as_feature("hotspot_contact_frequency", "rdock_derived", "proxy"),
320
+ "subpocket_match_score": _as_feature("subpocket_match_score", "rdock_derived", "proxy"),
321
+ "replicate_mean_score": _as_feature("replicate_mean_score", "rdock_derived", "proxy"),
322
+ "replicate_score_variance": _as_feature("replicate_score_variance", "rdock_derived", "proxy"),
323
+ "replicate_consensus_score": _as_feature("replicate_consensus_score", "rdock_derived", "proxy"),
324
+ }
325
+ return FeatureBundle(object_id=ligand_id, features=features)
326
+
327
+
328
+ def merge_bundles(object_id: str, bundles: Iterable[FeatureBundle]) -> FeatureBundle:
329
+ merged: Dict[str, FeatureValue] = {}
330
+ for bundle in bundles:
331
+ merged.update(bundle.features)
332
+ return FeatureBundle(object_id=object_id, features=merged)
333
+
334
+
335
+ def bundles_to_wide_frames(
336
+ bundles: List[FeatureBundle],
337
+ ordered_feature_names: List[str] | None = None,
338
+ ) -> Tuple[pd.DataFrame, pd.DataFrame, List[str]]:
339
+ if not bundles:
340
+ return pd.DataFrame(), pd.DataFrame(), []
341
+
342
+ if ordered_feature_names is None:
343
+ feature_set = set()
344
+ for bundle in bundles:
345
+ feature_set.update(bundle.features.keys())
346
+ ordered_feature_names = sorted(feature_set)
347
+
348
+ value_rows = []
349
+ mask_rows = []
350
+ for bundle in bundles:
351
+ vrow = {"ligand_id": bundle.object_id}
352
+ mrow = {"ligand_id": bundle.object_id}
353
+ for name in ordered_feature_names:
354
+ fv = bundle.features.get(name)
355
+ if fv is None or not fv.available or fv.value is None:
356
+ vrow[name] = np.nan
357
+ mrow[f"mask_{name}"] = 0
358
+ else:
359
+ vrow[name] = float(fv.value)
360
+ mrow[f"mask_{name}"] = 1
361
+ value_rows.append(vrow)
362
+ mask_rows.append(mrow)
363
+
364
+ return pd.DataFrame(value_rows), pd.DataFrame(mask_rows), ordered_feature_names
365
+
366
+
367
+ def compute_feature_diagnostics(values_df: pd.DataFrame, masks_df: pd.DataFrame, target: pd.Series | None = None) -> pd.DataFrame:
368
+ if values_df.empty:
369
+ return pd.DataFrame(columns=["feature", "missing_frac", "mean", "std", "min", "max", "is_constant", "corr_to_target"])
370
+
371
+ numeric_cols = [c for c in values_df.columns if c != "ligand_id"]
372
+ rows = []
373
+ for col in numeric_cols:
374
+ vals = pd.to_numeric(values_df[col], errors="coerce")
375
+ mask_col = f"mask_{col}"
376
+ if mask_col in masks_df.columns:
377
+ missing_frac = 1.0 - float(pd.to_numeric(masks_df[mask_col], errors="coerce").mean())
378
+ else:
379
+ missing_frac = float(vals.isna().mean())
380
+
381
+ finite_vals = vals[np.isfinite(vals)]
382
+ is_constant = finite_vals.nunique(dropna=True) <= 1 if not finite_vals.empty else True
383
+
384
+ if target is not None and len(target) == len(vals):
385
+ target_num = pd.to_numeric(target, errors="coerce")
386
+ paired = pd.concat([vals, target_num], axis=1).dropna()
387
+ if paired.shape[0] >= 3 and paired.iloc[:, 0].nunique(dropna=True) > 1 and paired.iloc[:, 1].nunique(dropna=True) > 1:
388
+ corr = paired.iloc[:, 0].corr(paired.iloc[:, 1])
389
+ corr_val = float(corr) if corr is not None and np.isfinite(corr) else np.nan
390
+ else:
391
+ corr_val = np.nan
392
+ else:
393
+ corr_val = np.nan
394
+
395
+ rows.append(
396
+ {
397
+ "feature": col,
398
+ "missing_frac": float(missing_frac),
399
+ "mean": float(finite_vals.mean()) if not finite_vals.empty else np.nan,
400
+ "std": float(finite_vals.std()) if not finite_vals.empty else np.nan,
401
+ "min": float(finite_vals.min()) if not finite_vals.empty else np.nan,
402
+ "max": float(finite_vals.max()) if not finite_vals.empty else np.nan,
403
+ "is_constant": bool(is_constant),
404
+ "corr_to_target": corr_val,
405
+ }
406
+ )
407
+
408
+ return pd.DataFrame(rows).sort_values(["missing_frac", "feature"], ascending=[False, True]).reset_index(drop=True)
libs/adaptive/hyperclustering.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Sequence
4
+
5
+ import numpy as np
6
+ from sklearn.cluster import AgglomerativeClustering
7
+
8
+
9
+ def hypercluster_representatives(
10
+ cluster_vectors: Dict[int, np.ndarray],
11
+ n_hyperclusters: int | None = None,
12
+ ) -> Dict[int, int]:
13
+ """Agglomerative clustering over cluster representative vectors."""
14
+ if not cluster_vectors:
15
+ return {}
16
+
17
+ cluster_ids = sorted(cluster_vectors)
18
+ x = np.vstack([cluster_vectors[cid] for cid in cluster_ids])
19
+
20
+ if len(cluster_ids) == 1:
21
+ return {cluster_ids[0]: 0}
22
+
23
+ n_clusters = n_hyperclusters or max(2, int(np.sqrt(len(cluster_ids))))
24
+ n_clusters = min(n_clusters, len(cluster_ids))
25
+
26
+ model = AgglomerativeClustering(n_clusters=n_clusters)
27
+ labels = model.fit_predict(x)
28
+ return {cluster_id: int(label) for cluster_id, label in zip(cluster_ids, labels)}
libs/adaptive/metrics.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Iterable, Sequence
4
+
5
+ import numpy as np
6
+
7
+ from .diversity import selection_diversity
8
+
9
+
10
+ def clustering_metrics(cluster_map: Dict[str, int], hypercluster_map: Dict[int, int]) -> Dict[str, float]:
11
+ return {
12
+ "ligand_count": float(len(cluster_map)),
13
+ "cluster_count": float(len(set(cluster_map.values())) if cluster_map else 0),
14
+ "hypercluster_count": float(len(set(hypercluster_map.values())) if hypercluster_map else 0),
15
+ }
16
+
17
+
18
+ def score_metrics(scores: Sequence[float]) -> Dict[str, float]:
19
+ if not scores:
20
+ return {
21
+ "evaluated_ligand_count": 0.0,
22
+ "mean_score": 0.0,
23
+ "best_score": 0.0,
24
+ }
25
+ arr = np.asarray(scores, dtype=float)
26
+ return {
27
+ "evaluated_ligand_count": float(arr.size),
28
+ "mean_score": float(np.mean(arr)),
29
+ "best_score": float(np.min(arr)),
30
+ }
31
+
32
+
33
+ def enrichment_metrics(scores: Sequence[float], labels: Sequence[int] | None, topk: int = 10) -> Dict[str, float]:
34
+ if labels is None or not scores or len(labels) != len(scores):
35
+ return {"topk_hit_rate": 0.0, "enrichment_like": 0.0}
36
+
37
+ idx_sorted = np.argsort(np.asarray(scores, dtype=float))
38
+ labels_arr = np.asarray(labels, dtype=int)
39
+ k = min(topk, len(idx_sorted))
40
+ top_hits = int(np.sum(labels_arr[idx_sorted[:k]]))
41
+ baseline = float(np.mean(labels_arr)) if labels_arr.size else 0.0
42
+ hit_rate = top_hits / max(k, 1)
43
+ enrichment = (hit_rate / baseline) if baseline > 0 else 0.0
44
+ return {"topk_hit_rate": float(hit_rate), "enrichment_like": float(enrichment)}
45
+
46
+
47
+ def diversity_metric(selected_fingerprints: Iterable[np.ndarray]) -> Dict[str, float]:
48
+ return {"selection_diversity": selection_diversity(selected_fingerprints)}
libs/adaptive/policies.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass
7
+ class PrioritizationPolicy:
8
+ utility_weight: float = 0.55
9
+ uncertainty_weight: float = 0.2
10
+ diversity_weight: float = 0.15
11
+ cluster_bonus_weight: float = 0.1
12
+ conservative_deprioritize_quantile: float = 0.15
libs/adaptive/prioritization.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict
4
+
5
+ from .policies import PrioritizationPolicy
6
+
7
+
8
+ def compute_priority(
9
+ predicted_utility: float,
10
+ uncertainty: float,
11
+ diversity_gain: float,
12
+ cluster_bonus: float,
13
+ policy: PrioritizationPolicy,
14
+ ) -> float:
15
+ """Weighted priority function used by adaptive queueing."""
16
+ return (
17
+ policy.utility_weight * predicted_utility
18
+ + policy.uncertainty_weight * uncertainty
19
+ + policy.diversity_weight * diversity_gain
20
+ + policy.cluster_bonus_weight * cluster_bonus
21
+ )
22
+
23
+
24
+ def cluster_bonus(cluster_load: Dict[int, int], cluster_id: int) -> float:
25
+ load = cluster_load.get(cluster_id, 0)
26
+ return 1.0 / (1.0 + float(load))
libs/adaptive/queue_manager.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Iterable, List
5
+
6
+ from .state import QueueItem
7
+
8
+ VALID_STATUSES = {"active", "deprioritized", "frozen", "completed"}
9
+
10
+
11
+ @dataclass
12
+ class QueueManager:
13
+ items: Dict[str, QueueItem]
14
+
15
+ @classmethod
16
+ def from_items(cls, items: Iterable[QueueItem]) -> "QueueManager":
17
+ return cls(items={item.ligand_id: item for item in items})
18
+
19
+ def set_status(self, ligand_id: str, status: str) -> None:
20
+ if status not in VALID_STATUSES:
21
+ raise ValueError(f"Invalid status: {status}")
22
+ self.items[ligand_id].status = status
23
+
24
+ def active_items(self) -> List[QueueItem]:
25
+ return [item for item in self.items.values() if item.status == "active"]
26
+
27
+ def completed_items(self) -> List[QueueItem]:
28
+ return [item for item in self.items.values() if item.status == "completed"]
29
+
30
+ def ordered_active(self) -> List[QueueItem]:
31
+ return sorted(self.active_items(), key=lambda item: item.priority, reverse=True)
libs/adaptive/scheduler.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import Dict, List
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from .metrics import score_metrics
11
+ from .policies import PrioritizationPolicy
12
+ from .prioritization import cluster_bonus, compute_priority
13
+ from .queue_manager import QueueManager
14
+ from .state import QueueItem, SchedulerState
15
+ from .surrogate_model import SurrogateConfig, SurrogateModel
16
+ from .weight_schedule import WeightScheduleConfig, compute_model_weight
17
+
18
+
19
+ @dataclass
20
+ class SchedulerConfig:
21
+ batch_size: int = 8
22
+ init_coverage_fraction: float = 0.25
23
+ conservative_deprioritize: bool = True
24
+ state_path: str = "results/state.json"
25
+ weight_schedule: WeightScheduleConfig = field(default_factory=WeightScheduleConfig)
26
+
27
+
28
+ class AdaptiveScheduler:
29
+ """Adaptive batch scheduler with queue state and online masked surrogate updates."""
30
+
31
+ def __init__(
32
+ self,
33
+ config: SchedulerConfig | None = None,
34
+ policy: PrioritizationPolicy | None = None,
35
+ surrogate_config: SurrogateConfig | None = None,
36
+ ) -> None:
37
+ self.config = config or SchedulerConfig()
38
+ self.policy = policy or PrioritizationPolicy()
39
+ self.surrogate = SurrogateModel(surrogate_config)
40
+ self.state = SchedulerState()
41
+ self.queue_manager = QueueManager.from_items([])
42
+ self.last_model_weight: float = 0.0
43
+
44
+ def initialize(
45
+ self,
46
+ ligands_df: pd.DataFrame,
47
+ cluster_map: Dict[str, int],
48
+ hypercluster_for_cluster: Dict[int, int],
49
+ ) -> None:
50
+ items: List[QueueItem] = []
51
+ cluster_load: Dict[int, int] = {}
52
+
53
+ for row in ligands_df.itertuples(index=False):
54
+ ligand_id = str(row.ligand_id)
55
+ cluster_id = int(cluster_map.get(ligand_id, -1))
56
+ hypercluster_id = int(hypercluster_for_cluster.get(cluster_id, -1))
57
+ bonus = cluster_bonus(cluster_load, cluster_id)
58
+ priority = compute_priority(
59
+ predicted_utility=0.0,
60
+ uncertainty=1.0,
61
+ diversity_gain=bonus,
62
+ cluster_bonus=bonus,
63
+ policy=self.policy,
64
+ )
65
+ items.append(
66
+ QueueItem(
67
+ ligand_id=ligand_id,
68
+ status="active",
69
+ priority=float(priority),
70
+ cluster_id=cluster_id,
71
+ hypercluster_id=hypercluster_id,
72
+ )
73
+ )
74
+ cluster_load[cluster_id] = cluster_load.get(cluster_id, 0) + 1
75
+
76
+ self.state = SchedulerState(queue=items, batch_history=[], round_idx=0)
77
+ self.queue_manager = QueueManager.from_items(items)
78
+
79
+ def select_batch(self) -> List[str]:
80
+ active = self.queue_manager.ordered_active()
81
+ if not active:
82
+ # If conservative deprioritization exhausted active queue, reactivate
83
+ # deprioritized candidates to continue spending the docking budget.
84
+ deprioritized = sorted(
85
+ [item for item in self.queue_manager.items.values() if item.status == "deprioritized"],
86
+ key=lambda item: item.priority,
87
+ reverse=True,
88
+ )
89
+ if not deprioritized:
90
+ return []
91
+ for item in deprioritized:
92
+ item.status = "active"
93
+ active = deprioritized
94
+
95
+ coverage_count = max(1, int(self.config.batch_size * self.config.init_coverage_fraction))
96
+ by_hypercluster: Dict[int, List[QueueItem]] = {}
97
+ for item in active:
98
+ by_hypercluster.setdefault(item.hypercluster_id, []).append(item)
99
+
100
+ selected: List[str] = []
101
+ # Broad initial coverage.
102
+ for _h_id, items in sorted(by_hypercluster.items(), key=lambda x: len(x[1]), reverse=True):
103
+ if len(selected) >= coverage_count:
104
+ break
105
+ selected.append(items[0].ligand_id)
106
+
107
+ # Fill remaining slots by priority.
108
+ for item in active:
109
+ if len(selected) >= self.config.batch_size:
110
+ break
111
+ if item.ligand_id not in selected:
112
+ selected.append(item.ligand_id)
113
+
114
+ for ligand_id in selected:
115
+ self.queue_manager.items[ligand_id].times_selected += 1
116
+ return selected
117
+
118
+ @staticmethod
119
+ def _mean_or_default(values: list[float], default: float = 0.0) -> float:
120
+ if not values:
121
+ return float(default)
122
+ return float(np.mean(np.asarray(values, dtype=float)))
123
+
124
+ def update_from_batch(
125
+ self,
126
+ evaluated_df: pd.DataFrame,
127
+ feature_values_df: pd.DataFrame,
128
+ feature_masks_df: pd.DataFrame,
129
+ ) -> Dict[str, float]:
130
+ # Mark completed ligands and store latest score.
131
+ score_map = dict(zip(evaluated_df["ligand_id"].astype(str), evaluated_df["docking_score"].astype(float)))
132
+ for ligand_id, score in score_map.items():
133
+ if ligand_id in self.queue_manager.items:
134
+ item = self.queue_manager.items[ligand_id]
135
+ item.status = "completed"
136
+ item.last_score = float(score)
137
+
138
+ if feature_values_df.empty or feature_masks_df.empty:
139
+ raise ValueError("Feature tables cannot be empty in adaptive update")
140
+
141
+ if "ligand_id" not in feature_values_df.columns or "ligand_id" not in feature_masks_df.columns:
142
+ raise ValueError("Feature tables must include ligand_id column")
143
+
144
+ ligand_order = feature_values_df["ligand_id"].astype(str).tolist()
145
+ features = feature_values_df.drop(columns=["ligand_id"]).to_numpy(dtype=float)
146
+ masks = feature_masks_df.drop(columns=["ligand_id"]).to_numpy(dtype=float)
147
+ feature_names = feature_values_df.drop(columns=["ligand_id"]).columns.tolist()
148
+ mask_names = feature_masks_df.drop(columns=["ligand_id"]).columns.tolist()
149
+
150
+ target = np.full(len(ligand_order), np.nan, dtype=float)
151
+ for i, ligand_id in enumerate(ligand_order):
152
+ if ligand_id in self.queue_manager.items:
153
+ score = self.queue_manager.items[ligand_id].last_score
154
+ if score is not None:
155
+ target[i] = float(score)
156
+
157
+ fit_stats = self.surrogate.fit(
158
+ features=features,
159
+ masks=masks,
160
+ y=target,
161
+ feature_names=feature_names,
162
+ mask_names=mask_names,
163
+ )
164
+
165
+ n_train = int(fit_stats.get("n_train", 0.0))
166
+ instability_ratio = float(fit_stats.get("instability_ratio", 1.0))
167
+ model_weight = compute_model_weight(
168
+ n_samples=n_train,
169
+ instability_ratio=instability_ratio,
170
+ config=self.config.weight_schedule,
171
+ )
172
+ if self.surrogate.model is None:
173
+ model_weight = 0.0
174
+ self.last_model_weight = float(model_weight)
175
+
176
+ # Predict for active items.
177
+ active_items = self.queue_manager.active_items()
178
+ active_ids = [item.ligand_id for item in active_items]
179
+
180
+ completed_items = [item for item in self.queue_manager.items.values() if item.last_score is not None]
181
+ global_completed = [float(item.last_score) for item in completed_items if item.last_score is not None]
182
+ global_mean_score = self._mean_or_default(global_completed, default=0.0)
183
+
184
+ cluster_scores: Dict[int, list[float]] = {}
185
+ hyper_scores: Dict[int, list[float]] = {}
186
+ for item in completed_items:
187
+ assert item.last_score is not None
188
+ cluster_scores.setdefault(item.cluster_id, []).append(float(item.last_score))
189
+ hyper_scores.setdefault(item.hypercluster_id, []).append(float(item.last_score))
190
+
191
+ if active_ids:
192
+ id_to_idx = {lid: idx for idx, lid in enumerate(ligand_order)}
193
+ x_active = np.vstack([features[id_to_idx[lid]] for lid in active_ids])
194
+ m_active = np.vstack([masks[id_to_idx[lid]] for lid in active_ids])
195
+ bundle = self.surrogate.predict_bundle(x_active, m_active)
196
+
197
+ cluster_load: Dict[int, int] = {}
198
+ for item in active_items:
199
+ cluster_load[item.cluster_id] = cluster_load.get(item.cluster_id, 0) + 1
200
+
201
+ for i, ligand_id in enumerate(active_ids):
202
+ item = self.queue_manager.items[ligand_id]
203
+
204
+ cluster_mean = self._mean_or_default(cluster_scores.get(item.cluster_id, []), default=np.nan)
205
+ hyper_mean = self._mean_or_default(hyper_scores.get(item.hypercluster_id, []), default=np.nan)
206
+ observed_docking = (
207
+ cluster_mean
208
+ if np.isfinite(cluster_mean)
209
+ else hyper_mean
210
+ if np.isfinite(hyper_mean)
211
+ else global_mean_score
212
+ )
213
+
214
+ docking_component = -float(observed_docking)
215
+ model_component = -float(bundle["expected_score"][i])
216
+ blended_utility = (1.0 - model_weight) * docking_component + model_weight * model_component
217
+
218
+ bonus = cluster_bonus(cluster_load, item.cluster_id)
219
+ item.priority = compute_priority(
220
+ predicted_utility=float(blended_utility),
221
+ uncertainty=float(bundle["uncertainty"][i]),
222
+ diversity_gain=bonus,
223
+ cluster_bonus=bonus,
224
+ policy=self.policy,
225
+ )
226
+
227
+ if self.config.conservative_deprioritize:
228
+ priorities = np.asarray([self.queue_manager.items[lid].priority for lid in active_ids], dtype=float)
229
+ threshold = float(np.quantile(priorities, self.policy.conservative_deprioritize_quantile))
230
+ for lid in active_ids:
231
+ if self.queue_manager.items[lid].priority < threshold:
232
+ self.queue_manager.items[lid].status = "deprioritized"
233
+
234
+ self.state.round_idx += 1
235
+ sm = score_metrics(evaluated_df["docking_score"].astype(float).tolist())
236
+ batch_record: Dict[str, float | str] = {
237
+ "round_idx": self.state.round_idx,
238
+ "batch_size": int(evaluated_df.shape[0]),
239
+ "model_weight": float(model_weight),
240
+ "n_train": float(n_train),
241
+ "train_mae": float(fit_stats.get("train_mae", np.nan)),
242
+ "val_mae": float(fit_stats.get("val_mae", np.nan)),
243
+ "instability_ratio": float(instability_ratio),
244
+ "surrogate_backend": self.surrogate.backend,
245
+ **sm,
246
+ }
247
+ self.state.batch_history.append(batch_record)
248
+ return fit_stats
249
+
250
+ def save_state(self, output_path: str | Path | None = None) -> Path:
251
+ target = Path(output_path or self.config.state_path)
252
+ self.state.queue = list(self.queue_manager.items.values())
253
+ return self.state.save(target)
libs/adaptive/state.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import asdict, dataclass, field
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List
6
+
7
+ import json
8
+
9
+
10
+ @dataclass
11
+ class QueueItem:
12
+ ligand_id: str
13
+ status: str = "active"
14
+ priority: float = 0.0
15
+ hypercluster_id: int = -1
16
+ cluster_id: int = -1
17
+ times_selected: int = 0
18
+ last_score: float | None = None
19
+
20
+
21
+ @dataclass
22
+ class SchedulerState:
23
+ queue: List[QueueItem] = field(default_factory=list)
24
+ batch_history: List[Dict[str, Any]] = field(default_factory=list)
25
+ round_idx: int = 0
26
+
27
+ def to_dict(self) -> Dict[str, Any]:
28
+ return {
29
+ "queue": [asdict(item) for item in self.queue],
30
+ "batch_history": self.batch_history,
31
+ "round_idx": self.round_idx,
32
+ }
33
+
34
+ @classmethod
35
+ def from_dict(cls, payload: Dict[str, Any]) -> "SchedulerState":
36
+ queue = [QueueItem(**item) for item in payload.get("queue", [])]
37
+ return cls(queue=queue, batch_history=payload.get("batch_history", []), round_idx=int(payload.get("round_idx", 0)))
38
+
39
+ def save(self, path: str | Path) -> Path:
40
+ target = Path(path)
41
+ target.parent.mkdir(parents=True, exist_ok=True)
42
+ with target.open("w", encoding="utf-8") as handle:
43
+ json.dump(self.to_dict(), handle, indent=2)
44
+ return target
45
+
46
+ @classmethod
47
+ def load(cls, path: str | Path) -> "SchedulerState":
48
+ source = Path(path)
49
+ with source.open("r", encoding="utf-8") as handle:
50
+ return cls.from_dict(json.load(handle))
libs/adaptive/surrogate_model.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, List, Optional
5
+
6
+ import numpy as np
7
+ from sklearn.ensemble import RandomForestRegressor
8
+
9
+ try:
10
+ from xgboost import XGBRegressor
11
+ except Exception: # pragma: no cover
12
+ XGBRegressor = None # type: ignore[assignment]
13
+
14
+
15
+ @dataclass
16
+ class SurrogateConfig:
17
+ prefer_xgboost: bool = True
18
+ random_state: int = 42
19
+ n_estimators: int = 200
20
+ min_train_samples: int = 8
21
+ max_depth_small: int = 3
22
+ max_depth_large: int = 6
23
+
24
+
25
+ class SurrogateModel:
26
+ """Surrogate model with explicit missing-feature masking support."""
27
+
28
+ def __init__(self, config: Optional[SurrogateConfig] = None):
29
+ self.config = config or SurrogateConfig()
30
+ self.model = None
31
+ self.backend = "uninitialized"
32
+ self.feature_names: List[str] = []
33
+ self.mask_names: List[str] = []
34
+
35
+ self._median: np.ndarray | None = None
36
+ self._iqr: np.ndarray | None = None
37
+ self._train_x: np.ndarray | None = None
38
+ self._train_y: np.ndarray | None = None
39
+ self.last_fit_stats: Dict[str, float] = {}
40
+
41
+ def _build_model(self, n_samples: int):
42
+ max_depth = self.config.max_depth_small if n_samples < 50 else self.config.max_depth_large
43
+ if self.config.prefer_xgboost and XGBRegressor is not None:
44
+ self.backend = "xgboost"
45
+ return XGBRegressor(
46
+ n_estimators=self.config.n_estimators,
47
+ max_depth=max_depth,
48
+ learning_rate=0.05,
49
+ subsample=0.9,
50
+ colsample_bytree=0.9,
51
+ reg_alpha=0.1,
52
+ reg_lambda=1.0,
53
+ random_state=self.config.random_state,
54
+ )
55
+
56
+ self.backend = "random_forest"
57
+ return RandomForestRegressor(
58
+ n_estimators=max(100, self.config.n_estimators),
59
+ max_depth=max_depth,
60
+ random_state=self.config.random_state,
61
+ n_jobs=-1,
62
+ )
63
+
64
+ def _fit_normalizer(self, x: np.ndarray, m: np.ndarray) -> None:
65
+ med = []
66
+ iqr = []
67
+ for j in range(x.shape[1]):
68
+ vals = x[m[:, j] > 0.5, j]
69
+ if vals.size == 0:
70
+ med.append(0.0)
71
+ iqr.append(1.0)
72
+ continue
73
+ q1 = float(np.quantile(vals, 0.25))
74
+ q3 = float(np.quantile(vals, 0.75))
75
+ inter = max(1e-6, q3 - q1)
76
+ med.append(float(np.median(vals)))
77
+ iqr.append(inter)
78
+ self._median = np.asarray(med, dtype=float)
79
+ self._iqr = np.asarray(iqr, dtype=float)
80
+
81
+ def _transform(self, x: np.ndarray, m: np.ndarray, fit: bool = False) -> np.ndarray:
82
+ x = np.asarray(x, dtype=float)
83
+ m = np.asarray(m, dtype=float)
84
+ if fit or self._median is None or self._iqr is None:
85
+ self._fit_normalizer(x, m)
86
+ assert self._median is not None and self._iqr is not None
87
+
88
+ x_filled = np.where(np.isfinite(x), x, np.nan)
89
+ for j in range(x.shape[1]):
90
+ col = x_filled[:, j]
91
+ missing = ~np.isfinite(col)
92
+ col[missing] = self._median[j]
93
+ x_filled[:, j] = (col - self._median[j]) / self._iqr[j]
94
+
95
+ # Explicit missingness information: concatenate mask vector.
96
+ return np.concatenate([x_filled, m], axis=1)
97
+
98
+ def fit(
99
+ self,
100
+ features: np.ndarray,
101
+ masks: np.ndarray,
102
+ y: np.ndarray,
103
+ feature_names: List[str],
104
+ mask_names: List[str],
105
+ ) -> Dict[str, float]:
106
+ y = np.asarray(y, dtype=float)
107
+ valid = np.isfinite(y)
108
+ n_samples = int(np.sum(valid))
109
+
110
+ self.feature_names = list(feature_names)
111
+ self.mask_names = list(mask_names)
112
+
113
+ if n_samples < self.config.min_train_samples:
114
+ self.model = None
115
+ self.backend = "warmup"
116
+ self.last_fit_stats = {
117
+ "n_train": float(n_samples),
118
+ "train_mae": np.nan,
119
+ "val_mae": np.nan,
120
+ "instability_ratio": 1.0,
121
+ }
122
+ return self.last_fit_stats
123
+
124
+ x = np.asarray(features, dtype=float)[valid]
125
+ m = np.asarray(masks, dtype=float)[valid]
126
+ yv = y[valid]
127
+
128
+ x_trans = self._transform(x, m, fit=True)
129
+ self._train_x = x_trans
130
+ self._train_y = yv
131
+
132
+ self.model = self._build_model(n_samples=n_samples)
133
+ self.model.fit(x_trans, yv)
134
+
135
+ train_pred = self.model.predict(x_trans)
136
+ train_mae = float(np.mean(np.abs(train_pred - yv)))
137
+
138
+ # Simple rolling validation proxy.
139
+ if n_samples >= 12:
140
+ split = int(max(8, n_samples * 0.8))
141
+ x_tr, x_val = x_trans[:split], x_trans[split:]
142
+ y_tr, y_val = yv[:split], yv[split:]
143
+
144
+ val_model = self._build_model(n_samples=split)
145
+ val_model.fit(x_tr, y_tr)
146
+ val_pred = val_model.predict(x_val)
147
+ val_mae = float(np.mean(np.abs(val_pred - y_val))) if y_val.size else train_mae
148
+ else:
149
+ val_mae = train_mae
150
+
151
+ instability = float((val_mae + 1e-6) / (train_mae + 1e-6))
152
+ self.last_fit_stats = {
153
+ "n_train": float(n_samples),
154
+ "train_mae": train_mae,
155
+ "val_mae": val_mae,
156
+ "instability_ratio": instability,
157
+ }
158
+ return self.last_fit_stats
159
+
160
+ def _rf_uncertainty(self, x: np.ndarray) -> np.ndarray:
161
+ assert self.model is not None
162
+ if not hasattr(self.model, "estimators_"):
163
+ return np.full(x.shape[0], float(np.std(self._train_y)) if self._train_y is not None else 1.0)
164
+ preds = np.vstack([tree.predict(x) for tree in self.model.estimators_])
165
+ return np.std(preds, axis=0)
166
+
167
+ def predict_bundle(self, features: np.ndarray, masks: np.ndarray, topk_threshold: float | None = None) -> Dict[str, np.ndarray]:
168
+ n = features.shape[0]
169
+ if self.model is None:
170
+ return {
171
+ "expected_score": np.zeros(n, dtype=float),
172
+ "topk_probability": np.full(n, 0.5, dtype=float),
173
+ "uncertainty": np.full(n, 1.0, dtype=float),
174
+ }
175
+
176
+ x = self._transform(np.asarray(features, dtype=float), np.asarray(masks, dtype=float), fit=False)
177
+ expected = self.model.predict(x)
178
+
179
+ if self.backend == "random_forest":
180
+ uncertainty = self._rf_uncertainty(x)
181
+ else:
182
+ residual_scale = (
183
+ float(np.std(self._train_y - self.model.predict(self._train_x)))
184
+ if self._train_x is not None and self._train_y is not None
185
+ else 1.0
186
+ )
187
+ uncertainty = np.full(expected.shape[0], max(1e-3, residual_scale))
188
+
189
+ if topk_threshold is None:
190
+ topk_threshold = float(np.quantile(self._train_y, 0.8)) if self._train_y is not None else 0.0
191
+
192
+ z = (expected - topk_threshold) / (uncertainty + 1e-6)
193
+ topk_prob = 1.0 / (1.0 + np.exp(-z))
194
+ return {
195
+ "expected_score": expected.astype(float),
196
+ "topk_probability": topk_prob.astype(float),
197
+ "uncertainty": uncertainty.astype(float),
198
+ }
199
+
200
+ def feature_importance(self) -> Dict[str, float]:
201
+ if self.model is None or not hasattr(self.model, "feature_importances_"):
202
+ return {}
203
+
204
+ names = self.feature_names + self.mask_names
205
+ importances = np.asarray(self.model.feature_importances_, dtype=float)
206
+ if importances.size != len(names):
207
+ return {}
208
+ return {name: float(value) for name, value in zip(names, importances)}
libs/adaptive/thresholding.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, List, Sequence
5
+
6
+ import numpy as np
7
+
8
+
9
+ @dataclass
10
+ class DynamicThresholdConfig:
11
+ min_evaluated: int = 500
12
+ patience_rounds: int = 8
13
+ min_model_weight: float = 0.35
14
+ quantile: float = 0.15
15
+ uncertainty_weight: float = 0.20
16
+ min_improvement: float = 0.02
17
+ exploration_margin: float = 0.45
18
+ exploitation_margin: float = 0.10
19
+ reference_evaluations: int = 5000
20
+
21
+
22
+ class DynamicEarlyStopController:
23
+ """
24
+ Conservative early-stop controller for adaptive replay.
25
+
26
+ Lower scores are considered better.
27
+ """
28
+
29
+ def __init__(self, config: DynamicThresholdConfig | None = None) -> None:
30
+ self.config = config or DynamicThresholdConfig()
31
+ self.best_score = np.inf
32
+ self.stagnant_rounds = 0
33
+ self.history: List[Dict[str, float | int | bool | str]] = []
34
+
35
+ def update(
36
+ self,
37
+ *,
38
+ round_idx: int,
39
+ n_evaluated: int,
40
+ all_scores: Sequence[float],
41
+ recent_scores: Sequence[float],
42
+ model_weight: float,
43
+ mean_uncertainty: float,
44
+ ) -> Dict[str, float | int | bool | str]:
45
+ cfg = self.config
46
+ scores = np.asarray(all_scores, dtype=float)
47
+ recent = np.asarray(recent_scores, dtype=float)
48
+
49
+ if scores.size == 0:
50
+ rec = {
51
+ "round_idx": int(round_idx),
52
+ "n_evaluated": int(n_evaluated),
53
+ "dynamic_threshold": np.nan,
54
+ "score_quantile": np.nan,
55
+ "best_score": np.nan,
56
+ "recent_mean_score": np.nan,
57
+ "mean_uncertainty": float(mean_uncertainty),
58
+ "model_weight": float(model_weight),
59
+ "stagnant_rounds": int(self.stagnant_rounds),
60
+ "eligible_for_stop": False,
61
+ "stop": False,
62
+ "reason": "no_scores",
63
+ }
64
+ self.history.append(rec)
65
+ return rec
66
+
67
+ score_quantile = float(np.nanquantile(scores, cfg.quantile))
68
+ best = float(np.nanmin(scores))
69
+ recent_mean = float(np.nanmean(recent)) if recent.size else float(np.nan)
70
+ uncertainty = float(max(0.0, mean_uncertainty))
71
+
72
+ if np.isfinite(self.best_score):
73
+ improvement = float(self.best_score - best)
74
+ else:
75
+ improvement = np.inf
76
+
77
+ if improvement > cfg.min_improvement:
78
+ self.stagnant_rounds = 0
79
+ else:
80
+ self.stagnant_rounds += 1
81
+ self.best_score = min(self.best_score, best)
82
+
83
+ coverage = float(min(1.0, n_evaluated / max(1.0, float(cfg.reference_evaluations))))
84
+ margin = (1.0 - coverage) * cfg.exploration_margin + coverage * cfg.exploitation_margin
85
+ dynamic_threshold = float(score_quantile + margin + cfg.uncertainty_weight * uncertainty)
86
+
87
+ eligible = (
88
+ int(n_evaluated) >= int(cfg.min_evaluated)
89
+ and float(model_weight) >= float(cfg.min_model_weight)
90
+ )
91
+ plateau = self.stagnant_rounds >= int(cfg.patience_rounds)
92
+ poor_recent = bool(np.isfinite(recent_mean) and recent_mean >= dynamic_threshold)
93
+ should_stop = bool(eligible and plateau and poor_recent)
94
+
95
+ if not eligible:
96
+ reason = "not_eligible"
97
+ elif not plateau:
98
+ reason = "improving_or_not_stagnant"
99
+ elif not poor_recent:
100
+ reason = "recent_batch_still_competitive"
101
+ else:
102
+ reason = "stagnation_above_dynamic_threshold"
103
+
104
+ rec = {
105
+ "round_idx": int(round_idx),
106
+ "n_evaluated": int(n_evaluated),
107
+ "dynamic_threshold": dynamic_threshold,
108
+ "score_quantile": score_quantile,
109
+ "best_score": self.best_score,
110
+ "recent_mean_score": recent_mean,
111
+ "mean_uncertainty": uncertainty,
112
+ "model_weight": float(model_weight),
113
+ "stagnant_rounds": int(self.stagnant_rounds),
114
+ "eligible_for_stop": bool(eligible),
115
+ "stop": should_stop,
116
+ "reason": reason,
117
+ }
118
+ self.history.append(rec)
119
+ return rec
120
+
libs/adaptive/weight_schedule.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Sequence
5
+
6
+
7
+ @dataclass
8
+ class WeightScheduleConfig:
9
+ sample_knots: tuple[int, int, int, int] = (20, 50, 100, 200)
10
+ weight_knots: tuple[float, float, float, float] = (0.1, 0.3, 0.5, 0.8)
11
+ max_weight: float = 0.9
12
+ min_weight: float = 0.05
13
+ instability_threshold: float = 2.0
14
+ instability_decay: float = 0.25
15
+
16
+
17
+ def _interp(x: float, xs: Sequence[float], ys: Sequence[float]) -> float:
18
+ if x <= xs[0]:
19
+ return float(ys[0])
20
+ if x >= xs[-1]:
21
+ return float(ys[-1])
22
+
23
+ for i in range(1, len(xs)):
24
+ if x <= xs[i]:
25
+ x0, x1 = xs[i - 1], xs[i]
26
+ y0, y1 = ys[i - 1], ys[i]
27
+ t = (x - x0) / max(1e-9, (x1 - x0))
28
+ return float(y0 + t * (y1 - y0))
29
+ return float(ys[-1])
30
+
31
+
32
+ def compute_model_weight(
33
+ n_samples: int,
34
+ instability_ratio: float = 1.0,
35
+ config: WeightScheduleConfig | None = None,
36
+ ) -> float:
37
+ cfg = config or WeightScheduleConfig()
38
+
39
+ base = _interp(float(n_samples), cfg.sample_knots, cfg.weight_knots)
40
+ if n_samples > cfg.sample_knots[-1]:
41
+ extra = min(cfg.max_weight - base, 0.05 * (n_samples - cfg.sample_knots[-1]) / 100.0)
42
+ base += max(0.0, extra)
43
+
44
+ if instability_ratio > cfg.instability_threshold:
45
+ base *= max(0.1, 1.0 - cfg.instability_decay)
46
+
47
+ base = max(cfg.min_weight, min(cfg.max_weight, base))
48
+ return float(base)
libs/analysis/__init__.py ADDED
File without changes
libs/analysis/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (162 Bytes). View file
 
libs/analysis/__pycache__/backend_diagnostic.cpython-312.pyc ADDED
Binary file (9.22 kB). View file
 
libs/analysis/__pycache__/ranking.cpython-312.pyc ADDED
Binary file (1.94 kB). View file
 
libs/analysis/backend_diagnostic.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Any, Iterable
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+
11
+ REQUIRED_REFERENCE_DIAG_COLUMNS = [
12
+ "dataset",
13
+ "target_name",
14
+ "reference_ligand_id",
15
+ "reference_ligand_score",
16
+ "reference_ligand_rank_percentile",
17
+ "adaptive_best_score",
18
+ "exhaustive_best_score",
19
+ ]
20
+
21
+ REQUIRED_BACKEND_COMPARISON_COLUMNS = [
22
+ "dataset",
23
+ "backend",
24
+ "analysis_scope",
25
+ "available",
26
+ "n_ligands",
27
+ "runtime_seconds",
28
+ "runtime_per_ligand",
29
+ "reference_ligand_score",
30
+ "reference_ligand_rank_percentile",
31
+ "best_score",
32
+ "score_gap_reference_vs_best",
33
+ "reference_pose_centroid_distance_A",
34
+ "reference_pose_in_expected_pocket",
35
+ ]
36
+
37
+ REQUIRED_POCKET_PREP_COLUMNS = [
38
+ "dataset",
39
+ "backend",
40
+ "pocket_variant",
41
+ "prep_variant",
42
+ "reference_ligand_score",
43
+ "reference_pose_centroid_distance_A",
44
+ "reference_pose_in_expected_pocket",
45
+ ]
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class ManualAgentsCheck:
50
+ exists: bool
51
+ path: str
52
+ manually_read: bool
53
+
54
+
55
+ def manual_agents_check(path: str | Path, manually_read: bool = True) -> ManualAgentsCheck:
56
+ p = Path(path).expanduser().resolve()
57
+ return ManualAgentsCheck(exists=p.exists(), path=str(p), manually_read=bool(manually_read and p.exists()))
58
+
59
+
60
+ def _safe_float(x: Any, default: float = np.nan) -> float:
61
+ try:
62
+ v = float(x)
63
+ return float(v) if np.isfinite(v) else float(default)
64
+ except Exception:
65
+ return float(default)
66
+
67
+
68
+ def compute_rank_percentile(df: pd.DataFrame, ligand_id: str, score_col: str, lower_is_better: bool = True) -> float:
69
+ if df.empty or score_col not in df.columns:
70
+ return np.nan
71
+ d = df[["ligand_id", score_col]].copy()
72
+ d["ligand_id"] = d["ligand_id"].astype(str)
73
+ d[score_col] = pd.to_numeric(d[score_col], errors="coerce")
74
+ d = d.dropna(subset=[score_col]).copy()
75
+ if d.empty:
76
+ return np.nan
77
+ d = d.sort_values(score_col, ascending=bool(lower_is_better)).reset_index(drop=True)
78
+ hit = d.index[d["ligand_id"] == str(ligand_id)]
79
+ if len(hit) == 0:
80
+ return np.nan
81
+ rank = int(hit[0]) + 1
82
+ return float(100.0 * rank / max(1, d.shape[0]))
83
+
84
+
85
+ def select_suspicious_datasets(reference_diag_df: pd.DataFrame, threshold_pct: float = 25.0, max_deep: int = 2) -> list[str]:
86
+ if reference_diag_df.empty:
87
+ return []
88
+ d = reference_diag_df.copy()
89
+ d["reference_ligand_rank_percentile"] = pd.to_numeric(d["reference_ligand_rank_percentile"], errors="coerce")
90
+ d = d.dropna(subset=["reference_ligand_rank_percentile"]).copy()
91
+ d = d[d["reference_ligand_rank_percentile"] >= float(threshold_pct)].copy()
92
+ if d.empty:
93
+ return []
94
+ d = d.sort_values("reference_ligand_rank_percentile", ascending=False)
95
+ return d["dataset"].astype(str).head(int(max(1, max_deep))).tolist()
96
+
97
+
98
+ def validate_required_columns(df: pd.DataFrame, required_columns: Iterable[str]) -> list[str]:
99
+ cols = set(df.columns)
100
+ missing = [c for c in required_columns if c not in cols]
101
+ return missing
102
+
103
+
104
+ def recommend_toolchain(
105
+ backend_comparison_df: pd.DataFrame,
106
+ pocket_prep_df: pd.DataFrame,
107
+ ) -> dict[str, Any]:
108
+ """
109
+ Choose practical recommendation from diagnostic evidence.
110
+
111
+ Policy:
112
+ - Prefer backend with best median reference rank percentile under "subset_default" scope.
113
+ - Penalize poor runtime-per-ligand if >2x best runtime.
114
+ - Use pocket/prep gain to detect whether core issue is mostly preparation/pocket.
115
+ """
116
+ out: dict[str, Any] = {
117
+ "recommended_main_backend": "rdock",
118
+ "recommended_rescoring": "gnina_or_haddock_shortlist_optional",
119
+ "keep_haddock": "optional_shortlist_only",
120
+ "main_failure_source": "mixed",
121
+ "evidence": [],
122
+ }
123
+
124
+ bdf = backend_comparison_df.copy()
125
+ if not bdf.empty:
126
+ bdf = bdf[bdf["analysis_scope"].astype(str) == "subset_default"].copy()
127
+ if not bdf.empty:
128
+ bdf["runtime_per_ligand"] = pd.to_numeric(bdf["runtime_per_ligand"], errors="coerce")
129
+ bdf["reference_ligand_rank_percentile"] = pd.to_numeric(bdf["reference_ligand_rank_percentile"], errors="coerce")
130
+ agg = (
131
+ bdf.groupby("backend", as_index=False)
132
+ .agg(
133
+ median_ref_rank_pct=("reference_ligand_rank_percentile", "median"),
134
+ median_runtime=("runtime_per_ligand", "median"),
135
+ available_ratio=("available", "mean"),
136
+ )
137
+ .sort_values(["median_ref_rank_pct", "median_runtime"], ascending=[True, True])
138
+ )
139
+ if not agg.empty:
140
+ best = agg.iloc[0]
141
+ best_runtime = max(1e-9, _safe_float(best["median_runtime"], 1.0))
142
+ candidate = str(best["backend"])
143
+ if _safe_float(best["available_ratio"], 0.0) < 0.5:
144
+ out["evidence"].append("best_rank_backend_not_reliably_available")
145
+ else:
146
+ out["recommended_main_backend"] = candidate
147
+
148
+ rd = agg[agg["backend"].astype(str).str.lower() == "rdock"]
149
+ if not rd.empty:
150
+ rd_runtime = max(1e-9, _safe_float(rd.iloc[0]["median_runtime"], best_runtime))
151
+ if best_runtime > 2.0 * rd_runtime and candidate != "rdock":
152
+ out["evidence"].append("candidate_backend_too_slow_vs_rdock")
153
+ out["recommended_main_backend"] = "rdock"
154
+
155
+ out["evidence"].append(f"rank_runtime_table={agg.to_dict(orient='records')}")
156
+
157
+ pdf = pocket_prep_df.copy()
158
+ if not pdf.empty:
159
+ pdf["reference_ligand_score"] = pd.to_numeric(pdf["reference_ligand_score"], errors="coerce")
160
+ deltas: list[float] = []
161
+ for (_, _), sub in pdf.groupby(["dataset", "backend"]):
162
+ default = sub[(sub["pocket_variant"] == "default") & (sub["prep_variant"] == "default")]
163
+ if default.empty:
164
+ continue
165
+ default_score = _safe_float(default.iloc[0]["reference_ligand_score"], np.nan)
166
+ best_score = _safe_float(sub["reference_ligand_score"].min(), np.nan)
167
+ if np.isfinite(default_score) and np.isfinite(best_score):
168
+ deltas.append(default_score - best_score)
169
+ mean_gain = float(np.mean(np.asarray(deltas, dtype=float))) if deltas else 0.0
170
+ if mean_gain > 1.0:
171
+ out["main_failure_source"] = "pocket_or_preparation"
172
+ elif mean_gain > 0.2:
173
+ out["main_failure_source"] = "mixed"
174
+ else:
175
+ out["main_failure_source"] = "backend_scoring_limitations"
176
+ out["evidence"].append(f"mean_reference_gain_from_pocket_prep={mean_gain:.3f}")
177
+
178
+ out["keep_haddock"] = "optional_shortlist_only"
179
+ return out
libs/analysis/ranking.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+
7
+ def resolve_reference_rank_percentile(
8
+ merged_df: pd.DataFrame,
9
+ reference_ligand_id: str,
10
+ *,
11
+ oracle_rank_col: str = "rank_percentile",
12
+ run_rank_col: str = "run_rank_percentile",
13
+ ) -> tuple[float, str]:
14
+ """
15
+ Resolve reference rank percentile with robust fallback.
16
+
17
+ Returns:
18
+ - rank percentile (float)
19
+ - source ("oracle", "run_fallback", "missing")
20
+ """
21
+ if merged_df.empty:
22
+ return float("nan"), "missing"
23
+
24
+ d = merged_df.copy()
25
+ if "ligand_id" not in d.columns:
26
+ return float("nan"), "missing"
27
+ d["ligand_id"] = d["ligand_id"].astype(str)
28
+ ref = d[d["ligand_id"] == str(reference_ligand_id)]
29
+ if ref.empty:
30
+ return float("nan"), "missing"
31
+
32
+ if oracle_rank_col in ref.columns:
33
+ oracle_val = pd.to_numeric(ref[oracle_rank_col], errors="coerce").iloc[0]
34
+ if np.isfinite(float(oracle_val)):
35
+ return float(oracle_val), "oracle"
36
+
37
+ if run_rank_col in d.columns:
38
+ run_val = pd.to_numeric(ref[run_rank_col], errors="coerce").iloc[0]
39
+ if np.isfinite(float(run_val)):
40
+ return float(run_val), "run_fallback"
41
+
42
+ return float("nan"), "missing"
43
+
libs/benchmark/__init__.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Benchmark utilities for large-scale and modality sanity-check runs."""
2
+
3
+ from .cleanup import CleanupItem, execute_results_cleanup, plan_results_cleanup
4
+ from .budget_efficiency import (
5
+ TimeImportanceControls,
6
+ clamp_time_importance,
7
+ controls_from_time_importance,
8
+ required_budget_metric_columns,
9
+ select_best_policy_budget,
10
+ summarize_diversity,
11
+ validate_budget_metric_schema,
12
+ )
13
+ from .disk_guard import (
14
+ DiskCleanupAction,
15
+ DiskSnapshot,
16
+ append_disk_snapshot,
17
+ requires_cleanup,
18
+ run_repository_local_cleanup,
19
+ snapshot_disk_state,
20
+ write_cleanup_actions,
21
+ write_disk_guard_report,
22
+ )
23
+ from .large_library import build_large_benchmark_library
24
+ from .ordering import cluster_naive_order
25
+ from .policy_repair import (
26
+ AdaptivePolicyVariant,
27
+ PolicyRuntimeState,
28
+ apply_stop_policy,
29
+ coverage_floor_reached,
30
+ coverage_fraction,
31
+ default_policy_variants,
32
+ effective_controls,
33
+ regret_stop_variant,
34
+ select_cluster_bootstrap_batch,
35
+ )
36
+ from .multifidelity import (
37
+ ExplorationControls,
38
+ StoppingControls,
39
+ UncertaintyControls,
40
+ controls_from_config,
41
+ enforce_control_limits,
42
+ simulate_multifidelity_policy,
43
+ )
44
+ from .overnight_stop import (
45
+ OBJECTIVES,
46
+ STOP_MODELS,
47
+ StopModelParams,
48
+ estimate_marginal_expected_gain,
49
+ estimate_probability_target_percentile,
50
+ is_trivial_objective_solution,
51
+ objective_value,
52
+ simulate_stop_model,
53
+ )
54
+ from .runtime import AUTO_MINUS_FOUR, ThreadAllocation, detect_system_threads, enforce_thread_fairness, resolve_threads_used
55
+ from .reuse import ReuseCheck, validate_reuse_inputs
56
+
57
+ __all__ = [
58
+ "AUTO_MINUS_FOUR",
59
+ "AdaptivePolicyVariant",
60
+ "CleanupItem",
61
+ "DiskCleanupAction",
62
+ "DiskSnapshot",
63
+ "PolicyRuntimeState",
64
+ "TimeImportanceControls",
65
+ "ThreadAllocation",
66
+ "ReuseCheck",
67
+ "apply_stop_policy",
68
+ "append_disk_snapshot",
69
+ "build_large_benchmark_library",
70
+ "clamp_time_importance",
71
+ "cluster_naive_order",
72
+ "coverage_floor_reached",
73
+ "coverage_fraction",
74
+ "controls_from_time_importance",
75
+ "default_policy_variants",
76
+ "detect_system_threads",
77
+ "effective_controls",
78
+ "estimate_marginal_expected_gain",
79
+ "estimate_probability_target_percentile",
80
+ "enforce_thread_fairness",
81
+ "execute_results_cleanup",
82
+ "is_trivial_objective_solution",
83
+ "objective_value",
84
+ "OBJECTIVES",
85
+ "STOP_MODELS",
86
+ "plan_results_cleanup",
87
+ "required_budget_metric_columns",
88
+ "regret_stop_variant",
89
+ "requires_cleanup",
90
+ "resolve_threads_used",
91
+ "run_repository_local_cleanup",
92
+ "simulate_multifidelity_policy",
93
+ "simulate_stop_model",
94
+ "StopModelParams",
95
+ "StoppingControls",
96
+ "ExplorationControls",
97
+ "UncertaintyControls",
98
+ "controls_from_config",
99
+ "enforce_control_limits",
100
+ "validate_reuse_inputs",
101
+ "select_best_policy_budget",
102
+ "select_cluster_bootstrap_batch",
103
+ "snapshot_disk_state",
104
+ "summarize_diversity",
105
+ "validate_budget_metric_schema",
106
+ "write_cleanup_actions",
107
+ "write_disk_guard_report",
108
+ ]
libs/benchmark/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (2.98 kB). View file
 
libs/benchmark/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (2.44 kB). View file
 
libs/benchmark/__pycache__/budget_efficiency.cpython-311.pyc ADDED
Binary file (7.96 kB). View file
 
libs/benchmark/__pycache__/budget_efficiency.cpython-312.pyc ADDED
Binary file (6.87 kB). View file
 
libs/benchmark/__pycache__/cleanup.cpython-311.pyc ADDED
Binary file (3.13 kB). View file
 
libs/benchmark/__pycache__/cleanup.cpython-312.pyc ADDED
Binary file (2.67 kB). View file