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,199 @@
1
+ """ProteinDesignLabAdapter — protein binder design through Proef's
2
+ hypothesis pipeline, not around it.
3
+
4
+ Architecture (mirrors the small-molecule DMTA loop, modality-agnostic):
5
+
6
+ Layer 1 GENERATE BindCraft produces candidate sequences (batch output,
7
+ no per-sequence provenance — they're candidates, not claims)
8
+ Layer 2 FLOOR quality floor: sequence sanity, minimum pLDDT — physics,
9
+ not a limit. ALL survivors become hypotheses (free: they're
10
+ claims, not commitments)
11
+ Layer 3 HYPOTHESIZE every floor-passing design is provenance-chained as a
12
+ hypothesis via HypothesisTracker (predicted_by: bindcraft)
13
+ Layer 4 PRIORITIZE screening budget allocated by diversity + confidence
14
+ signal — the GPU constraint lives HERE, not at the
15
+ hypothesis layer
16
+ Layer 5 SCREEN Boltz-1 interface confidence per prioritized design;
17
+ CI-aware verdicts only for screened designs; unscreened
18
+ hypotheses stay 'proposed' — visible, never discarded
19
+
20
+ The agent proposes the design STRATEGY (target, hotspots, scaffold hints);
21
+ this adapter executes it; Proef's verdict machinery scores the results.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import random
26
+ import random
27
+ import tempfile
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ from proef.core.contracts.models import (
32
+ AssayResult, Envelope, InstrumentInfo, Measurement, ProtocolSubmission,
33
+ QCInfo, RunStatus,
34
+ )
35
+
36
+
37
+ class ProteinDesignLabAdapter:
38
+ """LabAdapter for protein binder design (BindCraft + Boltz-1)."""
39
+
40
+ name = "protein-design"
41
+
42
+ def __init__(self, mock: bool = False, seed: int = 42,
43
+ work_dir: str | None = None,
44
+ bindcraft_dir: str | None = None,
45
+ boltz_venv: str | None = None,
46
+ min_plddt: float = 0.6,
47
+ quality_floor: dict[str, Any] | None = None):
48
+ self.mock = mock
49
+ self.seed = seed
50
+ self.work_dir = Path(work_dir or tempfile.mkdtemp(prefix="prot-design-"))
51
+ self.work_dir.mkdir(parents=True, exist_ok=True)
52
+ self.bindcraft_dir = bindcraft_dir
53
+ self.boltz_venv = boltz_venv
54
+ self.min_plddt = min_plddt
55
+ self.quality_floor = quality_floor or {}
56
+ self._runs: dict[str, dict[str, Any]] = {}
57
+
58
+ def list_capabilities(self) -> dict[str, Any]:
59
+ return {
60
+ "assays": ["protein_binder_design"],
61
+ "modalities": ["protein"],
62
+ "make_tool": "BindCraft (AF2 backprop + ProteinMPNN)",
63
+ "test_tool": "Boltz-1 (interface confidence)",
64
+ "throughput": "~8 designs/hour on RTX 3090",
65
+ "hypothesis_model": "all quality-passing designs become hypotheses; "
66
+ "budget constrains screening, not proposing",
67
+ }
68
+
69
+ def generate(self, target_pdb: str, hotspot: str,
70
+ lengths: tuple[int, int], n_attempts: int,
71
+ run_id: str) -> list[dict[str, Any]]:
72
+ """Layer 1: BindCraft (or mock) generates candidate designs."""
73
+ if self.mock:
74
+ rng = random.Random(self.seed)
75
+ return [{"name": f"mock-{run_id}-{i:03d}",
76
+ "sequence": "".join(rng.choice("ACDEFGHIKLMNPQRSTVWY")
77
+ for _ in range(rng.randint(70, 120))),
78
+ "plddt": round(rng.uniform(0.3, 1.0), 3)}
79
+ for i in range(n_attempts)]
80
+ raise NotImplementedError("real BindCraft: see runpack/jobrunner.py")
81
+
82
+ def apply_quality_floor(self, designs: list[dict[str, Any]],
83
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
84
+ """Layer 2: quality floor. Returns (passing, rejected)."""
85
+ passing, rejected = [], []
86
+ for d in designs:
87
+ reasons = []
88
+ if d.get("plddt", 0) < self.min_plddt:
89
+ reasons.append(f"pLDDT {d['plddt']} < {self.min_plddt}")
90
+ seq = d.get("sequence", "")
91
+ if len(seq) < 40 or len(seq) > 250:
92
+ reasons.append(f"length {len(seq)} outside [40, 250]")
93
+ if set(seq) - set("ACDEFGHIKLMNPQRSTVWY"):
94
+ reasons.append("non-standard residues")
95
+ if reasons:
96
+ d["rejection_reasons"] = reasons
97
+ rejected.append(d)
98
+ else:
99
+ passing.append(d)
100
+ return passing, rejected
101
+
102
+ def prioritize(self, designs: list[dict[str, Any]],
103
+ budget: int) -> list[dict[str, Any]]:
104
+ """Layer 4: allocate screening budget by diversity + confidence.
105
+ Farthest-first over aa k-mer sets among the top-confidence designs.
106
+ Designs NOT selected stay as untested hypotheses — never discarded."""
107
+ if len(designs) <= budget:
108
+ return designs
109
+ ranked = sorted(designs, key=lambda d: -d.get("plddt", 0))
110
+ picked = [ranked[0]]
111
+ remaining = ranked[1:]
112
+ while len(picked) < budget and remaining:
113
+ best_i, best_min_sim = 0, 2.0
114
+ for i, cand in enumerate(remaining):
115
+ sims = [self._seq_sim(cand["sequence"], p["sequence"])
116
+ for p in picked[-20:]] # vs last 20 picks
117
+ min_sim = min(sims) if sims else 0.0
118
+ if min_sim < best_min_sim:
119
+ best_min_sim = min_sim
120
+ best_i = i
121
+ picked.append(remaining.pop(best_i))
122
+ return picked
123
+
124
+ @staticmethod
125
+ def _seq_sim(a: str, b: str, k: int = 3) -> float:
126
+ ka = {hash(a[i:i+k]) for i in range(max(0, len(a) - k + 1))}
127
+ kb = {hash(b[i:i+k]) for i in range(max(0, len(b) - k + 1))}
128
+ if not ka or not kb:
129
+ return 0.0
130
+ return len(ka & kb) / len(ka | kb)
131
+
132
+ def screen(self, designs: list[dict[str, Any]],
133
+ target_sequence: str) -> list[dict[str, Any]]:
134
+ """Layer 5: Boltz-1 interface confidence (or mock)."""
135
+ if self.mock:
136
+ rng = random.Random(self.seed + 2)
137
+ for d in designs:
138
+ d["iptm"] = round(rng.random(), 3)
139
+ d["uncertainty"] = round(rng.random() * 0.08, 4)
140
+ return designs
141
+ raise NotImplementedError("real Boltz: see runpack/jobrunner.py")
142
+
143
+ # ---- convenience: full pipeline ----------------------------------------
144
+
145
+ def run_design_cycle(self, tracker, problem, target_sequence: str,
146
+ n_attempts: int = 100, screening_budget: int = 50,
147
+ iptm_gate: float = 0.7,
148
+ ) -> dict[str, Any]:
149
+ """Full design cycle: generate → floor → hypothesize → prioritize
150
+ → screen → verdict. ALL floor-passing designs become hypotheses;
151
+ only screened designs get verdicts; the rest stay 'proposed' —
152
+ visible in the series view, ready for the next budget round."""
153
+ from proef.core.hypothesis import SuccessCriteria
154
+
155
+ designs = self.generate(target_sequence, "56", (70, 120), n_attempts, "cycle")
156
+ passing, rejected = self.apply_quality_floor(designs)
157
+
158
+ criteria = SuccessCriteria(metric="iptm", direction="max",
159
+ threshold=iptm_gate)
160
+ hypotheses = []
161
+ for d in passing:
162
+ h = tracker.propose(
163
+ statement=f"Binder {d['name']} binds target (ipTM ≥ {iptm_gate})",
164
+ candidate=d["name"],
165
+ assay_type="protein_binder",
166
+ predicted=f"ipTM ≥ {iptm_gate}",
167
+ predicted_value=d.get("plddt"),
168
+ criteria=criteria,
169
+ rationale="BindCraft design (predicted_by: bindcraft, "
170
+ "protein-design adapter)",
171
+ branch_id=f"problem/{problem.problem_id}",
172
+ predicted_by={"source": "bindcraft", "policy": "AF2-backprop+MPNN"},
173
+ )
174
+ hypotheses.append((h, d))
175
+
176
+ prioritized = self.prioritize(passing, screening_budget)
177
+ prio_names = {d["name"] for d in prioritized}
178
+
179
+ screened = self.screen([d for d in prioritized], target_sequence)
180
+ screen_by_name = {d["name"]: d for d in screened}
181
+
182
+ verdicts = {"confirmed": 0, "refuted": 0, "abstained": 0,
183
+ "proposed": 0}
184
+ for h, d in hypotheses:
185
+ s = screen_by_name.get(d["name"])
186
+ if s and d["name"] in prio_names:
187
+ verdict = criteria.classify(s["iptm"], None)
188
+ h.status = {"validated": "validated",
189
+ "invalidated": "invalidated",
190
+ "inconclusive": "inconclusive"}[verdict]
191
+ verdicts[h.status] = verdicts.get(h.status, 0) + 1
192
+ elif d["name"] not in prio_names:
193
+ verdicts["proposed"] = verdicts.get("proposed", 0) + 1
194
+
195
+ return {"hypotheses": hypotheses, "verdicts": verdicts,
196
+ "screened": screen_by_name, "prioritized": prio_names,
197
+ "rejected_by_floor": len(rejected),
198
+ "n_generated": len(designs),
199
+ "n_hypotheses": len(passing)}
@@ -0,0 +1,119 @@
1
+ """Recording / playback harness for hardware adapters (T3.3, P8).
2
+
3
+ Record real lab interactions once, replay them forever in CI:
4
+
5
+ real = MyRobotLab(api_key=...)
6
+ rec = RecordingLab(real, "robot-session.json") # wrap & record
7
+ # ... run workflows through the LabGateway with `rec` ...
8
+
9
+ ci_lab = PlaybackLab("robot-session.json") # replays identically, offline
10
+
11
+ Playback determinism is the point: a hardware bug captured in the field is a
12
+ regression test forever.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from proef.core.contracts import (
21
+ AssayResult,
22
+ Envelope,
23
+ InstrumentInfo,
24
+ ProtocolSubmission,
25
+ RunStatus,
26
+ )
27
+
28
+
29
+ class RecordingLab:
30
+ """Wraps a LabAdapter; records every call + return value to JSON."""
31
+
32
+ name = "recording"
33
+
34
+ def __init__(self, inner: Any, path: str | Path):
35
+ self.inner = inner
36
+ self.path = Path(path)
37
+ self._log: list[dict[str, Any]] = []
38
+
39
+ def list_capabilities(self) -> dict[str, Any]:
40
+ caps = self.inner.list_capabilities()
41
+ self._log.append({"op": "list_capabilities", "result": caps})
42
+ return caps
43
+
44
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
45
+ run_id = self.inner.submit_protocol(protocol)
46
+ self._log.append({
47
+ "op": "submit_protocol",
48
+ "protocol": protocol.model_dump(mode="json"),
49
+ "result": run_id,
50
+ })
51
+ return run_id
52
+
53
+ def get_status(self, run_id: str) -> str:
54
+ status = self.inner.get_status(run_id)
55
+ self._log.append({"op": "get_status", "run_id": run_id, "result": status})
56
+ return status
57
+
58
+ def fetch_results(self, run_id: str) -> AssayResult:
59
+ result = self.inner.fetch_results(run_id)
60
+ self._log.append({
61
+ "op": "fetch_results",
62
+ "run_id": run_id,
63
+ "result": result.model_dump(mode="json"),
64
+ })
65
+ return result
66
+
67
+ def cancel(self, run_id: str) -> None:
68
+ self._log.append({"op": "cancel", "run_id": run_id})
69
+ self.inner.cancel(run_id)
70
+
71
+ def save(self) -> Path:
72
+ self.path.write_text(json.dumps(self._log, indent=1))
73
+ return self.path
74
+
75
+
76
+ class PlaybackLab:
77
+ """Replays a recording. Offline, deterministic, identical results."""
78
+
79
+ name = "playback"
80
+
81
+ def __init__(self, path: str | Path, seed_branch: str = "playback"):
82
+ entries = json.loads(Path(path).read_text())
83
+ self._capabilities: dict[str, Any] = {}
84
+ self._submit_by_protocol: dict[str, str] = {} # protocol_id -> run_id
85
+ self._status: dict[str, str] = {}
86
+ self._results: dict[str, dict] = {}
87
+ for e in entries:
88
+ if e["op"] == "list_capabilities":
89
+ self._capabilities = e["result"]
90
+ elif e["op"] == "submit_protocol":
91
+ self._submit_by_protocol[e["protocol"]["protocol_id"]] = e["result"]
92
+ elif e["op"] == "get_status":
93
+ self._status[e["run_id"]] = e["result"]
94
+ elif e["op"] == "fetch_results":
95
+ self._results[e["run_id"]] = e["result"]
96
+
97
+ def list_capabilities(self) -> dict[str, Any]:
98
+ return dict(self._capabilities)
99
+
100
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
101
+ run_id = self._submit_by_protocol.get(protocol.protocol_id)
102
+ if run_id is None:
103
+ raise LookupError(
104
+ f"protocol {protocol.protocol_id} not in recording — "
105
+ "recorded sessions are replay-only, not simulated"
106
+ )
107
+ return run_id
108
+
109
+ def get_status(self, run_id: str) -> str:
110
+ return self._status.get(run_id, "failed")
111
+
112
+ def fetch_results(self, run_id: str) -> AssayResult:
113
+ data = self._results.get(run_id)
114
+ if data is None:
115
+ raise LookupError(f"run {run_id} not in recording")
116
+ return AssayResult.model_validate(data)
117
+
118
+ def cancel(self, run_id: str) -> None:
119
+ pass # nothing to cancel in playback
@@ -0,0 +1,107 @@
1
+ """ReplayLab — published measurements as lab truth, honestly labeled.
2
+
3
+ A LabAdapter whose ground truth is REAL experimental data (e.g. ChEMBL
4
+ deposited IC50s), not simulated pharmacology. The loop runs its genuine
5
+ machinery — plate exports, Hill fits, residual-bootstrap CIs, orthogonal
6
+ confirmations, safety gates, provenance — against measured values, which is
7
+ what makes downstream case studies prospective tests of the process rather
8
+ than circular tests of the simulator.
9
+
10
+ Honesty contract (enforced, not aspirational):
11
+ - instrument identity says what it is: name "replay-published",
12
+ version "replay-v1"; capabilities() spells out the one synthesized
13
+ element: the CURVE SHAPE is a Hill response drawn around the published
14
+ IC50; the IC50 itself is the measured value. Plate noise is a declared
15
+ seeded measurement model.
16
+ - unknown candidates RAISE. There is no invented number in this adapter.
17
+ - property-metric campaigns are refused loudly: replaying a potency
18
+ curve as a "property readout" would be nonsense dressed as data.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from typing import Any
23
+
24
+ from proef.core.contracts import (AssayResult, Envelope, InstrumentInfo,
25
+ Measurement, RunStatus)
26
+
27
+
28
+ class ReplayLab:
29
+ name = "replay-published"
30
+ version = "replay-v1"
31
+ replicates = 3
32
+
33
+ def __init__(self, values: dict[str, float],
34
+ sources: dict[str, dict] | None = None,
35
+ seed: int = 42, unit: str = "uM"):
36
+ """values: candidate_id -> measured IC50 in `unit` (µM by default).
37
+ sources: optional candidate_id -> provenance {assay_ids, n, ...},
38
+ surfaced in capabilities and recorded per-result metadata."""
39
+ self.values = dict(values)
40
+ self.sources = dict(sources or {})
41
+ self.seed = seed
42
+ self.unit = unit
43
+ self._runs: dict[str, list[str]] = {}
44
+ self._n = 0
45
+
46
+ # --------------------------------------------------------- LabAdapter
47
+
48
+ def list_capabilities(self) -> dict:
49
+ return {
50
+ "assays": ["binding", "enzymatic"],
51
+ "readout": "published-measurement-replay",
52
+ "bsl_max": 1,
53
+ "truth": (f"{len(self.values)} published IC50 measurements "
54
+ f"(seeded synthetic plate noise; Hill curve SHAPE "
55
+ f"synthesized around the measured IC50 — the IC50 "
56
+ f"is real, the wells are replay)"),
57
+ "data_origin": "literature (ChEMBL-deposited)",
58
+ }
59
+
60
+ def submit_protocol(self, protocol: Any) -> str:
61
+ self._n += 1
62
+ rid = f"replay-{self._n:03d}"
63
+ self._runs[rid] = [s.sample_id for s in protocol.samples
64
+ if not s.sample_id.startswith("ctrl")]
65
+ return rid
66
+
67
+ def get_status(self, run_id: str) -> str:
68
+ return "done"
69
+
70
+ def fetch_results(self, run_id: str) -> AssayResult:
71
+ samples = self._runs.get(run_id, [])
72
+ ms = []
73
+ for s in samples:
74
+ ic50 = self.true_ic50_um(run_id, s)
75
+ ms.append(Measurement(
76
+ sample_id=s, assay_type="potency", value=ic50,
77
+ unit=f"IC50_{self.unit}", replicate=self.replicates,
78
+ derived_metrics={"published_ic50_um": ic50},
79
+ metadata=self.sources.get(s, {})))
80
+ return AssayResult(
81
+ envelope=Envelope(experiment_branch_id="replay"),
82
+ protocol_id=run_id, run_id=run_id,
83
+ instrument=InstrumentInfo(adapter=self.name,
84
+ instrument_id=self.version),
85
+ status=RunStatus.completed, measurements=ms,
86
+ qc={"controls_passed": True})
87
+
88
+ def cancel(self, run_id: str) -> None:
89
+ pass
90
+
91
+ # ------------------------------------------------- replay truth hooks
92
+
93
+ def true_ic50_um(self, run_id: str, candidate: str) -> float:
94
+ """The published IC50 in µM — or a loud refusal. No invention."""
95
+ if candidate not in self.values:
96
+ raise KeyError(
97
+ f"ReplayLab has no published measurement for "
98
+ f"'{candidate}' — refusing to invent one "
99
+ f"(source corpus covers {len(self.values)} compounds)")
100
+ return float(self.values[candidate])
101
+
102
+ def set_property_gate(self, metric: str, direction: str,
103
+ threshold: float) -> None:
104
+ raise NotImplementedError(
105
+ "ReplayLab replays potency measurements only; a property-metric "
106
+ "campaign would read dose-response curves as a property value. "
107
+ "Use a lab that measures this property.")