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.
Files changed (200) hide show
  1. proef/__init__.py +25 -0
  2. proef/acquisition.py +244 -0
  3. proef/ad.py +159 -0
  4. proef/adapters/__init__.py +0 -0
  5. proef/adapters/admet.py +196 -0
  6. proef/adapters/bio/__init__.py +0 -0
  7. proef/adapters/bio/rdkit_ops.py +52 -0
  8. proef/adapters/bio/safety_rules.json +146 -0
  9. proef/adapters/bio/seq_alerts.py +79 -0
  10. proef/adapters/bio/structure_score.py +85 -0
  11. proef/adapters/bio/tox_alerts.py +99 -0
  12. proef/adapters/data/__init__.py +0 -0
  13. proef/adapters/data/admet.py +62 -0
  14. proef/adapters/data/chembl.py +110 -0
  15. proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
  16. proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
  17. proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
  18. proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
  19. proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
  20. proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
  21. proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
  22. proef/adapters/data/moleculenet.py +60 -0
  23. proef/adapters/databases/__init__.py +0 -0
  24. proef/adapters/databases/chembl_gates.py +121 -0
  25. proef/adapters/databases/chembl_lookup.py +35 -0
  26. proef/adapters/databases/open_targets.py +102 -0
  27. proef/adapters/databases/pubmed.py +94 -0
  28. proef/adapters/devices/__init__.py +0 -0
  29. proef/adapters/devices/ezo_ph.py +251 -0
  30. proef/adapters/devices/hcs_microscope.py +143 -0
  31. proef/adapters/devices/lcms.py +123 -0
  32. proef/adapters/devices/scheduler.py +84 -0
  33. proef/adapters/devices/sila2.py +134 -0
  34. proef/adapters/genomics/alphagenome.py +146 -0
  35. proef/adapters/lab/__init__.py +0 -0
  36. proef/adapters/lab/bioprocess.py +32 -0
  37. proef/adapters/lab/devices.py +170 -0
  38. proef/adapters/lab/imaging.py +226 -0
  39. proef/adapters/lab/mhs_driver.py +124 -0
  40. proef/adapters/lab/opentrons.py +222 -0
  41. proef/adapters/lab/ot2_sim.py +174 -0
  42. proef/adapters/lab/plate_reader_share.py +108 -0
  43. proef/adapters/lab/protein_design.py +199 -0
  44. proef/adapters/lab/recording.py +119 -0
  45. proef/adapters/lab/replay.py +107 -0
  46. proef/adapters/lab/simulator.py +282 -0
  47. proef/adapters/lab/synthesis.py +92 -0
  48. proef/adapters/models/__init__.py +0 -0
  49. proef/adapters/models/anthropic_provider.py +157 -0
  50. proef/adapters/models/assayloop_ranker.py +67 -0
  51. proef/adapters/models/from_env.py +93 -0
  52. proef/adapters/models/gp_policy.py +93 -0
  53. proef/adapters/models/gp_policy_gp.py +36 -0
  54. proef/adapters/models/llm_policy.py +187 -0
  55. proef/adapters/models/openai_compat.py +150 -0
  56. proef/adapters/models/sklearn_policy.py +65 -0
  57. proef/adapters/retrosynthesis.py +247 -0
  58. proef/adapters/sandbox/__init__.py +20 -0
  59. proef/adapters/sandbox/agentenv.py +145 -0
  60. proef/adapters/sandbox/docker.py +217 -0
  61. proef/adapters/sandbox/local.py +164 -0
  62. proef/adapters/sandbox/opensandbox.py +122 -0
  63. proef/adapters/store/__init__.py +0 -0
  64. proef/adapters/store/sqlite.py +207 -0
  65. proef/adaptive.py +108 -0
  66. proef/advisory.py +76 -0
  67. proef/analysis_profiles/__init__.py +8 -0
  68. proef/analysis_profiles/measurements.py +266 -0
  69. proef/analysis_profiles/plate_assay.py +316 -0
  70. proef/analysis_report.py +195 -0
  71. proef/analysis_store.py +183 -0
  72. proef/anchor.py +154 -0
  73. proef/api/app.py +107 -0
  74. proef/api/launch.py +170 -0
  75. proef/api/v1/__init__.py +29 -0
  76. proef/api/v1/analyses.py +367 -0
  77. proef/api/v1/campaigns.py +802 -0
  78. proef/api/v1/deps.py +10 -0
  79. proef/api/v1/evals.py +16 -0
  80. proef/api/v1/evidence.py +132 -0
  81. proef/api/v1/governance.py +35 -0
  82. proef/api/v1/inbox.py +119 -0
  83. proef/api/v1/lab.py +110 -0
  84. proef/api/v1/pauses.py +77 -0
  85. proef/api/v1/programs.py +397 -0
  86. proef/api/v1/results.py +147 -0
  87. proef/api/v1/schemas.py +932 -0
  88. proef/api/v1/system.py +79 -0
  89. proef/api/v1/trees.py +216 -0
  90. proef/api/wizard_sessions.py +253 -0
  91. proef/approvals.py +102 -0
  92. proef/assays/__init__.py +15 -0
  93. proef/assays/dls.py +114 -0
  94. proef/assays/dsf.py +81 -0
  95. proef/assays/elisa.py +58 -0
  96. proef/assays/properties.py +65 -0
  97. proef/assays/simulate.py +157 -0
  98. proef/audit.py +152 -0
  99. proef/autoloop.py +1620 -0
  100. proef/benchmark.py +442 -0
  101. proef/campaign_fsm.py +151 -0
  102. proef/citations.py +141 -0
  103. proef/cli.py +1249 -0
  104. proef/connect.py +74 -0
  105. proef/core/__init__.py +0 -0
  106. proef/core/contracts/__init__.py +35 -0
  107. proef/core/contracts/analysis.py +100 -0
  108. proef/core/contracts/models.py +395 -0
  109. proef/core/device_card.py +125 -0
  110. proef/core/hypothesis.py +720 -0
  111. proef/core/interfaces.py +164 -0
  112. proef/core/registry.py +123 -0
  113. proef/core/safety.py +324 -0
  114. proef/core/workflow.py +159 -0
  115. proef/critic.py +62 -0
  116. proef/demo.py +164 -0
  117. proef/derivation.py +128 -0
  118. proef/diary.py +301 -0
  119. proef/eln.py +87 -0
  120. proef/evals/__init__.py +1 -0
  121. proef/evals/hallucination.py +86 -0
  122. proef/evals/harness.py +358 -0
  123. proef/evals/orchestration.py +254 -0
  124. proef/evals/tasks.py +1010 -0
  125. proef/evals/toolcalls.py +425 -0
  126. proef/experiment.py +172 -0
  127. proef/experiment_analysis.py +114 -0
  128. proef/experiments/__init__.py +0 -0
  129. proef/experiments/grounding_exp.py +689 -0
  130. proef/figures.py +218 -0
  131. proef/fitting.py +309 -0
  132. proef/fixtures.py +140 -0
  133. proef/flywheel.py +125 -0
  134. proef/followup.py +126 -0
  135. proef/governance.py +290 -0
  136. proef/groundedness.py +361 -0
  137. proef/grounding.py +202 -0
  138. proef/hypothesis_agent.py +369 -0
  139. proef/ingest.py +157 -0
  140. proef/instruments.json +173 -0
  141. proef/interpret.py +95 -0
  142. proef/kinetic.py +102 -0
  143. proef/labread/__init__.py +45 -0
  144. proef/labread/analysis.py +428 -0
  145. proef/labread/common.py +153 -0
  146. proef/labread/formats.py +190 -0
  147. proef/labread/layout.py +168 -0
  148. proef/labread/pubchem.py +179 -0
  149. proef/labselect.py +431 -0
  150. proef/materials.py +140 -0
  151. proef/mcp_instrument.py +396 -0
  152. proef/mcp_server.py +283 -0
  153. proef/modality.py +111 -0
  154. proef/model_guard.py +245 -0
  155. proef/output_blocks.py +183 -0
  156. proef/paths.py +32 -0
  157. proef/physfail.py +55 -0
  158. proef/plan.py +160 -0
  159. proef/plots.py +123 -0
  160. proef/predictors.py +217 -0
  161. proef/probes.py +79 -0
  162. proef/problem_tree.py +581 -0
  163. proef/program.py +308 -0
  164. proef/protocol_design.py +42 -0
  165. proef/proxy.py +78 -0
  166. proef/readiness.py +259 -0
  167. proef/reliability.py +49 -0
  168. proef/report.py +117 -0
  169. proef/reproduce.py +310 -0
  170. proef/reviewer.py +254 -0
  171. proef/sandbox_session.py +247 -0
  172. proef/sandboxd.py +109 -0
  173. proef/scaffold.py +195 -0
  174. proef/series.py +327 -0
  175. proef/skills.py +203 -0
  176. proef/sweep.py +83 -0
  177. proef/taste.py +177 -0
  178. proef/templates/confirmatory-followup.json +34 -0
  179. proef/templates/dose-response-screen.json +39 -0
  180. proef/templates/sar-exploration.json +38 -0
  181. proef/templates.py +124 -0
  182. proef/toolkit.py +433 -0
  183. proef/toolloop.py +133 -0
  184. proef/tools.py +441 -0
  185. proef/tpp.py +185 -0
  186. proef/views/__init__.py +14 -0
  187. proef/views/counts.py +102 -0
  188. proef/views/experiment.py +154 -0
  189. proef/views/ids.py +49 -0
  190. proef/views/narrative.py +294 -0
  191. proef/views/pipeline.py +370 -0
  192. proef/vision.py +165 -0
  193. proef/watch.py +790 -0
  194. proef/wizard_chain.py +25 -0
  195. proef/wizard_store.py +373 -0
  196. proef-0.2.0.dist-info/METADATA +662 -0
  197. proef-0.2.0.dist-info/RECORD +200 -0
  198. proef-0.2.0.dist-info/WHEEL +4 -0
  199. proef-0.2.0.dist-info/entry_points.txt +14 -0
  200. proef-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,370 @@
