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,222 @@
1
+ """Opentrons OT-2 / Flex driver — pinned to the PUBLISHED HTTP API contract.
2
+
3
+ Contract source (retrieved Oct 10, 2026):
4
+ - Opentrons/opentrons-integration-tools http-api/README.md (v3 flow:
5
+ POST /protocols multipart `files=@x.py`, POST /runs
6
+ {"data":{"protocolId":...}}, POST /runs/{id}/actions
7
+ {"data":{"actionType":"play"|"pause"|"stop"}},
8
+ GET /runs/{id}, GET /runs/{id}/commands)
9
+ - Opentrons/http-api-beta readme (v2 sessions; header requirements)
10
+ - every request carries the mandatory `Opentrons-Version` header
11
+ (docs.opentrons.com/http: "header Parameters |opentrons-version
12
+ required")
13
+
14
+ CONTRACT CROSS-CHECK (Oct 10, independent second reading): K-Dense
15
+ LabMCP's opentrons server (github.com/K-Dense-AI/lab-instrument-mcps)
16
+ confirms port 31950 + Opentrons-Version: 3 + the integration-tools
17
+ guide as the source of truth, and adds the decisive detail: every robot
18
+ serves its full OpenAPI spec at /openapi.json — so a hardware session
19
+ can machine-diff this driver against the actual device. SAFETY STANCE
20
+ adopted from the same source: stateless single-move commands are NOT
21
+ exposed (POST /runs/{id}/commands without authoritative deck state can
22
+ crash pipettes into labware); only complete, analyzed protocols run.
23
+
24
+ HONEST STATUS (S-T4): payloads conform to the documented contract and
25
+ CI runs them against ot2_sim.py — a spec-conformant SIMULATED robot that
26
+ rejects what a real robot would reject (missing header -> 400, wrong
27
+ multipart field -> 422). What remains hardware-only is behavior the docs
28
+ don't pin down (timings, analysis quirks, firmware drift): a physical
29
+ OT-2/Flex session can confirm, not replace, this conformance layer.
30
+
31
+ Semantics with the platform: Opentrons is the **Make** step of DMTA.
32
+ `fetch_results` returns execution evidence (run commands), not assay
33
+ values — the plate then goes to a reader (see PlateReaderShare/read_plate).
34
+
35
+ Requires no extra dependencies (stdlib urllib + http.server for the sim).
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import json
40
+ import uuid
41
+ import urllib.request
42
+ from typing import Any
43
+
44
+ from proef.core.contracts import (
45
+ AssayResult, Envelope, InstrumentInfo, Measurement, ProtocolSubmission,
46
+ RunStatus,
47
+ )
48
+
49
+ API_VERSION = "3" # documented current (integration-tools README)
50
+
51
+
52
+ class OpentronsTransport:
53
+ """Thin HTTP layer (injectable for tests). `Opentrons-Version` is
54
+ sent on EVERY request — the robot requires it; omitting it gets 400s
55
+ that look like network gremlins."""
56
+
57
+ def __init__(self, base_url: str, timeout: int = 30,
58
+ api_version: str = API_VERSION):
59
+ self.base_url = base_url.rstrip("/")
60
+ self.timeout = timeout
61
+ self.api_version = api_version
62
+
63
+ def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
64
+ h = {"Opentrons-Version": self.api_version,
65
+ "Accept": "application/json"}
66
+ h.update(extra or {})
67
+ return h
68
+
69
+ def request(self, method: str, path: str, body: dict | None = None) -> dict:
70
+ req = urllib.request.Request(
71
+ f"{self.base_url}{path}",
72
+ data=json.dumps(body).encode() if body is not None else None,
73
+ headers=self._headers({"Content-Type": "application/json"}),
74
+ method=method)
75
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp: # noqa: S310
76
+ payload = resp.read()
77
+ return json.loads(payload) if payload else {}
78
+
79
+ def upload(self, path: str, field: str, filename: str,
80
+ data: bytes) -> dict:
81
+ """multipart/form-data per the docs: -F "files=@x.py"."""
82
+ boundary = f"----proef{uuid.uuid4().hex}"
83
+ body = (f"--{boundary}\r\n"
84
+ f'Content-Disposition: form-data; name="{field}"; '
85
+ f'filename="{filename}"\r\n'
86
+ "Content-Type: application/octet-stream\r\n\r\n"
87
+ ).encode() + data + f"\r\n--{boundary}--\r\n".encode()
88
+ req = urllib.request.Request(
89
+ f"{self.base_url}{path}", data=body,
90
+ headers=self._headers(
91
+ {"Content-Type": f"multipart/form-data; boundary={boundary}"}),
92
+ method="POST")
93
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp: # noqa: S310
94
+ payload = resp.read()
95
+ return json.loads(payload) if payload else {}
96
+
97
+
98
+ def compile_protocol(protocol: ProtocolSubmission,
99
+ labware: str = "corning_96_wellplate_360ul_flat",
100
+ pipette: str = "p300_single") -> str:
101
+ """Abstract ProtocolSubmission -> Opentrons Python protocol (API v2).
102
+
103
+ metadata keys follow the documented schema: protocolName, not title."""
104
+ lines = [
105
+ "from opentrons import protocol_api",
106
+ "",
107
+ "metadata = {",
108
+ " 'protocolName': "
109
+ f"{protocol.title + '-' + protocol.protocol_id[:8]!r},",
110
+ " 'description': 'generated by Proef (opentrons driver)',",
111
+ " 'apiLevel': '2.13',",
112
+ "}",
113
+ "",
114
+ "def run(ctx: protocol_api.ProtocolContext):",
115
+ f" plate = ctx.load_labware({labware!r}, '1')",
116
+ " tiprack = ctx.load_labware('opentrons_96_tiprack_300ul', '2')",
117
+ f" pip = ctx.load_instrument({pipette!r}, 'right', "
118
+ "tip_racks=[tiprack])",
119
+ ]
120
+ for step in sorted(protocol.steps, key=lambda s: s.seq):
121
+ if step.op.value != "dispense":
122
+ continue # extend: mix, incubate, transfer chains
123
+ well = step.params.get("well", "A1")
124
+ vol = float(step.params.get("volume_ul", 10.0))
125
+ src = step.params.get("source", "A1")
126
+ lines += [
127
+ " pip.pick_up_tip()",
128
+ f" pip.aspirate({vol}, plate['{src}'].top())",
129
+ f" pip.dispense({vol}, plate['{well}'].top())",
130
+ " pip.drop_tip()",
131
+ ]
132
+ return "\n".join(lines) + "\n"
133
+
134
+
135
+ class OpentronsLab:
136
+ """LabAdapter over an Opentrons robot (contract-pinned)."""
137
+
138
+ name = "opentrons"
139
+
140
+ def __init__(self, transport: OpentronsTransport | None = None,
141
+ base_url: str = "http://169.254.8.32:31950"):
142
+ self.client = transport or OpentronsTransport(base_url)
143
+ self._runs: dict[str, dict[str, Any]] = {}
144
+
145
+ # -- contract -------------------------------------------------------------
146
+
147
+ def list_capabilities(self) -> dict[str, Any]:
148
+ info = self.client.request("GET", "") # robot serves versions at /
149
+ return {
150
+ "kind": "liquid_handler",
151
+ "robot": "opentrons",
152
+ "api_version": info.get("api_version"),
153
+ "firmware": info.get("firmware_version") or info.get("fw_version"),
154
+ "system_version": info.get("system_version"),
155
+ "operations": ["dispense", "aspirate", "transfer"],
156
+ "contract": "docs-pinned v3; CI-verified vs ot2_sim "
157
+ "(hardware confirmation = S-T4)",
158
+ "note": "Make-step adapter: assay readout comes from a plate reader",
159
+ }
160
+
161
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
162
+ script = compile_protocol(protocol).encode()
163
+ # 1. upload: POST /protocols, multipart field `files` (v3 docs)
164
+ created = self.client.upload("/protocols", "files",
165
+ "protocol.py", script)
166
+ protocol_id = (created.get("data") or {}).get("id")
167
+ if not protocol_id:
168
+ raise RuntimeError(f"unexpected protocol response: {created}")
169
+ # 2. create run: POST /runs {"data": {"protocolId": ...}}
170
+ run = self.client.request("POST", "/runs",
171
+ {"data": {"protocolId": protocol_id}})
172
+ run_id = (run.get("data") or {}).get("id")
173
+ if not run_id:
174
+ raise RuntimeError(f"unexpected run response: {run}")
175
+ self._runs[run_id] = {"protocol": protocol,
176
+ "protocol_id": protocol_id}
177
+ # 3. play it
178
+ self.client.request("POST", f"/runs/{run_id}/actions",
179
+ {"data": {"actionType": "play"}})
180
+ return run_id
181
+
182
+ def get_status(self, run_id: str) -> str:
183
+ status = ((self.client.request("GET", f"/runs/{run_id}")
184
+ .get("data") or {}).get("status") or "").lower()
185
+ return {"running": "running", "idle": "queued", "finished": "done",
186
+ "succeeded": "done", "completed": "done",
187
+ "failed": "failed", "stopped": "cancelled",
188
+ "on-long-pause": "running",
189
+ "recovering": "running"}.get(status, status or "unknown")
190
+
191
+ def fetch_results(self, run_id: str) -> AssayResult:
192
+ cmds = self.client.request("GET", f"/runs/{run_id}/commands")
193
+ executed = [
194
+ {"command": c.get("commandType"), "status": c.get("status"),
195
+ "params": c.get("params", {})}
196
+ for c in (cmds.get("data") or [])
197
+ if c.get("status") == "succeeded"
198
+ and c.get("commandType") not in ("pause", "loadLabware",
199
+ "loadPipette")
200
+ ]
201
+ protocol = self._runs.get(run_id, {}).get("protocol")
202
+ return AssayResult(
203
+ envelope=Envelope(experiment_branch_id="opentrons"),
204
+ protocol_id=protocol.protocol_id if protocol else run_id,
205
+ instrument=InstrumentInfo(adapter=self.name, instrument_id="ot-2",
206
+ raw_output_uri=f"opentrons://{run_id}/commands"),
207
+ status=RunStatus.completed if executed else RunStatus.failed,
208
+ measurements=[
209
+ Measurement(sample_id=f"cmd-{i}", assay_type="execution",
210
+ value=1.0, unit="executed",
211
+ metadata={"command": c["command"],
212
+ "params": c["params"]})
213
+ for i, c in enumerate(executed, 1)
214
+ ],
215
+ qc={"controls_passed": True,
216
+ "notes": f"{len(executed)} commands executed; "
217
+ "assay readout comes from the plate reader"},
218
+ )
219
+
220
+ def cancel(self, run_id: str) -> None:
221
+ self.client.request("POST", f"/runs/{run_id}/actions",
222
+ {"data": {"actionType": "stop"}})
@@ -0,0 +1,174 @@
1
+ """ot2_sim — a spec-conformant SIMULATED Opentrons robot (S-T4 CI seam).
2
+
3
+ Implements the documented v3 surface (see opentrons.py docstring for
4
+ sources) well enough to REJECT the mistakes a real robot rejects:
5
+ missing `Opentrons-Version` -> 400, wrong multipart field -> 422,
6
+ runs without a protocolId -> 400, unknown ids -> 404. It also plays
7
+ along like a robot: the uploaded Python protocol source is parsed for
8
+ pipette calls, and GET /runs/{id}/commands reports exactly those as
9
+ succeeded after play + a couple of polls.
10
+
11
+ This is a test double with teeth, not hardware: it pins the CONTRACT,
12
+ the physical robot remains S-T4's confirmation step.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ import threading
19
+ import uuid
20
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
21
+
22
+
23
+ class _State:
24
+ def __init__(self):
25
+ self.protocols: dict[str, dict] = {}
26
+ self.runs: dict[str, dict] = {}
27
+ self.requests: list[tuple[str, str]] = []
28
+
29
+
30
+ def make_server() -> tuple[ThreadingHTTPServer, _State]:
31
+ state = _State()
32
+
33
+ class Handler(BaseHTTPRequestHandler):
34
+ # -- plumbing -----------------------------------------------------
35
+ def log_message(self, *a):
36
+ pass
37
+
38
+ def _send(self, code: int, body: dict):
39
+ raw = json.dumps(body).encode()
40
+ self.send_response(code)
41
+ self.send_header("Content-Type", "application/json")
42
+ self.send_header("Content-Length", str(len(raw)))
43
+ self.end_headers()
44
+ self.wfile.write(raw)
45
+
46
+ def _version_ok(self) -> bool:
47
+ v = self.headers.get("Opentrons-Version")
48
+ return v in ("2", "3", "*")
49
+
50
+ def _plan(self, src: str) -> list[dict]:
51
+ """Extract pipette command plan from the uploaded protocol."""
52
+ plan = []
53
+ for m in re.finditer(
54
+ r"pip\.(pick_up_tip|aspirate|dispense|drop_tip)"
55
+ r"\(([^)]*)\)?", src):
56
+ plan.append({"id": uuid.uuid4().hex,
57
+ "commandType": {"pick_up_tip": "pickUpTip",
58
+ "aspirate": "aspirate",
59
+ "dispense": "dispense",
60
+ "drop_tip": "dropTip"}[m.group(1)],
61
+ "status": "succeeded",
62
+ "params": {"raw": m.group(2)[:80]}})
63
+ return plan
64
+
65
+ # -- routes ---------------------------------------------------------
66
+ def do_GET(self):
67
+ state.requests.append(("GET", self.path))
68
+ if self.path == "/":
69
+ return self._send(200, {
70
+ "api_version": "v3back", "system_version": "sim-0.1",
71
+ "firmware_version": "sim-smoothie"})
72
+ m = re.fullmatch(r"/runs/([\w-]+)", self.path)
73
+ if m:
74
+ if not self._version_ok():
75
+ return self._send(400, {"errors": [{"detail":
76
+ "Opentrons-Version header required"}]})
77
+ run = state.runs.get(m.group(1))
78
+ if not run:
79
+ return self._send(404, {"errors": [{"detail": "no run"}]})
80
+ if run["status"] == "running":
81
+ run["polls"] += 1
82
+ if run["polls"] >= 2:
83
+ run["status"] = "finished"
84
+ return self._send(200, {"data": {
85
+ "id": run["id"], "status": run["status"],
86
+ "protocolId": run["protocol_id"], "current": True}})
87
+ m = re.fullmatch(r"/runs/([\w-]+)/commands", self.path)
88
+ if m:
89
+ if not self._version_ok():
90
+ return self._send(400, {"errors": [{"detail": "version"}]})
91
+ run = state.runs.get(m.group(1))
92
+ if not run:
93
+ return self._send(404, {"errors": [{"detail": "no run"}]})
94
+ return self._send(200, {"data": run["commands"]})
95
+ return self._send(404, {"errors": [{"detail": "no route"}]})
96
+
97
+ def do_POST(self):
98
+ state.requests.append(("POST", self.path))
99
+ length = int(self.headers.get("Content-Length", 0))
100
+ raw = self.rfile.read(length) if length else b""
101
+ if not self._version_ok():
102
+ return self._send(400, {"errors": [{"detail":
103
+ "Opentrons-Version header is required on "
104
+ "protocol/run endpoints"}]})
105
+ if self.path == "/protocols":
106
+ ctype = self.headers.get("Content-Type", "")
107
+ if "multipart/form-data" not in ctype:
108
+ return self._send(422, {"errors": [{"detail":
109
+ "expected multipart/form-data"}]})
110
+ if b'name="files"' not in raw: # v3 field name
111
+ return self._send(422, {"errors": [{"detail":
112
+ "multipart field must be 'files' (v3)"}]})
113
+ pid = uuid.uuid4().hex
114
+ src = raw.decode("latin-1")
115
+ state.protocols[pid] = {"id": pid, "plan": self._plan(src)}
116
+ return self._send(201, {"data": {
117
+ "id": pid, "analysisSummaries": [{"id": "a-1"}]}})
118
+ if self.path == "/runs":
119
+ try:
120
+ body = json.loads(raw or b"{}")
121
+ except json.JSONDecodeError:
122
+ return self._send(400, {"errors": [{"detail": "json"}]})
123
+ pid = (body.get("data") or {}).get("protocolId")
124
+ if not pid:
125
+ return self._send(400, {"errors": [{"detail":
126
+ "data.protocolId required (integration-tools docs)"}]})
127
+ if pid not in state.protocols:
128
+ return self._send(404, {"errors": [{"detail":
129
+ "unknown protocolId"}]})
130
+ rid = uuid.uuid4().hex
131
+ state.runs[rid] = {"id": rid, "protocol_id": pid,
132
+ "status": "idle", "polls": 0,
133
+ "commands": state.protocols[pid]["plan"]}
134
+ return self._send(201, {"data": {"id": rid,
135
+ "status": "idle"}})
136
+ m = re.fullmatch(r"/runs/([\w-]+)/actions", self.path)
137
+ if m:
138
+ run = state.runs.get(m.group(1))
139
+ if not run:
140
+ return self._send(404, {"errors": [{"detail": "no run"}]})
141
+ action = ((json.loads(raw or b"{}").get("data") or {})
142
+ .get("actionType"))
143
+ if action not in ("play", "pause", "stop"):
144
+ return self._send(422, {"errors": [{"detail":
145
+ "actionType must be play|pause|stop"}]})
146
+ run["status"] = {"play": "running", "pause": "idle",
147
+ "stop": "stopped"}[action]
148
+ return self._send(200, {"data": run["commands"]})
149
+ return self._send(404, {"errors": [{"detail": "no route"}]})
150
+
151
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
152
+ return server, state
153
+
154
+
155
+ class SimulatedRobot:
156
+ """Context manager: run the sim on an ephemeral port in a thread."""
157
+
158
+ def __init__(self):
159
+ self.server, self.state = make_server()
160
+ self.thread = threading.Thread(target=self.server.serve_forever,
161
+ daemon=True)
162
+
163
+ @property
164
+ def base_url(self) -> str:
165
+ host, port = self.server.server_address[:2]
166
+ return f"http://{host}:{port}"
167
+
168
+ def __enter__(self) -> "SimulatedRobot":
169
+ self.thread.start()
170
+ return self
171
+
172
+ def __exit__(self, *a):
173
+ self.server.shutdown()
174
+ self.server.server_close()
@@ -0,0 +1,108 @@
1
+ """PlateReaderShare — adapter for network-share plate readers.
2
+
3
+ Most core-lab plate readers (Biotek Gen5, SoftMax Pro, SpectraMax, ClarioStar)
4
+ can be configured to **auto-export every completed read** to a network share.
5
+ This adapter treats that share as the device: register the expected run, then
6
+ `fetch_results` parses the newest matching export with `labread` (format
7
+ autodetect, control discovery, IC50 fit, Z' QC).
8
+
9
+ Real workflow, zero vendor SDKs. All parsing already exists in `labread`.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from proef.core.contracts import (
18
+ AssayResult, Envelope, InstrumentInfo, ProtocolSubmission, RunStatus,
19
+ )
20
+ from proef.labread import read_plate
21
+
22
+
23
+ class PlateReaderShare:
24
+ """LabAdapter over a watched share where the reader drops export files."""
25
+
26
+ name = "plate-reader-share"
27
+
28
+ def __init__(self, share_dir: str | Path, assay: str = "binding",
29
+ max_response: float | None = None,
30
+ wait_secs: int = 300, poll_secs: float = 2.0,
31
+ suffix: str = ".csv"):
32
+ self.share = Path(share_dir)
33
+ self.share.mkdir(parents=True, exist_ok=True)
34
+ self.assay = assay
35
+ self.max_response = max_response
36
+ self.wait_secs = wait_secs
37
+ self.poll_secs = poll_secs
38
+ self.suffix = suffix
39
+ self._expected: dict[str, tuple[float, ProtocolSubmission]] = {}
40
+
41
+ # -- contract -------------------------------------------------------------
42
+
43
+ def list_capabilities(self) -> dict[str, Any]:
44
+ return {"kind": "plate_reader", "readout": "auto-export-share",
45
+ "assays": [self.assay],
46
+ "formats": ["csv", "tsv", "xlsx", "grid"],
47
+ "note": "reader must be configured to auto-export to the share"}
48
+
49
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
50
+ """Register the run; the physical read is triggered by the technician /
51
+ robot deck, and the reader's auto-export lands in the share."""
52
+ run_id = f"share-{protocol.protocol_id[:8]}"
53
+ self._expected[run_id] = (time.time(), protocol)
54
+ return run_id
55
+
56
+ def get_status(self, run_id: str) -> str:
57
+ try:
58
+ self._result(run_id)
59
+ return "done"
60
+ except FileNotFoundError:
61
+ age = time.time() - self._expected.get(run_id, (time.time(), None))[0]
62
+ return "failed" if age > self.wait_secs else "running"
63
+
64
+ def fetch_results(self, run_id: str) -> AssayResult:
65
+ export, protocol = self._result(run_id)
66
+ plate = read_plate(export, max_response=self.max_response)
67
+ measurements = []
68
+ for sample, r in plate.analysis["compounds"].items():
69
+ if r["ic50_um"] is None:
70
+ continue
71
+ from proef.core.contracts import Measurement
72
+ measurements.append(Measurement(
73
+ sample_id=sample, assay_type=self.assay,
74
+ value=r["ic50_um"], unit="uM",
75
+ derived_metrics={"ic50_um": r["ic50_um"],
76
+ "z_prime": plate.z_prime},
77
+ ))
78
+ return AssayResult(
79
+ envelope=Envelope(experiment_branch_id="plate-reader-share"),
80
+ protocol_id=protocol.protocol_id,
81
+ instrument=InstrumentInfo(adapter=self.name, instrument_id=str(export),
82
+ raw_output_uri=str(export)),
83
+ status=RunStatus.completed,
84
+ measurements=measurements,
85
+ qc={"controls_passed": (plate.z_prime or 0) >= 0.3,
86
+ "z_prime": plate.z_prime},
87
+ )
88
+
89
+ def cancel(self, run_id: str) -> None:
90
+ self._expected.pop(run_id, None)
91
+
92
+ # -- internals ------------------------------------------------------------
93
+
94
+ def _result(self, run_id: str) -> tuple[Path, ProtocolSubmission]:
95
+ if run_id not in self._expected:
96
+ raise KeyError(f"unknown run {run_id}")
97
+ created, protocol = self._expected[run_id]
98
+ candidates = sorted(self.share.glob(f"*{self.suffix}"),
99
+ key=lambda p: p.stat().st_mtime)
100
+ # newest export created after this run was submitted
101
+ for export in reversed(candidates):
102
+ if export.stat().st_mtime >= created - 1:
103
+ return export, protocol
104
+ age = time.time() - created
105
+ if age > self.wait_secs:
106
+ raise FileNotFoundError(
107
+ f"no export appeared in {self.share} within {self.wait_secs}s")
108
+ raise FileNotFoundError(f"export pending ({age:.0f}s)")