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/api/v1/programs.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""/api/v1/programs and /api/v1/today, programs as containers of campaigns.
|
|
2
|
+
|
|
3
|
+
A PROGRAM is the scientific goal: a pre-registered gate (metric, direction,
|
|
4
|
+
value) and a modality. A CAMPAIGN is one run that tries to meet it. A program
|
|
5
|
+
has many campaigns; every candidate in all of them is judged against the same
|
|
6
|
+
gate, so program progress is "has anything claimed met the gate, and what is
|
|
7
|
+
the best result so far".
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from fastapi import APIRouter, HTTPException, Request
|
|
12
|
+
|
|
13
|
+
from proef import program as program_cfg
|
|
14
|
+
from proef.api.v1 import schemas as S
|
|
15
|
+
from proef.api.v1.deps import who
|
|
16
|
+
from proef.api.v1.pauses import pauses_for
|
|
17
|
+
from proef.api.launch import spawn_campaign
|
|
18
|
+
from proef.api.v1.campaigns import (_funnel, _load, _reviews, _status, _suggestions,
|
|
19
|
+
_summary_of, _ws, testable)
|
|
20
|
+
from proef.views.ids import row_status
|
|
21
|
+
|
|
22
|
+
router = APIRouter(tags=["programs"])
|
|
23
|
+
|
|
24
|
+
_CLAIMED = ("confirmed", "validated")
|
|
25
|
+
_RUNNING = ("running", "executing")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _gate(doc: dict) -> S.Gate:
|
|
29
|
+
direction = program_cfg.gate_direction(doc)
|
|
30
|
+
value = doc.get("gate_value")
|
|
31
|
+
if value is None:
|
|
32
|
+
try:
|
|
33
|
+
value = program_cfg.gate_threshold_um(doc)
|
|
34
|
+
except Exception:
|
|
35
|
+
value = None
|
|
36
|
+
metric = program_cfg.gate_metric(doc)
|
|
37
|
+
unit = program_cfg.gate_unit(doc)
|
|
38
|
+
from proef.derivation import criteria_label, metric_label
|
|
39
|
+
label = metric_label(metric)
|
|
40
|
+
if value is not None:
|
|
41
|
+
label = criteria_label(metric, direction, value)
|
|
42
|
+
if unit and "(" not in label:
|
|
43
|
+
label += f" {unit}"
|
|
44
|
+
return S.Gate(metric=metric, direction=direction,
|
|
45
|
+
threshold=float(value) if value is not None else None,
|
|
46
|
+
unit=unit, label=label)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _limits(doc: dict) -> S.Limits:
|
|
50
|
+
"""A program's caps; programs created before limits existed get the defaults."""
|
|
51
|
+
try:
|
|
52
|
+
return S.Limits(**(doc.get("limits") or {}))
|
|
53
|
+
except Exception: # noqa: BLE001 - a malformed stored value must not hide the program
|
|
54
|
+
return S.Limits()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _digest(eid: str):
|
|
58
|
+
"""(CampaignDigest, [hypotheses]) for one campaign, no chain verify."""
|
|
59
|
+
ws, row, detail, branch, recs = _load(eid)
|
|
60
|
+
reviews = _reviews(recs)
|
|
61
|
+
suggestions = _suggestions(recs)
|
|
62
|
+
hyps = [_summary_of(c, None, reviews, suggestions) for c in testable(detail.get("cards"))]
|
|
63
|
+
status = _status(detail.get("status") or row_status(row), recs)
|
|
64
|
+
return S.CampaignDigest(
|
|
65
|
+
id=eid, title=detail.get("objective") or row.get("question") or eid,
|
|
66
|
+
status=status, updated_at=row.get("updated_at"),
|
|
67
|
+
funnel=_funnel(hyps)), hyps
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def runs_committed(slug: str, lim: S.Limits) -> int:
|
|
71
|
+
"""Lab runs the program's campaigns have used or still hold in reserve. A campaign in progress reserves its
|
|
72
|
+
whole budget (read from the config it was launched with; the program cap if that is gone), so parallel
|
|
73
|
+
campaigns cannot together promise more than `max_lab_runs`. A finished one counts only what it used."""
|
|
74
|
+
import json
|
|
75
|
+
from proef.paths import CAMPAIGN_DIR
|
|
76
|
+
total = 0
|
|
77
|
+
for link in program_cfg.links_for(slug):
|
|
78
|
+
if link["role"] != "leaf" or link["eid"].startswith("hand-"):
|
|
79
|
+
continue # a hand run never submits to a lab
|
|
80
|
+
try:
|
|
81
|
+
_, row, detail, _, recs = _load(link["eid"])
|
|
82
|
+
except HTTPException:
|
|
83
|
+
continue
|
|
84
|
+
used = sum(1 for r in recs if r.event_type.value == "lab_run" and (r.decision or {}).get("run_id"))
|
|
85
|
+
if _status(detail.get("status") or row_status(row), recs) not in _RUNNING:
|
|
86
|
+
total += used
|
|
87
|
+
continue
|
|
88
|
+
try:
|
|
89
|
+
held = int(json.loads((CAMPAIGN_DIR / f"{link['eid']}.json").read_text())["budget"]["max_total_runs"])
|
|
90
|
+
except Exception: # noqa: BLE001 - no readable config: assume it may use the whole cap
|
|
91
|
+
held = lim.max_lab_runs
|
|
92
|
+
total += max(used, held)
|
|
93
|
+
return total
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def runs_left(slug: str, lim: S.Limits) -> int:
|
|
97
|
+
return max(0, lim.max_lab_runs - runs_committed(slug, lim))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _best(hyps, direction: str, cid: str, title: str) -> S.BestResult | None:
|
|
101
|
+
claimed = [h for h in hyps if h.state in _CLAIMED
|
|
102
|
+
and h.verdict and h.verdict.observed is not None]
|
|
103
|
+
pool = claimed or [h for h in hyps if h.verdict
|
|
104
|
+
and h.verdict.observed is not None]
|
|
105
|
+
if not pool:
|
|
106
|
+
return None
|
|
107
|
+
pick = (min if direction == "min" else max)(
|
|
108
|
+
pool, key=lambda h: h.verdict.observed)
|
|
109
|
+
return S.BestResult(campaign_id=cid, campaign_title=title,
|
|
110
|
+
candidate=pick.head, state=pick.state,
|
|
111
|
+
observed=pick.verdict.observed, ci=pick.verdict.ci)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _next_steps(p, digests, goal: S.Goal, gate: S.Gate,
|
|
115
|
+
unresolved: list[str]) -> list[S.NextStep]:
|
|
116
|
+
"""What a sensible scientist would do next, from the evidence alone."""
|
|
117
|
+
from proef.api.v1.campaigns import pending_approvals, problem_id_for
|
|
118
|
+
steps: list[S.NextStep] = []
|
|
119
|
+
waiting = 0
|
|
120
|
+
for link in program_cfg.links_for(p["slug"]):
|
|
121
|
+
try:
|
|
122
|
+
_, _, detail, _, _ = _load(link["eid"])
|
|
123
|
+
except HTTPException:
|
|
124
|
+
continue
|
|
125
|
+
waiting += len(pending_approvals(problem_id_for(link["eid"], detail)))
|
|
126
|
+
if waiting:
|
|
127
|
+
steps.append(S.NextStep(
|
|
128
|
+
kind="inbox", action="inbox",
|
|
129
|
+
title=f"{waiting} lab submission{'s are' if waiting > 1 else ' is'} pending approval",
|
|
130
|
+
detail="A campaign is paused at the gate until the submission is approved or declined."))
|
|
131
|
+
if unresolved:
|
|
132
|
+
steps.append(S.NextStep(
|
|
133
|
+
kind="follow_up", action="launch", candidates=unresolved,
|
|
134
|
+
title=f"Resolve {len(unresolved)} inconclusive candidate{'s' if len(unresolved) > 1 else ''}",
|
|
135
|
+
detail=f"{', '.join(unresolved)}: the interval straddles the gate. "
|
|
136
|
+
"A follow-up with more replicates near the gate would settle it."))
|
|
137
|
+
for d in digests:
|
|
138
|
+
if d.status == "awaiting_results":
|
|
139
|
+
steps.append(S.NextStep(
|
|
140
|
+
kind="submit_results", action="open_campaign", campaign_id=d.id,
|
|
141
|
+
title=f"Submit plate results for “{d.title}”",
|
|
142
|
+
detail="Its gate is registered. Run the plate, export a CSV, and submit it: "
|
|
143
|
+
"it is judged against that gate."))
|
|
144
|
+
running = sum(d.status in _RUNNING for d in digests)
|
|
145
|
+
if not digests:
|
|
146
|
+
steps.append(S.NextStep(kind="start", action="launch",
|
|
147
|
+
title="Start the first campaign",
|
|
148
|
+
detail=f"Test candidates against {gate.label or 'the gate'}."))
|
|
149
|
+
elif goal.met and goal.best:
|
|
150
|
+
steps.append(S.NextStep(
|
|
151
|
+
kind="milestone", action="new_program",
|
|
152
|
+
title=f"Goal met by {goal.best.candidate}",
|
|
153
|
+
detail="Next: confirm it in an orthogonal assay, or open a follow-on program "
|
|
154
|
+
"with a tighter gate (for example a lead-stage potency bar)."))
|
|
155
|
+
elif not running and goal.judged:
|
|
156
|
+
steps.append(S.NextStep(
|
|
157
|
+
kind="expand", action="launch",
|
|
158
|
+
title="No candidate meets the gate yet",
|
|
159
|
+
detail=f"{goal.refuted} of {goal.judged} judged candidates were refuted. "
|
|
160
|
+
"Propose new candidates or a different scaffold."))
|
|
161
|
+
return steps
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _program(p: dict, with_detail: bool):
|
|
165
|
+
doc = p.get("program") or {}
|
|
166
|
+
gate = _gate(doc)
|
|
167
|
+
direction = gate.direction or "min"
|
|
168
|
+
digests, results, all_best, unresolved = [], [], [], []
|
|
169
|
+
for link in program_cfg.links_for(p["slug"]):
|
|
170
|
+
if link["role"] != "leaf":
|
|
171
|
+
continue # campaign roots are containers
|
|
172
|
+
try:
|
|
173
|
+
dg, hyps = _digest(link["eid"])
|
|
174
|
+
except HTTPException:
|
|
175
|
+
continue # registry row gone (purged)
|
|
176
|
+
dg.best = _best(hyps, direction, dg.id, dg.title)
|
|
177
|
+
digests.append(dg)
|
|
178
|
+
if dg.best:
|
|
179
|
+
all_best.append(dg.best)
|
|
180
|
+
for h in hyps:
|
|
181
|
+
if h.state == "abstained" and (h.review is None
|
|
182
|
+
or h.review.decision == "follow_up"):
|
|
183
|
+
unresolved.append(h.head)
|
|
184
|
+
if h.verdict and h.verdict.observed is not None:
|
|
185
|
+
results.append(S.ProgramResult(
|
|
186
|
+
hypothesis_id=h.id, campaign_id=dg.id, campaign_title=dg.title,
|
|
187
|
+
candidate=h.head, state=h.state,
|
|
188
|
+
observed=h.verdict.observed, ci=h.verdict.ci))
|
|
189
|
+
claimed = [b for b in all_best if b.state in _CLAIMED]
|
|
190
|
+
pool = claimed or all_best
|
|
191
|
+
best = (min if direction == "min" else max)(
|
|
192
|
+
pool, key=lambda b: b.observed) if pool else None
|
|
193
|
+
f = [d.funnel for d in digests]
|
|
194
|
+
goal = S.Goal(met=bool(claimed), best=best,
|
|
195
|
+
claimed=sum(x.claimed for x in f),
|
|
196
|
+
refuted=sum(x.refuted for x in f),
|
|
197
|
+
abstained=sum(x.abstained for x in f),
|
|
198
|
+
judged=sum(x.judged for x in f))
|
|
199
|
+
base = dict(
|
|
200
|
+
slug=p["slug"], name=p["name"], objective=doc.get("objective") or None,
|
|
201
|
+
modality=doc.get("modality") or None, mode=p.get("mode"), limits=_limits(doc), gate=gate,
|
|
202
|
+
pause=pauses_for(None, p["slug"])[1],
|
|
203
|
+
goal=goal, campaigns=len(digests),
|
|
204
|
+
running=sum(d.status in _RUNNING for d in digests),
|
|
205
|
+
updated_at=max((d.updated_at or 0 for d in digests), default=None))
|
|
206
|
+
if not with_detail:
|
|
207
|
+
return S.ProgramSummary(**base)
|
|
208
|
+
digests.sort(key=lambda d: -(d.updated_at or 0))
|
|
209
|
+
return S.ProgramDetail(
|
|
210
|
+
**base, runs_left=runs_left(p["slug"], base["limits"]), campaign_list=digests, results=results,
|
|
211
|
+
next_steps=_next_steps(p, digests, goal, gate, unresolved))
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@router.get("/programs", response_model=list[S.ProgramSummary])
|
|
215
|
+
def list_programs() -> list[S.ProgramSummary]:
|
|
216
|
+
return [_program(p, False) for p in program_cfg.list_programs()]
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@router.get("/programs/{slug}", response_model=S.ProgramDetail)
|
|
220
|
+
def get_program(slug: str) -> S.ProgramDetail:
|
|
221
|
+
p = next((x for x in program_cfg.list_programs() if x["slug"] == slug), None)
|
|
222
|
+
if p is None:
|
|
223
|
+
raise HTTPException(404, S.Problem(
|
|
224
|
+
type="program-not-found", title="Program not found",
|
|
225
|
+
detail=slug).model_dump())
|
|
226
|
+
return _program(p, True)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def collect():
|
|
230
|
+
"""[(CampaignDigest, [HypothesisSummary])] for every live campaign."""
|
|
231
|
+
out = []
|
|
232
|
+
for row in _ws().ongoing() + _ws().finished(500):
|
|
233
|
+
if (row.get("payload") or {}).get("archived"):
|
|
234
|
+
continue
|
|
235
|
+
try:
|
|
236
|
+
out.append(_digest(row["id"]))
|
|
237
|
+
except HTTPException:
|
|
238
|
+
continue
|
|
239
|
+
return out
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@router.post("/programs", response_model=S.ProgramSummary, status_code=201)
|
|
243
|
+
def create_program(body: S.ProgramCreate) -> S.ProgramSummary:
|
|
244
|
+
slug = program_cfg._slug(body.name)
|
|
245
|
+
if any(p["slug"] == slug for p in program_cfg.list_programs()):
|
|
246
|
+
raise HTTPException(409, S.Problem(
|
|
247
|
+
type="program-exists", title="A program with this name exists",
|
|
248
|
+
detail=slug).model_dump())
|
|
249
|
+
program_cfg.save_program_record(
|
|
250
|
+
{"program": body.name, "custom": True, "objective": body.objective,
|
|
251
|
+
"modality": body.modality, "metric": body.metric,
|
|
252
|
+
"direction": body.direction, "gate_value": body.gate_value,
|
|
253
|
+
"unit": body.unit, "mode": "autonomous", "limits": body.limits.model_dump()}, slug)
|
|
254
|
+
p = next(x for x in program_cfg.list_programs() if x["slug"] == slug)
|
|
255
|
+
return _program(p, False)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _hand_run(p: dict, doc: dict, body: S.CampaignCreate, user: str) -> S.CampaignSummary:
|
|
259
|
+
"""A campaign the scientist runs at the bench: the program's gate is
|
|
260
|
+
pre-registered on every candidate NOW; plates are submitted later and judged
|
|
261
|
+
by that gate (see results.py). Nothing is spawned."""
|
|
262
|
+
import time
|
|
263
|
+
import uuid
|
|
264
|
+
|
|
265
|
+
from proef.adapters.store.sqlite import get_store
|
|
266
|
+
from proef.core.contracts import Actor, ActorKind, Envelope, EventType
|
|
267
|
+
from proef.core.hypothesis import (Constraint, HypothesisTracker, ProblemStatement,
|
|
268
|
+
SuccessCriteria)
|
|
269
|
+
from proef.core.interfaces import record_for
|
|
270
|
+
from proef.views import ids as _ids
|
|
271
|
+
cands = list(dict.fromkeys(c.strip() for c in body.candidates if c.strip()))
|
|
272
|
+
if not cands:
|
|
273
|
+
raise HTTPException(422, S.Problem(
|
|
274
|
+
type="candidates-required", title="Candidates are required",
|
|
275
|
+
detail="A hand-run campaign needs at least one candidate.").model_dump())
|
|
276
|
+
gate = _gate(doc)
|
|
277
|
+
if gate.threshold is None:
|
|
278
|
+
raise HTTPException(409, S.Problem(
|
|
279
|
+
type="no-gate", title="This program has no numeric gate",
|
|
280
|
+
detail="Set the program's success criterion first.").model_dump())
|
|
281
|
+
objective = body.objective or doc.get("objective") or p["name"]
|
|
282
|
+
pid = f"prob-{uuid.uuid4().hex[:8]}"
|
|
283
|
+
branch = f"problem/{pid}"
|
|
284
|
+
store = get_store(str(_ids.PROVENANCE_DB))
|
|
285
|
+
actor = Actor(kind=ActorKind.human, id=user)
|
|
286
|
+
t = HypothesisTracker(store, actor)
|
|
287
|
+
t.define_problem(ProblemStatement(problem_id=pid, objective=objective, constraints=[Constraint(
|
|
288
|
+
name=gate.metric or "ic50_um", description=gate.label or "gate", kind="hard",
|
|
289
|
+
limit=gate.threshold, unit=gate.unit or "uM")]), environment={"mode": "hand-run"})
|
|
290
|
+
crit = SuccessCriteria(metric=gate.metric or "ic50_um", direction=gate.direction or "min",
|
|
291
|
+
threshold=gate.threshold)
|
|
292
|
+
for c in cands:
|
|
293
|
+
t.propose(f"{c} meets the gate: {gate.label}", c, "binding", "not predicted: measured by hand",
|
|
294
|
+
None, criteria=crit, branch_id=branch)
|
|
295
|
+
store.append(record_for(Envelope(experiment_branch_id=branch), EventType.gate_decision, actor, decision={
|
|
296
|
+
"kind": "hand_run", "candidates": cands, "gate": gate.label,
|
|
297
|
+
"note": "criteria registered before any data; plates are submitted by a person and judged against them"}))
|
|
298
|
+
cid = f"hand-{int(time.time())}-{uuid.uuid4().hex[:4]}"
|
|
299
|
+
ws = _ws()
|
|
300
|
+
ws.register_agent(cid, objective, "", autonomy="observe")
|
|
301
|
+
ws.link_problem(cid, pid)
|
|
302
|
+
program_cfg.link_leaf(p["name"], cid, campaign_root=None, question=objective, status="executing")
|
|
303
|
+
return S.CampaignSummary(id=cid, title=objective, status="awaiting_results", autonomy="observe",
|
|
304
|
+
program=S.ProgramRef(slug=p["slug"], name=p["name"]))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def campaign_doc(p: dict, body: S.CampaignCreate, *, runs: int | None = None, hypotheses: int | None = None,
|
|
308
|
+
model_calls: int | None = None) -> dict:
|
|
309
|
+
"""The engine config for one campaign: the program's gate and caps, narrowed by what the request asks for.
|
|
310
|
+
`runs`/`hypotheses`/`model_calls` carry a research tree leaf's own slice of the program's budget."""
|
|
311
|
+
lim = _limits(p.get("program") or {})
|
|
312
|
+
doc = {**(p.get("program") or {}), "autonomy": body.autonomy,
|
|
313
|
+
# a campaign may ask for less than the program allows, never more
|
|
314
|
+
"k": min(body.k or lim.breadth, lim.breadth),
|
|
315
|
+
"rounds": min(body.rounds or min(2, lim.max_rounds), lim.max_rounds),
|
|
316
|
+
"replan": bool(body.replan and not [c for c in body.candidates if c.strip()]),
|
|
317
|
+
"followups": bool(body.followups and not [c for c in body.candidates if c.strip()]),
|
|
318
|
+
"orchestrator": body.orchestrator if not [c for c in body.candidates if c.strip()] else "fixed",
|
|
319
|
+
"max_families": lim.max_families, "max_variants_per_family": lim.max_variants_per_family,
|
|
320
|
+
"budget": {"max_total_runs": min(runs or lim.max_lab_runs, lim.max_lab_runs),
|
|
321
|
+
"max_hypotheses_total": min(hypotheses or lim.max_hypotheses, lim.max_hypotheses),
|
|
322
|
+
"max_model_calls": min(model_calls or lim.max_model_calls, lim.max_model_calls),
|
|
323
|
+
**({"wall_clock_secs": float(lim.max_wall_minutes * 60)} if lim.max_wall_minutes else {})},
|
|
324
|
+
"candidates": ",".join(c.strip() for c in body.candidates if c.strip())}
|
|
325
|
+
if body.objective:
|
|
326
|
+
doc["objective"] = body.objective
|
|
327
|
+
if body.sub_problem is not None:
|
|
328
|
+
sp = body.sub_problem
|
|
329
|
+
doc["objective"] = sp.objective
|
|
330
|
+
if sp.metric and sp.gate is not None:
|
|
331
|
+
doc.update(custom=True, metric=sp.metric, direction=sp.direction, gate_value=sp.gate, unit=sp.unit or "")
|
|
332
|
+
return doc
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
@router.post("/programs/{slug}/campaigns", response_model=S.CampaignSummary,
|
|
336
|
+
status_code=201)
|
|
337
|
+
def launch_campaign(slug: str, body: S.CampaignCreate, request: Request) -> S.CampaignSummary:
|
|
338
|
+
"""Start a campaign against the program's gate. Default autonomy is
|
|
339
|
+
`gate`: every lab submission waits for a human approval."""
|
|
340
|
+
p = next((x for x in program_cfg.list_programs() if x["slug"] == slug), None)
|
|
341
|
+
if p is None:
|
|
342
|
+
raise HTTPException(404, S.Problem(
|
|
343
|
+
type="program-not-found", title="Program not found",
|
|
344
|
+
detail=slug).model_dump())
|
|
345
|
+
if body.mode == "hand":
|
|
346
|
+
return _hand_run(p, p.get("program") or {}, body, who(request))
|
|
347
|
+
if not [c for c in body.candidates if c.strip()]:
|
|
348
|
+
from proef.adapters.models.from_env import model_status
|
|
349
|
+
if not model_status()["configured"]:
|
|
350
|
+
raise HTTPException(409, S.Problem(
|
|
351
|
+
type="model-not-configured", title="No model is configured",
|
|
352
|
+
detail="With no candidates, a model proposes the hypotheses. Name the candidates "
|
|
353
|
+
"yourself, or set PROEF_LLM_MODEL, PROEF_LLM_TOKEN and PROEF_LLM_BASE_URL "
|
|
354
|
+
"(PROEF_LLM_API=openai for OpenAI-compatible endpoints) and restart.").model_dump())
|
|
355
|
+
left = runs_left(slug, _limits(p.get("program") or {}))
|
|
356
|
+
if left < 1:
|
|
357
|
+
raise HTTPException(409, S.Problem(
|
|
358
|
+
type="program-budget-exhausted", title="The program has no lab runs left",
|
|
359
|
+
detail="Its other campaigns have used or reserved all of its lab runs. Wait for one to finish, "
|
|
360
|
+
"or raise the program's lab-run limit.").model_dump())
|
|
361
|
+
doc = campaign_doc(p, body, runs=left)
|
|
362
|
+
cid = spawn_campaign(doc, p["name"])
|
|
363
|
+
if cid is None:
|
|
364
|
+
raise HTTPException(500, S.Problem(
|
|
365
|
+
type="launch-failed", title="Campaign did not start").model_dump())
|
|
366
|
+
return S.CampaignSummary(
|
|
367
|
+
id=cid, title=doc.get("objective") or p["name"], status="running",
|
|
368
|
+
autonomy=body.autonomy,
|
|
369
|
+
program=S.ProgramRef(slug=slug, name=p["name"]))
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
@router.get("/today", response_model=S.Today)
|
|
373
|
+
def today() -> S.Today:
|
|
374
|
+
"""The home screen: what needs me, how each program is doing, and the
|
|
375
|
+
campaigns that belong to no program."""
|
|
376
|
+
from proef.approvals import ApprovalInbox
|
|
377
|
+
from proef.governance import HaltSwitch
|
|
378
|
+
from proef.paths import APPROVALS_FILE
|
|
379
|
+
programs = [_program(p, False) for p in program_cfg.list_programs()]
|
|
380
|
+
linked = {l["eid"] for p in program_cfg.list_programs()
|
|
381
|
+
for l in program_cfg.links_for(p["slug"])}
|
|
382
|
+
standalone, abstentions, running = [], [], 0
|
|
383
|
+
for dg, hyps in collect():
|
|
384
|
+
running += dg.status in _RUNNING
|
|
385
|
+
abst = [h.head for h in hyps if h.state == "abstained" and h.review is None]
|
|
386
|
+
if abst:
|
|
387
|
+
abstentions.append(S.AbstentionNote(
|
|
388
|
+
campaign_id=dg.id, campaign_title=dg.title, candidates=abst))
|
|
389
|
+
if dg.id not in linked:
|
|
390
|
+
standalone.append(dg)
|
|
391
|
+
standalone.sort(key=lambda d: -(d.updated_at or 0))
|
|
392
|
+
return S.Today(
|
|
393
|
+
attention=S.Attention(
|
|
394
|
+
pending_approvals=len(ApprovalInbox(str(APPROVALS_FILE)).pending()),
|
|
395
|
+
abstentions=abstentions, running=running,
|
|
396
|
+
halted=HaltSwitch().engaged() is not None),
|
|
397
|
+
programs=programs, standalone=standalone)
|
proef/api/v1/results.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""POST /api/v1/campaigns/{id}/results, a person submits a measured plate to a campaign.
|
|
2
|
+
|
|
3
|
+
The honest way to close the loop for a hand-run experiment: the file is judged
|
|
4
|
+
by the SAME verdict code a live campaign uses (pre-registered criteria, CI veto,
|
|
5
|
+
abstention), only for hypotheses that are still open. The submission, the file's
|
|
6
|
+
digest and who made it are sealed before anything is judged.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
|
15
|
+
|
|
16
|
+
from proef.api.v1 import schemas as S
|
|
17
|
+
from proef.api.v1.campaigns import _load
|
|
18
|
+
from proef.api.v1.deps import who
|
|
19
|
+
from proef.core.contracts import Actor, ActorKind, Envelope, EventType
|
|
20
|
+
from proef.core.interfaces import record_for
|
|
21
|
+
|
|
22
|
+
router = APIRouter(prefix="/campaigns", tags=["campaigns"])
|
|
23
|
+
|
|
24
|
+
MEASURED = ("measured", "historical")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _problem(status: int, type_: str, title: str, detail: str = "") -> HTTPException:
|
|
28
|
+
return HTTPException(status, S.Problem(type=type_, title=title, detail=detail).model_dump())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _gate(h) -> str:
|
|
32
|
+
c = h.criteria
|
|
33
|
+
return f"{c.metric} {'≤' if c.direction == 'min' else '≥'} {c.threshold:g}"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _inspect(eid: str, data: bytes, filename: str, max_response: float | None):
|
|
37
|
+
from proef.adapters.store.sqlite import get_store
|
|
38
|
+
from proef.core.hypothesis import HypothesisTracker
|
|
39
|
+
from proef.analysis_profiles.measurements import read_plate_or_table
|
|
40
|
+
from proef.labread import QC_ZPRIME_FLOOR
|
|
41
|
+
from proef.physfail import classify
|
|
42
|
+
from proef.views import ids as _ids
|
|
43
|
+
from proef.watch import AutoAnalysisAgent
|
|
44
|
+
|
|
45
|
+
_, _, _, branch, recs = _load(eid)
|
|
46
|
+
if not branch:
|
|
47
|
+
raise _problem(409, "no-ledger", "Campaign has no ledger branch yet", eid)
|
|
48
|
+
if not filename.lower().endswith(".csv"):
|
|
49
|
+
raise _problem(422, "rejected-upload", "CSV only for now",
|
|
50
|
+
"Export the plate as CSV (long table or a supported reader format).")
|
|
51
|
+
sha = hashlib.sha256(data).hexdigest()
|
|
52
|
+
run_id = f"upload-{sha[:8]}"
|
|
53
|
+
with tempfile.TemporaryDirectory() as td:
|
|
54
|
+
path = Path(td) / f"{run_id}.csv"
|
|
55
|
+
path.write_bytes(data)
|
|
56
|
+
try:
|
|
57
|
+
res = read_plate_or_table(path, max_response=max_response)
|
|
58
|
+
except Exception as exc: # noqa: BLE001
|
|
59
|
+
raise _problem(422, "unreadable-file", "Could not read this file", str(exc)[:200]) from None
|
|
60
|
+
store = get_store(str(_ids.PROVENANCE_DB))
|
|
61
|
+
tracker = HypothesisTracker.resume(store, Actor(kind=ActorKind.human, id="preview"), branch)
|
|
62
|
+
open_h = [h for h in tracker.hypotheses.values() if h.status in AutoAnalysisAgent._OPEN]
|
|
63
|
+
judged = sorted({h.candidate for h in tracker.hypotheses.values() if h.status not in AutoAnalysisAgent._OPEN})
|
|
64
|
+
samples = {str(r.get("sample")) for r in (m if isinstance(m, dict) else m.model_dump() for m in res.records)
|
|
65
|
+
if r.get("sample") and not r.get("control")}
|
|
66
|
+
matches = [h for h in open_h if h.candidate in samples]
|
|
67
|
+
phys = classify([r["value"] for r in (m if isinstance(m, dict) else m.model_dump() for m in res.records)])
|
|
68
|
+
seen = any((r.decision or {}).get("kind") == "results_submitted" and (r.decision or {}).get("sha256") == sha
|
|
69
|
+
for r in recs)
|
|
70
|
+
return dict(branch=branch, store=store, sha=sha, run_id=run_id, res=res, open_h=open_h, judged=judged,
|
|
71
|
+
samples=samples, matches=matches, phys=phys, seen=seen, floor=QC_ZPRIME_FLOOR)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _preview(info, filename: str) -> S.ResultsPreview:
|
|
75
|
+
res, phys = info["res"], info["phys"]
|
|
76
|
+
matched = {h.candidate for h in info["matches"]}
|
|
77
|
+
z = res.z_prime
|
|
78
|
+
return S.ResultsPreview(
|
|
79
|
+
run_id=info["run_id"], filename=filename, sha256=info["sha"], n_wells=len(res.records),
|
|
80
|
+
z_prime=z, z_kind=(res.analysis or {}).get("z_prime_kind"),
|
|
81
|
+
qc_ok=(z is not None and z >= info["floor"]) or getattr(res, "no_plate_qc", False),
|
|
82
|
+
kind="measurements" if getattr(res, "no_plate_qc", False) else "plate",
|
|
83
|
+
failure=phys["evidence"] if phys["kind"] == "physical" else None,
|
|
84
|
+
matches=[S.ResultMatch(hypothesis_id=h.hypothesis_id, candidate=h.candidate,
|
|
85
|
+
statement=h.statement, gate=_gate(h)) for h in info["matches"]],
|
|
86
|
+
in_file_only=sorted(info["samples"] - matched - set(info["judged"])),
|
|
87
|
+
waiting_for_data=sorted(h.candidate for h in info["open_h"] if h.candidate not in matched),
|
|
88
|
+
already_judged=sorted(set(info["judged"]) & info["samples"]),
|
|
89
|
+
already_submitted=info["seen"])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@router.post("/{eid}/results", response_model=S.ResultsPreview | S.ResultsOutcome)
|
|
93
|
+
async def submit_results(eid: str, request: Request, file: UploadFile = File(...),
|
|
94
|
+
origin: str = Form("measured"), dry_run: bool = Form(True),
|
|
95
|
+
max_response: float | None = Form(None)):
|
|
96
|
+
"""dry_run=true (default): show which open hypotheses this plate would be judged against.
|
|
97
|
+
dry_run=false: seal the submission, then judge. Idempotent per file digest."""
|
|
98
|
+
if origin not in MEASURED:
|
|
99
|
+
raise _problem(422, "proxy-evidence", "Only measured or historical data can judge a hypothesis",
|
|
100
|
+
f"'{origin}' data stays in Analyze; it cannot produce a campaign verdict.")
|
|
101
|
+
data = await file.read()
|
|
102
|
+
name = file.filename or "upload.csv"
|
|
103
|
+
info = _inspect(eid, data, name, max_response)
|
|
104
|
+
prev = _preview(info, name)
|
|
105
|
+
if dry_run:
|
|
106
|
+
return prev
|
|
107
|
+
if prev.already_submitted:
|
|
108
|
+
raise _problem(409, "already-submitted", "This exact file was already submitted", info["sha"][:12])
|
|
109
|
+
if prev.failure:
|
|
110
|
+
raise _problem(409, "physical-failure", "This plate shows a physical failure",
|
|
111
|
+
f"{prev.failure}: no verdicts are derived from it. Re-run the plate.")
|
|
112
|
+
if not info["matches"]:
|
|
113
|
+
raise _problem(409, "nothing-to-judge", "No open hypothesis matches this file",
|
|
114
|
+
"None of the samples in the file belong to an open hypothesis of this campaign.")
|
|
115
|
+
from proef.core.hypothesis import HypothesisTracker
|
|
116
|
+
from proef.flywheel import Flywheel
|
|
117
|
+
from proef.paths import DATA_DIR
|
|
118
|
+
from proef.watch import AutoAnalysisAgent, LabEvent
|
|
119
|
+
user, store, branch = who(request), info["store"], info["branch"]
|
|
120
|
+
pid = branch.split("/", 1)[-1]
|
|
121
|
+
inbox = Path(DATA_DIR) / "inbox" / pid
|
|
122
|
+
inbox.mkdir(parents=True, exist_ok=True)
|
|
123
|
+
path = inbox / f"{info['run_id']}.csv"
|
|
124
|
+
path.write_bytes(data)
|
|
125
|
+
actor = Actor(kind=ActorKind.human, id=user)
|
|
126
|
+
# seal FIRST: a gap between "submitted" and "judged" is visible, never silent
|
|
127
|
+
store.append(record_for(Envelope(experiment_branch_id=branch), EventType.gate_decision, actor, decision={
|
|
128
|
+
"kind": "results_submitted", "sha256": info["sha"], "original_name": name, "run_id": info["run_id"],
|
|
129
|
+
"evidence_origin": origin, "candidates": [h.candidate for h in info["matches"]],
|
|
130
|
+
"z_prime": prev.z_prime, "note": "judged by the campaign's pre-registered criteria; "
|
|
131
|
+
"hypotheses that already have a verdict are left alone"}))
|
|
132
|
+
flywheel = Flywheel()
|
|
133
|
+
|
|
134
|
+
def _on_verdict(h) -> None:
|
|
135
|
+
flywheel.submit(h.candidate, h.family, h.assay_type, h.status, h.observed_value, h.observed_ci,
|
|
136
|
+
problem_id=pid, threshold=(h.criteria.threshold if h.criteria else None),
|
|
137
|
+
evidence_run=h.evidence_run_id)
|
|
138
|
+
|
|
139
|
+
tracker = HypothesisTracker.resume(store, actor, branch, on_verdict=_on_verdict)
|
|
140
|
+
msgs: list[str] = []
|
|
141
|
+
agent = AutoAnalysisAgent(store=store, tracker=tracker, notify=msgs.append, branch_id=branch,
|
|
142
|
+
max_response=max_response)
|
|
143
|
+
out = agent.handle(LabEvent(kind="plate_ready", source="upload", path=path)) or {}
|
|
144
|
+
verdicts = [S.ResultVerdict(hypothesis_id=v[0], candidate=v[1], status=v[2], observed=v[3])
|
|
145
|
+
for v in out.get("verdicts") or []]
|
|
146
|
+
return S.ResultsOutcome(run_id=info["run_id"], verdicts=verdicts, messages=msgs,
|
|
147
|
+
failure=(out.get("error") or None))
|