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,369 @@
1
+ """Agent-driven hypothesis generation — the agent decides the structure.
2
+
3
+ Given a ProblemStatement (and optionally a candidate library), a ModelProvider
4
+ proposes the hypothesis structure itself:
5
+
6
+ - how many mechanistic FAMILIES (distinct bets) and what they claim
7
+ - how many VARIANTS per family (parameter sweeps) and WHICH variables to
8
+ tune (warhead type, concentration range, assay modality...)
9
+ - a self-assessed score per family (used by the portfolio filter unless the
10
+ operator overrides it)
11
+
12
+ Everything the agent produces is JSON-validated, provenance-recorded (prompt +
13
+ response + structure), and constrained by operator limits (max_families,
14
+ max_variants_per_family) — autonomy inside guardrails, as everywhere else.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import re
20
+ from typing import Any, Callable
21
+
22
+ from proef.core.contracts import ToolInvocation
23
+ from proef.core.hypothesis import (
24
+ Constraint, Hypothesis, HypothesisTracker, ProblemStatement, SuccessCriteria,
25
+ )
26
+ from proef.core.interfaces import record_for
27
+ from proef.protocol_design import sanitize_protocol
28
+
29
+ PROMPT = """You are the hypothesis lead of a {role}.
30
+
31
+ PROBLEM
32
+ objective: {objective}
33
+ context: {context}
34
+ constraints: {constraints}
35
+ success metric: {success_metric}
36
+
37
+ CANDIDATE LIBRARY (measured/predicted so far)
38
+ {candidates}
39
+
40
+ Decide the hypothesis structure yourself:
41
+ - How many DISTINCT mechanistic families to pursue (each family = one
42
+ falsifiable mechanistic claim; variants = the same claim with different
43
+ parameterizations, e.g. analogs or tuned assay variables).
44
+ - For each variant: which variables you tune and why (declare them in
45
+ "variables"), what it predicts, and its rationale.
46
+ - Your own confidence score per family (0-1) — be honest.
47
+
48
+ - "protocol" is optional: the dose ladder (3 to 8 concentrations in uM, 0.001 to 1000) YOU would test this
49
+ variant at. Bracket the gate with doses on both sides of it. The lab validates it and may replace it.
50
+
51
+ Limits: at most {max_families} families, at most {max_variants_per_family}
52
+ variants per family. Prefer few distinct ideas over many similar ones.
53
+
54
+ Reply ONLY with JSON:
55
+ {{"families": [
56
+ {{"family": "short-family-id",
57
+ "parent_statement": "falsifiable mechanistic claim",
58
+ "kind": "mechanistic",
59
+ "mechanism": "the CAUSAL story — {mechanism_hint}; not 'it fits'",
60
+ "refutation_condition": "the ONE observation that kills this family",
61
+ "predicted_observables": ["what else must be true if this holds"],
62
+ "citation": "PMID or DOI grounding the rationale ('' if none — never invent)",
63
+ "rationale": "why this bet",
64
+ "confidence": 0.0-1.0,
65
+ "variables": ["what you tune across variants"],
66
+ "variants": [
67
+ {{"statement": "falsifiable variant prediction",
68
+ "candidate": "the {candidate_kind} or sample name only, e.g. {candidate_example}, with no prefix such as 'proposed'",
69
+ "assay_type": "binding",{instrument_field}{tools_field}
70
+ "predicted": "human-readable prediction",
71
+ "predicted_value": 20.0,
72
+ "rationale": "why this variant",
73
+ "variables": {{"tuned_param": "value"}},
74
+ "protocol": {{"concentrations_uM": [0.1, 0.5, 2, 10, 50], "why": "brackets the gate on both sides"}}}}
75
+ ]}}
76
+ ]}}"""
77
+
78
+
79
+ from proef.core.contracts.models import coerce_assay_type
80
+
81
+
82
+ def propose_families_with_agent(
83
+ tracker: HypothesisTracker,
84
+ problem: ProblemStatement,
85
+ model: Any,
86
+ candidates: list[dict[str, Any]] | None = None,
87
+ max_families: int = 3,
88
+ max_variants_per_family: int = 3,
89
+ max_total_hypotheses: int | None = None,
90
+ existing_keys: set[tuple[str, str]] | None = None,
91
+ skill_guidance: str | None = None,
92
+ flywheel: Any = None,
93
+ branch_id: str | None = None,
94
+ score_fn: Callable[[dict[str, Any]], float] | None = None,
95
+ notify: Callable[[str], None] | None = None,
96
+ findings: str | None = None,
97
+ modality: str | None = None,
98
+ instruments: dict | None = None,
99
+ predictors: list[str] | None = None,
100
+ registry: Any = None,
101
+ grounding: str | None = None,
102
+ ) -> tuple[list[Hypothesis], dict[str, float]]:
103
+ """max_total_hypotheses: hard cap on hypotheses this generation may add.
104
+ existing_keys: (candidate, statement) pairs already tried — duplicates the
105
+ agent re-proposes are dropped (no re-running the same experiment).
106
+ skill_guidance: Agent Skills text (e.g. the proef/opentrons skill)
107
+ injected into the prompt so domain procedure shapes the generation."""
108
+
109
+ """The agent designs the hypothesis portfolio; returns (variants, scores).
110
+
111
+ Enforces operator limits post-hoc (truncates), records the raw generation
112
+ into provenance, and derives family scores from the agent's confidence
113
+ unless `score_fn` is given.
114
+ """
115
+ from proef.core.contracts import Envelope, EventType
116
+
117
+ branch = branch_id or f"problem/{problem.problem_id}"
118
+ env = Envelope(experiment_branch_id=branch)
119
+ actor = tracker.actor
120
+ say = notify or (lambda m: None)
121
+
122
+ if skill_guidance:
123
+ guidance_block = ("PROCEDURAL GUIDANCE (Agent Skills — follow while "
124
+ "designing):\n" + skill_guidance[:3000])
125
+ else:
126
+ guidance_block = ""
127
+ from proef.modality import pack_or_default
128
+ pack = pack_or_default(modality)
129
+ menu = (instruments or {}).get("menu") or []
130
+ runs_on = (instruments or {}).get("runs_on")
131
+ if menu:
132
+ from proef.labselect import menu_text
133
+ instrument_block = ("\n\nAVAILABLE INSTRUMENTS (the operator's fence: choose only from these; real and simulated "
134
+ "are labelled)\n" + menu_text(menu) + "\nFor each variant name the instrument that would run it "
135
+ "in \"instrument\", or leave it empty if none fits. The lab checks your pick against what each "
136
+ "instrument declares, and a person sees the result.")
137
+ instrument_field = '\n "instrument": "name from the list above, or empty",'
138
+ else:
139
+ instrument_block, instrument_field = "", ""
140
+ # prediction tools: the operator enables them, the model proposes which fit, code validates and runs them
141
+ from proef.predictors import DEFAULT as _DEFAULT_REG
142
+ _REG = registry if registry is not None else _DEFAULT_REG # a replay passes one that plays back what was recorded
143
+ tool_menu = _REG.menu(predictors, modality)
144
+ if tool_menu:
145
+ tools_block = ("\n\nPREDICTION TOOLS (priors the lab computes; never evidence: the measured result judges)\n"
146
+ + _REG.menu_text(tool_menu) + "\nFor each variant you may list the tools that fit in \"tools\" and give "
147
+ "the candidate's \"smiles\" when it is a small molecule. Leave both empty if unsure: never guess a SMILES.")
148
+ tools_field = '\n "tools": ["name from the list above"], "smiles": "SMILES or empty",'
149
+ else:
150
+ tools_block, tools_field = "", ""
151
+ prompt = PROMPT.format(
152
+ instrument_field=instrument_field, tools_field=tools_field,
153
+ role=pack.prompt_role, mechanism_hint=pack.mechanism_hint,
154
+ candidate_kind=pack.candidate_kind, candidate_example=pack.candidate_example,
155
+ objective=problem.objective,
156
+ context=problem.context or "-",
157
+ constraints=json.dumps([c.model_dump() for c in problem.constraints]),
158
+ success_metric=problem.success_metric or "-",
159
+ candidates=json.dumps(candidates or [], indent=1)[:4000],
160
+ max_families=max_families,
161
+ max_variants_per_family=max_variants_per_family,
162
+ ) + instrument_block + tools_block + ("\n\n" + guidance_block if guidance_block else "")
163
+ if grounding:
164
+ prompt += "\n\n" + grounding[:3000]
165
+ if findings:
166
+ prompt += ("\n\nRESULTS SO FAR (re-plan from these: do not repeat a refuted idea, "
167
+ "build on what held up, and pick candidates not yet tested)\n" + findings)
168
+ negatives_injected: list[str] = []
169
+ if flywheel is not None:
170
+ negs = flywheel.prompt_context()
171
+ if negs:
172
+ prompt = prompt + "\n\n" + negs
173
+ negatives_injected = [line.split(" ")[1] for line
174
+ in negs.splitlines()[1:] if line.startswith("- ")]
175
+ say("prompt includes previously ruled-out candidates (flywheel)")
176
+ inv = ToolInvocation(envelope=env.model_copy(), tool="c.fm.generate_molecules")
177
+ # every ATTEMPT leaves its flywheel context, written before the call: a generation that fails or is refused writes no
178
+ # hypothesis_generation record, and a replay hands the contexts out one per attempt
179
+ tracker.store.append(record_for(env, EventType.tool_invocation, actor, decision={
180
+ "kind": "generation_attempt", "flywheel_context": (negs[:4000] if flywheel is not None and negs else "")}))
181
+ raw = model.generate(inv, prompt).output["text"]
182
+ # record the raw generation (agent reasoning is provenance too)
183
+ store_append = tracker.store.append
184
+ import hashlib as _hl
185
+ store_append(record_for(env, EventType.tool_invocation, actor,
186
+ decision={"kind": "hypothesis_generation",
187
+ # what the flywheel put in the prompt: a replay has no flywheel, so it replays this
188
+ "flywheel_context": (negs[:4000] if flywheel is not None and negs else ""),
189
+ "prompt_chars": len(prompt),
190
+ "response_chars": len(raw),
191
+ # retrieval trace: what shaped this gen
192
+ "trace": {
193
+ "prompt_sha256":
194
+ _hl.sha256(
195
+ prompt.encode()).hexdigest()[:16],
196
+ "model": getattr(model, "model",
197
+ "unknown"),
198
+ "skill_guidance_chars":
199
+ len(skill_guidance or ""),
200
+ "flywheel_negatives":
201
+ len(negatives_injected)
202
+ if "negatives_injected" in dir()
203
+ else 0,
204
+ "candidates_count":
205
+ len(candidates or []),
206
+ }}))
207
+
208
+ doc = _extract_json(raw)
209
+ families_in = doc.get("families", [])[:max_families]
210
+ family_scores: dict[str, float] = {}
211
+ family_info: dict[str, dict[str, Any]] = {}
212
+ specs: list[dict[str, Any]] = []
213
+ # the program's primary hard constraint is the gate: variant criteria
214
+ # inherit its metric/direction (threshold stays the variant's own
215
+ # predicted value when the agent declared one)
216
+ _con = next((c for c in problem.constraints if c.kind == "hard"
217
+ and c.limit is not None), None)
218
+ _gate = None
219
+ if _con is not None:
220
+ _gate = {"metric": _con.name,
221
+ "direction": "max" if ">=" in (_con.description or "")
222
+ else "min",
223
+ "threshold": float(_con.limit)}
224
+ for fam in families_in:
225
+ fid = str(fam.get("family", f"fam-{len(family_scores)}"))[:40]
226
+ family_scores[fid] = float(fam.get("confidence", 0.5))
227
+ family_info[fid] = {k: fam.get(k, "") for k in ("parent_statement", "mechanism", "refutation_condition",
228
+ "rationale", "citation")}
229
+ say(f"family '{fid}' (confidence {family_scores[fid]:.2f}): "
230
+ f"{fam.get('parent_statement', '')[:80]}")
231
+ for v in fam.get("variants", [])[:max_variants_per_family]:
232
+ _assay = str(coerce_assay_type(
233
+ v.get("assay_type", "binding")).value)
234
+ # THE GATE IS THE PROGRAM'S, never the model's. A variant's predicted value is a PREDICTION (kept on the
235
+ # hypothesis, shown in the plan, used by acquisition); it must not become the pre-registered criterion,
236
+ # or a model could move the gate by predicting a number. Every variant is judged against the gate a person fixed.
237
+ if _gate is None:
238
+ _spec_criteria = None
239
+ else:
240
+ # which assays are dose-response fits is domain data in the modality pack, shared with the plan
241
+ from proef.autoloop import criteria_for_assay
242
+ _c = criteria_for_assay(_assay, SuccessCriteria(
243
+ metric=_gate["metric"], direction=_gate["direction"], threshold=float(_gate["threshold"])),
244
+ modality)
245
+ _spec_criteria = {"metric": _c.metric, "direction": _c.direction, "threshold": _c.threshold}
246
+ spec = {
247
+ "predicted_by": {"source": "llm",
248
+ "model": str(getattr(model, "model_version",
249
+ "")
250
+ or getattr(model, "name",
251
+ "llm"))},
252
+ "statement": v.get("statement", ""),
253
+ "candidate": clean_candidate(v.get("candidate", "")),
254
+ "assay_type": _assay,
255
+ "criteria": _spec_criteria,
256
+ "predicted": v.get("predicted", v.get("statement", "")),
257
+ "predicted_value": v.get("predicted_value"),
258
+ "rationale": v.get("rationale", ""),
259
+ "variables": v.get("variables", {}),
260
+ "protocol": sanitize_protocol(v.get("protocol")),
261
+ }
262
+ if v.get("smiles"):
263
+ # the model's structure CLAIM, kept apart from the hypothesis and from any prediction: the ground step shows it (labelled as a claim) when it
264
+ # offers the compute tools, and nothing that selects or scores reads it
265
+ if not isinstance(getattr(tracker, "claimed_structures", None), dict):
266
+ tracker.claimed_structures = {}
267
+ tracker.claimed_structures[spec["candidate"]] = str(v["smiles"])[:400]
268
+ if tool_menu and (v.get("tools") or v.get("smiles")):
269
+ # the SMILES stays local to the prediction: it is the model's claim, so it is not written onto the
270
+ # hypothesis, where structure-keyed logic (series, applicability domain) would trust it
271
+ _preds = _REG.run(v.get("tools") if isinstance(v.get("tools"), list) else [], {"smiles": str(v.get("smiles") or "")},
272
+ predictors, modality)
273
+ spec["metadata"] = {**spec.get("metadata", {}), "predictions": _preds}
274
+ if menu:
275
+ # the model's pick is validated on FACTS (in the pool, declares the assay, is where this runs); its
276
+ # reasoning is never read. The result rides in the sealed proposal record.
277
+ from proef.labselect import check_pick
278
+ _chk = check_pick(v.get("instrument"), _assay, menu, runs_on, int((instruments or {}).get("max_bsl", 2)))
279
+ spec["metadata"] = {**spec.get("metadata", {}), "lab_pick": _chk["pick"], "lab_check": _chk}
280
+ for k in ("mechanism", "refutation_condition", "citation",
281
+ "predicted_observables"):
282
+ if fam.get(k) is not None:
283
+ spec[k] = fam[k]
284
+ elif v.get(k) is not None:
285
+ spec[k] = v[k]
286
+ specs.append({"family": fid, "parent_statement":
287
+ fam.get("parent_statement", ""), **spec})
288
+
289
+ # dedup against already-tried hypotheses + global total cap
290
+ existing = existing_keys or set()
291
+ seen: set[tuple[str, str]] = set()
292
+ kept_specs: list[dict[str, Any]] = []
293
+ for s_ in specs:
294
+ key = (s_["candidate"], s_["statement"])
295
+ if key in existing or key in seen:
296
+ say(f"dropped duplicate hypothesis: {s_['candidate']} — "
297
+ "already proposed/tried")
298
+ continue
299
+ if max_total_hypotheses is not None and len(kept_specs) >= max_total_hypotheses:
300
+ say(f"hypothesis budget reached ({max_total_hypotheses}) — "
301
+ "truncating portfolio (recorded)")
302
+ break
303
+ seen.add(key)
304
+ kept_specs.append(s_)
305
+ specs = kept_specs
306
+
307
+ # verify every cited reference — the "never invent" clause, enforced
308
+ cited = sorted({s.get("citation") for s in specs if s.get("citation")})
309
+ if cited:
310
+ from proef import citations
311
+ results = {c: citations.verify(c) for c in cited}
312
+ for s in specs:
313
+ c = s.get("citation")
314
+ if c and c in results:
315
+ s["citation_status"] = results[c]["status"]
316
+ s["citation_detail"] = results[c]["detail"]
317
+ summary = ", ".join(f"{c}={results[c]['status']}" for c in cited)
318
+ say(f"citation check: {summary}")
319
+ bad = [c for c in cited if results[c]["status"] == "invalid"]
320
+ if bad:
321
+ say(f"WARNING: {len(bad)} fabricated/unresolvable citation(s) "
322
+ "penalized in portfolio scoring")
323
+
324
+ variants = tracker.propose_families(problem, [
325
+ {**{k: f[k] for k in ("family", "parent_statement", "kind", "rationale")
326
+ if k in f}, "variants": [s for s in specs if s["family"] == f.get("family")]}
327
+ for f in families_in
328
+ ])
329
+ # carry per-variant tuned variables into hypothesis metadata
330
+ for h in variants:
331
+ for s in specs:
332
+ if s["candidate"] == h.candidate and s["statement"] == h.statement:
333
+ h.metadata["variables"] = s.get("variables", {})
334
+ if s.get("protocol"):
335
+ h.metadata["protocol"] = s["protocol"]
336
+ tracker.family_info = family_info # the plan shown to the person is built from these
337
+ tracker.family_scores = family_scores
338
+ return variants, family_scores
339
+
340
+
341
+ _LABEL_PREFIX = re.compile(r"^\s*(?:proposed|candidate|compound|sample|hypothesis)\s*[:_\-]\s*", re.I)
342
+
343
+
344
+ def clean_candidate(raw: Any) -> str:
345
+ """A model sometimes echoes a label into the name ("proposed: erlotinib", "proposed_osimertinib"). A candidate id is
346
+ the compound or sample name only, because it is what the lab sample, the plate and the verdict are keyed on."""
347
+ name = str(raw or "")
348
+ for _ in range(2):
349
+ name = _LABEL_PREFIX.sub("", name)
350
+ return name.strip()
351
+
352
+
353
+ def _extract_json(raw: str) -> dict[str, Any]:
354
+ text = raw.strip()
355
+ doc = None
356
+ try:
357
+ doc = json.loads(text)
358
+ except json.JSONDecodeError:
359
+ import re
360
+ m = re.search(r"\{.*\}", text, re.S)
361
+ if m:
362
+ doc = json.loads(m.group(0))
363
+ if not isinstance(doc, dict) or "families" not in doc:
364
+ raise ValueError(
365
+ "agent response must be a JSON object with a 'families' key — "
366
+ "use a model that follows the schema (see PROMPT): " + text[:120])
367
+ return doc
368
+
369
+
proef/ingest.py ADDED
@@ -0,0 +1,157 @@
1
+ """Institutional-memory ingestion — the inverse of `proef prove --eln`.
2
+
3
+ What the lab learned BEFORE Proef existed must count. `ingest_eln`
4
+ reads an ELN-style CSV — either the export format itself (proef prove
5
+ --eln) or a simple lab table (candidate,outcome,observed_uM,...) — and
6
+ feeds two places:
7
+
8
+ 1. the flywheel: negative memory ("ALREADY RULED OUT") and family
9
+ priors now include pre-Proef history, with the import source
10
+ stamped into evidence_run so history never masquerades as a live run;
11
+ 2. the provenance chain (optional): one gate_decision record per
12
+ scientific row under external/<file>, carrying the file's sha256 —
13
+ imports are auditable, and an edited-after-export CSV is LOUDLY
14
+ flagged (export_eln writes a .sha256 sidecar; we verify against it).
15
+
16
+ Nothing is silently dropped: every skipped row is reported with a
17
+ reason. Simulated/external data must say so (P-conventions).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import csv
22
+ import hashlib
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ VERDICT_MAP = { # lab vocabularies -> flywheel outcome
27
+ "confirmed": "confirmed", "validated": "validated", "active": "validated",
28
+ "hit": "validated",
29
+ "invalidated": "invalidated", "refuted": "refuted", "failed": "invalidated",
30
+ "rejected": "invalidated", "abandoned": "invalidated", "dead": "invalidated",
31
+ "inconclusive": "inconclusive", "abstained": "inconclusive",
32
+ "tested": "tested",
33
+ }
34
+ _ALIASES = {"outcome": "verdict", "result": "verdict", "status": "verdict",
35
+ "ic50_uM": "observed_uM", "ic50": "observed_uM",
36
+ "observed": "observed_uM", "potency_uM": "observed_uM",
37
+ "ci_low_uM": "ci95_low_uM", "ci_high_uM": "ci95_high_uM",
38
+ "compound": "candidate", "compound_id": "candidate",
39
+ "family_id": "family", "assay_type": "assay"}
40
+
41
+
42
+ def _num(s: Any) -> float | None:
43
+ try:
44
+ return float(s) if s not in ("", None) else None
45
+ except (TypeError, ValueError):
46
+ return None
47
+
48
+
49
+ def read_eln_csv(path: str | Path) -> list[dict[str, str]]:
50
+ """Rows normalized onto the ELN export column names (alias-mapped,
51
+ case-insensitive headers, BOM-tolerant)."""
52
+ p = Path(path)
53
+ raw = p.read_bytes()
54
+ text = raw.decode("utf-8-sig", errors="replace")
55
+ out: list[dict[str, str]] = []
56
+ for row in csv.DictReader(text.splitlines()):
57
+ norm = {}
58
+ for k, v in row.items():
59
+ if k is None:
60
+ continue
61
+ kk = k.strip().lower()
62
+ for alias, target in _ALIASES.items():
63
+ if kk == alias.lower():
64
+ kk = target.lower()
65
+ break
66
+ norm[kk] = (v or "").strip()
67
+ # ELN columns already lowercase; canonicalize the canonical names
68
+ for col in ("candidate", "verdict", "family", "assay", "observed_uM",
69
+ "ci95_low_uM", "ci95_high_uM", "threshold", "run_id",
70
+ "event", "branch", "record_hash"):
71
+ norm.setdefault(col, norm.get(col, ""))
72
+ out.append(norm)
73
+ return out
74
+
75
+
76
+ def ingest_eln(path: str | Path, *, flywheel: Any, store: Any = None,
77
+ problem_id: str | None = None, dry_run: bool = False,
78
+ branch_root: str = "external") -> dict[str, Any]:
79
+ """Import an ELN CSV into flywheel memory (+ provenance chain).
80
+
81
+ Returns {source, sha256, checksum_match, rows, ingested,
82
+ provenance_written, skipped:[{row, reason}]}."""
83
+ p = Path(path)
84
+ digest = hashlib.sha256(p.read_bytes()).hexdigest()
85
+ sidecar = p.with_suffix(p.suffix + ".sha256")
86
+ checksum_match: bool | None = None
87
+ if sidecar.exists(): # written by export_eln: the detached seal
88
+ expected = sidecar.read_text().split()[0] if sidecar.stat().st_size else ""
89
+ checksum_match = (expected == digest)
90
+ rows = read_eln_csv(p)
91
+ source_tag = f"eln:{p.name}:{digest[:8]}"
92
+ summary: dict[str, Any] = {"source": str(p), "sha256": digest,
93
+ "checksum_match": checksum_match,
94
+ "rows": len(rows), "ingested": 0,
95
+ "provenance_written": 0, "skipped": []}
96
+ if checksum_match is False:
97
+ summary["skipped"].append(
98
+ {"row": -1, "reason": "WARNING: .sha256 sidecar does not match "
99
+ "the CSV — the export was edited after "
100
+ "`proef prove --eln`; values were still "
101
+ "imported, but treat them as unsealed"})
102
+
103
+ records = []
104
+ for i, row in enumerate(rows):
105
+ cand = row.get("candidate") or ""
106
+ verdict = (row.get("verdict") or "").lower()
107
+ if not cand:
108
+ if verdict: # a scientific verdict with no candidate: unusable
109
+ summary["skipped"].append(
110
+ {"row": i, "reason": "no candidate column"})
111
+ continue # non-scientific event (problem_defined, review...)
112
+ if not verdict:
113
+ continue # structural row (proposed without verdict, gate...)
114
+ outcome = VERDICT_MAP.get(verdict)
115
+ if outcome is None:
116
+ summary["skipped"].append(
117
+ {"row": i, "reason": f"unknown verdict '{verdict}'"})
118
+ continue
119
+ observed = _num(row.get("observed_uM"))
120
+ lo, hi = _num(row.get("ci95_low_uM")), _num(row.get("ci95_high_uM"))
121
+ ci = (lo, hi) if lo is not None and hi is not None else None
122
+ run = row.get("run_id") or ""
123
+ if not dry_run:
124
+ flywheel.submit(cand, row.get("family") or None,
125
+ row.get("assay") or "imported", outcome,
126
+ observed, ci, problem_id=problem_id,
127
+ threshold=_num(row.get("threshold")),
128
+ evidence_run=(f"{run};{source_tag}" if run
129
+ else source_tag))
130
+ summary["ingested"] += 1
131
+ records.append({"candidate": cand, "outcome": outcome,
132
+ "observed": observed, "ci": list(ci) if ci else None,
133
+ "family": row.get("family", ""),
134
+ "assay": row.get("assay", ""),
135
+ "threshold": _num(row.get("threshold")),
136
+ "original_run_id": run,
137
+ "original_record_hash": row.get("record_hash", "")})
138
+
139
+ if store is not None and records and not dry_run:
140
+ from proef.core.contracts import Envelope, EventType
141
+ from proef.core.interfaces import record_for, system_actor
142
+ branch = f"{branch_root}/{p.stem}"
143
+ env = Envelope(experiment_branch_id=branch)
144
+ store.append(record_for(
145
+ env, EventType.gate_decision, system_actor("ingest"),
146
+ decision={"kind": "external_outcomes_imported",
147
+ "source_file": p.name, "source_sha256": digest,
148
+ "checksum_match": checksum_match,
149
+ "n_records": len(records), "problem_id": problem_id}))
150
+ for rec in records:
151
+ store.append(record_for(
152
+ env, EventType.gate_decision, system_actor("ingest"),
153
+ decision={"kind": "external_outcome", "imported": True,
154
+ "data_origin": f"imported from {source_tag}",
155
+ "problem_id": problem_id, **rec}))
156
+ summary["provenance_written"] = len(records) + 1
157
+ return summary