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
proef/taste.py ADDED
@@ -0,0 +1,177 @@
1
+ """Taste distillation — what distinguishes hypotheses scientists accept?
2
+
3
+ The Anthropic ART campaign treats its own hypothesis stream as an object
4
+ of study: which of thousands of agent reports were judged worth testing,
5
+ and what features did the keepers share? This module closes the same loop
6
+ over Proef's own provenance: every portfolio decision (selected or
7
+ rejected, with recorded reasons) is evidence about selection taste.
8
+
9
+ Output is a report of observed accept-rate deltas and DETERMINISTIC
10
+ amendment suggestions. Tighten-only by construction: the report proposes
11
+ prompt amendments for human review and never writes to prompts, gates,
12
+ or the agent's tool surface (same invariant as the advisory tier).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from pathlib import Path
17
+
18
+ PROVENANCE_DB = "proef.db"
19
+
20
+
21
+ def _features(recs) -> tuple[dict[str, dict], list[dict]]:
22
+ """(hypothesis_id -> feature map, [filter decisions]) from one
23
+ branch's records."""
24
+ feats: dict[str, dict] = {}
25
+ decisions: list[dict] = []
26
+ for r in recs:
27
+ if r.event_type.value == "hypothesis_proposed" and r.artifact:
28
+ d = r.decision or {}
29
+ meta = r.artifact.metadata or {}
30
+ cit = d.get("citation") or d.get("citation_detail") or ""
31
+ feats[r.artifact.artifact_id] = {
32
+ "candidate": str(meta.get("candidate")
33
+ or d.get("candidate") or "?"),
34
+ "mechanism": bool(d.get("mechanism")),
35
+ "refutation": bool(d.get("refutation_condition")),
36
+ "citation": bool(cit),
37
+ "citation_verified": (d.get("citation_status")
38
+ or meta.get("citation_status"))
39
+ == "verified",
40
+ "rationale": bool(d.get("rationale")),
41
+ "family": str(d.get("family") or ""),
42
+ }
43
+ elif r.event_type.value == "hypotheses_filtered":
44
+ decisions.extend((r.decision or {}).get("decisions", []))
45
+ return feats, decisions
46
+
47
+
48
+ def fold_taste(feats_all: dict[str, dict],
49
+ decisions_all: list[dict]) -> dict:
50
+ """Aggregate feature rows + filter decisions into a taste report
51
+ ({n, accepted, overall_rate, by_feature, families, amendments}).
52
+ One decision per hypothesis (latest wins)."""
53
+ # fold: one decision per hypothesis (latest wins)
54
+ by_hid: dict[str, dict] = {}
55
+ for d in decisions_all:
56
+ by_hid[d.get("hypothesis_id")] = d
57
+ rows = []
58
+ for hid, d in by_hid.items():
59
+ f = feats_all.get(hid)
60
+ if not f:
61
+ continue
62
+ rows.append({**f, "selected": bool(d.get("selected")),
63
+ "reason": d.get("reason") or ""})
64
+ n = len(rows)
65
+ acc = sum(1 for r in rows if r["selected"])
66
+ overall = acc / n if n else 0.0
67
+
68
+ def rate(key: str) -> dict:
69
+ with_f = [r for r in rows if r[key]]
70
+ without = [r for r in rows if not r[key]]
71
+ rw = (sum(1 for r in with_f if r["selected"]) / len(with_f)
72
+ if with_f else None)
73
+ rwo = (sum(1 for r in without if r["selected"]) / len(without)
74
+ if without else None)
75
+ return {"n": len(with_f), "rate": round(rw, 3) if rw is not None
76
+ else None, "rate_without": round(rwo, 3) if rwo is not None
77
+ else None}
78
+
79
+ by_feature = {k: rate(k) for k in
80
+ ("mechanism", "refutation", "citation",
81
+ "citation_verified", "rationale")}
82
+
83
+ fams: dict[str, dict] = {}
84
+ for r in rows:
85
+ if not r["family"]:
86
+ continue
87
+ f = fams.setdefault(r["family"], {"n": 0, "accepted": 0})
88
+ f["n"] += 1
89
+ f["accepted"] += 1 if r["selected"] else 0
90
+
91
+ amendments: list[str] = []
92
+ for key, label in (("mechanism", "a stated mechanism"),
93
+ ("citation_verified", "a VERIFIED citation"),
94
+ ("refutation", "a refutation condition")):
95
+ s = by_feature[key]
96
+ if s["rate"] is None or s["rate_without"] is None:
97
+ continue
98
+ cov = s["n"] / n if n else 0.0
99
+ if s["rate"] > s["rate_without"] * 1.3 and s["n"] >= 3:
100
+ # rewarded — only actionable when proposals lack headroom;
101
+ # near-universal coverage just confirms the existing prompt
102
+ if cov < 0.8:
103
+ amendments.append(
104
+ f"{label} is the strongest acceptance signal so far "
105
+ f"({s['rate']:.0%} vs {s['rate_without']:.0%}) but only "
106
+ f"{cov:.0%} of proposals carry it — tightening the "
107
+ f"generator's requirement has clear headroom")
108
+ elif s["rate"] < s["rate_without"] * 0.7 and s["n"] >= 3:
109
+ amendments.append(
110
+ f"hypotheses with {label} are accepted LESS "
111
+ f"({s['rate']:.0%} vs {s['rate_without']:.0%}) — review "
112
+ f"whether the requirement adds noise")
113
+ dead = [fam for fam, f in fams.items()
114
+ if f["n"] >= 3 and f["accepted"] == 0]
115
+ for fam in dead:
116
+ amendments.append(
117
+ f"family '{fam}' proposed {fams[fam]['n']}x, never selected — "
118
+ f"consider excluding it from proposal prompts")
119
+ return {"n": n, "accepted": acc,
120
+ "overall_rate": round(overall, 3) if n else 0.0,
121
+ "by_feature": by_feature, "families": fams,
122
+ "amendments": amendments}
123
+
124
+
125
+ def taste_report(db_path: str | Path | None = None) -> dict:
126
+ """Aggregate accept/reject rates by hypothesis feature across all
127
+ provenance branches. Returns {n, accepted, overall_rate, by_feature,
128
+ families, amendments} — amendments are strings, advisory only."""
129
+ db_path = db_path or PROVENANCE_DB
130
+ from proef.adapters.store.sqlite import get_store
131
+ store = get_store(str(db_path))
132
+ feats_all: dict[str, dict] = {}
133
+ decisions_all: list[dict] = []
134
+ for br in store.branches():
135
+ if not br.startswith("problem/"):
136
+ continue
137
+ try:
138
+ recs = store.branch_records(br)
139
+ except Exception:
140
+ continue
141
+ feats, decisions = _features(recs)
142
+ feats_all.update(feats)
143
+ decisions_all.extend(decisions)
144
+ return fold_taste(feats_all, decisions_all)
145
+
146
+
147
+ def render_taste(report: dict) -> str:
148
+ """Human-readable taste report (proef taste)."""
149
+ if not report["n"]:
150
+ return "no portfolio decisions with feature data yet — run a " \
151
+ "campaign first"
152
+ lines = [f"portfolio decisions: {report['n']} "
153
+ f"({report['accepted']} accepted, "
154
+ f"{report['overall_rate']:.0%} overall)"]
155
+ labels = {"mechanism": "mechanism stated", "refutation": "refutation "
156
+ "condition", "citation": "citation present",
157
+ "citation_verified": "citation VERIFIED",
158
+ "rationale": "rationale present"}
159
+ for key, label in labels.items():
160
+ s = report["by_feature"][key]
161
+ if s["rate"] is not None:
162
+ base = f" {label}: {s['rate']:.0%} accepted (n={s['n']})"
163
+ if s["rate_without"] is not None:
164
+ base += f" vs {s['rate_without']:.0%} without"
165
+ lines.append(base)
166
+ dead = {f: v for f, v in report["families"].items()
167
+ if v["n"] >= 3 and v["accepted"] == 0}
168
+ if dead:
169
+ lines.append("never-selected families: "
170
+ + ", ".join(sorted(dead)))
171
+ if report["amendments"]:
172
+ lines.append("proposed amendments (advisory — human review "
173
+ "required, nothing is applied):")
174
+ lines.extend(f" • {a}" for a in report["amendments"])
175
+ else:
176
+ lines.append("no amendment suggestions at current sample size")
177
+ return "\n".join(lines)
@@ -0,0 +1,34 @@
1
+ {
2
+ "template": "confirmatory-followup",
3
+ "description": "Confirm a lead with an orthogonal assay, then a counterscreen",
4
+ "problem": {
5
+ "objective": "Confirm {lead} activity in an orthogonal assay and rule out assay interference",
6
+ "constraints": [
7
+ {
8
+ "name": "confirmation",
9
+ "description": "activity confirmed in >= 1 orthogonal assay",
10
+ "kind": "hard"
11
+ }
12
+ ],
13
+ "success_metric": "confirmed lead with clean counterscreen"
14
+ },
15
+ "hypotheses": [],
16
+ "hypothesis_source": "agent",
17
+ "autonomy": "gate",
18
+ "assay": {
19
+ "type": "enzymatic",
20
+ "concentrations": [
21
+ "0.5uM",
22
+ "2uM",
23
+ "10uM",
24
+ "40uM"
25
+ ],
26
+ "counterscreen": true
27
+ },
28
+ "fields": {
29
+ "lead": {
30
+ "prompt": "Lead compound ID",
31
+ "required": true
32
+ }
33
+ }
34
+ }
@@ -0,0 +1,39 @@
1
+ {
2
+ "template": "dose-response-screen",
3
+ "description": "Screen a compound list through a dose-response assay and rank by potency",
4
+ "problem": {
5
+ "objective": "Rank compounds by binding potency and identify those with IC50 <= {threshold} uM",
6
+ "constraints": [
7
+ {
8
+ "name": "potency",
9
+ "description": "IC50 <= 20 uM",
10
+ "kind": "hard",
11
+ "limit": 20.0,
12
+ "unit": "uM"
13
+ }
14
+ ],
15
+ "success_metric": "IC50 ranking consistent across replicates"
16
+ },
17
+ "hypotheses": [],
18
+ "hypothesis_source": "agent",
19
+ "autonomy": "gate",
20
+ "assay": {
21
+ "type": "binding",
22
+ "concentrations": [
23
+ "0.5uM",
24
+ "2uM",
25
+ "10uM",
26
+ "40uM"
27
+ ]
28
+ },
29
+ "fields": {
30
+ "compounds": {
31
+ "prompt": "Compound IDs to screen (comma-separated)",
32
+ "required": true
33
+ },
34
+ "threshold": {
35
+ "prompt": "Potency threshold (uM)",
36
+ "default": 20
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,38 @@
1
+ {
2
+ "template": "sar-exploration",
3
+ "description": "Explore SAR across a chemotype: dose-response + selectivity panel",
4
+ "problem": {
5
+ "objective": "Map the SAR of the {chemotype} chemotype against {target}",
6
+ "constraints": [
7
+ {
8
+ "name": "diversity",
9
+ "description": "at least 2 mechanistic families explored",
10
+ "kind": "hard"
11
+ }
12
+ ],
13
+ "success_metric": "SAR trend established (monotonic potency vs substitution)"
14
+ },
15
+ "hypotheses": [],
16
+ "hypothesis_source": "agent",
17
+ "autonomy": "observe",
18
+ "assay": {
19
+ "type": "binding",
20
+ "concentrations": [
21
+ "0.1uM",
22
+ "1uM",
23
+ "10uM",
24
+ "50uM"
25
+ ],
26
+ "selectivity_panel": true
27
+ },
28
+ "fields": {
29
+ "chemotype": {
30
+ "prompt": "Chemotype name",
31
+ "required": true
32
+ },
33
+ "target": {
34
+ "prompt": "Target (e.g. EGFR, HPK1)",
35
+ "required": true
36
+ }
37
+ }
38
+ }
proef/templates.py ADDED
@@ -0,0 +1,124 @@
1
+ """Campaign templates — scientist-callable presets.
2
+
3
+ `proef templates` lists them; `proef campaign auto --template dose-response-screen
4
+ --field compounds=C1,C2,C3` fills the template (prompts for missing required
5
+ fields), turns the compound list into a hypothesis portfolio, and runs the
6
+ campaign. Users never see JSON unless they want to.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ TEMPLATE_DIR = Path(__file__).parent / "templates"
15
+ USER_TEMPLATE_DIR = Path(".data/templates") # drop your own .json here
16
+
17
+
18
+ def list_templates() -> list[dict[str, str]]:
19
+ out = []
20
+ seen = set()
21
+ for d in (TEMPLATE_DIR, USER_TEMPLATE_DIR):
22
+ if not d.exists():
23
+ continue
24
+ for f in sorted(d.glob("*.json")):
25
+ doc = json.loads(f.read_text())
26
+ name = doc["template"]
27
+ if name in seen:
28
+ continue
29
+ seen.add(name)
30
+ out.append({"name": name,
31
+ "description": doc.get("description", ""),
32
+ "source": "user" if d == USER_TEMPLATE_DIR else "built-in"})
33
+ return out
34
+
35
+
36
+ def load_template(name: str) -> dict[str, Any]:
37
+ for d in (USER_TEMPLATE_DIR, TEMPLATE_DIR): # user overrides built-in
38
+ path = d / f"{name}.json"
39
+ if path.exists():
40
+ return json.loads(path.read_text())
41
+ raise FileNotFoundError(
42
+ f"unknown template '{name}' — available: "
43
+ + ", ".join(t["name"] for t in list_templates()))
44
+
45
+
46
+ def save_user_template(name: str, description: str, problem: dict[str, Any],
47
+ assay: dict[str, Any]) -> Path:
48
+ """Persist a reusable template under .data/templates/<name>.json."""
49
+ from proef.paths import ensure_dirs
50
+ ensure_dirs()
51
+ USER_TEMPLATE_DIR.mkdir(parents=True, exist_ok=True)
52
+ safe = "".join(c for c in name.lower() if c.isalnum() or c in "-_")
53
+ path = USER_TEMPLATE_DIR / f"{safe}.json"
54
+ path.write_text(json.dumps({
55
+ "template": safe,
56
+ "description": description,
57
+ "problem": problem,
58
+ "hypotheses": [],
59
+ "hypothesis_source": "config",
60
+ "autonomy": "gate",
61
+ "assay": assay,
62
+ "fields": {
63
+ "compounds": {"prompt": "Compounds (comma-separated)",
64
+ "required": True},
65
+ "threshold": {"prompt": "Potency threshold (uM)",
66
+ "default": 20},
67
+ },
68
+ }, indent=1))
69
+ return path
70
+
71
+
72
+ def fill(template: dict[str, Any], fields: dict[str, str],
73
+ prompt_missing: bool = True) -> dict[str, Any]:
74
+ """Interpolate {placeholders} from fields; prompt (or error) on missing
75
+ required fields. Returns the rendered template doc."""
76
+ values = dict(fields)
77
+ for key, spec in template.get("fields", {}).items():
78
+ if key in values:
79
+ continue
80
+ if spec.get("default") is not None:
81
+ values[key] = str(spec["default"])
82
+ elif prompt_missing:
83
+ values[key] = input(f"{spec['prompt']}: ").strip()
84
+ elif spec.get("required"):
85
+ raise ValueError(f"missing required field '{key}' ({spec['prompt']})")
86
+
87
+ def sub(obj: Any) -> Any:
88
+ if isinstance(obj, str):
89
+ for k, v in values.items():
90
+ obj = obj.replace("{" + k + "}", v)
91
+ return obj
92
+ if isinstance(obj, list):
93
+ return [sub(x) for x in obj]
94
+ if isinstance(obj, dict):
95
+ return {k: sub(v) for k, v in obj.items()}
96
+ return obj
97
+
98
+ rendered = sub({k: v for k, v in template.items() if k != "fields"})
99
+ rendered["_values"] = values
100
+ return rendered
101
+
102
+
103
+ def build_campaign(rendered: dict[str, Any]) -> dict[str, Any]:
104
+ """Turn a filled template into a campaign config (the `proef campaign auto` JSON):
105
+ compounds become one hypothesis each with the template's potency criteria."""
106
+ compounds = [c.strip() for c in
107
+ rendered.get("_values", {}).get("compounds", "").split(",") if c.strip()]
108
+ threshold = float(rendered.get("_values", {}).get("threshold", 20) or 20)
109
+ assay = rendered.get("assay", {})
110
+ concs = assay.get("concentrations", ["0.5uM", "2uM", "10uM", "40uM"])
111
+ hypotheses = [
112
+ {"statement": f"{c} binds with IC50 <= {threshold:g} uM",
113
+ "candidate": c, "assay_type": assay.get("type", "binding"),
114
+ "predicted": f"IC50 <= {threshold:g}", "predicted_value": threshold,
115
+ "rationale": ""}
116
+ for c in compounds
117
+ ]
118
+ return {
119
+ "problem": rendered["problem"],
120
+ "hypotheses": hypotheses,
121
+ "k": int(rendered.get("_values", {}).get("k", 2) or 2),
122
+ "autonomy": rendered.get("autonomy", "gate"),
123
+ "concentrations": concs,
124
+ }