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
|
@@ -0,0 +1,802 @@
|
|
|
1
|
+
"""/api/v1/campaigns, the campaign cockpit's data.
|
|
2
|
+
|
|
3
|
+
Everything here is a pure adaptation of the existing read-models in
|
|
4
|
+
`proef.views` into the typed v1 contract (see schemas.py); no engine logic
|
|
5
|
+
lives in this file.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
from fastapi import APIRouter, HTTPException, Query, Request
|
|
12
|
+
|
|
13
|
+
from proef import views
|
|
14
|
+
from proef.api.v1 import schemas as S
|
|
15
|
+
from proef.api.v1.deps import who
|
|
16
|
+
from proef.views import ids as _ids
|
|
17
|
+
from proef.views.experiment import _branch_records, _problem_id
|
|
18
|
+
from proef.views.ids import row_status
|
|
19
|
+
from proef.wizard_store import WizardStore
|
|
20
|
+
|
|
21
|
+
router = APIRouter(prefix="/campaigns", tags=["campaigns"])
|
|
22
|
+
|
|
23
|
+
_STATE = {"inconclusive": "abstained", "invalidated": "refuted"}
|
|
24
|
+
_JUDGED = {"confirmed", "validated", "abstained", "refuted"}
|
|
25
|
+
_TESTED = _JUDGED | {"in_lab"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _norm(x: str | None) -> str | None:
|
|
29
|
+
return _STATE.get(x, x) if x else x
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ------------------------------------------------------------------ helpers
|
|
33
|
+
def _ws() -> WizardStore:
|
|
34
|
+
return WizardStore()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _program_index() -> dict[str, S.ProgramRef]:
|
|
38
|
+
"""eid -> the program that links it."""
|
|
39
|
+
from proef import program as program_cfg
|
|
40
|
+
out: dict[str, S.ProgramRef] = {}
|
|
41
|
+
for p in program_cfg.list_programs():
|
|
42
|
+
for link in program_cfg.links_for(p["slug"]):
|
|
43
|
+
out.setdefault(link["eid"],
|
|
44
|
+
S.ProgramRef(slug=p["slug"], name=p["name"]))
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _cand(rec) -> str | None:
|
|
49
|
+
d = rec.decision or {}
|
|
50
|
+
if d.get("candidate"):
|
|
51
|
+
return str(d["candidate"])
|
|
52
|
+
if rec.artifact:
|
|
53
|
+
c = (rec.artifact.metadata or {}).get("candidate")
|
|
54
|
+
return str(c) if c else None
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def summarize(rec) -> tuple[str, str, str | None]:
|
|
59
|
+
"""(kind, human text, candidate) for one provenance record."""
|
|
60
|
+
et = rec.event_type.value
|
|
61
|
+
d = rec.decision or {}
|
|
62
|
+
cand = _cand(rec)
|
|
63
|
+
if et == "problem_defined":
|
|
64
|
+
return "problem", f"Problem defined: {d.get('objective', '')}", None
|
|
65
|
+
if et == "hypothesis_proposed":
|
|
66
|
+
label = cand or str(d.get("statement", ""))[:60]
|
|
67
|
+
return "proposed", f"Proposed {label}", cand
|
|
68
|
+
if et == "hypotheses_filtered":
|
|
69
|
+
if d.get("kind") == "plan_review":
|
|
70
|
+
return ("review", f"Plan review: {len(d.get('decisions') or [])} hypothes"
|
|
71
|
+
f"{'is' if len(d.get('decisions') or []) == 1 else 'es'} removed before testing", None)
|
|
72
|
+
if d.get("kind") == "acquisition_selection":
|
|
73
|
+
return ("batch", f"Batch chosen by {d.get('policy')}: "
|
|
74
|
+
f"{len(d.get('picks') or [])} picked, "
|
|
75
|
+
f"{len(d.get('refusals') or [])} refused", None)
|
|
76
|
+
decs = d.get("decisions") or []
|
|
77
|
+
return ("batch", f"Portfolio filtered: "
|
|
78
|
+
f"{sum(1 for x in decs if x.get('selected'))} of "
|
|
79
|
+
f"{len(decs)} selected", None)
|
|
80
|
+
if et == "lab_run":
|
|
81
|
+
return ("run", f"Run {d.get('run_id', '?')} submitted"
|
|
82
|
+
+ (f": {d['title']}" if d.get("title") else ""), cand)
|
|
83
|
+
if et == "synthesis_complete":
|
|
84
|
+
return ("make", f"Synthesised {d.get('candidate', '?')}: yield "
|
|
85
|
+
f"{d.get('yield_pct', '?')}%, purity {d.get('purity', '?')}%",
|
|
86
|
+
cand)
|
|
87
|
+
if et in ("hypothesis_validated", "hypothesis_invalidated",
|
|
88
|
+
"hypothesis_inconclusive"):
|
|
89
|
+
word = {"hypothesis_validated": "VALIDATED",
|
|
90
|
+
"hypothesis_invalidated": "REFUTED",
|
|
91
|
+
"hypothesis_inconclusive": "ABSTAINED"}[et]
|
|
92
|
+
obs = d.get("observed")
|
|
93
|
+
if d.get("family_id") and not cand:
|
|
94
|
+
# a family's claim, derived from its variants' verdicts
|
|
95
|
+
return ("verdict", f"Family “{d['family_id']}”: {word} ({d.get('reason') or 'derived from its variants'})", None)
|
|
96
|
+
return ("verdict", f"{cand or '?'}: {word}"
|
|
97
|
+
+ (f": observed {obs}" if obs is not None else ""), cand)
|
|
98
|
+
if et == "gate_decision" and d.get("kind") == "orchestrator_choice":
|
|
99
|
+
who_ = {"model": "the model", "fixed": "the configured order", "fixed-fallback": "the configured order (the model's choice was not usable)"}.get(d.get("source"), "the orchestrator")
|
|
100
|
+
return ("gate", f"After round {d.get('round')}: {who_} chose {str(d.get('chosen', '?')).replace('_', ' ')}"
|
|
101
|
+
+ (f": {d['why']}" if d.get("why") else ""), None)
|
|
102
|
+
if et == "gate_decision" and d.get("kind") == "campaign_stopped":
|
|
103
|
+
why_ = {"halt": "the operator's stop switch", "wall_clock": "the wall-clock budget", "orchestrator": "the orchestrator"}.get(d.get("why"), str(d.get("why")))
|
|
104
|
+
return ("gate", f"Campaign ended early by {why_}" + (f": {d['detail']}" if d.get("detail") else ""), None)
|
|
105
|
+
if et == "tool_invocation" and d.get("kind") == "tool_call":
|
|
106
|
+
outcome = "refused" if d.get("refused") else (d.get("status") or "done")
|
|
107
|
+
return ("tool", f"{rec.actor.id} called {d.get('tool', '?')}: {outcome}", None)
|
|
108
|
+
if et == "gate_decision" and d.get("kind") == "tool_refused":
|
|
109
|
+
return ("gate", f"Tool refused ({d.get('tool', '?')}): {d.get('reason', '')}", None)
|
|
110
|
+
if et == "gate_decision" and d.get("kind") == "human_approval":
|
|
111
|
+
verb = "approved" if d.get("approve") else "declined"
|
|
112
|
+
return ("review", f"{rec.actor.id} {verb} the lab submission “{d.get('title', '')}”", cand)
|
|
113
|
+
if et == "gate_decision" and d.get("kind") == "human_review":
|
|
114
|
+
verb = {"follow_up": "follow up", "accept": "accept as inconclusive",
|
|
115
|
+
"drop": "drop"}.get(d.get("decision"), d.get("decision"))
|
|
116
|
+
return ("review", f"{rec.actor.id} decided to {verb} {cand or '?'}"
|
|
117
|
+
+ (f": “{d['note']}”" if d.get("note") else ""), cand)
|
|
118
|
+
if et == "gate_decision" and d.get("kind") == "plan_decision":
|
|
119
|
+
who_ = d.get("decided_by", "someone")
|
|
120
|
+
if not d.get("approved"):
|
|
121
|
+
return ("review", f"{who_} {'emptied' if d.get('reason') == 'every hypothesis was removed' else 'declined'} "
|
|
122
|
+
"the research plan: nothing was submitted to the lab"
|
|
123
|
+
+ (f" (“{d['note']}”)" if d.get("note") else ""), None)
|
|
124
|
+
rm = len(d.get("removed") or [])
|
|
125
|
+
return ("review", f"{who_} approved the research plan: {d.get('n_kept')} of {d.get('n_proposed')} "
|
|
126
|
+
f"hypotheses go ahead" + (f" ({rm} removed)" if rm else ""), None)
|
|
127
|
+
if et == "gate_decision" and d.get("kind") == "hand_run":
|
|
128
|
+
return ("run", f"{rec.actor.id} registered a hand-run campaign for "
|
|
129
|
+
f"{', '.join(d.get('candidates') or [])} against {d.get('gate', 'the gate')}", None)
|
|
130
|
+
if et == "gate_decision" and d.get("kind") == "results_submitted":
|
|
131
|
+
return ("run", f"{rec.actor.id} submitted a plate ({d.get('original_name', '?')}): judging "
|
|
132
|
+
f"{', '.join(d.get('candidates') or []) or 'nothing'}", None)
|
|
133
|
+
if et == "gate_decision" and d.get("kind") == "analysis_attached":
|
|
134
|
+
return ("review", f"{rec.actor.id} attached analysis {d.get('analysis_id', '?')} as evidence"
|
|
135
|
+
+ (f" for {d['candidate']}" if d.get("candidate") else ""), d.get("candidate"))
|
|
136
|
+
if et == "gate_decision":
|
|
137
|
+
kind = d.get("kind", "gate")
|
|
138
|
+
reason = d.get("reason") or d.get("action") or ""
|
|
139
|
+
return ("gate", f"{kind.replace('_', ' ').capitalize()}"
|
|
140
|
+
+ (f": {reason}" if reason else ""), cand)
|
|
141
|
+
if et == "stage_transition":
|
|
142
|
+
stage = str(d.get("stage", d.get("kind", "")))
|
|
143
|
+
if d.get("kind") == "round_start":
|
|
144
|
+
return ("round", f"Round {d.get('round')} started: "
|
|
145
|
+
f"{', '.join(d.get('candidates') or [])}", None)
|
|
146
|
+
if stage.endswith("-complete") and stage.startswith("round-"):
|
|
147
|
+
return "round", f"Round {stage.split('-')[1]} complete", None
|
|
148
|
+
if d.get("kind") == "review_report":
|
|
149
|
+
n = len(d.get("findings") or [])
|
|
150
|
+
return ("review", "Reviewer: no findings" if not n
|
|
151
|
+
else f"Reviewer: {n} finding(s)", None)
|
|
152
|
+
return "event", et.replace("_", " ").capitalize(), cand
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _ts(rec) -> float | None:
|
|
156
|
+
return getattr(getattr(rec, "envelope", None), "created_at", None)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
ROLE = {
|
|
160
|
+
"campaign": "Campaign orchestrator: proposes, selects, tests and judges",
|
|
161
|
+
"synthesis": "Make: synthesis and batch QC",
|
|
162
|
+
"bioprocess": "Make: bioprocess stability QC",
|
|
163
|
+
"reviewer": "Independent reviewer: audits every verdict",
|
|
164
|
+
"llm-reviewer": "Advisory LLM reviewer: can only add flags",
|
|
165
|
+
"safety": "Safety gate: refuses unsafe submissions",
|
|
166
|
+
"planner": "Planner: decomposes the objective into sub-problems",
|
|
167
|
+
"program": "Program registry",
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _actor(rec) -> tuple[str, str, str | None]:
|
|
172
|
+
a = rec.actor
|
|
173
|
+
return a.id, a.kind.value, a.model_version
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _role(aid: str, kind: str) -> str:
|
|
177
|
+
if kind == "human":
|
|
178
|
+
return "Scientist: human decisions"
|
|
179
|
+
return ROLE.get(aid, aid)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
_QUIET = {"proposed", "event"} # kept in provenance, hidden in the feed
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def activity_items(recs, limit: int = 50) -> list[S.ActivityItem]:
|
|
186
|
+
out = []
|
|
187
|
+
for r in recs:
|
|
188
|
+
kind, text, cand = summarize(r)
|
|
189
|
+
if kind in _QUIET:
|
|
190
|
+
continue
|
|
191
|
+
out.append(S.ActivityItem(ts=_ts(r), kind=kind, text=text,
|
|
192
|
+
candidate=cand, actor=_actor(r)[0], event=r.event_type.value,
|
|
193
|
+
hash=(r.record_hash or "")[:7] or None))
|
|
194
|
+
return list(reversed(out))[:limit]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _id2cand(recs) -> dict[str, str]:
|
|
198
|
+
m: dict[str, str] = {}
|
|
199
|
+
for r in recs:
|
|
200
|
+
if r.event_type.value == "hypothesis_proposed":
|
|
201
|
+
c = _cand(r)
|
|
202
|
+
hid = (r.decision or {}).get("hypothesis_id")
|
|
203
|
+
for k in (hid, r.artifact.artifact_id if r.artifact else None):
|
|
204
|
+
if k and c:
|
|
205
|
+
m[k] = c
|
|
206
|
+
return m
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _why_rounds(recs, detail_rounds) -> list[S.Round]:
|
|
210
|
+
id2c = _id2cand(recs)
|
|
211
|
+
# one record per round's selection. A plan REMOVAL also writes a 'filtered' record (kind plan_review); counting it
|
|
212
|
+
# would shift every round's explanation by one
|
|
213
|
+
portfolio = [r.decision for r in recs
|
|
214
|
+
if r.event_type.value == "hypotheses_filtered"
|
|
215
|
+
and (r.decision or {}).get("decisions") is not None
|
|
216
|
+
and (r.decision or {}).get("kind") != "plan_review"]
|
|
217
|
+
out = []
|
|
218
|
+
for rd in detail_rounds:
|
|
219
|
+
n = rd["round"]
|
|
220
|
+
sel, why = rd.get("selection"), None
|
|
221
|
+
if sel:
|
|
222
|
+
why = S.Why(
|
|
223
|
+
policy=sel.get("policy"),
|
|
224
|
+
policy_version=(str(sel["policy_version"])
|
|
225
|
+
if sel.get("policy_version") is not None else None),
|
|
226
|
+
k=sel.get("k"),
|
|
227
|
+
target=sel.get("target"), direction=sel.get("direction"),
|
|
228
|
+
note=sel.get("note", ""),
|
|
229
|
+
picks=[S.Pick(candidate=p["candidate"],
|
|
230
|
+
reason=p.get("reason", ""),
|
|
231
|
+
score=p.get("acquisition"), mean=p.get("mean"),
|
|
232
|
+
sd=p.get("sd")) for p in sel.get("picks", [])],
|
|
233
|
+
refusals=[S.Refusal(candidate=x["candidate"],
|
|
234
|
+
reason=x.get("reason", ""))
|
|
235
|
+
for x in sel.get("refusals", [])])
|
|
236
|
+
elif 0 <= n - 1 < len(portfolio):
|
|
237
|
+
decs = portfolio[n - 1].get("decisions", [])
|
|
238
|
+
|
|
239
|
+
def name(d):
|
|
240
|
+
return id2c.get(d.get("hypothesis_id"),
|
|
241
|
+
d.get("hypothesis_id", "?"))
|
|
242
|
+
why = S.Why(
|
|
243
|
+
policy="portfolio score", k=sum(1 for d in decs
|
|
244
|
+
if d.get("selected")),
|
|
245
|
+
picks=[S.Pick(candidate=name(d), reason=d.get("reason", ""),
|
|
246
|
+
score=d.get("score"))
|
|
247
|
+
for d in decs if d.get("selected")],
|
|
248
|
+
refusals=[S.Refusal(candidate=name(d),
|
|
249
|
+
reason=d.get("reason") or "not selected")
|
|
250
|
+
for d in decs if not d.get("selected")])
|
|
251
|
+
out.append(S.Round(n=n, candidates=rd["candidates"],
|
|
252
|
+
verdicts={k: _norm(v) or v
|
|
253
|
+
for k, v in rd.get("verdicts", {}).items()},
|
|
254
|
+
why=why))
|
|
255
|
+
return out
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _reviews(recs) -> dict[str, S.Review]:
|
|
259
|
+
"""Latest human decision per hypothesis id (and candidate)."""
|
|
260
|
+
out: dict[str, S.Review] = {}
|
|
261
|
+
for r in recs:
|
|
262
|
+
d = r.decision or {}
|
|
263
|
+
if d.get("kind") != "human_review" or not d.get("decision"):
|
|
264
|
+
continue
|
|
265
|
+
rv = S.Review(decision=d["decision"], note=d.get("note", ""),
|
|
266
|
+
by=r.actor.id, ts=_ts(r),
|
|
267
|
+
follow_up_campaign_id=d.get("follow_up_campaign_id"))
|
|
268
|
+
for k in (d.get("hypothesis_id"), d.get("candidate")):
|
|
269
|
+
if k:
|
|
270
|
+
out[str(k)] = rv
|
|
271
|
+
return out
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _suggestions(recs) -> dict[str, S.Suggestion]:
|
|
275
|
+
"""The model's suggestion per hypothesis, and whether a follow-up was made from it. The FIRST real proposal wins: a later
|
|
276
|
+
duplicate (status duplicate_proposal) must not replace a valid suggestion, and a proposal whose action was not one of
|
|
277
|
+
the three is not shown at all, rather than as an accept."""
|
|
278
|
+
ran = {(r.decision or {}).get("followup_of") for r in recs
|
|
279
|
+
if r.event_type.value == "hypothesis_proposed" and (r.decision or {}).get("followup_of")}
|
|
280
|
+
out: dict[str, S.Suggestion] = {}
|
|
281
|
+
for r in recs:
|
|
282
|
+
d = r.decision or {}
|
|
283
|
+
hid = str(d.get("hypothesis_id") or "")
|
|
284
|
+
if d.get("kind") != "followup_proposal" or not hid or hid in out:
|
|
285
|
+
continue
|
|
286
|
+
v, pr = d.get("validation") or {}, d.get("params") or {}
|
|
287
|
+
if d.get("action") not in ("follow_up", "accept", "drop") or v.get("status") in ("duplicate_proposal", "unknown_hypothesis"):
|
|
288
|
+
continue
|
|
289
|
+
out[hid] = S.Suggestion(
|
|
290
|
+
action=d["action"], ok=bool(v.get("ok")), status=str(v.get("status", "")), reasons=list(v.get("reasons") or []),
|
|
291
|
+
replicates=pr.get("replicates"), replicates_requested=pr.get("replicates_requested"),
|
|
292
|
+
concentrations=pr.get("concentrations"), why=str(d.get("rationale") or "")[:300], ran=hid in ran)
|
|
293
|
+
return out
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _summary_of(card, gate_label: str | None = None,
|
|
297
|
+
reviews: dict | None = None, suggestions: dict | None = None) -> S.HypothesisSummary:
|
|
298
|
+
v = card.get("verdict")
|
|
299
|
+
verdict = None
|
|
300
|
+
if v and v.get("status"):
|
|
301
|
+
status = _norm(str(v["status"]).lower())
|
|
302
|
+
if status in ("confirmed", "validated", "abstained", "refuted"):
|
|
303
|
+
ci = v.get("ci")
|
|
304
|
+
verdict = S.Verdict(
|
|
305
|
+
status=status, observed=v.get("observed"),
|
|
306
|
+
ci=list(ci) if ci else None, unit_label=v.get("unit_label"),
|
|
307
|
+
margin=v.get("margin") or None,
|
|
308
|
+
extrapolation=bool(v.get("extrapolation")))
|
|
309
|
+
return S.HypothesisSummary(
|
|
310
|
+
id=card["key"], candidate=card.get("candidate"), family=card.get("family"),
|
|
311
|
+
head=card.get("head") or card["key"],
|
|
312
|
+
statement=card.get("statement") or "",
|
|
313
|
+
state=_norm(card["state"]), stage=card.get("stage") or "",
|
|
314
|
+
round=card.get("round"), verdict=verdict,
|
|
315
|
+
gate_label=gate_label or card.get("gate_label"),
|
|
316
|
+
selected=bool(card.get("selected")),
|
|
317
|
+
review=(reviews or {}).get(card["key"])
|
|
318
|
+
or (reviews or {}).get(str(card.get("candidate"))),
|
|
319
|
+
suggestion=(suggestions or {}).get(card["key"]))
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _funnel(hyps: list[S.HypothesisSummary]) -> S.Funnel:
|
|
323
|
+
st = [h.state for h in hyps]
|
|
324
|
+
tested = sum(s in _TESTED for s in st)
|
|
325
|
+
return S.Funnel(
|
|
326
|
+
proposed=len(st),
|
|
327
|
+
selected=tested + sum(s in ("selected", "refused") for s in st),
|
|
328
|
+
tested=tested, judged=sum(s in _JUDGED for s in st),
|
|
329
|
+
claimed=sum(s in ("confirmed", "validated") for s in st),
|
|
330
|
+
refuted=sum(s == "refuted" for s in st),
|
|
331
|
+
abstained=sum(s == "abstained" for s in st))
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _gate(recs, cards, detail) -> S.Gate:
|
|
335
|
+
"""The campaign's gate, from what the VERDICTS were judged against (the
|
|
336
|
+
recorded decision), then the problem's hard constraint, then the program.
|
|
337
|
+
Per-card proposal-time thresholds are not authoritative (a hypothesis
|
|
338
|
+
can be proposed against a prediction, then judged against the gate)."""
|
|
339
|
+
from proef.derivation import criteria_label
|
|
340
|
+
for r in reversed(recs):
|
|
341
|
+
d = r.decision or {}
|
|
342
|
+
if d.get("threshold") is not None and d.get("metric") \
|
|
343
|
+
and d.get("verdict"):
|
|
344
|
+
direction = d.get("direction") or "min"
|
|
345
|
+
return S.Gate(
|
|
346
|
+
metric=d["metric"], direction=direction,
|
|
347
|
+
threshold=float(d["threshold"]),
|
|
348
|
+
label=criteria_label(d["metric"], direction,
|
|
349
|
+
d["threshold"]))
|
|
350
|
+
for c in detail.get("constraints") or []:
|
|
351
|
+
if c.get("limit") is not None:
|
|
352
|
+
direction = "max" if ">=" in (c.get("description") or "") else "min"
|
|
353
|
+
label = criteria_label(c.get("name"), direction, c["limit"])
|
|
354
|
+
if c.get("unit") and "(" not in label:
|
|
355
|
+
label += f" {c['unit']}"
|
|
356
|
+
return S.Gate(metric=c.get("name"), direction=direction,
|
|
357
|
+
threshold=float(c["limit"]), unit=c.get("unit"),
|
|
358
|
+
label=label)
|
|
359
|
+
g = ((detail.get("program") or {}).get("gate")) or {}
|
|
360
|
+
if g.get("value") is not None:
|
|
361
|
+
return S.Gate(metric=g.get("metric"), direction=g.get("direction"),
|
|
362
|
+
threshold=g["value"], unit=g.get("unit"),
|
|
363
|
+
label=f"{g.get('metric')} {g.get('symbol', '')} "
|
|
364
|
+
f"{g['value']}")
|
|
365
|
+
for c in cards:
|
|
366
|
+
if c.get("threshold") is not None:
|
|
367
|
+
return S.Gate(threshold=float(c["threshold"]),
|
|
368
|
+
label=c.get("gate_label"))
|
|
369
|
+
return S.Gate()
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _reviewer(recs) -> S.Reviewer | None:
|
|
373
|
+
last = None
|
|
374
|
+
for r in recs:
|
|
375
|
+
d = r.decision or {}
|
|
376
|
+
if d.get("kind") == "review_report":
|
|
377
|
+
last = d
|
|
378
|
+
if last is None:
|
|
379
|
+
return None
|
|
380
|
+
return S.Reviewer(
|
|
381
|
+
critical=last.get("critical", 0), warnings=last.get("warnings", 0),
|
|
382
|
+
findings=[S.ReviewFinding(severity=f.get("severity", "?"),
|
|
383
|
+
kind=f.get("kind", "?"),
|
|
384
|
+
candidate=f.get("candidate"),
|
|
385
|
+
detail=f.get("detail", ""))
|
|
386
|
+
for f in last.get("findings") or []])
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _chain(branch: str | None, recs) -> S.ChainStatus:
|
|
390
|
+
if not branch:
|
|
391
|
+
return S.ChainStatus(verified=True, records=0)
|
|
392
|
+
from proef.adapters.store.sqlite import get_store
|
|
393
|
+
problems = get_store(str(_ids.PROVENANCE_DB)).verify_chain(branch)
|
|
394
|
+
return S.ChainStatus(verified=not problems, records=len(recs),
|
|
395
|
+
problems=problems[:10])
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
_IN_PROGRESS = ("running", "executing")
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _status(raw: str, recs) -> str:
|
|
402
|
+
"""The registry status lags (a launched campaign stays 'executing' for
|
|
403
|
+
ever when no log marker exists); the ledger knows: the autonomous loop
|
|
404
|
+
writes its reviewer report last, so its presence means the campaign is
|
|
405
|
+
complete."""
|
|
406
|
+
if any((r.decision or {}).get("kind") == "hand_run" for r in recs):
|
|
407
|
+
# nothing is running: the person runs the plate, so the campaign is
|
|
408
|
+
# either waiting for their data or done
|
|
409
|
+
judged = {r.artifact.artifact_id for r in recs if r.artifact and r.event_type.value in (
|
|
410
|
+
"hypothesis_validated", "hypothesis_invalidated", "hypothesis_inconclusive")}
|
|
411
|
+
proposed = {r.artifact.artifact_id for r in recs
|
|
412
|
+
if r.artifact and r.event_type.value == "hypothesis_proposed"}
|
|
413
|
+
return "awaiting_results" if proposed - judged else "completed"
|
|
414
|
+
if any((r.decision or {}).get("kind") == "plan_decision" and not (r.decision or {}).get("approved")
|
|
415
|
+
for r in recs):
|
|
416
|
+
return "declined" # the person declined (or emptied) the plan: nothing was submitted
|
|
417
|
+
if raw in ("executing", "running", "interrupted", "verdict recorded") \
|
|
418
|
+
and any((r.decision or {}).get("kind") == "review_report"
|
|
419
|
+
for r in recs):
|
|
420
|
+
return "completed"
|
|
421
|
+
return raw
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
_PID = re.compile(r"\[problem/([^\]]+)\]")
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def campaign_for_problem(pid: str) -> tuple[str, str] | None:
|
|
428
|
+
"""(campaign id, title) whose agent runs the problem branch `pid`."""
|
|
429
|
+
ws = _ws()
|
|
430
|
+
try: # a running campaign announces its branch itself
|
|
431
|
+
from proef.autoloop import announced_branches
|
|
432
|
+
announced = {v: k for k, v in announced_branches().items()}
|
|
433
|
+
except Exception:
|
|
434
|
+
announced = {}
|
|
435
|
+
for e in ws.ongoing() + ws.finished(500):
|
|
436
|
+
ag = (e.get("payload") or {}).get("agent") or {}
|
|
437
|
+
if ag.get("problem_id") == pid or announced.get(pid) == e["id"]:
|
|
438
|
+
return e["id"], e.get("question") or e["id"]
|
|
439
|
+
return None
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def problem_id_for(eid: str, detail: dict) -> str | None:
|
|
443
|
+
"""The campaign's problem branch id. A RUNNING campaign has not been linked in the registry yet, but it
|
|
444
|
+
announces its branch the moment it exists: use that, so what it is waiting for shows up on its own page."""
|
|
445
|
+
pid = (detail.get("agent") or {}).get("problem_id")
|
|
446
|
+
if pid:
|
|
447
|
+
return pid
|
|
448
|
+
try:
|
|
449
|
+
from proef.autoloop import announced_branches
|
|
450
|
+
return announced_branches().get(eid)
|
|
451
|
+
except Exception: # noqa: BLE001 - best effort, as everywhere the branch map is read
|
|
452
|
+
return None
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def testable(cards: list) -> list:
|
|
456
|
+
"""Cards a person can test. A family's parent claim has no candidate of its own: it is the idea the
|
|
457
|
+
variants test, shown in the plan, and must not be counted as a hypothesis awaiting an experiment."""
|
|
458
|
+
return [c for c in cards or [] if c.get("candidate")]
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def plan_of(payload) -> S.Plan | None:
|
|
462
|
+
"""The plan carried by an approval request, if it has one (tolerant of malformed payloads)."""
|
|
463
|
+
if not isinstance(payload, dict) or "families" not in payload:
|
|
464
|
+
return None
|
|
465
|
+
try:
|
|
466
|
+
return S.Plan(**payload)
|
|
467
|
+
except Exception: # noqa: BLE001 - a bad payload must not hide the approval itself
|
|
468
|
+
return None
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def pending_approvals(problem_id: str | None) -> list[S.ApprovalRef]:
|
|
472
|
+
"""Lab submissions of THIS campaign waiting for a human (gate autonomy)."""
|
|
473
|
+
if not problem_id:
|
|
474
|
+
return []
|
|
475
|
+
from proef.approvals import ApprovalInbox
|
|
476
|
+
from proef.paths import APPROVALS_FILE
|
|
477
|
+
out = []
|
|
478
|
+
for k, v in ApprovalInbox(str(APPROVALS_FILE)).state().items():
|
|
479
|
+
m = _PID.search(v.get("title", ""))
|
|
480
|
+
if v.get("status") == "pending" and m and m.group(1) == problem_id:
|
|
481
|
+
out.append(S.ApprovalRef(id=k, title=v["title"], detail=v.get("detail", ""),
|
|
482
|
+
ts=v.get("ts"), plan=plan_of(v.get("payload"))))
|
|
483
|
+
return out
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _load(eid: str):
|
|
487
|
+
ws = _ws()
|
|
488
|
+
row = ws.get(eid)
|
|
489
|
+
if not row:
|
|
490
|
+
raise HTTPException(404, S.Problem(
|
|
491
|
+
type="campaign-not-found", title="Campaign not found",
|
|
492
|
+
detail=eid).model_dump())
|
|
493
|
+
detail = views.experiment_detail(eid, ws) or {}
|
|
494
|
+
branch = detail.get("branch")
|
|
495
|
+
recs = _branch_records(branch, _ids.PROVENANCE_DB)
|
|
496
|
+
return ws, row, detail, branch, recs
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
# ------------------------------------------------------------------ routes
|
|
500
|
+
@router.get("", response_model=list[S.CampaignSummary])
|
|
501
|
+
def list_campaigns(program: str | None = Query(None),
|
|
502
|
+
status: str | None = Query(None),
|
|
503
|
+
include_archived: bool = False) -> list[S.CampaignSummary]:
|
|
504
|
+
ws = _ws()
|
|
505
|
+
rows = ws.ongoing() + ws.finished(500)
|
|
506
|
+
progs = _program_index()
|
|
507
|
+
from proef.governance import PauseRegistry
|
|
508
|
+
held = PauseRegistry().active()
|
|
509
|
+
out = []
|
|
510
|
+
for e in rows:
|
|
511
|
+
payload = e.get("payload") or {}
|
|
512
|
+
if payload.get("archived") and not include_archived:
|
|
513
|
+
continue
|
|
514
|
+
ag = payload.get("agent") or {}
|
|
515
|
+
pref = progs.get(e["id"])
|
|
516
|
+
st = row_status(e)
|
|
517
|
+
if st in ("executing", "running", "interrupted") and ag.get("problem_id"):
|
|
518
|
+
st = _status(st, _branch_records(f"problem/{ag['problem_id']}",
|
|
519
|
+
_ids.PROVENANCE_DB))
|
|
520
|
+
if program and (not pref or pref.slug != program):
|
|
521
|
+
continue
|
|
522
|
+
if status and st != status:
|
|
523
|
+
continue
|
|
524
|
+
out.append(S.CampaignSummary(
|
|
525
|
+
id=e["id"], title=e.get("question") or e["id"], status=st,
|
|
526
|
+
autonomy=ag.get("autonomy"), program=pref,
|
|
527
|
+
updated_at=e.get("updated_at"),
|
|
528
|
+
problem_id=ag.get("problem_id"),
|
|
529
|
+
paused=st in _IN_PROGRESS and (f"campaign:{ag.get('problem_id')}" in held
|
|
530
|
+
or bool(pref and f"program:{pref.slug}" in held))))
|
|
531
|
+
out.sort(key=lambda c: -(c.updated_at or 0))
|
|
532
|
+
return out
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def plan_review_of(recs) -> S.PlanReview | None:
|
|
536
|
+
"""The first (initial) plan decision on the chain, if a person reviewed a model's plan."""
|
|
537
|
+
for r in recs:
|
|
538
|
+
d = r.decision or {}
|
|
539
|
+
if d.get("kind") == "plan_decision" and d.get("stage", "initial") == "initial":
|
|
540
|
+
return S.PlanReview(approved=bool(d.get("approved")), by=str(d.get("decided_by") or "someone"),
|
|
541
|
+
proposed=int(d.get("n_proposed") or 0), kept=int(d.get("n_kept") or 0),
|
|
542
|
+
removed=len(d.get("removed") or []), note=d.get("note") or None,
|
|
543
|
+
ts=r.ts.timestamp() if getattr(r, "ts", None) else None)
|
|
544
|
+
return None
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def llm_use(recs) -> S.LlmUse | None:
|
|
548
|
+
"""Which models took part, from what was RECORDED (never from current config)."""
|
|
549
|
+
models, proposed, reviewed = [], 0, False
|
|
550
|
+
for r in recs:
|
|
551
|
+
d = r.decision or {}
|
|
552
|
+
pb = d.get("predicted_by") if r.event_type.value == "hypothesis_proposed" else None
|
|
553
|
+
if isinstance(pb, dict) and pb.get("source") == "llm":
|
|
554
|
+
proposed += 1
|
|
555
|
+
models.append(str(pb.get("model") or "unknown model"))
|
|
556
|
+
if d.get("kind") == "review_report_llm" and not d.get("unavailable"):
|
|
557
|
+
reviewed = True
|
|
558
|
+
models.append(str(d.get("model") or "unknown model").split("/")[-1])
|
|
559
|
+
return S.LlmUse(models=sorted(set(models)), proposed_hypotheses=proposed, reviewed=reviewed) \
|
|
560
|
+
if models else None
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
@router.get("/{eid}", response_model=S.CampaignDetail)
|
|
564
|
+
def get_campaign(eid: str) -> S.CampaignDetail:
|
|
565
|
+
ws, row, detail, branch, recs = _load(eid)
|
|
566
|
+
cards = testable(detail.get("cards"))
|
|
567
|
+
gate = _gate(recs, cards, detail)
|
|
568
|
+
rounds = _why_rounds(recs, detail.get("rounds") or [])
|
|
569
|
+
tested_cands = {c for r in rounds for c in r.candidates}
|
|
570
|
+
reviews = _reviews(recs)
|
|
571
|
+
suggestions = _suggestions(recs)
|
|
572
|
+
hyps = [_summary_of(c, gate.label, reviews, suggestions) for c in cards]
|
|
573
|
+
runs = sum(1 for r in recs if r.event_type.value == "lab_run"
|
|
574
|
+
and (r.decision or {}).get("run_id"))
|
|
575
|
+
progs = _program_index()
|
|
576
|
+
pid = problem_id_for(eid, detail)
|
|
577
|
+
from proef.api.v1.pauses import pauses_for
|
|
578
|
+
own_pause, program_pause = pauses_for(pid, progs.get(eid).slug if progs.get(eid) else None)
|
|
579
|
+
return S.CampaignDetail(
|
|
580
|
+
pause=own_pause, paused_by_program=program_pause,
|
|
581
|
+
paused=bool(own_pause or program_pause) and _status(detail.get("status") or row_status(row), recs) in _IN_PROGRESS,
|
|
582
|
+
llm=llm_use(recs),
|
|
583
|
+
plan_review=plan_review_of(recs),
|
|
584
|
+
awaiting_approvals=pending_approvals(pid),
|
|
585
|
+
id=eid, title=row.get("question") or eid,
|
|
586
|
+
status=_status(detail.get("status") or row_status(row), recs),
|
|
587
|
+
autonomy=(detail.get("agent") or {}).get("autonomy"),
|
|
588
|
+
program=progs.get(eid), updated_at=row.get("updated_at"),
|
|
589
|
+
problem_id=pid,
|
|
590
|
+
objective=detail.get("objective"), branch=branch,
|
|
591
|
+
gate=gate,
|
|
592
|
+
budget=S.Budget(runs_used=runs,
|
|
593
|
+
runs_max=(detail.get("spec") or {}).get("run_budget")),
|
|
594
|
+
funnel=_funnel(hyps), rounds=rounds,
|
|
595
|
+
hypotheses=hyps,
|
|
596
|
+
eliminated=[S.Refusal(candidate=str(x.get("candidate")),
|
|
597
|
+
reason=x.get("reason") or "not selected")
|
|
598
|
+
for x in detail.get("eliminated") or []
|
|
599
|
+
if str(x.get("candidate")) not in tested_cands],
|
|
600
|
+
reviewer=_reviewer(recs), chain=_chain(branch, recs))
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
@router.get("/{eid}/hypotheses/{hid}", response_model=S.HypothesisDetail)
|
|
604
|
+
def get_hypothesis(eid: str, hid: str) -> S.HypothesisDetail:
|
|
605
|
+
_, _, detail, branch, recs = _load(eid)
|
|
606
|
+
card = next((c for c in detail.get("cards") or [] if c["key"] == hid), None)
|
|
607
|
+
if card is None:
|
|
608
|
+
raise HTTPException(404, S.Problem(
|
|
609
|
+
type="hypothesis-not-found", title="Hypothesis not found",
|
|
610
|
+
detail=hid).model_dump())
|
|
611
|
+
base = _summary_of(card, _gate(recs, detail.get("cards") or [], detail).label,
|
|
612
|
+
_reviews(recs), _suggestions(recs))
|
|
613
|
+
cand = card.get("candidate")
|
|
614
|
+
mine = [r for r in recs
|
|
615
|
+
if (r.decision or {}).get("hypothesis_id") == hid
|
|
616
|
+
or (r.artifact and r.artifact.artifact_id == hid)
|
|
617
|
+
or (cand and _cand(r) == cand)]
|
|
618
|
+
from proef.derivation import describe
|
|
619
|
+
deriv, runs = None, []
|
|
620
|
+
for r in mine:
|
|
621
|
+
d = r.decision or {}
|
|
622
|
+
if d.get("derivation"):
|
|
623
|
+
deriv = describe(d["derivation"])
|
|
624
|
+
for k in ("evidence_run_id", "run_id"):
|
|
625
|
+
if d.get(k) and d[k] not in runs:
|
|
626
|
+
runs.append(d[k])
|
|
627
|
+
events = []
|
|
628
|
+
for r in mine:
|
|
629
|
+
kind, text, c = summarize(r)
|
|
630
|
+
events.append(S.ActivityItem(ts=_ts(r), kind=kind, text=text,
|
|
631
|
+
candidate=c, actor=_actor(r)[0]))
|
|
632
|
+
return S.HypothesisDetail(
|
|
633
|
+
**base.model_dump(), rationale=card.get("rationale"),
|
|
634
|
+
predicted=card.get("predicted"), predicted_by=card.get("predicted_by"),
|
|
635
|
+
mechanism=card.get("mechanism"),
|
|
636
|
+
refutation_condition=card.get("refutation_condition"),
|
|
637
|
+
citation=card.get("citation"),
|
|
638
|
+
citation_status=card.get("citation_status"),
|
|
639
|
+
evidence=card.get("evidence"), derivation=deriv, evidence_runs=runs,
|
|
640
|
+
events=events)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
@router.get("/{eid}/hypotheses/{hid}/curves", response_model=S.CurveSet)
|
|
644
|
+
def get_curves(eid: str, hid: str) -> S.CurveSet:
|
|
645
|
+
"""The recorded dose–response data behind a verdict: every plate point,
|
|
646
|
+
the fit with its interval, and the plate's QC: so a scientist can LOOK at
|
|
647
|
+
the evidence, not only read the number."""
|
|
648
|
+
import math
|
|
649
|
+
|
|
650
|
+
from proef.fitting import hill_fit, hill_response
|
|
651
|
+
from proef.labread import read_plate
|
|
652
|
+
from proef.paths import DATA_DIR
|
|
653
|
+
_, _, detail, branch, recs = _load(eid)
|
|
654
|
+
card = next((c for c in detail.get("cards") or [] if c["key"] == hid), None)
|
|
655
|
+
if card is None:
|
|
656
|
+
raise HTTPException(404, S.Problem(
|
|
657
|
+
type="hypothesis-not-found", title="Hypothesis not found",
|
|
658
|
+
detail=hid).model_dump())
|
|
659
|
+
cand = card.get("candidate")
|
|
660
|
+
items = views.narrative_data(recs, [], str(DATA_DIR)).get(
|
|
661
|
+
"evidence", {}).get("curves", [])
|
|
662
|
+
mine = sorted((i for i in items if i.get("candidate") == cand),
|
|
663
|
+
key=lambda i: i["run_id"])
|
|
664
|
+
out = S.CurveSet(candidate=cand)
|
|
665
|
+
for n, it in enumerate(mine):
|
|
666
|
+
try:
|
|
667
|
+
res = read_plate(it["path"])
|
|
668
|
+
except Exception as exc: # unreadable evidence file: say so
|
|
669
|
+
out.note = f"could not read {it['run_id']}: {str(exc)[:80]}"
|
|
670
|
+
continue
|
|
671
|
+
pts = [(float(r["conc_um"]), float(r["value"]))
|
|
672
|
+
for r in (m if isinstance(m, dict) else m.model_dump()
|
|
673
|
+
for m in res.records)
|
|
674
|
+
if r.get("sample") == cand and not r.get("control")
|
|
675
|
+
and isinstance(r.get("conc_um"), (int, float))
|
|
676
|
+
and isinstance(r.get("value"), (int, float))]
|
|
677
|
+
if not pts:
|
|
678
|
+
continue
|
|
679
|
+
comp = (res.analysis.get("compounds") or {}).get(cand) or {}
|
|
680
|
+
fit = None
|
|
681
|
+
if comp:
|
|
682
|
+
line: list[S.CurvePoint] = []
|
|
683
|
+
hf = hill_fit(pts, None)
|
|
684
|
+
if comp.get("ic50_um") and hf:
|
|
685
|
+
lo, hi = min(c for c, _ in pts) / 1.6, max(c for c, _ in pts) * 1.6
|
|
686
|
+
for i in range(60):
|
|
687
|
+
c = lo * (hi / lo) ** (i / 59)
|
|
688
|
+
line.append(S.CurvePoint(
|
|
689
|
+
conc_um=c, value=hill_response(c, comp["ic50_um"],
|
|
690
|
+
hf["top"])))
|
|
691
|
+
ci = comp.get("ic50_ci")
|
|
692
|
+
fit = S.CurveFit(
|
|
693
|
+
ic50_um=comp.get("ic50_um"),
|
|
694
|
+
ci=list(ci) if ci else None, top=hf["top"] if hf else None,
|
|
695
|
+
method=comp.get("fit_method"), model=comp.get("fit_model"),
|
|
696
|
+
right_censored=bool(comp.get("right_censored")),
|
|
697
|
+
left_censored=bool(comp.get("left_censored")), line=line)
|
|
698
|
+
out.curves.append(S.Curve(
|
|
699
|
+
run_id=it["run_id"],
|
|
700
|
+
label="Primary screen" if n == 0 else f"Confirmation {n}",
|
|
701
|
+
points=[S.CurvePoint(conc_um=c, value=v) for c, v in sorted(pts)],
|
|
702
|
+
fit=fit, z_prime=res.z_prime,
|
|
703
|
+
z_kind=(res.analysis or {}).get("z_prime_kind"),
|
|
704
|
+
unit=getattr(res, "response_unit", None)))
|
|
705
|
+
if not out.curves and not out.note:
|
|
706
|
+
out.note = "no recorded plate file found for this candidate"
|
|
707
|
+
return out
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
@router.get("/{eid}/activity", response_model=list[S.ActivityItem])
|
|
711
|
+
def get_activity(eid: str, limit: int = Query(50, ge=1, le=500)
|
|
712
|
+
) -> list[S.ActivityItem]:
|
|
713
|
+
_, _, _, _, recs = _load(eid)
|
|
714
|
+
return activity_items(recs, limit)
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def _served_detail(decision: dict | None) -> dict | None:
|
|
718
|
+
"""A record's decision as the workbench serves it. The ledger keeps a model's answer so a run can be replayed, but the answer
|
|
719
|
+
can be large and can carry study data, so the workbench serves its size, not its text. Whoever needs it reads the ledger."""
|
|
720
|
+
if (decision or {}).get("kind") == "model_response":
|
|
721
|
+
n = decision.get("response_chars", len(decision.get("response") or ""))
|
|
722
|
+
return {**decision, "response": f"<{n} characters, sealed in the ledger>"}
|
|
723
|
+
return decision
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
@router.get("/{eid}/provenance", response_model=S.ProvenanceView)
|
|
727
|
+
def get_provenance(eid: str, limit: int = Query(500, ge=1, le=5000),
|
|
728
|
+
actor: str | None = Query(None, description="only this agent / person")
|
|
729
|
+
) -> S.ProvenanceView:
|
|
730
|
+
_, _, _, branch, recs = _load(eid)
|
|
731
|
+
items = []
|
|
732
|
+
for r in recs:
|
|
733
|
+
aid, kind, model = _actor(r)
|
|
734
|
+
if actor and aid != actor:
|
|
735
|
+
continue
|
|
736
|
+
_, text, _ = summarize(r)
|
|
737
|
+
detail = _served_detail(r.decision)
|
|
738
|
+
items.append(S.ProvenanceRecord(
|
|
739
|
+
ts=_ts(r), event=r.event_type.value, summary=text, actor=aid,
|
|
740
|
+
actor_kind=kind, model_version=model, detail=detail))
|
|
741
|
+
return S.ProvenanceView(chain=_chain(branch, recs), records=items[-limit:])
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
@router.get("/{eid}/agents", response_model=list[S.AgentSummary])
|
|
745
|
+
def get_agents(eid: str) -> list[S.AgentSummary]:
|
|
746
|
+
"""Who acted in this campaign, each agent/service/person with what it did."""
|
|
747
|
+
_, _, _, _, recs = _load(eid)
|
|
748
|
+
by: dict[str, dict] = {}
|
|
749
|
+
for r in recs:
|
|
750
|
+
aid, kind, model = _actor(r)
|
|
751
|
+
e = by.setdefault(aid, {"kind": kind, "model": model, "n": 0,
|
|
752
|
+
"ts": None, "text": ""})
|
|
753
|
+
e["n"] += 1
|
|
754
|
+
e["model"] = e["model"] or model
|
|
755
|
+
_, text, _ = summarize(r)
|
|
756
|
+
e["ts"], e["text"] = _ts(r), text
|
|
757
|
+
out = [S.AgentSummary(id=k, kind=v["kind"], role=_role(k, v["kind"]),
|
|
758
|
+
model_version=v["model"], events=v["n"],
|
|
759
|
+
last_ts=v["ts"], last_text=v["text"])
|
|
760
|
+
for k, v in by.items()]
|
|
761
|
+
return sorted(out, key=lambda a: -a.events)
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
@router.post("/{eid}/hypotheses/{hid}/review", response_model=S.Review)
|
|
765
|
+
def review_hypothesis(eid: str, hid: str, body: S.ReviewIn,
|
|
766
|
+
request: Request) -> S.Review:
|
|
767
|
+
"""Record the scientist's decision on a hypothesis. Append-only and sealed
|
|
768
|
+
in the same hash chain as everything the agents did."""
|
|
769
|
+
from proef.adapters.store.sqlite import get_store
|
|
770
|
+
from proef.core.contracts import Actor, ActorKind, Envelope, EventType
|
|
771
|
+
from proef.core.interfaces import record_for
|
|
772
|
+
_, _, detail, branch, recs = _load(eid)
|
|
773
|
+
card = next((c for c in detail.get("cards") or [] if c["key"] == hid), None)
|
|
774
|
+
if card is None or not branch:
|
|
775
|
+
raise HTTPException(404, S.Problem(
|
|
776
|
+
type="hypothesis-not-found", title="Hypothesis not found",
|
|
777
|
+
detail=hid).model_dump())
|
|
778
|
+
user = who(request)
|
|
779
|
+
rec = record_for(
|
|
780
|
+
Envelope(experiment_branch_id=branch), EventType.gate_decision,
|
|
781
|
+
Actor(kind=ActorKind.human, id=user),
|
|
782
|
+
decision={"kind": "human_review", "hypothesis_id": hid,
|
|
783
|
+
"candidate": card.get("candidate"),
|
|
784
|
+
"decision": body.decision, "note": body.note[:500],
|
|
785
|
+
"follow_up_campaign_id": body.follow_up_campaign_id})
|
|
786
|
+
get_store(str(_ids.PROVENANCE_DB)).append(rec)
|
|
787
|
+
return S.Review(decision=body.decision, note=body.note[:500], by=user,
|
|
788
|
+
ts=_ts(rec),
|
|
789
|
+
follow_up_campaign_id=body.follow_up_campaign_id)
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
@router.post("/{eid}/archive", response_model=S.CampaignSummary)
|
|
793
|
+
def archive_campaign(eid: str) -> S.CampaignSummary:
|
|
794
|
+
ws = _ws()
|
|
795
|
+
if not ws.get(eid):
|
|
796
|
+
raise HTTPException(404, S.Problem(
|
|
797
|
+
type="campaign-not-found", title="Campaign not found",
|
|
798
|
+
detail=eid).model_dump())
|
|
799
|
+
ws.set_archived(eid, True)
|
|
800
|
+
row = ws.get(eid)
|
|
801
|
+
return S.CampaignSummary(id=eid, title=row.get("question") or eid,
|
|
802
|
+
status=row_status(row))
|