proef 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- proef/__init__.py +25 -0
- proef/acquisition.py +244 -0
- proef/ad.py +159 -0
- proef/adapters/__init__.py +0 -0
- proef/adapters/admet.py +196 -0
- proef/adapters/bio/__init__.py +0 -0
- proef/adapters/bio/rdkit_ops.py +52 -0
- proef/adapters/bio/safety_rules.json +146 -0
- proef/adapters/bio/seq_alerts.py +79 -0
- proef/adapters/bio/structure_score.py +85 -0
- proef/adapters/bio/tox_alerts.py +99 -0
- proef/adapters/data/__init__.py +0 -0
- proef/adapters/data/admet.py +62 -0
- proef/adapters/data/chembl.py +110 -0
- proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
- proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
- proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
- proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
- proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
- proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
- proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
- proef/adapters/data/moleculenet.py +60 -0
- proef/adapters/databases/__init__.py +0 -0
- proef/adapters/databases/chembl_gates.py +121 -0
- proef/adapters/databases/chembl_lookup.py +35 -0
- proef/adapters/databases/open_targets.py +102 -0
- proef/adapters/databases/pubmed.py +94 -0
- proef/adapters/devices/__init__.py +0 -0
- proef/adapters/devices/ezo_ph.py +251 -0
- proef/adapters/devices/hcs_microscope.py +143 -0
- proef/adapters/devices/lcms.py +123 -0
- proef/adapters/devices/scheduler.py +84 -0
- proef/adapters/devices/sila2.py +134 -0
- proef/adapters/genomics/alphagenome.py +146 -0
- proef/adapters/lab/__init__.py +0 -0
- proef/adapters/lab/bioprocess.py +32 -0
- proef/adapters/lab/devices.py +170 -0
- proef/adapters/lab/imaging.py +226 -0
- proef/adapters/lab/mhs_driver.py +124 -0
- proef/adapters/lab/opentrons.py +222 -0
- proef/adapters/lab/ot2_sim.py +174 -0
- proef/adapters/lab/plate_reader_share.py +108 -0
- proef/adapters/lab/protein_design.py +199 -0
- proef/adapters/lab/recording.py +119 -0
- proef/adapters/lab/replay.py +107 -0
- proef/adapters/lab/simulator.py +282 -0
- proef/adapters/lab/synthesis.py +92 -0
- proef/adapters/models/__init__.py +0 -0
- proef/adapters/models/anthropic_provider.py +157 -0
- proef/adapters/models/assayloop_ranker.py +67 -0
- proef/adapters/models/from_env.py +93 -0
- proef/adapters/models/gp_policy.py +93 -0
- proef/adapters/models/gp_policy_gp.py +36 -0
- proef/adapters/models/llm_policy.py +187 -0
- proef/adapters/models/openai_compat.py +150 -0
- proef/adapters/models/sklearn_policy.py +65 -0
- proef/adapters/retrosynthesis.py +247 -0
- proef/adapters/sandbox/__init__.py +20 -0
- proef/adapters/sandbox/agentenv.py +145 -0
- proef/adapters/sandbox/docker.py +217 -0
- proef/adapters/sandbox/local.py +164 -0
- proef/adapters/sandbox/opensandbox.py +122 -0
- proef/adapters/store/__init__.py +0 -0
- proef/adapters/store/sqlite.py +207 -0
- proef/adaptive.py +108 -0
- proef/advisory.py +76 -0
- proef/analysis_profiles/__init__.py +8 -0
- proef/analysis_profiles/measurements.py +266 -0
- proef/analysis_profiles/plate_assay.py +316 -0
- proef/analysis_report.py +195 -0
- proef/analysis_store.py +183 -0
- proef/anchor.py +154 -0
- proef/api/app.py +107 -0
- proef/api/launch.py +170 -0
- proef/api/v1/__init__.py +29 -0
- proef/api/v1/analyses.py +367 -0
- proef/api/v1/campaigns.py +802 -0
- proef/api/v1/deps.py +10 -0
- proef/api/v1/evals.py +16 -0
- proef/api/v1/evidence.py +132 -0
- proef/api/v1/governance.py +35 -0
- proef/api/v1/inbox.py +119 -0
- proef/api/v1/lab.py +110 -0
- proef/api/v1/pauses.py +77 -0
- proef/api/v1/programs.py +397 -0
- proef/api/v1/results.py +147 -0
- proef/api/v1/schemas.py +932 -0
- proef/api/v1/system.py +79 -0
- proef/api/v1/trees.py +216 -0
- proef/api/wizard_sessions.py +253 -0
- proef/approvals.py +102 -0
- proef/assays/__init__.py +15 -0
- proef/assays/dls.py +114 -0
- proef/assays/dsf.py +81 -0
- proef/assays/elisa.py +58 -0
- proef/assays/properties.py +65 -0
- proef/assays/simulate.py +157 -0
- proef/audit.py +152 -0
- proef/autoloop.py +1620 -0
- proef/benchmark.py +442 -0
- proef/campaign_fsm.py +151 -0
- proef/citations.py +141 -0
- proef/cli.py +1249 -0
- proef/connect.py +74 -0
- proef/core/__init__.py +0 -0
- proef/core/contracts/__init__.py +35 -0
- proef/core/contracts/analysis.py +100 -0
- proef/core/contracts/models.py +395 -0
- proef/core/device_card.py +125 -0
- proef/core/hypothesis.py +720 -0
- proef/core/interfaces.py +164 -0
- proef/core/registry.py +123 -0
- proef/core/safety.py +324 -0
- proef/core/workflow.py +159 -0
- proef/critic.py +62 -0
- proef/demo.py +164 -0
- proef/derivation.py +128 -0
- proef/diary.py +301 -0
- proef/eln.py +87 -0
- proef/evals/__init__.py +1 -0
- proef/evals/hallucination.py +86 -0
- proef/evals/harness.py +358 -0
- proef/evals/orchestration.py +254 -0
- proef/evals/tasks.py +1010 -0
- proef/evals/toolcalls.py +425 -0
- proef/experiment.py +172 -0
- proef/experiment_analysis.py +114 -0
- proef/experiments/__init__.py +0 -0
- proef/experiments/grounding_exp.py +689 -0
- proef/figures.py +218 -0
- proef/fitting.py +309 -0
- proef/fixtures.py +140 -0
- proef/flywheel.py +125 -0
- proef/followup.py +126 -0
- proef/governance.py +290 -0
- proef/groundedness.py +361 -0
- proef/grounding.py +202 -0
- proef/hypothesis_agent.py +369 -0
- proef/ingest.py +157 -0
- proef/instruments.json +173 -0
- proef/interpret.py +95 -0
- proef/kinetic.py +102 -0
- proef/labread/__init__.py +45 -0
- proef/labread/analysis.py +428 -0
- proef/labread/common.py +153 -0
- proef/labread/formats.py +190 -0
- proef/labread/layout.py +168 -0
- proef/labread/pubchem.py +179 -0
- proef/labselect.py +431 -0
- proef/materials.py +140 -0
- proef/mcp_instrument.py +396 -0
- proef/mcp_server.py +283 -0
- proef/modality.py +111 -0
- proef/model_guard.py +245 -0
- proef/output_blocks.py +183 -0
- proef/paths.py +32 -0
- proef/physfail.py +55 -0
- proef/plan.py +160 -0
- proef/plots.py +123 -0
- proef/predictors.py +217 -0
- proef/probes.py +79 -0
- proef/problem_tree.py +581 -0
- proef/program.py +308 -0
- proef/protocol_design.py +42 -0
- proef/proxy.py +78 -0
- proef/readiness.py +259 -0
- proef/reliability.py +49 -0
- proef/report.py +117 -0
- proef/reproduce.py +310 -0
- proef/reviewer.py +254 -0
- proef/sandbox_session.py +247 -0
- proef/sandboxd.py +109 -0
- proef/scaffold.py +195 -0
- proef/series.py +327 -0
- proef/skills.py +203 -0
- proef/sweep.py +83 -0
- proef/taste.py +177 -0
- proef/templates/confirmatory-followup.json +34 -0
- proef/templates/dose-response-screen.json +39 -0
- proef/templates/sar-exploration.json +38 -0
- proef/templates.py +124 -0
- proef/toolkit.py +433 -0
- proef/toolloop.py +133 -0
- proef/tools.py +441 -0
- proef/tpp.py +185 -0
- proef/views/__init__.py +14 -0
- proef/views/counts.py +102 -0
- proef/views/experiment.py +154 -0
- proef/views/ids.py +49 -0
- proef/views/narrative.py +294 -0
- proef/views/pipeline.py +370 -0
- proef/vision.py +165 -0
- proef/watch.py +790 -0
- proef/wizard_chain.py +25 -0
- proef/wizard_store.py +373 -0
- proef-0.2.0.dist-info/METADATA +662 -0
- proef-0.2.0.dist-info/RECORD +200 -0
- proef-0.2.0.dist-info/WHEEL +4 -0
- proef-0.2.0.dist-info/entry_points.txt +14 -0
- proef-0.2.0.dist-info/licenses/LICENSE +202 -0
proef/benchmark.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
"""Benchmark harness (P2: policies vs datasets, all offline-capable).
|
|
2
|
+
|
|
3
|
+
A Policy maps a SMILES -> prediction. The harness scores policies on a
|
|
4
|
+
DatasetAdapter with standard metrics and records results as provenance-friendly
|
|
5
|
+
JSON. Built-in baselines:
|
|
6
|
+
|
|
7
|
+
- RandomPolicy — sanity floor
|
|
8
|
+
- CharRidgePolicy — pure-Python char n-gram + ridge regression (no deps)
|
|
9
|
+
- RDKitDescPolicy — RDKit descriptors + ridge (requires [bio-rdkit])
|
|
10
|
+
|
|
11
|
+
These are deliberately weak baselines: their job is to validate the harness and
|
|
12
|
+
give a floor that real model adapters must beat.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import math
|
|
19
|
+
import time
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Callable
|
|
22
|
+
from typing import Any, Protocol
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Policy(Protocol):
|
|
26
|
+
name: str
|
|
27
|
+
|
|
28
|
+
def fit(self, data: list[tuple[str, float]]) -> None: ...
|
|
29
|
+
|
|
30
|
+
def predict(self, smiles: str) -> float: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---------------------------------------------------------------- baselines
|
|
34
|
+
|
|
35
|
+
class RandomPolicy:
|
|
36
|
+
name = "random"
|
|
37
|
+
|
|
38
|
+
def fit(self, data): # noqa: ARG002
|
|
39
|
+
self.mean = sum(y for _, y in data) / len(data)
|
|
40
|
+
|
|
41
|
+
def predict(self, smiles: str) -> float: # noqa: ARG002
|
|
42
|
+
h = int(hashlib.sha256(smiles.encode()).hexdigest()[:8], 16)
|
|
43
|
+
return self.mean + (h % 100) / 100.0 - 0.5
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class MeanPolicy:
|
|
47
|
+
name = "predict-mean"
|
|
48
|
+
|
|
49
|
+
def fit(self, data):
|
|
50
|
+
self.mean = sum(y for _, y in data) / len(data)
|
|
51
|
+
|
|
52
|
+
def predict(self, smiles: str) -> float: # noqa: ARG002
|
|
53
|
+
return self.mean
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CharRidgePolicy:
|
|
57
|
+
"""Hashed char 3-gram features + closed-form ridge regression. Stdlib only."""
|
|
58
|
+
|
|
59
|
+
name = "char3gram-ridge"
|
|
60
|
+
|
|
61
|
+
def __init__(self, ngram: int = 3, l2: float = 1.0, dim: int = 256):
|
|
62
|
+
self.ngram, self.l2, self.dim = ngram, l2, dim
|
|
63
|
+
|
|
64
|
+
def _featurize(self, smiles: str) -> list[float]:
|
|
65
|
+
v = [0.0] * self.dim
|
|
66
|
+
for i in range(len(smiles) - self.ngram + 1):
|
|
67
|
+
g = smiles[i:i + self.ngram]
|
|
68
|
+
h = int(hashlib.md5(g.encode()).hexdigest()[:8], 16) # noqa: S324
|
|
69
|
+
v[h % self.dim] += 1.0
|
|
70
|
+
norm = math.sqrt(sum(x * x for x in v)) or 1.0
|
|
71
|
+
return [x / norm for x in v]
|
|
72
|
+
|
|
73
|
+
def fit(self, data: list[tuple[str, float]]) -> None:
|
|
74
|
+
X = [self._featurize(s) for s, _ in data]
|
|
75
|
+
y = [label for _, label in data]
|
|
76
|
+
self.mean = sum(y) / len(y)
|
|
77
|
+
yc = [v - self.mean for v in y]
|
|
78
|
+
d = self.dim
|
|
79
|
+
ata = [[0.0] * d for _ in range(d)]
|
|
80
|
+
aty = [0.0] * d
|
|
81
|
+
for xi, yi in zip(X, yc):
|
|
82
|
+
nz = [(j, v) for j, v in enumerate(xi) if v]
|
|
83
|
+
for a, va in nz:
|
|
84
|
+
aty[a] += va * yi
|
|
85
|
+
for b, vb in nz:
|
|
86
|
+
ata[a][b] += va * vb
|
|
87
|
+
for j in range(d):
|
|
88
|
+
ata[j][j] += self.l2
|
|
89
|
+
self.w = _solve(ata, aty)
|
|
90
|
+
from proef.ad import ApplicabilityDomain
|
|
91
|
+
self.ad = ApplicabilityDomain.from_smiles([s for s, _ in data],
|
|
92
|
+
basis="char3")
|
|
93
|
+
|
|
94
|
+
def predict(self, smiles: str) -> float:
|
|
95
|
+
x = self._featurize(smiles)
|
|
96
|
+
return self.mean + sum(w * v for w, v in zip(self.w, x) if v)
|
|
97
|
+
|
|
98
|
+
def predict_with_ad(self, smiles: str) -> tuple[float, dict]:
|
|
99
|
+
"""predict() + nearest-neighbour Tanimoto applicability-domain
|
|
100
|
+
stamp (char 3-gram basis): the number always comes back, but
|
|
101
|
+
outside the training chemistry it carries `extrapolation` so
|
|
102
|
+
abstention rules widen and cards chip — the local-model guard."""
|
|
103
|
+
return self.predict(smiles), self.ad.check(smiles)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _solve(a: list[list[float]], b: list[float]) -> list[float]:
|
|
107
|
+
"""Gaussian elimination with partial pivoting."""
|
|
108
|
+
n = len(b)
|
|
109
|
+
m = [row[:] + [b[i]] for i, row in enumerate(a)]
|
|
110
|
+
for col in range(n):
|
|
111
|
+
piv = max(range(col, n), key=lambda r: abs(m[r][col]))
|
|
112
|
+
m[col], m[piv] = m[piv], m[col]
|
|
113
|
+
pv = m[col][col]
|
|
114
|
+
if abs(pv) < 1e-12:
|
|
115
|
+
continue
|
|
116
|
+
m[col] = [v / pv for v in m[col]]
|
|
117
|
+
for r in range(n):
|
|
118
|
+
if r != col and m[r][col]:
|
|
119
|
+
f = m[r][col]
|
|
120
|
+
m[r] = [rv - f * cv for rv, cv in zip(m[r], m[col])]
|
|
121
|
+
return [m[i][n] for i in range(n)]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class RDKitDescPolicy:
|
|
125
|
+
"""RDKit descriptors + ridge (optional extra [bio-rdkit])."""
|
|
126
|
+
|
|
127
|
+
name = "rdkit-desc-ridge"
|
|
128
|
+
|
|
129
|
+
def __init__(self, l2: float = 1.0):
|
|
130
|
+
self.l2 = l2
|
|
131
|
+
|
|
132
|
+
def _desc(self, smiles: str) -> list[float]:
|
|
133
|
+
from rdkit import Chem
|
|
134
|
+
from rdkit.Chem import Descriptors, rdMolDescriptors as rd
|
|
135
|
+
|
|
136
|
+
mol = Chem.MolFromSmiles(smiles)
|
|
137
|
+
if mol is None:
|
|
138
|
+
return [0.0] * 6
|
|
139
|
+
return [
|
|
140
|
+
Descriptors.MolWt(mol), Descriptors.MolLogP(mol), Descriptors.TPSA(mol),
|
|
141
|
+
rd.CalcNumHBD(mol), rd.CalcNumHBA(mol), rd.CalcNumRotatableBonds(mol),
|
|
142
|
+
]
|
|
143
|
+
|
|
144
|
+
def fit(self, data):
|
|
145
|
+
X = [self._desc(s) for s, _ in data]
|
|
146
|
+
y = [v for _, v in data]
|
|
147
|
+
n = len(y)
|
|
148
|
+
self.means = [sum(row[j] for row in X) / n for j in range(6)]
|
|
149
|
+
self.stds = [math.sqrt(sum((row[j] - self.means[j]) ** 2 for row in X) / n) or 1.0
|
|
150
|
+
for j in range(6)]
|
|
151
|
+
Xn = [[(row[j] - self.means[j]) / self.stds[j] for j in range(6)] for row in X]
|
|
152
|
+
yc = [v for _, v in data]
|
|
153
|
+
self.mean = sum(yc) / n
|
|
154
|
+
yc = [v - self.mean for v in yc]
|
|
155
|
+
ata = [[sum(Xn[i][a] * Xn[i][b] for i in range(n)) + (self.l2 if a == b else 0.0)
|
|
156
|
+
for b in range(6)] for a in range(6)]
|
|
157
|
+
aty = [sum(Xn[i][a] * yc[i] for i in range(n)) for a in range(6)]
|
|
158
|
+
self.w = _solve(ata, aty)
|
|
159
|
+
|
|
160
|
+
def predict(self, smiles: str) -> float:
|
|
161
|
+
row = self._desc(smiles)
|
|
162
|
+
xn = [(row[j] - self.means[j]) / self.stds[j] for j in range(6)]
|
|
163
|
+
return self.mean + sum(w * v for w, v in zip(self.w, xn))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# ------------------------------------------------------------------ metrics
|
|
167
|
+
|
|
168
|
+
def spearman(pred: list[float], true: list[float]) -> float:
|
|
169
|
+
def rank(v):
|
|
170
|
+
# AVERAGE ranks over tie blocks: resolving ties by input order
|
|
171
|
+
# smuggles an arbitrary ordering into rho (and tightens bootstrap
|
|
172
|
+
# CIs falsely for coarse/integer predictions)
|
|
173
|
+
order = sorted(range(len(v)), key=lambda i: (v[i], i))
|
|
174
|
+
r = [0.0] * len(v)
|
|
175
|
+
i = 0
|
|
176
|
+
while i < len(order):
|
|
177
|
+
j = i
|
|
178
|
+
while (j + 1 < len(order)
|
|
179
|
+
and v[order[j + 1]] == v[order[i]]):
|
|
180
|
+
j += 1
|
|
181
|
+
avg = (i + j) / 2.0
|
|
182
|
+
for k in range(i, j + 1):
|
|
183
|
+
r[order[k]] = avg
|
|
184
|
+
i = j + 1
|
|
185
|
+
return r
|
|
186
|
+
n = len(pred)
|
|
187
|
+
rp, rt = rank(pred), rank(true)
|
|
188
|
+
mp, mt = sum(rp) / n, sum(rt) / n
|
|
189
|
+
num = sum((rp[i] - mp) * (rt[i] - mt) for i in range(n))
|
|
190
|
+
den = math.sqrt(sum((rp[i] - mp) ** 2 for i in range(n))
|
|
191
|
+
* sum((rt[i] - mt) ** 2 for i in range(n)))
|
|
192
|
+
return num / den if den else 0.0
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def rmse(pred: list[float], true: list[float]) -> float:
|
|
196
|
+
return math.sqrt(sum((p - t) ** 2 for p, t in zip(pred, true)) / len(pred))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def roc_auc(scores: list[float], labels: list[float]) -> float:
|
|
200
|
+
"""Mann-Whitney AUC with tie handling. Labels are 0/1."""
|
|
201
|
+
pos = [s for s, l in zip(scores, labels) if l == 1]
|
|
202
|
+
neg = [s for s, l in zip(scores, labels) if l != 1]
|
|
203
|
+
if not pos or not neg:
|
|
204
|
+
return 0.5
|
|
205
|
+
allv = sorted(scores)
|
|
206
|
+
# average ranks (1-based) over tie blocks
|
|
207
|
+
rank: dict[float, float] = {}
|
|
208
|
+
i = 0
|
|
209
|
+
while i < len(allv):
|
|
210
|
+
j = i
|
|
211
|
+
while j < len(allv) and allv[j] == allv[i]:
|
|
212
|
+
j += 1
|
|
213
|
+
avg = (i + 1 + j) / 2 # mean of 1-based positions i+1..j
|
|
214
|
+
rank[allv[i]] = avg
|
|
215
|
+
i = j
|
|
216
|
+
rsum = sum(rank[s] for s in pos)
|
|
217
|
+
n, n1 = len(scores), len(pos)
|
|
218
|
+
return (rsum - n1 * (n1 + 1) / 2) / (n1 * (n - n1))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
SCAFFOLD_BACKEND = "rdkit"
|
|
222
|
+
try: # probe once: a silent fallback would change what 'scaffold split' MEANS
|
|
223
|
+
# A real call, not just an import: some rdkit builds import fine and then fail on every molecule
|
|
224
|
+
# (2026.09.2: RuntimeError "bad any cast" in MurckoScaffold). Such a build counts as no rdkit, and the
|
|
225
|
+
# backend stamped into results says so instead of crashing a campaign's diary.
|
|
226
|
+
from rdkit import Chem as _Chem
|
|
227
|
+
from rdkit.Chem.Scaffolds import MurckoScaffold as _Murcko
|
|
228
|
+
_Murcko.MurckoScaffoldSmiles(mol=_Chem.MolFromSmiles("c1ccccc1N"), includeChirality=False)
|
|
229
|
+
except Exception: # noqa: BLE001 - ImportError, or a broken build
|
|
230
|
+
SCAFFOLD_BACKEND = "none"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def scaffold(smiles: str) -> str:
|
|
234
|
+
"""Bemis-Murcko scaffold (requires rdkit). WITHOUT rdkit the SMILES
|
|
235
|
+
itself is returned — grouping then controls EXACT duplicates only,
|
|
236
|
+
not scaffold neighbors. run_benchmark stamps that into the results
|
|
237
|
+
so a leakage claim is never made on the wrong grouping."""
|
|
238
|
+
if SCAFFOLD_BACKEND == "rdkit":
|
|
239
|
+
from rdkit.Chem.Scaffolds import MurckoScaffold
|
|
240
|
+
from rdkit import Chem
|
|
241
|
+
mol = Chem.MolFromSmiles(smiles)
|
|
242
|
+
if mol is None:
|
|
243
|
+
return smiles
|
|
244
|
+
return MurckoScaffold.MurckoScaffoldSmiles(mol=mol, includeChirality=False)
|
|
245
|
+
return smiles
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def scaffold_split(data: list[tuple[str, float]], train_frac: float = 0.8, seed: int = 0):
|
|
249
|
+
"""Group by scaffold, assign whole scaffolds to train/test. Prevents
|
|
250
|
+
near-duplicate leakage between train and test molecules."""
|
|
251
|
+
groups: dict[str, list] = {}
|
|
252
|
+
for item in data:
|
|
253
|
+
groups.setdefault(scaffold(item[0]), []).append(item)
|
|
254
|
+
keys = sorted(groups, key=lambda k: (len(groups[k]), k))
|
|
255
|
+
import random as _random
|
|
256
|
+
|
|
257
|
+
_random.Random(seed).shuffle(keys)
|
|
258
|
+
cut = int(len(data) * train_frac)
|
|
259
|
+
train, test, n = [], [], 0
|
|
260
|
+
for k in keys:
|
|
261
|
+
(train if n < cut else test).extend(groups[k])
|
|
262
|
+
n += len(groups[k])
|
|
263
|
+
return train, test
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def run_benchmark(dataset: Any, policies: list[Policy], train_frac: float = 0.8,
|
|
267
|
+
split: str = "index", seeds: tuple[int, ...] = (0,),
|
|
268
|
+
out: str | Path | None = None) -> dict[str, Any]:
|
|
269
|
+
"""Evaluate policies. `split`: "index" (temporal-ish) or "scaffold" (leak-safe).
|
|
270
|
+
Multiple `seeds` -> per-policy mean±std for the primary metric."""
|
|
271
|
+
data = list(dataset.load())
|
|
272
|
+
classification = getattr(dataset, "task", "regression") == "classification"
|
|
273
|
+
results: dict[str, Any] = {
|
|
274
|
+
"dataset": getattr(dataset, "name", "unknown"),
|
|
275
|
+
"task": dataset.task if hasattr(dataset, "task") else "regression",
|
|
276
|
+
"split": split, "seeds": list(seeds),
|
|
277
|
+
"split_note": ("scaffold grouping needs rdkit: exact-duplicate "
|
|
278
|
+
"grouping only — scaffold-neighbour leakage NOT "
|
|
279
|
+
"controlled"
|
|
280
|
+
if split == "scaffold" and SCAFFOLD_BACKEND != "rdkit"
|
|
281
|
+
else None),
|
|
282
|
+
"n_train": int(len(data) * train_frac), "n_test": len(data) - int(len(data) * train_frac),
|
|
283
|
+
"timestamp": time.time(),
|
|
284
|
+
"policies": {},
|
|
285
|
+
}
|
|
286
|
+
for policy in policies:
|
|
287
|
+
t0 = time.time()
|
|
288
|
+
primary: list[float] = []
|
|
289
|
+
last_entry: dict[str, Any] = {}
|
|
290
|
+
for seed in seeds:
|
|
291
|
+
policy_name = policy.name
|
|
292
|
+
if split == "scaffold":
|
|
293
|
+
train, test = scaffold_split(data, train_frac, seed)
|
|
294
|
+
else:
|
|
295
|
+
cut = int(len(data) * train_frac)
|
|
296
|
+
train, test = data[:cut], data[cut:]
|
|
297
|
+
policy.fit(train)
|
|
298
|
+
preds = [policy.predict(s) for s, _ in test]
|
|
299
|
+
truth = [y for _, y in test]
|
|
300
|
+
entry: dict[str, Any] = {"fit_secs": round(time.time() - t0, 3)}
|
|
301
|
+
if classification:
|
|
302
|
+
entry["roc_auc"] = round(roc_auc(preds, truth), 4)
|
|
303
|
+
primary.append(entry["roc_auc"])
|
|
304
|
+
else:
|
|
305
|
+
entry["spearman"] = round(spearman(preds, truth), 4)
|
|
306
|
+
entry["rmse"] = round(rmse(preds, truth), 4)
|
|
307
|
+
primary.append(entry["spearman"])
|
|
308
|
+
last_entry = entry
|
|
309
|
+
if len(seeds) > 1:
|
|
310
|
+
mean = sum(primary) / len(primary)
|
|
311
|
+
std = (sum((v - mean) ** 2 for v in primary) / len(primary)) ** 0.5
|
|
312
|
+
metric = "roc_auc" if classification else "spearman"
|
|
313
|
+
last_entry[metric] = f"{mean:.4f}±{std:.4f}"
|
|
314
|
+
last_entry[f"{metric}_mean"] = round(mean, 4)
|
|
315
|
+
last_entry[f"{metric}_std"] = round(std, 4)
|
|
316
|
+
results["policies"][policy_name] = last_entry
|
|
317
|
+
if out:
|
|
318
|
+
Path(out).write_text(json.dumps(results, indent=1))
|
|
319
|
+
return results
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
# ------------------------------------------------------------- statistics
|
|
323
|
+
# Small-n honesty toolkit: every headline number in reports and case studies
|
|
324
|
+
# should carry a bootstrap CI, and multi-test screens should be FDR-corrected.
|
|
325
|
+
|
|
326
|
+
def bootstrap_ci(values: list[float], stat: Callable[[list[float]], float] | None = None,
|
|
327
|
+
n_boot: int = 2000, seed: int = 7,
|
|
328
|
+
alpha: float = 0.05) -> tuple[float, float]:
|
|
329
|
+
"""Percentile bootstrap CI for a statistic over a sample (default mean)."""
|
|
330
|
+
import random
|
|
331
|
+
|
|
332
|
+
if not values:
|
|
333
|
+
return (float("nan"), float("nan"))
|
|
334
|
+
stat = stat or (lambda vs: sum(vs) / len(vs))
|
|
335
|
+
rng = random.Random(seed)
|
|
336
|
+
n = len(values)
|
|
337
|
+
boots = sorted(stat([values[rng.randrange(n)] for _ in range(n)])
|
|
338
|
+
for _ in range(n_boot))
|
|
339
|
+
lo = boots[int(alpha / 2 * n_boot)]
|
|
340
|
+
hi = boots[min(n_boot - 1, int((1 - alpha / 2) * n_boot))]
|
|
341
|
+
return round(lo, 4), round(hi, 4)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def spearman_ci(pred: list[float], true: list[float], n_boot: int = 1000,
|
|
345
|
+
seed: int = 7) -> tuple[float, float, float]:
|
|
346
|
+
"""(rho, ci_low, ci_high) — bootstrap over paired observations."""
|
|
347
|
+
import random
|
|
348
|
+
|
|
349
|
+
rho = spearman(pred, true)
|
|
350
|
+
if len(pred) < 4:
|
|
351
|
+
return rho, float("nan"), float("nan")
|
|
352
|
+
rng = random.Random(seed)
|
|
353
|
+
n = len(pred)
|
|
354
|
+
pairs = list(zip(pred, true))
|
|
355
|
+
boots = []
|
|
356
|
+
for _ in range(n_boot):
|
|
357
|
+
sample = [pairs[rng.randrange(n)] for _ in range(n)]
|
|
358
|
+
boots.append(spearman([p for p, _ in sample], [t for _, t in sample]))
|
|
359
|
+
boots.sort()
|
|
360
|
+
return rho, round(boots[int(0.025 * n_boot)], 4), \
|
|
361
|
+
round(boots[min(n_boot - 1, int(0.975 * n_boot))], 4)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def benjamini_hochberg(pvals: list[float], fdr: float = 0.10) -> list[bool]:
|
|
365
|
+
"""BH significance flags: discoveries at the requested false-discovery
|
|
366
|
+
rate. Empty input -> empty output."""
|
|
367
|
+
n = len(pvals)
|
|
368
|
+
if n == 0:
|
|
369
|
+
return []
|
|
370
|
+
order = sorted(range(n), key=lambda i: pvals[i])
|
|
371
|
+
k_max = 0
|
|
372
|
+
for rank, i in enumerate(order, start=1):
|
|
373
|
+
if pvals[i] <= fdr * rank / n:
|
|
374
|
+
k_max = rank
|
|
375
|
+
flags = [False] * n
|
|
376
|
+
if k_max:
|
|
377
|
+
for i in order[:k_max]:
|
|
378
|
+
flags[i] = True
|
|
379
|
+
return flags
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# ------------------------------------------- assay-selection metrics
|
|
383
|
+
# Shared vocabulary with assaybench (Genentech/AssayLoop): a method ranks or
|
|
384
|
+
# sequentially acquires from a universe; these score how early the hits show.
|
|
385
|
+
|
|
386
|
+
def fraction_of_hits(picked, hits) -> float:
|
|
387
|
+
picked = set(picked)
|
|
388
|
+
return len(picked & set(hits)) / len(hits) if hits else float("nan")
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def percent_essential(picked, hits) -> float:
|
|
392
|
+
"""Fraction of what you spent budget on that actually was a hit."""
|
|
393
|
+
return len(set(picked) & set(hits)) / len(picked) if picked else 0.0
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def enrichment_factor(picked, universe, hits, budget: int | None = None) -> float:
|
|
397
|
+
base = len(set(hits)) / len(set(universe))
|
|
398
|
+
top = list(picked)[: budget or len(picked)]
|
|
399
|
+
if not top or base <= 0:
|
|
400
|
+
return float("nan")
|
|
401
|
+
return (len(set(top) & set(hits)) / len(top)) / base
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def shortfall(picked, hits) -> float:
|
|
405
|
+
"""Fraction of true hits still missing after the picks."""
|
|
406
|
+
return 1.0 - fraction_of_hits(picked, hits)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def adjusted_nauc(rounds: list[list], universe, hits) -> float:
|
|
410
|
+
"""Cumulative hit-recall vs fraction-of-library assayed, rescaled so a
|
|
411
|
+
random policy scores 0 and the oracle ordering (all hits first) scores 1.
|
|
412
|
+
Same convention as assaybench's adjusted_nauc."""
|
|
413
|
+
hits = set(hits)
|
|
414
|
+
U = len(list(universe)) or 1
|
|
415
|
+
if not hits:
|
|
416
|
+
return float("nan")
|
|
417
|
+
seen: set = set()
|
|
418
|
+
xs, cum, found = [], [], 0
|
|
419
|
+
for rnd in rounds:
|
|
420
|
+
new = [g for g in rnd if g not in seen]
|
|
421
|
+
seen.update(new)
|
|
422
|
+
found += len(set(new) & hits)
|
|
423
|
+
xs.append(len(seen) / U)
|
|
424
|
+
cum.append(found / len(hits))
|
|
425
|
+
if not xs or xs[-1] <= 0:
|
|
426
|
+
return float("nan")
|
|
427
|
+
|
|
428
|
+
def auc(xs_, ys_):
|
|
429
|
+
a, px, py = 0.0, 0.0, 0.0
|
|
430
|
+
for x, y in zip(xs_, ys_):
|
|
431
|
+
a += (y + py) / 2 * (x - px)
|
|
432
|
+
px, py = x, y
|
|
433
|
+
return a
|
|
434
|
+
|
|
435
|
+
xf = xs[-1]
|
|
436
|
+
A = auc(xs, cum)
|
|
437
|
+
xo = min(len(hits) / U, xf)
|
|
438
|
+
oracle = xo / 2 + max(0.0, xf - xo)
|
|
439
|
+
random_ = xf ** 2 / 2
|
|
440
|
+
if oracle <= random_:
|
|
441
|
+
return float("nan")
|
|
442
|
+
return round((A - random_) / (oracle - random_), 4)
|
proef/campaign_fsm.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""The decision point after a round, as an explicit state with the actions it allows, and who chooses among them.
|
|
2
|
+
|
|
3
|
+
After a round's results are in, a campaign can follow up abstentions, re-plan, go on to the next round, or stop. That used to be two
|
|
4
|
+
`if cfg.flag` blocks in a fixed order, so nothing else could choose. Now the allowed actions are COMPUTED from preconditions in
|
|
5
|
+
code (what the operator permits, the budget, what already happened this round), and an orchestrator chooses among them:
|
|
6
|
+
- the fixed orchestrator reproduces the old order exactly;
|
|
7
|
+
- the model orchestrator asks a model. It can only pick an allowed action. Anything else, a refused call or an unparseable
|
|
8
|
+
answer falls back to the fixed choice, and the fallback is recorded.
|
|
9
|
+
Every choice is a ledger record. The operator's `followups` and `replan` flags are what the model MAY choose, never what it must.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from enum import Enum
|
|
17
|
+
from typing import Any, Protocol
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class State(str, Enum):
|
|
21
|
+
ROUND_JUDGED = "round_judged" # a round's results are in: what next?
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Action(str, Enum):
|
|
25
|
+
FOLLOW_UP = "follow_up"
|
|
26
|
+
REPLAN = "replan"
|
|
27
|
+
NEXT_ROUND = "next_round"
|
|
28
|
+
STOP = "stop"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
ACTION_HELP = {
|
|
32
|
+
Action.FOLLOW_UP: "ask what to do with the abstained results (a validated follow-up may then run)",
|
|
33
|
+
Action.REPLAN: "propose new hypotheses from the results so far (a person approves them under approvals)",
|
|
34
|
+
Action.NEXT_ROUND: "go on to the next round with what is queued",
|
|
35
|
+
Action.STOP: "end the campaign here and keep what has been learned",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class View:
|
|
41
|
+
"""The facts an orchestrator may use. Plain data: no handles to a lab, a store or a tracker."""
|
|
42
|
+
round_no: int
|
|
43
|
+
rounds: int
|
|
44
|
+
verdicts: dict[str, str]
|
|
45
|
+
abstained: list[str]
|
|
46
|
+
queued: int
|
|
47
|
+
runs_left: int
|
|
48
|
+
done: set[str] = field(default_factory=set)
|
|
49
|
+
background: str = "" # outside information read for this round (untrusted context; empty when grounding is off)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Choice:
|
|
54
|
+
action: str
|
|
55
|
+
why: str = ""
|
|
56
|
+
source: str = "fixed" # fixed | model | fixed-fallback
|
|
57
|
+
valid: bool = True
|
|
58
|
+
reasons: list[str] = field(default_factory=list)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def allowed_actions(state: State, *, view: View, followups_permitted: bool, replan_permitted: bool, has_model: bool,
|
|
62
|
+
agent_source: bool) -> list[str]:
|
|
63
|
+
"""What this state allows, from preconditions. next_round is always allowed, and so is stop while a round remains."""
|
|
64
|
+
if state is not State.ROUND_JUDGED:
|
|
65
|
+
return []
|
|
66
|
+
out: list[str] = []
|
|
67
|
+
if followups_permitted and has_model and view.abstained and Action.FOLLOW_UP.value not in view.done:
|
|
68
|
+
out.append(Action.FOLLOW_UP.value)
|
|
69
|
+
if replan_permitted and agent_source and view.round_no < max(1, view.rounds) and Action.REPLAN.value not in view.done:
|
|
70
|
+
out.append(Action.REPLAN.value)
|
|
71
|
+
out.append(Action.NEXT_ROUND.value)
|
|
72
|
+
if view.round_no < max(1, view.rounds):
|
|
73
|
+
out.append(Action.STOP.value) # on the last round there is nothing left to end
|
|
74
|
+
return out
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _help(action: str, view: View) -> str:
|
|
78
|
+
if action == Action.FOLLOW_UP.value and view.round_no >= max(1, view.rounds):
|
|
79
|
+
return "record a suggestion for a person about the abstained results (this is the last round, so nothing can run)"
|
|
80
|
+
return ACTION_HELP[Action(action)]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Orchestrator(Protocol):
|
|
84
|
+
def choose(self, state: State, allowed: list[str], view: View) -> Choice: ...
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class FixedOrchestrator:
|
|
88
|
+
"""The order the engine always had: follow up, then re-plan, then the next round. It never stops a campaign early."""
|
|
89
|
+
|
|
90
|
+
def choose(self, state: State, allowed: list[str], view: View) -> Choice:
|
|
91
|
+
for a in (Action.FOLLOW_UP.value, Action.REPLAN.value):
|
|
92
|
+
if a in allowed:
|
|
93
|
+
return Choice(a, "the configured order", "fixed")
|
|
94
|
+
return Choice(Action.NEXT_ROUND.value, "nothing else is allowed or configured", "fixed")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
PROMPT = """You steer a research campaign between rounds. A round just finished.
|
|
98
|
+
|
|
99
|
+
ROUND {round_no} OF {rounds}
|
|
100
|
+
RESULTS SO FAR (candidate: verdict)
|
|
101
|
+
{verdicts}
|
|
102
|
+
ABSTAINED: {abstained}
|
|
103
|
+
QUEUED FOR THE NEXT ROUND: {queued} hypotheses. LAB RUNS LEFT IN THE BUDGET: {runs_left}.
|
|
104
|
+
ALREADY DONE THIS ROUND: {done}
|
|
105
|
+
|
|
106
|
+
YOU MAY CHOOSE ONE OF THESE ACTIONS (nothing else is allowed):
|
|
107
|
+
{actions}
|
|
108
|
+
|
|
109
|
+
Choose the single most useful action now. You will be asked again after it, until you choose next_round or stop.
|
|
110
|
+
Reply ONLY with JSON: {{"action": "one of the actions above", "why": "one sentence"}}"""
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class ModelOrchestrator:
|
|
114
|
+
"""Asks a model which allowed action to take. The model decides nothing outside the list, and a failure is not an error: the
|
|
115
|
+
fixed orchestrator answers instead and the choice says so."""
|
|
116
|
+
|
|
117
|
+
RESERVE = 4 # model calls kept for the follow-up, re-plan and review work that steering must not starve
|
|
118
|
+
|
|
119
|
+
def __init__(self, model: Any, fallback: Orchestrator | None = None, reserve: int | None = None):
|
|
120
|
+
self.model, self.fallback = model, fallback or FixedOrchestrator()
|
|
121
|
+
self.reserve = self.RESERVE if reserve is None else reserve
|
|
122
|
+
|
|
123
|
+
def choose(self, state: State, allowed: list[str], view: View) -> Choice:
|
|
124
|
+
from proef.core.contracts import Envelope, ToolInvocation
|
|
125
|
+
prompt = PROMPT.format(
|
|
126
|
+
round_no=view.round_no, rounds=view.rounds,
|
|
127
|
+
verdicts="\n".join(f"- {c}: {v}" for c, v in sorted(view.verdicts.items()))[:3000] or "- nothing judged yet",
|
|
128
|
+
abstained=", ".join(view.abstained) or "none", queued=view.queued, runs_left=view.runs_left,
|
|
129
|
+
done=", ".join(sorted(view.done)) or "nothing",
|
|
130
|
+
actions="\n".join(f"- {a}: {_help(a, view)}" for a in allowed))
|
|
131
|
+
if view.background:
|
|
132
|
+
prompt += "\n\n" + view.background[:3000]
|
|
133
|
+
fb = self.fallback.choose(state, allowed, view)
|
|
134
|
+
left = getattr(self.model, "remaining", None)
|
|
135
|
+
if callable(left) and left() <= self.reserve:
|
|
136
|
+
# steering must not spend the calls the real work needs: with only the reserve left, the fixed order answers
|
|
137
|
+
return Choice(fb.action, fb.why, "fixed-fallback", False,
|
|
138
|
+
[f"{left()} model calls left, kept for follow-ups, re-plans and the review"])
|
|
139
|
+
try:
|
|
140
|
+
raw = self.model.generate(ToolInvocation(envelope=Envelope(experiment_branch_id="orchestrator"),
|
|
141
|
+
tool="c.fm.generate_molecules"), prompt).output["text"]
|
|
142
|
+
m = re.search(r"\{.*\}", raw, re.S)
|
|
143
|
+
data = json.loads(m.group(0)) if m else {}
|
|
144
|
+
except Exception as exc: # noqa: BLE001 - a refused, failed or unparseable call is not a campaign failure
|
|
145
|
+
return Choice(fb.action, fb.why, "fixed-fallback", False, [f"the model's answer could not be used ({type(exc).__name__})"])
|
|
146
|
+
action = str(data.get("action") or "")[:30]
|
|
147
|
+
why = str(data.get("why") or "")[:300]
|
|
148
|
+
if action not in allowed:
|
|
149
|
+
return Choice(fb.action, fb.why, "fixed-fallback", False,
|
|
150
|
+
[f"'{action}' is not one of the allowed actions ({', '.join(allowed)})"])
|
|
151
|
+
return Choice(action, why, "model", True, [])
|