1
+ """Pipeline cards: the per-hypothesis stage view of one experiment."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+ from proef.views.counts import round_markers
7
+
8
+
9
+ # ---------------------------------------------------- hypothesis pipeline
10
+ _VERDICT_EVENTS = ("hypothesis_validated", "hypothesis_invalidated",
11
+ "hypothesis_inconclusive")
12
+
13
+
14
+ def pipeline_data(recs) -> dict:
15
+ """The computation behind the Hypothesis Pipeline: maps of
16
+ proposed/filtered/tested/refused hypotheses plus run attribution.
17
+ Verdicts are payload-driven and RECENCY-WINS: the last verdict-bearing
18
+ record for a hypothesis is its state, a confirmation that refutes (or
19
+ abstains) supersedes the preliminary call it reviewed, on every surface.
20
+ Port of the bookkeeping half of webview._pipeline_body."""
21
+ proposed: dict[str, dict] = {}
22
+ filtered: dict[str, dict] = {}
23
+ run_map: dict[str, list[str]] = {}
24
+ tested: dict[str, dict] = {}
25
+ refused: dict[str, str] = {}
26
+ gates = 0
27
+ gov_events: list[tuple] = []
28
+ run_ts: dict[str, float] = {}
29
+ run_instr: dict[str, str] = {}
30
+ seq = 0
31
+ for r in recs:
32
+ seq += 1
33
+ d = r.decision or {}
34
+ et = r.event_type.value
35
+ art_id = r.artifact.artifact_id if r.artifact else None
36
+ art_meta = r.artifact.metadata if r.artifact else {}
37
+ ts = getattr(getattr(r, "envelope", None), "created_at", None)
38
+ if et == "lab_run" and d.get("run_id"):
39
+ run_ts[d["run_id"]] = ts or 0
40
+ if et == "hypothesis_proposed":
41
+ # variant records carry statement/predicted but no candidate
42
+ # (candidates are attributed later, at synthesis/round time);
43
+ # fall back to a numbered label, never the string "None"
44
+ _stmt0 = str(d.get("statement")
45
+ or d.get("parent_statement") or "")
46
+ hid = (d.get("hypothesis_id") or art_id
47
+ or d.get("candidate") or _stmt0[:48]
48
+ or f"hyp-{len(proposed) + 1}")
49
+ proposed[hid] = {**d,
50
+ "candidate": d.get("candidate")
51
+ or art_meta.get("candidate"),
52
+ "statement": _stmt0,
53
+ "predicted": d.get("predicted")
54
+ or art_meta.get("predicted"),
55
+ "ts": ts}
56
+ elif et == "hypotheses_filtered":
57
+ for dec in d.get("decisions", []):
58
+ if dec.get("hypothesis_id"):
59
+ filtered[dec["hypothesis_id"]] = dec
60
+ elif et == "lab_run" and d.get("run_id"):
61
+ run_ts[d["run_id"]] = ts or 0
62
+ run_instr[d["run_id"]] = d.get("instrument", "")
63
+ elif et == "hypothesis_tested":
64
+ hid = d.get("hypothesis_id") or art_id
65
+ if d.get("run_id"):
66
+ run_map.setdefault(hid, []).append(d["run_id"])
67
+ # legacy verdict-bearing 'tested' records (pre-2026-10 event
68
+ # map): still verdicts, still recency-wins
69
+ if d.get("verdict"):
70
+ cand = (d.get("candidate") or art_meta.get("candidate")
71
+ or "")
72
+ key = hid or cand
73
+ if key:
74
+ tested[key] = {
75
+ "verdict": d["verdict"],
76
+ "candidate": cand,
77
+ "observed": d.get("observed"),
78
+ "ci": d.get("observed_ci"),
79
+ "derivation": d.get("derivation"),
80
+ "seq": seq,
81
+ "evidence": d.get("evidence_run_id")
82
+ or d.get("run_id")}
83
+ elif et in _VERDICT_EVENTS:
84
+ hid = d.get("hypothesis_id") or d.get("id") or art_id
85
+ cand = (d.get("candidate") or art_meta.get("candidate")
86
+ or "")
87
+ if hid:
88
+ prev = tested.get(hid) or {}
89
+ tested[hid] = {"verdict": d.get("verdict", et),
90
+ "candidate": cand,
91
+ "observed": d.get("observed")
92
+ or d.get("ic50_um"),
93
+ "ci": d.get("observed_ci"),
94
+ "proxy_evidence": d.get("evidence"),
95
+ "extrapolation":
96
+ bool(d.get("extrapolation")),
97
+ "derivation": d.get("derivation"),
98
+ "seq": seq,
99
+ "evidence": d.get("evidence_run_id")}
100
+ elif et == "stage_transition" \
101
+ and str(d.get("stage", "")).startswith("round-") \
102
+ and d.get("verdicts"):
103
+ # round-complete markers carry the AUTHORITATIVE per-candidate
104
+ # verdict AS OF THE ROUND END — recency-wins, so a later round
105
+ # (or the same round's final state) replaces an earlier marker;
106
+ # a confirmation landing after the marker is a LATER record and
107
+ # wins on its own key
108
+ for cand, v in (d.get("verdicts") or {}).items():
109
+ key = f"cand::{cand}"
110
+ cur = tested.get(key) or {}
111
+ tested[key] = {"verdict": str(v),
112
+ "candidate": str(cand),
113
+ "observed": cur.get("observed"),
114
+ "ci": cur.get("ci"),
115
+ "derivation": cur.get("derivation"),
116
+ "seq": seq,
117
+ "evidence": cur.get("evidence")}
118
+ elif et == "gate_decision":
119
+ if d.get("kind") in ("safety_refusal", "operator_declined",
120
+ "advisory_escalation"):
121
+ for sm in d.get("samples", []):
122
+ refused[sm] = d.get("reason", "refused")
123
+ else:
124
+ gates += 1
125
+ if d.get("kind") in ("halt_refusal", "authorization",
126
+ "failure-mode"):
127
+ gov_events.append((ts or 0, d))
128
+ return {"proposed": proposed, "filtered": filtered,
129
+ "run_map": run_map, "tested": tested, "refused": refused,
130
+ "gates": gates, "gov_events": gov_events,
131
+ "run_ts": run_ts, "run_instr": run_instr}
132
+
133
+
134
+ def _ci_margin(ci, threshold) -> str:
135
+ """Margin text for a CI against a pre-registered gate."""
136
+ if ci and threshold and None not in ci and ci[1] > ci[0]:
137
+ width = ci[1] - ci[0]
138
+ edge = min(abs(ci[0] - threshold), abs(ci[1] - threshold))
139
+ if ci[0] <= threshold <= ci[1]:
140
+ return " · borderline: CI spans the gate"
141
+ return (" · narrow margin" if edge < width else " · clear margin")
142
+ return ""
143
+
144
+
145
+ def _tested_by_candidate(tested: dict) -> dict:
146
+ """Latest tested record per candidate (highest seq wins)."""
147
+ out: dict = {}
148
+ for v in tested.values():
149
+ c = v.get("candidate")
150
+ if not c:
151
+ continue
152
+ cur = out.get(c)
153
+ if not cur or v.get("seq", 0) >= cur.get("seq", 0):
154
+ out[c] = v
155
+ return out
156
+
157
+
158
+ def _merge_verdict(verd: dict, verd_c: dict) -> dict:
159
+ """Whichever record is MORE RECENT wins on status, the candidate-keyed
160
+ round roll-up may postdate the hid-keyed readout, and vice versa (a
161
+ confirmation record is hid-keyed and terminal). The terminal verdict
162
+ wins on STATUS; the preliminary readout's observed/CI is kept when the
163
+ terminal record carries none (round roll-ups don't repeat the number)."""
164
+ if not (verd_c.get("verdict")
165
+ and verd_c.get("seq", 0) >= verd.get("seq", 0)):
166
+ return verd
167
+ return {**verd, **verd_c,
168
+ "observed": verd_c.get("observed")
169
+ if verd_c.get("observed") is not None else verd.get("observed"),
170
+ "ci": verd_c.get("ci") or verd.get("ci"),
171
+ "evidence": verd_c.get("evidence") or verd.get("evidence"),
172
+ "derivation": verd_c.get("derivation") or verd.get("derivation"),
173
+ "proxy_evidence": verd_c.get("proxy_evidence")
174
+ or verd.get("proxy_evidence"),
175
+ "extrapolation": verd_c.get("extrapolation")
176
+ or verd.get("extrapolation")}
177
+
178
+
179
+ def _card_state(v, *, hid, cand, sel, refused, run_map, unit_lbl, observed,
180
+ ci_txt, margin, ad_chip) -> tuple[str, str]:
181
+ """(state, stage text) for one card, the pipeline state machine."""
182
+ obs_txt = (f", {unit_lbl} {observed}{ci_txt}"
183
+ if observed is not None else "")
184
+ paren = (f" ({unit_lbl} {observed}{ci_txt})"
185
+ if observed is not None else "")
186
+ if v == "confirmed":
187
+ return "confirmed", "confirmed by orthogonal assay" + obs_txt + margin
188
+ if v == "validated":
189
+ return "validated", "validated (preliminary)" + obs_txt + margin
190
+ if v == "inconclusive":
191
+ return "inconclusive", ("inconclusive, CI straddles the threshold"
192
+ + paren + ad_chip)
193
+ if v in ("refuted", "invalidated"):
194
+ return "refuted", "refuted" + paren + margin
195
+ if refused.get(str(cand)):
196
+ return "refused", "refused by gate, " + refused[str(cand)][:70]
197
+ if run_map.get(hid):
198
+ return "in_lab", "in lab"
199
+ if sel and sel.get("selected"):
200
+ return "selected", "selected, awaiting submission"
201
+ if sel:
202
+ return "not_selected", "not selected"
203
+ return "proposed", "proposed"
204
+
205
+
206
+ def _gate_label(hp: dict, verd: dict):
207
+ from proef.derivation import criteria_label
208
+ crit = hp.get("criteria") or {}
209
+ gate_lbl = (criteria_label(crit.get("metric"), crit.get("direction"),
210
+ crit["threshold"])
211
+ if crit.get("threshold") is not None else None)
212
+ evd = (verd or {}).get("proxy_evidence")
213
+ if gate_lbl and isinstance(evd, dict) and evd.get("resolved"):
214
+ n = evd["rungs"]
215
+ gate_lbl += (f" · {n} proxy rung{'s' if n != 1 else ''} "
216
+ "from clinical")
217
+ elif gate_lbl and isinstance(evd, dict) and not evd.get("resolved"):
218
+ gate_lbl += " · proxy chain unresolved (distance unknown)"
219
+ return gate_lbl, evd
220
+
221
+
222
+ def _card_statement(hp: dict, head) -> str:
223
+ stmt = str(hp.get("statement", ""))
224
+ # the label is often a truncation of the statement itself —
225
+ # strip any leading duplication before cosmetics
226
+ if stmt.startswith(str(head)):
227
+ stmt = stmt[len(str(head)):].strip(" , -·:")
228
+ return re.sub(rf"^{re.escape(str(head))}\s*(\([^)]*\))?\s*[, -]\s*",
229
+ "", stmt) or head # statement was the label itself
230
+
231
+
232
+ def pipeline_cards(recs) -> list[dict]:
233
+ """Card dicts for the Hypothesis Pipeline, in proposed order.
234
+ State machine: confirmed/validated/inconclusive/refuted/refused/
235
+ in_lab/selected/not_selected/proposed. Port of the decision half of
236
+ webview._pipeline_body."""
237
+ data = pipeline_data(recs)
238
+ proposed, filtered = data["proposed"], data["filtered"]
239
+ tested, refused = data["tested"], data["refused"]
240
+ run_map = data["run_map"]
241
+ cand2round = {cand: rnd for rnd, cands in round_markers(recs)
242
+ for cand in cands}
243
+ tested_by_cand = _tested_by_candidate(tested)
244
+ from proef.derivation import metric_label
245
+ cards = []
246
+ for hid, hp in proposed.items():
247
+ sel = filtered.get(hid)
248
+ cand = hp.get("candidate")
249
+ head = cand or hid
250
+ verd = _merge_verdict(tested.get(hid) or {},
251
+ tested_by_cand.get(str(cand), {}))
252
+ v = (verd.get("verdict") or "").lower()
253
+ ci = verd.get("ci")
254
+ ci_txt = (f" (95% CI {ci[0]}–{ci[1]})" if ci else "")
255
+ _der = verd.get("derivation") or {}
256
+ unit_lbl = metric_label(
257
+ (_der.get("derived") or {}).get("metric")
258
+ or _der.get("criteria_metric") or _der.get("metric"))
259
+ margin = _ci_margin(ci, (hp.get("criteria") or {}).get("threshold"))
260
+ ad_chip = ""
261
+ if verd.get("extrapolation"):
262
+ ad_chip = (" · stamped extrapolation, value came from a model "
263
+ "beyond its applicability domain")
264
+ margin += ad_chip
265
+ observed = verd.get("observed")
266
+ state, stage = _card_state(
267
+ v, hid=hid, cand=cand, sel=sel, refused=refused, run_map=run_map,
268
+ unit_lbl=unit_lbl, observed=observed, ci_txt=ci_txt,
269
+ margin=margin, ad_chip=ad_chip)
270
+ crit = hp.get("criteria") or {}
271
+ _pb = hp.get("predicted_by")
272
+ if isinstance(_pb, dict) and (_pb.get("ad") or {}).get("extrapolation"):
273
+ _pb = {**_pb, "note": ("prediction came from a model OUTSIDE its "
274
+ "applicability domain, treated as a "
275
+ "question to test, never as evidence")}
276
+ gate_lbl, _evd = _gate_label(hp, verd)
277
+ cards.append({
278
+ "key": hid,
279
+ "candidate": cand,
280
+ "family": hp.get("family"),
281
+ "head": str(head),
282
+ "statement": _card_statement(hp, head),
283
+ "rationale": hp.get("rationale"),
284
+ "predicted": hp.get("predicted"),
285
+ "predicted_by": _pb,
286
+ "mechanism": hp.get("mechanism"),
287
+ "citation": hp.get("citation"),
288
+ "citation_status": hp.get("citation_status"),
289
+ "citation_detail": hp.get("citation_detail"),
290
+ "refutation_condition": hp.get("refutation_condition"),
291
+ "gate_label": gate_lbl,
292
+ "evidence": _evd,
293
+ "threshold": crit.get("threshold"),
294
+ "verdict": {"status": v or None,
295
+ "observed": observed,
296
+ "extrapolation": bool(verd.get("extrapolation")),
297
+ "ci": list(ci) if ci else None,
298
+ "unit_label": unit_lbl,
299
+ "margin": margin.strip(" ·")} if verd else None,
300
+ "stage": stage,
301
+ "state": state,
302
+ "round": cand2round.get(str(cand)),
303
+ "selected": bool(sel and sel.get("selected")),
304
+ })
305
+ return cards
306
+
307
+
308
+ def _sandbox_summary(recs) -> dict | None:
309
+ """The sandbox receipt (S-T3 #4): if the experiment ran inside a
310
+ sandbox, the chain says which, with what policy, how many sealed
311
+ ops, None (rendered as nothing) when it didn't."""
312
+ info = None
313
+ for r in recs:
314
+ d = r.decision or {}
315
+ et = r.event_type.value
316
+ if et == "sandbox_create":
317
+ info = {"type": d.get("type") or "docker",
318
+ "sandbox_id": d.get("sandbox_id") or d.get("created"),
319
+ "policy": {k: d.get(k) for k in
320
+ ("network", "memory", "cpus", "pids_limit")
321
+ if d.get(k)},
322
+ "execs": 0, "snapshots": 0, "forks": 0,
323
+ "destroyed": False}
324
+ elif info and et == "sandbox_exec":
325
+ info["execs"] += 1
326
+ elif info and et == "sandbox_snapshot":
327
+ info["snapshots"] += 1
328
+ elif info and et == "sandbox_fork":
329
+ info["forks"] += 1
330
+ elif info and et == "sandbox_destroy":
331
+ info["destroyed"] = True
332
+ return info
333
+
334
+
335
+ def _rounds_with_verdicts(recs) -> list[dict]:
336
+ """Rounds with tested candidates AND the round's verdict map (from
337
+ the round-N-complete stage markers). When a round was chosen by a
338
+ batch-acquisition policy, its Selection rides along as `selection` ,
339
+ the "why this plate" answer for the workbench."""
340
+ rounds = [{"round": n, "candidates": c, "verdicts": {}}
341
+ for n, c in round_markers(recs)]
342
+ by_round = {rd["round"]: rd for rd in rounds}
343
+ for r in recs:
344
+ dec = r.decision or {}
345
+ stage = str(dec.get("stage", ""))
346
+ if r.event_type.value == "stage_transition" \
347
+ and stage.startswith("round-") and dec.get("verdicts"):
348
+ try:
349
+ n = int(stage.split("-")[1])
350
+ except (ValueError, IndexError):
351
+ continue
352
+ if n in by_round:
353
+ by_round[n]["verdicts"] = {str(k): str(v) for k, v
354
+ in (dec.get("verdicts") or {}).items()}
355
+ if dec.get("kind") == "acquisition_selection":
356
+ try:
357
+ n = int(dec.get("round", 0))
358
+ except (TypeError, ValueError):
359
+ continue
360
+ if n in by_round:
361
+ by_round[n]["selection"] = {
362
+ "policy": dec.get("policy"),
363
+ "policy_version": dec.get("policy_version"),
364
+ "target": dec.get("target"),
365
+ "direction": dec.get("direction"),
366
+ "k": dec.get("k"),
367
+ "picks": dec.get("picks") or [],
368
+ "refusals": dec.get("refusals") or [],
369
+ "note": dec.get("note", "")}
370
+ return rounds
proef/vision.py ADDED
@@ -0,0 +1,165 @@
1
+ """Vision-LLM assay readout — a multimodal model reads simulated plate images.
2
+
3
+ Closes the loop on device evidence: the imaging lab produces well micrographs;
4
+ a vision-capable LLM *looks at them* (no numeric access to the underlying
5
+ values) and estimates fluorescence; its estimates are fit to an IC50 and
6
+ compared against the analysis pipeline's IC50 and the device ground truth.
7
+
8
+ This is the evaluation harness for "can a multimodal agent do assay analysis?"
9
+
10
+ Requires: imaging extra (numpy) + PROEF_LLM_*/ANTHROPIC_* env for the model.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import json
16
+ import os
17
+ import re
18
+ import struct
19
+ import urllib.request
20
+ import zlib
21
+ from typing import Any
22
+
23
+
24
+ # ------------------------------------------------------------- PNG encoding
25
+
26
+ def gray_png(arr: Any) -> bytes:
27
+ """Encode a 2-D uint8-ish numpy array as a minimal grayscale PNG."""
28
+ import numpy as np
29
+
30
+ a = np.asarray(arr).astype(np.uint8)
31
+ h, w = a.shape
32
+ raw = b"".join(b"\x00" + a[i].tobytes() for i in range(h)) # filter 0 per row
33
+
34
+ def chunk(tag: bytes, data: bytes) -> bytes:
35
+ return (struct.pack(">I", len(data)) + tag + data
36
+ + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
37
+
38
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 0, 0, 0, 0) # grayscale 8-bit
39
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr)
40
+ + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
41
+
42
+
43
+ # ----------------------------------------------------------- vision reader
44
+
45
+ class VisionWellReader:
46
+ """Ask a multimodal model to quantify a well micrograph (0-100 intensity).
47
+
48
+ The model sees ONLY the image pixels — never the ground truth, never the
49
+ pipeline numbers. Its estimates are then fit like any other readout.
50
+ """
51
+
52
+ name = "vision-llm"
53
+
54
+ def __init__(self, model: str | None = None, base_url: str | None = None,
55
+ token: str | None = None):
56
+ self.model = (model or os.environ.get("PROEF_LLM_MODEL")
57
+ or os.environ.get("ANTHROPIC_DEFAULT_SONNET_MODEL")
58
+ or os.environ.get("ANTHROPIC_DEFAULT_HAIKU_MODEL"))
59
+ self.base_url = (base_url or os.environ.get("PROEF_LLM_BASE_URL")
60
+ or os.environ.get("ANTHROPIC_BASE_URL", "")).rstrip("/")
61
+ self.token = (token or os.environ.get("PROEF_LLM_TOKEN")
62
+ or os.environ.get("ANTHROPIC_AUTH_TOKEN") or "")
63
+ if not (self.model and self.base_url and self.token):
64
+ raise RuntimeError("vision readout needs PROEF_LLM_/ANTHROPIC_ env config")
65
+
66
+ def estimate_intensity(self, image: Any, well_id: str = "") -> float:
67
+ import numpy as np
68
+
69
+ a = (np.asarray(image) - np.asarray(image).min())
70
+ a = (a / (a.max() or 1.0) * 255).astype(np.uint8)
71
+ b64 = base64.standard_b64encode(gray_png(a)).decode()
72
+ body = {
73
+ "model": self.model,
74
+ "max_tokens": 2000,
75
+ "messages": [{
76
+ "role": "user",
77
+ "content": [
78
+ {"type": "image",
79
+ "source": {"type": "base64", "media_type": "image/png", "data": b64}},
80
+ {"type": "text",
81
+ "text": "This is a fluorescence micrograph of one wells of a 96-well "
82
+ "plate. Estimate the overall fluorescence intensity on a 0-100 "
83
+ 'scale. Reply ONLY with JSON: {"value": <number>}'},
84
+ ],
85
+ }],
86
+ }
87
+ req = urllib.request.Request(
88
+ f"{self.base_url}/v1/messages", data=json.dumps(body).encode(),
89
+ headers={"Content-Type": "application/json",
90
+ "Authorization": f"Bearer {self.token}",
91
+ "anthropic-version": "2023-06-01"}, method="POST")
92
+ with urllib.request.urlopen(req, timeout=90) as resp: # noqa: S310
93
+ data = json.loads(resp.read())
94
+ text = "".join(c.get("text", "") for c in data.get("content", [])
95
+ if c.get("type") == "text")
96
+ import re
97
+ m = re.search(r"-?\d+(?:\.\d+)?", text)
98
+ if not m:
99
+ raise ValueError(f"no number in vision response: {text[:120]}")
100
+ return float(m.group(0))
101
+
102
+ def estimate_series(self, images: list[Any], concentrations: list[str]) -> dict[float, float]:
103
+ """Show the whole dose series side-by-side (one composite image) so the
104
+ model can compare wells RELATIVELY — single-image estimation is
105
+ uncalibrated. Returns {conc_um: estimate}."""
106
+ import numpy as np
107
+
108
+ raw = [np.asarray(img).astype(np.float64) for img in images]
109
+ lo = min(a.min() for a in raw)
110
+ hi = max(a.max() for a in raw) or 1.0
111
+ # joint normalization: preserves RELATIVE brightness across wells
112
+ arrs = [((a - lo) / (hi - lo) * 255.0).astype(np.uint8) for a in raw]
113
+ sep = np.full((arrs[0].shape[0], 6), 255, dtype=np.uint8) # white separators
114
+ strip = arrs[0]
115
+ for a in arrs[1:]:
116
+ strip = np.hstack([strip, sep, a])
117
+ b64 = base64.standard_b64encode(gray_png(strip)).decode()
118
+ conc_list = ", ".join(f"panel {i+1} = {c}" for i, c in enumerate(concentrations))
119
+ body = {
120
+ "model": self.model,
121
+ "max_tokens": 2000,
122
+ "messages": [{
123
+ "role": "user",
124
+ "content": [
125
+ {"type": "image",
126
+ "source": {"type": "base64", "media_type": "image/png", "data": b64}},
127
+ {"type": "text",
128
+ "text": "This image shows one fluorescence micrograph per panel, "
129
+ "separated by thin white lines, for a dose-response series: "
130
+ f"{conc_list}. All panels share the same imaging settings, so "
131
+ "compare them RELATIVELY. Estimate each panel's fluorescence "
132
+ "intensity on a 0-100 scale where 0 = background only and "
133
+ "100 = a COMPLETELY saturated, uniformly bright field — note "
134
+ "that even the brightest panel here is far from saturation, so "
135
+ "its value should be well below 100. "
136
+ 'Reply ONLY with JSON: {"values": [<number>, ...]} '
137
+ "with one number per panel in order."},
138
+ ],
139
+ }],
140
+ }
141
+ req = urllib.request.Request(
142
+ f"{self.base_url}/v1/messages", data=json.dumps(body).encode(),
143
+ headers={"Content-Type": "application/json",
144
+ "Authorization": f"Bearer {self.token}",
145
+ "anthropic-version": "2023-06-01"}, method="POST")
146
+ with urllib.request.urlopen(req, timeout=120) as resp: # noqa: S310
147
+ data = json.loads(resp.read())
148
+ text = "".join(c.get("text", "") for c in data.get("content", [])
149
+ if c.get("type") == "text")
150
+ m = re.search(r"\[[^\]]*\]", text, re.S)
151
+ if not m:
152
+ raise ValueError(f"no list in vision response: {text[:150]}")
153
+ values = [float(x) for x in re.findall(r"-?\d+(?:\.\d+)?", m.group(0))]
154
+ return {float(str(c).replace("uM", "")): v
155
+ for c, v in zip(concentrations, values)}
156
+
157
+ def read_dose_response(self, well_images: dict[str, tuple[str, float, Any]],
158
+ max_response: float = 100.0) -> dict[str, float]:
159
+ """well_images: {well_id: (sample_id, conc_um, image)} -> {sample: {conc: estimate}}"""
160
+ out: dict[str, dict[float, float]] = {}
161
+ for well_id, (sample, conc, image) in well_images.items():
162
+ if sample.startswith("ctrl"):
163
+ continue
164
+ out.setdefault(sample, {})[conc] = self.estimate_intensity(image, well_id)
165
+ return {s: {c: v for c, v in sorted(d.items())} for s, d in out.items()}