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/diary.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""Campaign diary, provenance rendered as a lab notebook, not a log.
|
|
2
|
+
|
|
3
|
+
`proef diary <branch> --db campaign.db --html diary.html` turns the hash-chained
|
|
4
|
+
records into a dated narrative a scientist actually reads:
|
|
5
|
+
|
|
6
|
+
Round 1, hypothesis H4 (C-101 binds IC50<=20): proposed from covalent
|
|
7
|
+
warhead precedent; tested by run sim-…; VALIDATED (measured 8.9 uM).
|
|
8
|
+
Gate approve_wetlab_protocol: APPROVED by scripted-scientist.
|
|
9
|
+
...
|
|
10
|
+
|
|
11
|
+
Same light-blueprint style as the report.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import html as _html
|
|
16
|
+
import time
|
|
17
|
+
import json
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
_CSS = """
|
|
22
|
+
:root{--bg:#f3f1ea;--line:#c9c2b0;--paper:#faf8f2;--ink:#2a2823;--dim:#6b6558;
|
|
23
|
+
--green:#2f6b38;--red:#8a4034;--amber:#8a6a2c;
|
|
24
|
+
--mono:'IBM Plex Mono',ui-monospace,Consolas,monospace;}
|
|
25
|
+
body{margin:0;background:var(--bg);color:var(--ink);
|
|
26
|
+
font-family:ui-sans-serif,system-ui,sans-serif;padding:40px 20px}
|
|
27
|
+
.wrap{max-width:820px;margin:0 auto}
|
|
28
|
+
h1{font-size:22px;margin:0 0 2px} .sub{color:var(--dim);font-size:13px;margin:0 0 26px}
|
|
29
|
+
.entry{background:var(--paper);border:1px solid var(--line);padding:14px 18px;
|
|
30
|
+
margin:10px 0;border-left:3px solid var(--line)}
|
|
31
|
+
.entry.validated{border-left-color:var(--green)}
|
|
32
|
+
.entry.invalidated{border-left-color:var(--red)}
|
|
33
|
+
.entry.inconclusive{border-left-color:var(--amber)}
|
|
34
|
+
.entry.gate{border-left-color:#1f7a86}
|
|
35
|
+
.k{font-family:var(--mono);font-size:10.5px;letter-spacing:.08em;
|
|
36
|
+
text-transform:uppercase;color:var(--dim)}
|
|
37
|
+
.title{font-weight:600;font-size:14.5px;margin:2px 0 4px}
|
|
38
|
+
.body{font-size:13.5px;color:#4a463d;line-height:1.55}
|
|
39
|
+
.mono{font-family:var(--mono);font-size:12px}
|
|
40
|
+
.stats{display:flex;gap:14px;flex-wrap:wrap;margin:14px 0 24px}
|
|
41
|
+
.stat{background:var(--paper);border:1px solid var(--line);padding:10px 16px}
|
|
42
|
+
.stat b{display:block;font-size:18px} .stat span{font-family:var(--mono);
|
|
43
|
+
font-size:10.5px;color:var(--dim);text-transform:uppercase;letter-spacing:.06em}
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def build_diary_html(records: list[Any], branch: str) -> str:
|
|
48
|
+
"""Fold provenance records into notebook entries, grouped as one flow per
|
|
49
|
+
hypothesis (swimlanes) preceded by campaign-level events."""
|
|
50
|
+
counts = {"hypotheses": 0, "validated": 0, "invalidated": 0,
|
|
51
|
+
"inconclusive": 0, "gates": 0, "runs": 0}
|
|
52
|
+
|
|
53
|
+
labrun_info: dict[str, dict] = {} # run_id -> lab_run decision
|
|
54
|
+
shared: list[str] = [] # campaign-level entries
|
|
55
|
+
lanes: dict[str, dict] = {} # candidate -> {"hid", "statement", "entries"}
|
|
56
|
+
hid_to_cand: dict[str, str] = {}
|
|
57
|
+
|
|
58
|
+
def _lane(hid: str | None, cand: str, stmt: str = "") -> dict:
|
|
59
|
+
if cand not in lanes:
|
|
60
|
+
lanes[cand] = {"hid": hid, "statement": stmt, "entries": []}
|
|
61
|
+
return lanes[cand]
|
|
62
|
+
|
|
63
|
+
for r in records:
|
|
64
|
+
ev = r.event_type.value
|
|
65
|
+
d = r.decision or {}
|
|
66
|
+
art = (r.artifact.metadata if r.artifact else {}) or {}
|
|
67
|
+
art_id = r.artifact.artifact_id if r.artifact else None
|
|
68
|
+
cand = art.get("candidate")
|
|
69
|
+
if art_id and cand:
|
|
70
|
+
hid_to_cand[art_id] = cand
|
|
71
|
+
|
|
72
|
+
if ev == "problem_defined":
|
|
73
|
+
cons = ", ".join(c.get("name", "?") for c in d.get("constraints", [])) or ", "
|
|
74
|
+
shared.append(_entry("problem", d.get("objective", ""),
|
|
75
|
+
f"constraints: {cons} · success metric: "
|
|
76
|
+
f"{d.get('success_metric', ', ')}"))
|
|
77
|
+
elif ev == "hypothesis_proposed":
|
|
78
|
+
stmt = (d.get("statement") or art.get("statement", "")) or ""
|
|
79
|
+
counts["hypotheses"] += 1
|
|
80
|
+
lane = _lane(art_id, cand or stmt[:24] or "?", stmt)
|
|
81
|
+
bits = []
|
|
82
|
+
if d.get("mechanism"):
|
|
83
|
+
bits.append(f"mechanism: {d['mechanism']}")
|
|
84
|
+
if d.get("rationale"):
|
|
85
|
+
bits.append(f"rationale: {d['rationale']}")
|
|
86
|
+
if d.get("citation"):
|
|
87
|
+
_cs = d.get("citation_status", "unverified")
|
|
88
|
+
_tag = {"verified": "verified",
|
|
89
|
+
"invalid": "UNVERIFIABLE, penalized",
|
|
90
|
+
"check-failed": "? check failed (offline)"}.get(_cs, "")
|
|
91
|
+
bits.append(f"citation: {d['citation']}"
|
|
92
|
+
+ (f" ({_tag})" if _tag else ""))
|
|
93
|
+
if d.get("predicted"):
|
|
94
|
+
bits.append(f"prediction: {d['predicted']}")
|
|
95
|
+
if d.get("refutation_condition"):
|
|
96
|
+
bits.append(f"refuted if: {d['refutation_condition']}")
|
|
97
|
+
lane["entries"].append(_entry("hypothesis proposed", stmt,
|
|
98
|
+
" · ".join(bits) or ", "))
|
|
99
|
+
elif ev == "hypotheses_filtered":
|
|
100
|
+
dec = d.get("decisions", [])
|
|
101
|
+
sel = sum(1 for x in dec if x.get("selected"))
|
|
102
|
+
shared.append(_entry(
|
|
103
|
+
"portfolio filter",
|
|
104
|
+
f"{sel} of {len(dec)} hypotheses selected for the lab",
|
|
105
|
+
"; ".join(f"{hid_to_cand.get(x['hypothesis_id'], x['hypothesis_id'])}: "
|
|
106
|
+
f"{'selected' if x.get('selected') else 'passed over'} "
|
|
107
|
+
f"({x.get('reason', '')})" for x in dec)[:400]))
|
|
108
|
+
elif ev == "hypothesis_tested" and d.get("run_id"):
|
|
109
|
+
lane = _lane(art_id, hid_to_cand.get(art_id, cand or "?"))
|
|
110
|
+
counts["runs"] += 1
|
|
111
|
+
rid = d.get("run_id", "?")
|
|
112
|
+
info = labrun_info.get(rid, {})
|
|
113
|
+
lane["entries"].append(_entry(
|
|
114
|
+
*_run_submission_entry(rid, cand, info,
|
|
115
|
+
ts=getattr(getattr(r, "envelope", None),
|
|
116
|
+
"created_at", None))))
|
|
117
|
+
lane["entries"].append(_run_output_html(
|
|
118
|
+
rid, cand, assay=info.get("assay"),
|
|
119
|
+
instrument=info.get("instrument")))
|
|
120
|
+
elif ev == "lab_run" and d.get("run_id"):
|
|
121
|
+
labrun_info[d["run_id"]] = d
|
|
122
|
+
elif (ev in ("hypothesis_validated", "hypothesis_invalidated",
|
|
123
|
+
"hypothesis_inconclusive")
|
|
124
|
+
or (ev == "hypothesis_tested" and d.get("verdict"))):
|
|
125
|
+
# every verdict — including refuted confirmations and honest
|
|
126
|
+
# abstentions — renders here; nothing decides in silence
|
|
127
|
+
_v = str(d.get("verdict") or ev.split("_")[1])
|
|
128
|
+
_bucket = {"validated": "validated", "confirmed": "validated",
|
|
129
|
+
"invalidated": "invalidated", "refuted": "invalidated",
|
|
130
|
+
"inconclusive": "inconclusive"}.get(_v)
|
|
131
|
+
if _bucket:
|
|
132
|
+
counts[_bucket] += 1
|
|
133
|
+
lane = _lane(art_id, hid_to_cand.get(art_id, cand or "?"), art.get("statement", ""))
|
|
134
|
+
bits = [f"observed {d.get('observed', ', ')} µM",
|
|
135
|
+
f"threshold {d.get('threshold', ', ')}"]
|
|
136
|
+
if d.get("observed_ci"):
|
|
137
|
+
lo, hi = d["observed_ci"]
|
|
138
|
+
bits.append(f"95% CI {lo}–{hi}")
|
|
139
|
+
if _v == "inconclusive":
|
|
140
|
+
bits.append("CI straddles threshold, honest abstention")
|
|
141
|
+
if d.get("evidence_run_id"):
|
|
142
|
+
bits.append(f"evidence run `{d['evidence_run_id']}`")
|
|
143
|
+
_conf = d.get("confirmation") or {}
|
|
144
|
+
head = {"confirmed": "HYPOTHESIS CONFIRMED (ORTHOGONAL)",
|
|
145
|
+
"refuted": "HYPOTHESIS REFUTED (ORTHOGONAL)",
|
|
146
|
+
"inconclusive": "HYPOTHESIS INCONCLUSIVE",
|
|
147
|
+
"validated": "HYPOTHESIS VALIDATED",
|
|
148
|
+
"invalidated": "HYPOTHESIS INVALIDATED"}.get(
|
|
149
|
+
_v, ev.replace("hypothesis_", "HYPOTHESIS ").upper())
|
|
150
|
+
if _conf:
|
|
151
|
+
bits.append(f"agreement rule: {_conf.get('rule', ', ')}")
|
|
152
|
+
lane["entries"].append(_entry(
|
|
153
|
+
head,
|
|
154
|
+
lane.get("statement") or d.get("metric", ""),
|
|
155
|
+
" · ".join(bits), cls=_bucket or "tested"))
|
|
156
|
+
elif ev == "tool_invocation" and d.get("kind") == "tool_call":
|
|
157
|
+
shared.append(_entry(
|
|
158
|
+
f"tool call: {d.get('tool', '?')}",
|
|
159
|
+
"REFUSED" if d.get("refused") else str(d.get("status") or "done").upper(),
|
|
160
|
+
f"by {r.actor.id} · args {d.get('args_hash', '')} · result {d.get('result_hash', '')}",
|
|
161
|
+
cls="gate" if d.get("refused") else ""))
|
|
162
|
+
elif ev == "gate_decision":
|
|
163
|
+
counts["gates"] += 1
|
|
164
|
+
approved = d.get("approved", d.get("pass", d.get("match")))
|
|
165
|
+
shared.append(_entry(
|
|
166
|
+
f"review gate, {d.get('gate', d.get('question', ''))}",
|
|
167
|
+
"APPROVED" if approved else "REJECTED",
|
|
168
|
+
f"by {d.get('approved_by', 'operator')} · "
|
|
169
|
+
f"{d.get('reason', '')}", cls="gate"))
|
|
170
|
+
elif ev == "stage_transition" and d.get("stage"):
|
|
171
|
+
shared.append(_entry("stage", d.get("stage", ""), d.get("detail", "")))
|
|
172
|
+
|
|
173
|
+
counts["validated_or_not"] = counts["validated"] + counts["invalidated"]
|
|
174
|
+
|
|
175
|
+
def _lane_html(cand: str, lane: dict) -> str:
|
|
176
|
+
status = ""
|
|
177
|
+
for e in lane["entries"]:
|
|
178
|
+
if "CONFIRMED" in e:
|
|
179
|
+
status = "confirmed"
|
|
180
|
+
elif "REFUTED" in e or "INVALIDATED" in e:
|
|
181
|
+
status = "refuted"
|
|
182
|
+
elif "INCONCLUSIVE" in e:
|
|
183
|
+
status = "inconclusive"
|
|
184
|
+
elif "VALIDATED" in e:
|
|
185
|
+
status = "validated (unconfirmed)"
|
|
186
|
+
head = (f"<div class='lane-head'><b>{_html.escape(cand)}</b>"
|
|
187
|
+
f"<span class='mono'>{_html.escape(status)}</span></div>")
|
|
188
|
+
return ("<div class='lane'>" + head + "".join(lane["entries"]) + "</div>")
|
|
189
|
+
|
|
190
|
+
body = "\n".join(shared)
|
|
191
|
+
if lanes:
|
|
192
|
+
body += "<h2 class='lane-title'>Hypothesis flows</h2>" + "".join(
|
|
193
|
+
_lane_html(c, l) for c, l in lanes.items())
|
|
194
|
+
from proef.series import series_summary
|
|
195
|
+
multi = [s for s in series_summary(records)
|
|
196
|
+
if s["kind"] != "ungrouped" and s["n_members"] > 1]
|
|
197
|
+
if multi:
|
|
198
|
+
body += "<h2 class='lane-title'>Series view</h2>"
|
|
199
|
+
for s in multi:
|
|
200
|
+
rows = "".join(
|
|
201
|
+
f"<div class='pt'>{_html.escape(str(m['candidate']))}: "
|
|
202
|
+
f"{_html.escape(str(m['verdict']))}"
|
|
203
|
+
+ (f" IC50 {m['observed']} uM"
|
|
204
|
+
if isinstance(m.get('observed'), (int, float)) else "")
|
|
205
|
+
+ "</div>" for m in s["members"][:8])
|
|
206
|
+
pairs = "; ".join(
|
|
207
|
+
f"{p['a']} vs {p['b']}: {p['call']} ({p['fold_a_over_b']}x)"
|
|
208
|
+
for p in s["matched_pairs"][:6])
|
|
209
|
+
body += (
|
|
210
|
+
"<div class='lane'><div class='lane-head'><b>"
|
|
211
|
+
f"{_html.escape(str(s['key'])[:40])}</b>"
|
|
212
|
+
f"<span class='mono'>{_html.escape(str(s['kind']))}</span>"
|
|
213
|
+
"</div>"
|
|
214
|
+
f"<p class='sub'>{_html.escape(s['label'])} · grouping: "
|
|
215
|
+
f"{_html.escape(s['backend'])}</p>"
|
|
216
|
+
f"<div class='pts'>{rows}</div>"
|
|
217
|
+
+ (f"<p class='sub'>matched pairs, ΔIC50 with CI: "
|
|
218
|
+
f"{_html.escape(pairs)}</p>" if pairs else "")
|
|
219
|
+
+ "</div>")
|
|
220
|
+
if not body:
|
|
221
|
+
body = "<p class='sub'>no narrative events recorded yet</p>"
|
|
222
|
+
|
|
223
|
+
stats = "".join(f"<div class='stat'><b>{v}</b><span>{k}</span></div>"
|
|
224
|
+
for k, v in counts.items()
|
|
225
|
+
if k != "validated_or_not")
|
|
226
|
+
return f"""<!DOCTYPE html><html><head><meta charset="utf-8">
|
|
227
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
228
|
+
<title>Campaign diary, {_html.escape(branch)}</title><style>{_CSS}
|
|
229
|
+
.lane{{border:1px solid #d8d2c2;border-radius:8px;padding:10px 14px;margin:10px 0;background:#faf8f2}}
|
|
230
|
+
.lane-head{{display:flex;justify-content:space-between;align-items:center;margin-bottom:6px}}
|
|
231
|
+
.lane-title{{margin:18px 0 6px;font-size:15px}}
|
|
232
|
+
.runout .title{{color:#1f7a86}}
|
|
233
|
+
.runout svg{{max-width:100%;height:auto;margin:6px 0}}
|
|
234
|
+
.pts{{display:flex;gap:10px;flex-wrap:wrap}}
|
|
235
|
+
.pt{{font-family:var(--mono);font-size:11px;color:var(--dim)}}
|
|
236
|
+
</style></head>
|
|
237
|
+
<body><div class="wrap">
|
|
238
|
+
<h1>Campaign diary</h1>
|
|
239
|
+
<p class="sub">branch <span class="mono">{_html.escape(branch)}</span> ·
|
|
240
|
+
{len(records)} provenance records · hash-chained, verify with
|
|
241
|
+
<span class="mono">proef prove</span></p>
|
|
242
|
+
<div class="stats">{stats}</div>
|
|
243
|
+
{body}
|
|
244
|
+
</div></body></html>"""
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _run_submission_entry(run_id: str, candidate: str | None,
|
|
248
|
+
info: dict, ts: float | None) -> tuple[str, str, str]:
|
|
249
|
+
"""Scientist-readable description of what was sent to the lab, and why."""
|
|
250
|
+
assay = info.get("assay", "assay")
|
|
251
|
+
inst = info.get("instrument", "lab instrument")
|
|
252
|
+
concs = info.get("concentrations") or []
|
|
253
|
+
conc_txt = (", ".join(str(c) for c in concs[:-1]) + f" and {concs[-1]}"
|
|
254
|
+
if len(concs) > 1 else (str(concs[0]) if concs else ""))
|
|
255
|
+
title = str(info.get("title", ""))
|
|
256
|
+
purpose = ("orthogonally confirm the initial hit"
|
|
257
|
+
if "confirmation" in title.lower()
|
|
258
|
+
else "test the potency hypothesis")
|
|
259
|
+
bits = []
|
|
260
|
+
if candidate:
|
|
261
|
+
bits.append(f"{candidate} at {conc_txt} µM" if concs
|
|
262
|
+
else f"{candidate}")
|
|
263
|
+
if info.get("n_controls"):
|
|
264
|
+
bits.append(f"{info['n_controls']} buffer control"
|
|
265
|
+
if info["n_controls"] == 1 else f"{info['n_controls']} buffer controls")
|
|
266
|
+
if info.get("replicates"):
|
|
267
|
+
bits.append(f"{info['replicates']} replicates")
|
|
268
|
+
bits.append(f"on {inst}")
|
|
269
|
+
when = time.strftime("%H:%M", time.localtime(ts)) if ts else ""
|
|
270
|
+
head = f"{assay.capitalize()} run, to {purpose}"
|
|
271
|
+
body = " · ".join(bits) + (f" · submitted {when}" if when else "")
|
|
272
|
+
return ("lab run submitted", head, body)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _run_output_html(run_id: str, candidate: str | None,
|
|
276
|
+
assay: str | None = None,
|
|
277
|
+
instrument: str | None = None) -> str:
|
|
278
|
+
"""Scientist-facing lab output for one run. Device-aware: dispatches to
|
|
279
|
+
the matching output renderer (dose-response, image, robot log, table)."""
|
|
280
|
+
from pathlib import Path
|
|
281
|
+
from proef.output_blocks import dispatch_output
|
|
282
|
+
f = Path(".data/inbox") / f"{run_id}.csv"
|
|
283
|
+
ctx = {"assay": assay, "instrument": instrument,
|
|
284
|
+
"run_id": run_id, "candidate": candidate}
|
|
285
|
+
return dispatch_output(f, ctx)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _fmt_conc(c: float) -> str:
|
|
289
|
+
return f"{c:g} µM"
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _entry(kind: str, title: str, body: str, cls: str = "") -> str:
|
|
293
|
+
return (f"<div class='entry {cls}'><div class='k'>{_html.escape(kind)}</div>"
|
|
294
|
+
f"<div class='title'>{_html.escape(title or '')}</div>"
|
|
295
|
+
f"<div class='body'>{_html.escape(body or '')}</div></div>")
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def write_diary(records: list[Any], branch: str, path: str | Path) -> Path:
|
|
299
|
+
p = Path(path)
|
|
300
|
+
p.write_text(build_diary_html(records, branch))
|
|
301
|
+
return p
|
proef/eln.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""ELN export — provenance into the lab's system of record.
|
|
2
|
+
|
|
3
|
+
Flattens a provenance branch into an electronic-lab-notebook-friendly CSV
|
|
4
|
+
(one row per event, key scientific fields lifted out of the decision blob)
|
|
5
|
+
plus a lossless JSON sidecar. Column names follow common ELN conventions
|
|
6
|
+
(Benchling/SISSYO importers map these with minimal or no transformation).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import csv
|
|
11
|
+
import json
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
COLUMNS = ["timestamp", "branch", "event", "actor", "artifact_id",
|
|
15
|
+
"statement", "candidate", "family", "verdict", "observed_uM",
|
|
16
|
+
"ci95_low_uM", "ci95_high_uM", "threshold", "run_id",
|
|
17
|
+
"instrument", "instrument_version", "assay", "record_hash",
|
|
18
|
+
"detail"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def branch_to_rows(records: list) -> list[dict]:
|
|
22
|
+
rows = []
|
|
23
|
+
for r in records:
|
|
24
|
+
d = r.decision or {}
|
|
25
|
+
art = r.artifact
|
|
26
|
+
meta = (art.metadata if art else {}) or {}
|
|
27
|
+
ci = d.get("observed_ci") or [None, None]
|
|
28
|
+
conf = d.get("confirmation") or {}
|
|
29
|
+
der = d.get("derivation") or {}
|
|
30
|
+
design = (d.get("design") or {}).get("mode") if isinstance(
|
|
31
|
+
d.get("design"), dict) else None
|
|
32
|
+
_mb = (der.get("measured_by") if isinstance(der, dict)
|
|
33
|
+
else "") or ""
|
|
34
|
+
import re as _re
|
|
35
|
+
_m = _re.match(r"^(.*?)\s*\(([^)]+)\)$", _mb)
|
|
36
|
+
instrument = (d.get("instrument")
|
|
37
|
+
or (_m.group(1) if _m else _mb))
|
|
38
|
+
inst_ver = (d.get("instrument_version")
|
|
39
|
+
or (_m.group(2) if _m else ""))
|
|
40
|
+
rows.append({
|
|
41
|
+
"timestamp": f"{r.envelope.created_at:.0f}",
|
|
42
|
+
"branch": r.envelope.experiment_branch_id,
|
|
43
|
+
"event": r.event_type.value,
|
|
44
|
+
"actor": (r.actor.id + "/" + r.actor.kind.value) if r.actor else "",
|
|
45
|
+
"artifact_id": art.artifact_id if art else "",
|
|
46
|
+
"statement": d.get("statement") or meta.get("statement", ""),
|
|
47
|
+
"candidate": meta.get("candidate") or d.get("candidate", ""),
|
|
48
|
+
"family": meta.get("family") or d.get("family_id")
|
|
49
|
+
or d.get("family", ""),
|
|
50
|
+
"verdict": d.get("verdict", ""),
|
|
51
|
+
"observed_uM": d.get("observed", ""),
|
|
52
|
+
"ci95_low_uM": ci[0] if ci else "",
|
|
53
|
+
"ci95_high_uM": ci[1] if len(ci or []) > 1 else "",
|
|
54
|
+
"threshold": d.get("threshold", ""),
|
|
55
|
+
"run_id": d.get("run_id") or d.get("evidence_run_id", ""),
|
|
56
|
+
"instrument": instrument,
|
|
57
|
+
"instrument_version": inst_ver,
|
|
58
|
+
"assay": d.get("assay") or design or "",
|
|
59
|
+
"record_hash": r.record_hash or "",
|
|
60
|
+
"detail": json.dumps({k: v for k, v in d.items()
|
|
61
|
+
if k in ("rationale", "mechanism",
|
|
62
|
+
"refutation_condition", "citation",
|
|
63
|
+
"objective", "reason", "verdict",
|
|
64
|
+
"confirmation")
|
|
65
|
+
or k.startswith("n_")},
|
|
66
|
+
sort_keys=True)[:2000],
|
|
67
|
+
})
|
|
68
|
+
return rows
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def export_eln(records: list, out_csv: str | Path,
|
|
72
|
+
out_json: str | Path | None = None) -> Path:
|
|
73
|
+
rows = branch_to_rows(records)
|
|
74
|
+
p = Path(out_csv)
|
|
75
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
with p.open("w", newline="") as f:
|
|
77
|
+
w = csv.DictWriter(f, fieldnames=COLUMNS)
|
|
78
|
+
w.writeheader()
|
|
79
|
+
w.writerows(rows)
|
|
80
|
+
if out_json:
|
|
81
|
+
Path(out_json).write_text(json.dumps(rows, indent=1))
|
|
82
|
+
# detached checksum: editing the flat CSV silently is detectable
|
|
83
|
+
import hashlib
|
|
84
|
+
digest = hashlib.sha256(p.read_bytes()).hexdigest()
|
|
85
|
+
p.with_suffix(p.suffix + ".sha256").write_text(
|
|
86
|
+
f"{digest} {p.name}\n")
|
|
87
|
+
return p
|
proef/evals/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Proef eval suite — 'agentic science' as a measurable claim."""
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Do the deterministic detectors catch what a model fabricates, without crying wolf? (5F, and the narrative kinds of 5G)
|
|
2
|
+
|
|
3
|
+
Scored against `evals/fixtures/hallucination.json`: per category, recall on injected items and false-positive rate on clean ones. The
|
|
4
|
+
thresholds are in the fixture's readme and were set before the first run. The fixture includes deliberately hard cases, so a score below
|
|
5
|
+
1.0 is the detectors' real limit, not a bug in the eval. Offline and deterministic (a fake citation fetch, a throwaway cache)."""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from unittest import mock
|
|
12
|
+
|
|
13
|
+
from proef import citations, groundedness as g
|
|
14
|
+
from proef.evals.harness import TaskResult, _evals_dir, register
|
|
15
|
+
|
|
16
|
+
RECALL_MIN, FPR_MAX = 0.80, 0.20
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _text(x):
|
|
20
|
+
return x["text"] if isinstance(x, dict) else x
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _fixture() -> dict:
|
|
24
|
+
return json.loads((_evals_dir() / "fixtures" / "hallucination.json").read_text())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _detectors(fx: dict) -> dict:
|
|
28
|
+
def citation_flag(c):
|
|
29
|
+
real = set(fx["fabricated_citation"]["real_pmids"])
|
|
30
|
+
|
|
31
|
+
def fetch(url):
|
|
32
|
+
pid = next((p for p in real if f"id={p}" in url), None)
|
|
33
|
+
return json.dumps({"result": {pid: {"title": "t", "pubdate": "2020", "source": "J"}}} if pid else {"result": {}, "esearchresult": {"idlist": []}}).encode()
|
|
34
|
+
with tempfile.TemporaryDirectory() as d, mock.patch.object(citations, "CACHE", Path(d) / "c.json"):
|
|
35
|
+
return citations.verify(c, fetch)["status"] == "invalid"
|
|
36
|
+
f = fx
|
|
37
|
+
return {
|
|
38
|
+
"untestable_refutation": lambda x: g.untestable_refutation(_text(x)) is not None,
|
|
39
|
+
"invented_candidate": lambda x: g.not_in_library(_text(x), f["invented_candidate"]["library"]),
|
|
40
|
+
"bad_structure": lambda x: g.structure_problem(x["smiles"], x["name"], f["bad_structure"]["library_structures"]) is not None,
|
|
41
|
+
"quoted_number": lambda x: bool(g.quoted_number_problems(_text(x), [{**q, "ci_um": tuple(q["ci_um"])} for q in f["quoted_number"]["findings"]],
|
|
42
|
+
f["quoted_number"]["gate_um"])),
|
|
43
|
+
"gate_misstated": lambda x: bool(g.gate_misstated(_text(x), f["gate_misstated"]["gate_um"])),
|
|
44
|
+
"unsupported_value": lambda x: bool(g.unsupported_values(x["text"], x["bodies"], x.get("extra", "")) or g.misattributed_values(x["text"], x["bodies"])),
|
|
45
|
+
"claimed_refused": lambda x: any(f["kind"] == "claimed_refused_call" for f in g.loop_narrative_flags(
|
|
46
|
+
x["text"], x["calls"], {"pubmed_search", "chembl_search", "opentargets_summary"}, [])),
|
|
47
|
+
"state_claims": lambda x: bool(g.state_claims(x["text"], x["verdicts"], x.get("queued"), x.get("runs_left"))),
|
|
48
|
+
"ruled_out": lambda x: g.ruled_out(x["candidate"], x["family"], f["ruled_out"]["negatives"]) is not None,
|
|
49
|
+
"phantom_tool": lambda x: bool(g.phantom_tool_claims(_text(x), set(f["phantom_tool"]["called"]), set(f["phantom_tool"]["offered"]))),
|
|
50
|
+
"fabricated_citation": lambda x: citation_flag(x),
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def score() -> dict[str, dict]:
|
|
55
|
+
try:
|
|
56
|
+
from rdkit import RDLogger
|
|
57
|
+
RDLogger.DisableLog("rdApp.*") # the injected unparseable structures are meant to fail: no stderr noise
|
|
58
|
+
except ImportError:
|
|
59
|
+
pass
|
|
60
|
+
fx = _fixture()
|
|
61
|
+
out = {}
|
|
62
|
+
for cat, detect in _detectors(fx).items():
|
|
63
|
+
inj, cln = fx[cat]["injected"], fx[cat]["clean"]
|
|
64
|
+
hit = [bool(detect(x)) for x in inj]
|
|
65
|
+
fp = [bool(detect(x)) for x in cln]
|
|
66
|
+
out[cat] = {"injected": len(inj), "caught": sum(hit), "recall": round(sum(hit) / len(inj), 3), "clean": len(cln), "false_positives": sum(fp),
|
|
67
|
+
"false_positive_rate": round(sum(fp) / len(cln), 3),
|
|
68
|
+
"missed": [_text(x) if not isinstance(x, dict) or "text" in x else x for x, h in zip(inj, hit) if not h],
|
|
69
|
+
"wrongly_flagged": [_text(x) if not isinstance(x, dict) or "text" in x else x for x, h in zip(cln, fp) if h]}
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@register("hallucination-detectors",
|
|
74
|
+
"deterministic detectors for what a model fabricates (invented candidate, bad structure, untestable refuted-if, misquoted number, misstated "
|
|
75
|
+
"gate, wrong claim about the campaign's own state, repeated ruled-out idea, phantom tool call, fabricated citation): recall and false-positive rate per category on a labelled fixture that "
|
|
76
|
+
"includes hard cases on purpose", suite="hallucination")
|
|
77
|
+
def _t_hallucination_detectors():
|
|
78
|
+
res = score()
|
|
79
|
+
ok = all(v["recall"] >= RECALL_MIN and v["false_positive_rate"] <= FPR_MAX for v in res.values())
|
|
80
|
+
mean = sum(max(0.0, v["recall"] - v["false_positive_rate"]) for v in res.values()) / len(res)
|
|
81
|
+
worst = min(res, key=lambda k: res[k]["recall"] - res[k]["false_positive_rate"])
|
|
82
|
+
return TaskResult("hallucination-detectors", "what a model fabricates is caught, and clean text is not flagged", round(mean, 3), ok,
|
|
83
|
+
{"categories": res, "recall_min": RECALL_MIN, "false_positive_rate_max": FPR_MAX},
|
|
84
|
+
f"{sum(v['caught'] for v in res.values())}/{sum(v['injected'] for v in res.values())} injected caught, "
|
|
85
|
+
f"{sum(v['false_positives'] for v in res.values())}/{sum(v['clean'] for v in res.values())} clean wrongly flagged; weakest: {worst} "
|
|
86
|
+
f"(recall {res[worst]['recall']}, false-positive {res[worst]['false_positive_rate']}); simulated-author fixture, not a real model")
|