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/series.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""series — think in series, not singletons (S-T1 chemotype/SAR view).
|
|
2
|
+
|
|
3
|
+
Med-chem reasoning is SERIES reasoning: proposed -> tested -> judged
|
|
4
|
+
grouped by chemotype, with per-series verdict rollups and matched-pair
|
|
5
|
+
tables (congeners differing by one substitution, delta-IC50 WITH CIs).
|
|
6
|
+
The per-compound hypothesis remains the epistemic atom; this module is
|
|
7
|
+
only the VIEW, and it aggregates honestly:
|
|
8
|
+
|
|
9
|
+
- grouping keys, in priority order: explicit family (modality-agnostic
|
|
10
|
+
hook — biologics/sequences use this), then Bemis-Murcko scaffold from
|
|
11
|
+
SMILES when rdkit is the backend, then ungrouped singletons.
|
|
12
|
+
The backend used is STAMPED on every series so a "same chemotype"
|
|
13
|
+
claim is never made on exact-duplicate grouping.
|
|
14
|
+
- rollups reuse the verdict vocabulary (confirmed / preliminary /
|
|
15
|
+
refuted / abstained); abstentions are counted, never averaged away.
|
|
16
|
+
- matched pairs classify delta-log10-IC50 against the retention band
|
|
17
|
+
(default 3.2-fold): a CI straddling the band boundary ABSTAINS —
|
|
18
|
+
the same small-n physics as every verdict in this repo.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import math
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from proef.benchmark import SCAFFOLD_BACKEND, scaffold
|
|
26
|
+
|
|
27
|
+
RETAIN_FOLD = 3.2 # "retains potency" = within this fold-change
|
|
28
|
+
_TLOG = math.log10(RETAIN_FOLD)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _norm_verdict(v: str | None) -> str:
|
|
32
|
+
s = (v or "").lower()
|
|
33
|
+
if s == "confirmed":
|
|
34
|
+
return "confirmed"
|
|
35
|
+
if s in ("validated",):
|
|
36
|
+
return "preliminary"
|
|
37
|
+
if s in ("refuted", "invalidated", "failed"):
|
|
38
|
+
return "refuted"
|
|
39
|
+
if s in ("", "proposed", "designed"):
|
|
40
|
+
return "proposed"
|
|
41
|
+
return "abstained"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def chemotype_key(member: dict[str, Any]) -> tuple[str, str]:
|
|
45
|
+
"""(key, kind) for one member: family > Murcko scaffold > singleton."""
|
|
46
|
+
fam = (member.get("family") or "").strip()
|
|
47
|
+
if fam:
|
|
48
|
+
return fam, "family"
|
|
49
|
+
smi = member.get("smiles") or ""
|
|
50
|
+
if smi and SCAFFOLD_BACKEND == "rdkit":
|
|
51
|
+
k = scaffold(smi)
|
|
52
|
+
if k:
|
|
53
|
+
return k, "chemotype:Murcko"
|
|
54
|
+
return (member.get("candidate") or member.get("hypothesis_id")
|
|
55
|
+
or smi), "ungrouped"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build_series(members: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
|
59
|
+
"""members: [{candidate, hypothesis_id?, smiles?, family?, verdict,
|
|
60
|
+
observed, ci}] -> {key: {kind, label, members, rollup}}.
|
|
61
|
+
|
|
62
|
+
Verdict counts follow views.verdict_tally semantics; a series whose
|
|
63
|
+
members abstain reports the abstentions — it does not roll up to a
|
|
64
|
+
false confidence."""
|
|
65
|
+
series: dict[str, dict[str, Any]] = {}
|
|
66
|
+
for m in members:
|
|
67
|
+
key, kind = chemotype_key(m)
|
|
68
|
+
s = series.setdefault(key, {"key": key, "kind": kind,
|
|
69
|
+
"members": [],
|
|
70
|
+
"rollup": {"confirmed": 0,
|
|
71
|
+
"preliminary": 0,
|
|
72
|
+
"refuted": 0,
|
|
73
|
+
"abstained": 0,
|
|
74
|
+
"proposed": 0}})
|
|
75
|
+
v = _norm_verdict(m.get("verdict"))
|
|
76
|
+
s["rollup"][v] += 1
|
|
77
|
+
s["members"].append({**m, "verdict_norm": v})
|
|
78
|
+
for s in series.values():
|
|
79
|
+
r = s["rollup"]
|
|
80
|
+
s["n_tested"] = sum(1 for m in s["members"]
|
|
81
|
+
if m["verdict_norm"] != "proposed")
|
|
82
|
+
s["n_members"] = len(s["members"])
|
|
83
|
+
s["label"] = (f"{r['confirmed']} confirmed, {r['refuted']} refuted, "
|
|
84
|
+
f"{r['preliminary']} preliminary, "
|
|
85
|
+
f"{r['abstained']} abstained"
|
|
86
|
+
+ (f", {r['proposed']} proposed (untested)"
|
|
87
|
+
if r["proposed"] else ""))
|
|
88
|
+
s["chemotype_backend"] = ("rdkit-Murcko" if SCAFFOLD_BACKEND == "rdkit"
|
|
89
|
+
else "none(exact-id fallback)")
|
|
90
|
+
return series
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _se_from_ci(point: float, ci: Any) -> float | None:
|
|
94
|
+
"""log10 standard error from a 95% CI on the IC50 scale."""
|
|
95
|
+
if not ci or point <= 0:
|
|
96
|
+
return None
|
|
97
|
+
lo, hi = (ci[0], ci[1]) if isinstance(ci, (list, tuple)) and len(ci) == 2 \
|
|
98
|
+
else (None, None)
|
|
99
|
+
if not lo or not hi or lo <= 0 or hi <= 0:
|
|
100
|
+
return None
|
|
101
|
+
return (math.log10(hi) - math.log10(lo)) / (2 * 1.96)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def matched_pairs(series: dict[str, Any],
|
|
105
|
+
retain_fold: float = RETAIN_FOLD) -> list[dict[str, Any]]:
|
|
106
|
+
"""Congener pairs with both members holding measured IC50s:
|
|
107
|
+
delta = log10(IC50_a / IC50_b) with a propagated 95% CI, classified
|
|
108
|
+
against the retention band (<= retain_fold change = 'retained';
|
|
109
|
+
CI beyond = 'loss'/'gain'; CI straddling the boundary = ABSTAINED).
|
|
110
|
+
a is the alphabetically-first candidate: positive delta means
|
|
111
|
+
a is the weaker (higher IC50) congener."""
|
|
112
|
+
t = math.log10(retain_fold)
|
|
113
|
+
meas = [m for m in series["members"]
|
|
114
|
+
if isinstance(m.get("observed"), (int, float)) and m["observed"] > 0]
|
|
115
|
+
pairs = []
|
|
116
|
+
for i in range(len(meas)):
|
|
117
|
+
for j in range(i + 1, len(meas)):
|
|
118
|
+
a, b = sorted((meas[i], meas[j]),
|
|
119
|
+
key=lambda m: str(m.get("candidate")))
|
|
120
|
+
da = math.log10(a["observed"])
|
|
121
|
+
db = math.log10(b["observed"])
|
|
122
|
+
delta = da - db
|
|
123
|
+
sea, seb = _se_from_ci(a["observed"], a.get("ci")), \
|
|
124
|
+
_se_from_ci(b["observed"], b.get("ci"))
|
|
125
|
+
if sea is not None and seb is not None:
|
|
126
|
+
hw = 1.96 * math.hypot(sea, seb)
|
|
127
|
+
else:
|
|
128
|
+
hw = 0.0 # CIs not recorded: point estimate alone, disclosed
|
|
129
|
+
lo, hi = delta - hw, delta + hw
|
|
130
|
+
if hi < -t:
|
|
131
|
+
call = "gain" # a meaningfully stronger
|
|
132
|
+
elif lo > t:
|
|
133
|
+
call = "loss" # a meaningfully weaker
|
|
134
|
+
elif lo >= -t and hi <= t:
|
|
135
|
+
call = "retained"
|
|
136
|
+
else:
|
|
137
|
+
call = "abstained" # CI straddles a band boundary
|
|
138
|
+
pairs.append({
|
|
139
|
+
"a": a.get("candidate"), "b": b.get("candidate"),
|
|
140
|
+
"ic50_a": a["observed"], "ic50_b": b["observed"],
|
|
141
|
+
"delta_log10": round(delta, 3),
|
|
142
|
+
"ci95": [round(lo, 3), round(hi, 3)] if hw else None,
|
|
143
|
+
"fold_a_over_b": round(10 ** delta, 3),
|
|
144
|
+
"call": call,
|
|
145
|
+
"cited_cis": hw > 0,
|
|
146
|
+
})
|
|
147
|
+
return pairs
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _collect(recs):
|
|
151
|
+
"""(latest verdicts per hypothesis, family-claim markers) from the
|
|
152
|
+
chain. One pass; verdict records supersede proposed (recency wins,
|
|
153
|
+
payload-driven — same reading rule as every verdict surface here)."""
|
|
154
|
+
latest: dict[str, dict[str, Any]] = {}
|
|
155
|
+
smiles_by: dict[str, str] = {}
|
|
156
|
+
family_by: dict[str, str] = {}
|
|
157
|
+
claims: dict[str, dict[str, Any]] = {}
|
|
158
|
+
verdict_events = ("hypothesis_validated", "hypothesis_invalidated",
|
|
159
|
+
"hypothesis_inconclusive", "hypothesis_tested")
|
|
160
|
+
for r in recs:
|
|
161
|
+
d = r.decision or {}
|
|
162
|
+
art = (r.artifact.metadata if r.artifact else {}) or {}
|
|
163
|
+
et = r.event_type.value
|
|
164
|
+
cand = d.get("candidate") or art.get("candidate")
|
|
165
|
+
key = d.get("hypothesis_id") or art.get("hypothesis_id") or cand
|
|
166
|
+
if d.get("smiles") or art.get("smiles"):
|
|
167
|
+
if cand:
|
|
168
|
+
smiles_by[cand] = d.get("smiles") or art.get("smiles")
|
|
169
|
+
if d.get("family") or art.get("family"):
|
|
170
|
+
if cand:
|
|
171
|
+
family_by[cand] = d.get("family") or art.get("family")
|
|
172
|
+
if et == "hypothesis_proposed" and d.get("family_id"):
|
|
173
|
+
claims[d["family_id"]] = {
|
|
174
|
+
"family_id": d["family_id"],
|
|
175
|
+
"parent_statement": d.get("parent_statement", ""),
|
|
176
|
+
"kind": d.get("kind", "mechanistic"),
|
|
177
|
+
"retain_fold": d.get("retain_fold"),
|
|
178
|
+
"n_variants": d.get("n_variants", 0)}
|
|
179
|
+
continue
|
|
180
|
+
if et == "hypothesis_proposed" and key and key not in latest:
|
|
181
|
+
latest[key] = {"hypothesis_id": key, "candidate": cand or key,
|
|
182
|
+
"verdict": None, "observed": None, "ci": None,
|
|
183
|
+
"smiles": d.get("smiles") or "",
|
|
184
|
+
"family": d.get("family") or ""}
|
|
185
|
+
if et in verdict_events and d.get("verdict") and key:
|
|
186
|
+
if d.get("claim_kind") == "series-derived":
|
|
187
|
+
continue # a derived CLAIM verdict is not a member datum
|
|
188
|
+
prev = latest.get(key) or {}
|
|
189
|
+
latest[key] = {
|
|
190
|
+
"hypothesis_id": key, "candidate": cand or key,
|
|
191
|
+
"verdict": d.get("verdict"),
|
|
192
|
+
"observed": d.get("observed") or d.get("ic50_um"),
|
|
193
|
+
"ci": d.get("observed_ci") or d.get("ic50_ci"),
|
|
194
|
+
"smiles": d.get("smiles") or smiles_by.get(cand or "", ""),
|
|
195
|
+
"family": d.get("family") or family_by.get(cand or "", ""),
|
|
196
|
+
"seq": prev.get("seq", 0),
|
|
197
|
+
}
|
|
198
|
+
return latest, claims
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def resolve_series_claims(recs, retain_fold: float = RETAIN_FOLD,
|
|
202
|
+
) -> list[dict[str, Any]]:
|
|
203
|
+
"""Derive verdicts for family-tagged claims from their members'
|
|
204
|
+
CI-aware verdicts.
|
|
205
|
+
|
|
206
|
+
A series claim is NEVER directly tested — its status is derived, and
|
|
207
|
+
the derivation cannot manufacture confidence: abstention dominates
|
|
208
|
+
(any straddling CI, any unresolved member, any point-only pair that
|
|
209
|
+
looks like loss/gain ⇒ inconclusive); refutation requires a CI fully
|
|
210
|
+
beyond the retention band. Tree-rollup vocabulary translated:
|
|
211
|
+
achieved≡confirmed, downgraded-by-unresolved⇒inconclusive, never
|
|
212
|
+
refuted-from-absence. Statuses: confirmed | refuted | inconclusive |
|
|
213
|
+
open (not enough resolved evidence to even abstain-meaningfully).
|
|
214
|
+
"""
|
|
215
|
+
latest, claims = _collect(recs)
|
|
216
|
+
out = []
|
|
217
|
+
for fid, claim in claims.items():
|
|
218
|
+
fold = float(claim.get("retain_fold") or retain_fold)
|
|
219
|
+
t = math.log10(fold)
|
|
220
|
+
members = [m for m in latest.values() if m.get("family") == fid]
|
|
221
|
+
base = {"family_id": fid, "parent_statement": claim["parent_statement"],
|
|
222
|
+
"kind": claim["kind"], "retain_fold": fold,
|
|
223
|
+
"derived": True,
|
|
224
|
+
"derived_from": sorted(
|
|
225
|
+
(str(m["candidate"]), str(m["verdict"]))
|
|
226
|
+
for m in members)}
|
|
227
|
+
if not members:
|
|
228
|
+
out.append({**base, "status": "open",
|
|
229
|
+
"reason": "no member hypotheses on the chain"})
|
|
230
|
+
continue
|
|
231
|
+
n_res = sum(1 for m in members if m["verdict"] is not None)
|
|
232
|
+
if n_res == 0:
|
|
233
|
+
out.append({**base, "status": "open",
|
|
234
|
+
"reason": f"all {len(members)} members untested/"
|
|
235
|
+
"proposed — a series claim abstains until"
|
|
236
|
+
" members resolve"})
|
|
237
|
+
continue
|
|
238
|
+
ser = build_series(members)
|
|
239
|
+
s = ser.get(fid) or next(iter(ser.values()))
|
|
240
|
+
if claim.get("kind") == "series":
|
|
241
|
+
pairs = matched_pairs(s, retain_fold=fold)
|
|
242
|
+
measured = [m for m in members
|
|
243
|
+
if isinstance(m.get("observed"), (int, float))
|
|
244
|
+
and m["observed"] > 0]
|
|
245
|
+
if len(measured) < 2:
|
|
246
|
+
out.append({**base, "status": "inconclusive", "pairs": pairs,
|
|
247
|
+
"reason": "fewer than 2 members measured — "
|
|
248
|
+
"retention needs congeners to compare"})
|
|
249
|
+
continue
|
|
250
|
+
if any(p["call"] == "abstained" for p in pairs):
|
|
251
|
+
status, reason = "inconclusive", \
|
|
252
|
+
"a congener pair's CI straddles the retention band — " \
|
|
253
|
+
"the series claim abstains with it"
|
|
254
|
+
elif any(p["call"] in ("gain", "loss") and not p["cited_cis"]
|
|
255
|
+
for p in pairs):
|
|
256
|
+
status, reason = "inconclusive", \
|
|
257
|
+
"a beyond-band pair has no CIs on record — cannot call " \
|
|
258
|
+
"loss without uncertainty"
|
|
259
|
+
elif any(p["call"] in ("gain", "loss") for p in pairs):
|
|
260
|
+
status, reason = "refuted", \
|
|
261
|
+
"a congener pair's CI lies fully beyond the " \
|
|
262
|
+
f"{retain_fold}-fold retention band"
|
|
263
|
+
elif pairs and all(p["call"] == "retained" for p in pairs):
|
|
264
|
+
status, reason = "confirmed", (
|
|
265
|
+
f"all {len(pairs)} measured congener pairs retain "
|
|
266
|
+
f"potency within {fold}x (CIs on record)")
|
|
267
|
+
else:
|
|
268
|
+
status, reason = "inconclusive", \
|
|
269
|
+
"members resolved but no comparable pairs with CIs"
|
|
270
|
+
out.append({**base, "status": status, "reason": reason,
|
|
271
|
+
"pairs": pairs})
|
|
272
|
+
else:
|
|
273
|
+
# mechanistic family rollup: any member refuted refutes the
|
|
274
|
+
# shared claim; confirmation needs every tested member
|
|
275
|
+
ref = sum(1 for m in members if m["verdict"] in
|
|
276
|
+
("refuted", "invalidated", "failed"))
|
|
277
|
+
conf = sum(1 for m in members if m["verdict"] == "confirmed")
|
|
278
|
+
abst = sum(1 for m in members if m["verdict"] in
|
|
279
|
+
("inconclusive", "validated"))
|
|
280
|
+
if ref:
|
|
281
|
+
status, reason = "refuted", f"{ref} member(s) refuted"
|
|
282
|
+
elif conf and abst == 0 and n_res == len(members) \
|
|
283
|
+
and all(m["verdict"] == "confirmed" for m in members):
|
|
284
|
+
status, reason = "confirmed", \
|
|
285
|
+
f"all {conf} members confirmed"
|
|
286
|
+
else:
|
|
287
|
+
status, reason = "inconclusive", \
|
|
288
|
+
f"{abst} abstention(s)/preliminar(y|ies) block " \
|
|
289
|
+
"family-level confirmation"
|
|
290
|
+
out.append({**base, "status": status, "reason": reason,
|
|
291
|
+
"counts": {"confirmed": conf, "refuted": ref,
|
|
292
|
+
"blocked": abst}})
|
|
293
|
+
return sorted(out, key=lambda c: c["family_id"])
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def series_summary(recs) -> list[dict[str, Any]]:
|
|
297
|
+
"""Provenance-records-first builder: verdicts (recency-wins per
|
|
298
|
+
hypothesis), observed IC50 + CI, and structure keys pulled from
|
|
299
|
+
hypothesis_proposed / synthesis / verdict payloads. Feeds the
|
|
300
|
+
workbench rollup and the diary. Family series carry their derived
|
|
301
|
+
claim status (resolve_series_claims) when one exists."""
|
|
302
|
+
latest, claims = _collect(recs)
|
|
303
|
+
claim_status = {c["family_id"]: c for c in resolve_series_claims(recs)}
|
|
304
|
+
members = list(latest.values())
|
|
305
|
+
series = build_series(members)
|
|
306
|
+
out = []
|
|
307
|
+
for s in series.values():
|
|
308
|
+
out.append({"key": s["key"][:48], "kind": s["kind"],
|
|
309
|
+
"backend": s["chemotype_backend"],
|
|
310
|
+
"n_members": len(s["members"]),
|
|
311
|
+
"rollup": s["rollup"], "label": s["label"],
|
|
312
|
+
"members": sorted(
|
|
313
|
+
({"candidate": m.get("candidate"),
|
|
314
|
+
"verdict": m.get("verdict_norm"),
|
|
315
|
+
"observed": m.get("observed")}
|
|
316
|
+
for m in s["members"]),
|
|
317
|
+
key=lambda x: str(x["candidate"])),
|
|
318
|
+
"matched_pairs": matched_pairs(s),
|
|
319
|
+
"claim_status": (claim_status.get(s["key"], {})
|
|
320
|
+
.get("status") if s["kind"] == "family"
|
|
321
|
+
else None),
|
|
322
|
+
"claim_reason": (claim_status.get(s["key"], {})
|
|
323
|
+
.get("reason") if s["kind"] == "family"
|
|
324
|
+
else None)})
|
|
325
|
+
out.sort(key=lambda x: (-x["rollup"]["confirmed"],
|
|
326
|
+
-x["n_members"], str(x["key"])))
|
|
327
|
+
return out
|
proef/skills.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Agent-skills integration (K-Dense scientific-agent-skills).
|
|
2
|
+
|
|
3
|
+
Proef agents are LLM + tools inside sandboxes. The Agent Skills standard
|
|
4
|
+
(agentskills.io) gives those agents domain knowledge — e.g. `opentrons-integration`
|
|
5
|
+
for protocol authoring, `rdkit` for cheminformatics, `database-lookup` for
|
|
6
|
+
ChEMBL/PubChem queries. This module pre-loads curated skills into an agent's
|
|
7
|
+
skill directory (local dir, sandbox rootfs template, etc.).
|
|
8
|
+
|
|
9
|
+
Division of labor: skills teach the agent *how*; Proef core decides
|
|
10
|
+
*whether* (SafetyEngine) and records *what happened* (provenance).
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
REPO = "https://github.com/K-Dense-AI/scientific-agent-skills"
|
|
20
|
+
|
|
21
|
+
# Curated for Proef agent roles (name = skill dir in that repo)
|
|
22
|
+
RECOMMENDED_SKILLS: dict[str, list[str]] = {
|
|
23
|
+
"design-agent": ["rdkit", "datamol", "medchem", "molfeat"],
|
|
24
|
+
"target-agent": ["database-lookup", "paper-lookup", "biopython"],
|
|
25
|
+
"assay-planning-agent": ["opentrons-integration", "pylabrobot",
|
|
26
|
+
"database-lookup"],
|
|
27
|
+
"analysis-agent": ["scientific-visualization", "statsmodels", "scikit-learn"],
|
|
28
|
+
"trial-agent": ["database-lookup", "paper-lookup"],
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def install_skills(skills: list[str], dest: str | Path,
|
|
33
|
+
repo: str = REPO, ref: str = "main",
|
|
34
|
+
repo_path: str | Path | None = None) -> list[Path]:
|
|
35
|
+
"""Install selected skills from the scientific-agent-skills repo into `dest`.
|
|
36
|
+
|
|
37
|
+
Copies from a local checkout when `repo_path` is given (offline/CI),
|
|
38
|
+
otherwise performs a sparse clone. Returns installed skill dirs.
|
|
39
|
+
"""
|
|
40
|
+
dest = Path(dest)
|
|
41
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
installed: list[Path] = []
|
|
43
|
+
if repo_path:
|
|
44
|
+
src_root = Path(repo_path) / "skills"
|
|
45
|
+
for name in skills:
|
|
46
|
+
src = src_root / name
|
|
47
|
+
if not src.is_dir():
|
|
48
|
+
continue
|
|
49
|
+
target = dest / name
|
|
50
|
+
if target.exists():
|
|
51
|
+
shutil.rmtree(target)
|
|
52
|
+
shutil.copytree(src, target)
|
|
53
|
+
installed.append(target)
|
|
54
|
+
return installed
|
|
55
|
+
import hashlib
|
|
56
|
+
tmp = dest / f".clone-{hashlib.sha1(repo.encode()).hexdigest()[:8]}"
|
|
57
|
+
try:
|
|
58
|
+
subprocess.run(
|
|
59
|
+
["git", "clone", "--depth", "1", "--branch", ref, "--",
|
|
60
|
+
repo, str(tmp)],
|
|
61
|
+
check=True, capture_output=True)
|
|
62
|
+
for name in skills:
|
|
63
|
+
src = tmp / "skills" / name
|
|
64
|
+
if src.is_dir():
|
|
65
|
+
target = dest / name
|
|
66
|
+
if target.exists():
|
|
67
|
+
shutil.rmtree(target)
|
|
68
|
+
shutil.copytree(src, target)
|
|
69
|
+
installed.append(target)
|
|
70
|
+
finally:
|
|
71
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
72
|
+
return installed
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_skill_instructions(skill_dir: str | Path) -> str:
|
|
76
|
+
"""Read a SKILL.md's body (frontmatter stripped) as agent instructions.
|
|
77
|
+
Accepts either the skill directory or the SKILL.md file itself."""
|
|
78
|
+
p = Path(skill_dir)
|
|
79
|
+
if p.is_file() and p.name == "SKILL.md":
|
|
80
|
+
p = p.parent
|
|
81
|
+
text = (p / "SKILL.md").read_text()
|
|
82
|
+
if text.startswith("---"):
|
|
83
|
+
end = text.find("---", 3)
|
|
84
|
+
if end != -1:
|
|
85
|
+
return text[end + 3:].strip()
|
|
86
|
+
return text.strip()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ------------------------------------------------------------- discovery
|
|
90
|
+
|
|
91
|
+
DEFAULT_SKILL_PATHS = [
|
|
92
|
+
"~/.agents/skills", # `npx skills add` convention (user-level)
|
|
93
|
+
".agents/skills", # project-level
|
|
94
|
+
"~/.claude/skills", # Claude Code
|
|
95
|
+
"skills", # this repo / sandbox rootfs
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _parse_frontmatter(text: str) -> dict[str, Any]:
|
|
100
|
+
if not text.startswith("---"):
|
|
101
|
+
return {}
|
|
102
|
+
end = text.find("---", 3)
|
|
103
|
+
if end == -1:
|
|
104
|
+
return {}
|
|
105
|
+
block = text[3:end]
|
|
106
|
+
try:
|
|
107
|
+
import yaml
|
|
108
|
+
return yaml.safe_load(block) or {}
|
|
109
|
+
except ImportError:
|
|
110
|
+
return _naive_yaml(block)
|
|
111
|
+
except Exception:
|
|
112
|
+
return {}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _naive_yaml(block: str) -> dict[str, Any]:
|
|
116
|
+
"""Minimal frontmatter parser (flat keys + one nested block), for hosts
|
|
117
|
+
without PyYAML. Not a general YAML parser."""
|
|
118
|
+
out: dict[str, Any] = {}
|
|
119
|
+
nested: dict[str, Any] | None = None
|
|
120
|
+
for line in block.splitlines():
|
|
121
|
+
stripped = line.strip()
|
|
122
|
+
if not stripped or stripped.startswith("#"):
|
|
123
|
+
continue
|
|
124
|
+
indented = line.startswith((" ", "\t"))
|
|
125
|
+
if indented and nested is not None:
|
|
126
|
+
m2 = re.match(r"^([-\w]+):\s*(.*)$", stripped)
|
|
127
|
+
if m2:
|
|
128
|
+
nested[m2.group(1)] = m2.group(2).strip().strip('"').strip("'")
|
|
129
|
+
continue
|
|
130
|
+
m = re.match(r"^([-\w]+):\s*(.*)$", stripped)
|
|
131
|
+
if not m:
|
|
132
|
+
continue
|
|
133
|
+
key, value = m.group(1), m.group(2).strip().strip('"').strip("'")
|
|
134
|
+
if value == "":
|
|
135
|
+
nested = {}
|
|
136
|
+
out[key] = nested
|
|
137
|
+
else:
|
|
138
|
+
nested = None
|
|
139
|
+
out[key] = value
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def discover_skills(paths: list[str | Path] | None = None,
|
|
144
|
+
include_repo: str = REPO) -> dict[str, dict[str, Any]]:
|
|
145
|
+
"""Discover installed Agent Skills across standard directories.
|
|
146
|
+
|
|
147
|
+
Returns {name: {path, description, version, source}} — the index an agent
|
|
148
|
+
(or the sandbox builder) consults to load guidance. Proef's own skills
|
|
149
|
+
are always included; K-Dense scientific skills appear once installed via
|
|
150
|
+
`npx skills add`, `gh skill install`, or `install_skills()`.
|
|
151
|
+
"""
|
|
152
|
+
import os
|
|
153
|
+
|
|
154
|
+
if paths is None:
|
|
155
|
+
paths = DEFAULT_SKILL_PATHS
|
|
156
|
+
index: dict[str, dict[str, Any]] = {}
|
|
157
|
+
for base in paths:
|
|
158
|
+
base = Path(os.path.expanduser(str(base)))
|
|
159
|
+
if not base.is_dir():
|
|
160
|
+
continue
|
|
161
|
+
for skill_md in base.glob("*/SKILL.md"):
|
|
162
|
+
fm = _parse_frontmatter(skill_md.read_text(errors="replace"))
|
|
163
|
+
name = fm.get("name") or skill_md.parent.name
|
|
164
|
+
index[name] = {
|
|
165
|
+
"path": str(skill_md.parent),
|
|
166
|
+
"description": fm.get("description", ""),
|
|
167
|
+
"version": (fm.get("metadata") or {}).get("version", ""),
|
|
168
|
+
"source": str(base),
|
|
169
|
+
}
|
|
170
|
+
# skills bundled with this package/repo
|
|
171
|
+
own = Path(__file__).resolve().parent.parent / "skills"
|
|
172
|
+
if own.is_dir():
|
|
173
|
+
for skill_md in own.glob("*/SKILL.md"):
|
|
174
|
+
fm = _parse_frontmatter(skill_md.read_text(errors="replace"))
|
|
175
|
+
index.setdefault(fm.get("name") or skill_md.parent.name, {
|
|
176
|
+
"path": str(skill_md.parent),
|
|
177
|
+
"description": fm.get("description", ""),
|
|
178
|
+
"version": (fm.get("metadata") or {}).get("version", ""),
|
|
179
|
+
"source": "proef",
|
|
180
|
+
})
|
|
181
|
+
return index
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def guidance_for(skill_name: str, paths: list[str | Path] | None = None) -> str:
|
|
185
|
+
"""Convenience: discovered skill -> instruction text for a prompt."""
|
|
186
|
+
found = discover_skills(paths)
|
|
187
|
+
if skill_name not in found:
|
|
188
|
+
raise KeyError(f"skill '{skill_name}' not installed; "
|
|
189
|
+
f"available: {sorted(found)}")
|
|
190
|
+
return load_skill_instructions(found[skill_name]["path"])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def recommend_for_role(role: str, paths: list[str | Path] | None = None,
|
|
194
|
+
auto_install: bool = False, dest: str | Path = ".agents/skills") -> list[dict[str, Any]]:
|
|
195
|
+
"""Skills RECOMMENDED_SKILLS says this role needs, that are actually
|
|
196
|
+
discoverable. With auto_install, missing ones are pulled from the repo."""
|
|
197
|
+
wanted = RECOMMENDED_SKILLS.get(role, [])
|
|
198
|
+
if auto_install:
|
|
199
|
+
missing = [w for w in wanted if w not in discover_skills(paths)]
|
|
200
|
+
if missing:
|
|
201
|
+
install_skills(missing, dest)
|
|
202
|
+
found = discover_skills(paths)
|
|
203
|
+
return [found[w] for w in wanted if w in found]
|
proef/sweep.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Parallel campaign harness — fan one problem across candidate shards.
|
|
2
|
+
|
|
3
|
+
The ART campaign ran ~950 coordinated agent sessions; Proef's unit of
|
|
4
|
+
fan-out is the campaign. `run_sweep` partitions a candidate pool across
|
|
5
|
+
`fan` shards, runs one full gated campaign per shard (each with its own
|
|
6
|
+
problem branch, budget and verdict chain), then folds the shards into a
|
|
7
|
+
single roll-up record on the parent branch — the same tree-rollup pattern
|
|
8
|
+
problem trees use, so the workbench and reviewer read it unchanged.
|
|
9
|
+
|
|
10
|
+
Shards run sequentially today (deterministic, sqlite-safe); the
|
|
11
|
+
workbench's subprocess fan-out (api/launch.py) is the live parallel
|
|
12
|
+
counterpart and streams per-shard via branch announcements.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import Any, Callable
|
|
17
|
+
|
|
18
|
+
from proef.core.contracts import Envelope, EventType
|
|
19
|
+
from proef.core.hypothesis import Constraint, ProblemStatement
|
|
20
|
+
from proef.core.interfaces import ProvenanceStore, record_for, system_actor
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def run_sweep(problem: ProblemStatement, candidates: list[str],
|
|
24
|
+
lab_factory: Callable[[], Any], store: ProvenanceStore,
|
|
25
|
+
*, fan: int = 3, k_per_shard: int = 2, threshold: float,
|
|
26
|
+
unit: str = "uM", metric: str = "potency", seed: int = 0,
|
|
27
|
+
rounds: int = 1, notify: Callable[[str], None] | None = None,
|
|
28
|
+
) -> dict:
|
|
29
|
+
"""Partition `candidates` across `fan` shard campaigns and roll the
|
|
30
|
+
verdicts up. Returns {shards, verdicts, tally, best} — verdicts keyed
|
|
31
|
+
by candidate, tally by status, best = confirmed/validated candidates."""
|
|
32
|
+
from proef.autoloop import CampaignConfig, run_campaign
|
|
33
|
+
|
|
34
|
+
say = notify or (lambda m: None)
|
|
35
|
+
base = problem.problem_id or "sweep"
|
|
36
|
+
constraint = Constraint(name=metric, kind="hard", limit=threshold,
|
|
37
|
+
unit=unit,
|
|
38
|
+
description=f"{metric} <= {threshold:g} {unit}")
|
|
39
|
+
shards: list[list[str]] = [[] for _ in range(max(1, fan))]
|
|
40
|
+
for i, c in enumerate(candidates):
|
|
41
|
+
shards[i % len(shards)].append(c)
|
|
42
|
+
|
|
43
|
+
verdicts: dict[str, str] = {}
|
|
44
|
+
shard_summaries = []
|
|
45
|
+
for i, shard in enumerate(shards):
|
|
46
|
+
if not shard:
|
|
47
|
+
continue
|
|
48
|
+
shard_problem = ProblemStatement(
|
|
49
|
+
objective=problem.objective,
|
|
50
|
+
problem_id=f"{base}-sw{i}",
|
|
51
|
+
constraints=[constraint],
|
|
52
|
+
success_metric=problem.success_metric)
|
|
53
|
+
specs = [{"statement": f"{c} {metric} <= {threshold:g} {unit}",
|
|
54
|
+
"candidate": c, "assay_type": "binding",
|
|
55
|
+
"predicted": f"<= {threshold:g}", "rationale": "sweep"}
|
|
56
|
+
for c in shard]
|
|
57
|
+
say(f"shard {i}: {len(shard)} candidates, k={k_per_shard}")
|
|
58
|
+
report = run_campaign(
|
|
59
|
+
CampaignConfig(problem=shard_problem, hypotheses=specs,
|
|
60
|
+
k=k_per_shard, rounds=rounds, autonomy="act",
|
|
61
|
+
inbox=f".data/inbox-sweep-{base}-sw{i}",
|
|
62
|
+
poll_secs=0.05),
|
|
63
|
+
lab_factory(), store, notify=say)
|
|
64
|
+
verdicts.update(report.verdicts)
|
|
65
|
+
shard_summaries.append({"shard": i, "problem_id": shard_problem.problem_id,
|
|
66
|
+
"candidates": shard,
|
|
67
|
+
"verdicts": dict(report.verdicts)})
|
|
68
|
+
|
|
69
|
+
tally: dict[str, int] = {}
|
|
70
|
+
for v in verdicts.values():
|
|
71
|
+
tally[v] = tally.get(v, 0) + 1
|
|
72
|
+
best = sorted(c for c, v in verdicts.items()
|
|
73
|
+
if v in ("confirmed", "validated"))
|
|
74
|
+
store.append(record_for(
|
|
75
|
+
Envelope(experiment_branch_id=f"problem/{base}"),
|
|
76
|
+
EventType.gate_decision,
|
|
77
|
+
system_actor("sweep"),
|
|
78
|
+
decision={"kind": "sweep-rollup", "fan": fan,
|
|
79
|
+
"shards": shard_summaries, "tally": tally,
|
|
80
|
+
"best": best}))
|
|
81
|
+
say(f"SWEEP ROLL-UP: {tally} · best: {best or '—'}")
|
|
82
|
+
return {"shards": shard_summaries, "verdicts": verdicts,
|
|
83
|
+
"tally": tally, "best": best}
|