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/labselect.py ADDED
@@ -0,0 +1,431 @@
1
+ """Capability-matched lab selection inside the OPERATOR's fence (S-T5).
2
+
3
+ Division of authority, mirroring the tighten-only safety doctrine:
4
+
5
+ * The PROGRAM CREATOR declares the pool of permitted instruments
6
+ (consent for physical action is a human act; nobody downstream may
7
+ add to the fence).
8
+ * The MATCHER selects which pool member can serve the experiment's
9
+ declared needs, deterministically, and RECORDS the rationale ,
10
+ including every refusal reason of the ones not chosen.
11
+ * AGENTS may recommend, never re-fence.
12
+
13
+ Nothing is ever selected outside the pool, and a simulated instrument is
14
+ never silently preferred away from validated hardware: ordering is
15
+ hardware_validated -> declared order, and `simulated` is recorded on the
16
+ decision so the workbench can badge it.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ from pathlib import Path
22
+
23
+ from dataclasses import dataclass, field
24
+ from typing import Any
25
+
26
+
27
+ @dataclass
28
+ class LabRequirement:
29
+ """What the experiment needs, from the hypothesis/readout spec."""
30
+ assay_types: frozenset = frozenset()
31
+ readouts: frozenset = frozenset()
32
+ max_bsl: int = 2
33
+ physical: bool = True # False = analysis-only campaign
34
+
35
+ @staticmethod
36
+ def build(spec: dict | None) -> "LabRequirement":
37
+ s = dict(spec or {})
38
+ return LabRequirement(
39
+ assay_types=frozenset(s.get("assay_types") or ()),
40
+ readouts=frozenset(s.get("readouts") or ()),
41
+ max_bsl=int(s.get("max_bsl", 2)),
42
+ physical=bool(s.get("physical", True)))
43
+
44
+
45
+ def normalize_caps(adapter: Any) -> dict:
46
+ """One capability vocabulary from heterogeneous adapters: legacy
47
+ dicts, sensor readouts, or MCP-declared typed tools."""
48
+ raw = dict(adapter.list_capabilities() or {})
49
+ assays = {str(a) for a in raw.get("assays") or []}
50
+ readouts = {str(r) for r in raw.get("measures") or []}
51
+ readouts |= {str(r) for r in raw.get("modalities") or []}
52
+ if raw.get("readout"):
53
+ readouts.add(str(raw["readout"]))
54
+ assays.add("sensor")
55
+ for t in raw.get("tools") or []: # MCP profiles
56
+ if t.get("read_only"):
57
+ readouts.add(str(t["name"]))
58
+ return {
59
+ "assay_types": assays,
60
+ "readouts": readouts,
61
+ "bsl_max": raw.get("bsl_max"),
62
+ "simulated": bool(raw.get("simulated")
63
+ or raw.get("adapter_simulated", False)
64
+ # virtual labs don't self-label in legacy dicts;
65
+ # their names do
66
+ or getattr(adapter, "name", "") in (
67
+ "simulator", "imaging-simulator")),
68
+ "simulator": raw.get("simulated") is None and (
69
+ raw.get("adapter_simulated") or getattr(adapter, "name", "")
70
+ in ("simulator", "imaging-simulator")),
71
+ "hardware_validated": bool(raw.get("hardware_validated", False)),
72
+ "kind": str(raw.get("kind", "")),
73
+ }
74
+
75
+
76
+ @dataclass
77
+ class Selection:
78
+ lab: Any
79
+ name: str
80
+ rationale: dict = field(default_factory=dict)
81
+
82
+
83
+ def select_lab(pool: list, req: LabRequirement):
84
+ """pool: [(name, adapter)] -> (Selection | None, refusals). Always
85
+ returns the refusals list (why each DECLINED instrument was declined)
86
+ , the decision record is as informative when selection succeeds.
87
+ Deterministic: eligible = capability-superset AND BSL-compatible;
88
+ ordered hardware-validated first, then pool order (operator intent)."""
89
+ if req.physical and not pool:
90
+ return None, [{"name": None, "why": ["empty pool, physical "
91
+ "campaign has no permitted "
92
+ "instruments"]}]
93
+ eligible, refusals = [], []
94
+ for name, lab in pool:
95
+ caps = normalize_caps(lab)
96
+ why = []
97
+ missing_a = [a for a in req.assay_types if a not in caps["assay_types"]]
98
+ missing_r = [r for r in req.readouts if r not in caps["readouts"]
99
+ and r not in caps["assay_types"]]
100
+ if not req.physical:
101
+ pass
102
+ else:
103
+ if missing_a:
104
+ why.append(f"no assay: {', '.join(sorted(missing_a))}")
105
+ if missing_r:
106
+ why.append(f"no readout: {', '.join(sorted(missing_r))}")
107
+ if caps["bsl_max"] is not None and caps["bsl_max"] < req.max_bsl:
108
+ why.append(f"BSL ceiling {caps['bsl_max']} < {req.max_bsl}")
109
+ if why:
110
+ refusals.append({"name": name, "why": why})
111
+ else:
112
+ eligible.append((name, lab, caps))
113
+ if not eligible:
114
+ return None, refusals
115
+ # deterministic: hardware-validated before simulated; pool (operator
116
+ # declaration) order breaks remaining ties
117
+ eligible.sort(key=lambda e: (not e[2]["hardware_validated"],))
118
+ name, lab, caps = eligible[0]
119
+ return Selection(
120
+ lab=lab, name=name,
121
+ rationale={"requirement": {
122
+ "assay_types": sorted(req.assay_types),
123
+ "readouts": sorted(req.readouts),
124
+ "max_bsl": req.max_bsl,
125
+ "physical": req.physical},
126
+ "chosen": {"name": name, "simulated": caps["simulated"]},
127
+ "order_rule": "hardware-validated first, then declared "
128
+ "order; capability-superset required",
129
+ "declined": refusals,
130
+ "eligible": [n for n, _, _ in eligible]}), refusals
131
+
132
+
133
+ SAFE_NAME = __import__("re").compile(r"[A-Za-z0-9_.\-]{1,40}")
134
+
135
+
136
+ def safe_names(names, report: list | None = None) -> list[str]:
137
+ """The capability names an instrument's server supplied, restricted to what is safe to show a model: a short token of letters,
138
+ digits and `_ . -`. An instrument's server is untrusted input, and a name is the one place it could put an instruction in a prompt.
139
+ Anything else is DROPPED and, if a list is given, reported there."""
140
+ keep = []
141
+ for n in names:
142
+ n = str(n)
143
+ if SAFE_NAME.fullmatch(n):
144
+ keep.append(n)
145
+ elif report is not None:
146
+ report.append(n[:60])
147
+ return sorted(set(keep))
148
+
149
+
150
+ def build_menu(pool: list) -> list[dict]:
151
+ """What a model may choose an instrument from: the operator's pool as plain data. One source for the prompt and for
152
+ `check_pick`, so the menu and the validator cannot drift. Names the instruments declared are restricted (`safe_names`)."""
153
+ out = []
154
+ for name, adapter in pool:
155
+ caps = normalize_caps(adapter)
156
+ dropped: list[str] = []
157
+ out.append({"name": name, "assay_types": safe_names(caps["assay_types"], dropped), "readouts": safe_names(caps["readouts"], dropped),
158
+ "dropped_names": dropped,
159
+ "bsl_max": caps["bsl_max"], "simulated": caps["simulated"],
160
+ "hardware_validated": caps["hardware_validated"]})
161
+ return out
162
+
163
+
164
+ def menu_text(menu: list[dict]) -> str:
165
+ """The menu as the prompt shows it. Real and simulated instruments are labelled, so a model sees the difference."""
166
+ lines = []
167
+ for m in menu:
168
+ kind = "hardware-validated" if m["hardware_validated"] else ("simulated" if m["simulated"] else "real, not validated")
169
+ bsl = f", BSL up to {m['bsl_max']}" if m.get("bsl_max") is not None else ""
170
+ lines.append(f"- {m['name']}: assays {', '.join(m['assay_types']) or 'not declared'}{bsl} ({kind})")
171
+ return "\n".join(lines)
172
+
173
+
174
+ # Assay names that are catch-alls or instrument kinds, not capabilities an adapter can meaningfully declare: "custom" is what
175
+ # an unknown assay name falls back to (coerce_assay_type), and "plate_reader" names an instrument. A capability list cannot
176
+ # refuse them, so they are never checked against one (checking them blocked every property/materials campaign).
177
+ GENERIC_ASSAYS = frozenset({"custom", "plate_reader"})
178
+
179
+
180
+ def _why_not(m: dict, assay_type: str, max_bsl: int) -> list[str]:
181
+ why = []
182
+ if assay_type not in GENERIC_ASSAYS and m["assay_types"] and assay_type not in m["assay_types"]:
183
+ why.append(f"{m['name']} declares no '{assay_type}' assay")
184
+ if m.get("bsl_max") is not None and m["bsl_max"] < max_bsl:
185
+ why.append(f"{m['name']} BSL ceiling {m['bsl_max']} is below the campaign's {max_bsl}")
186
+ return why
187
+
188
+
189
+ def check_pick(pick: str | None, assay_type: str, menu: list[dict], runs_on: str | None, max_bsl: int = 2) -> dict:
190
+ """Validate a model's instrument pick FACTS-FIRST: is the name in the pool, does the instrument declare the assay, and is
191
+ it the instrument this campaign actually runs on. The model's reasoning is never read. Never fixes a pick silently: it
192
+ reports `status`, `ok` and `reasons`, and `runs_on` is where the run will really go.
193
+
194
+ status: ok | unstated | unverified | invented | lacks | other_instrument | cannot_run"""
195
+ by_name = {m["name"]: m for m in menu}
196
+ # the model's string is bounded and coerced: a list, a dict or a flood of text must not crash a campaign or bloat the record
197
+ if isinstance(pick, str):
198
+ pick = pick[:80].strip() or None
199
+ elif not pick:
200
+ pick = None
201
+ else:
202
+ pick = str(pick)[:80] # a list or dict is not a name: it will be reported as not in the pool
203
+
204
+ def serves(m: dict) -> bool:
205
+ return not _why_not(m, assay_type, max_bsl)
206
+
207
+ eligible = [m["name"] for m in menu if serves(m)]
208
+ out = {"pick": pick, "runs_on": runs_on, "eligible": eligible, "reasons": [], "flags": []}
209
+ if pick is not None and pick not in by_name:
210
+ return {**out, "status": "invented", "ok": False,
211
+ "reasons": [f"'{pick}' is not in the operator's pool ({', '.join(by_name) or 'empty'})"]}
212
+ if pick is not None and not serves(by_name[pick]):
213
+ return {**out, "status": "lacks", "ok": False, "reasons": _why_not(by_name[pick], assay_type, max_bsl)}
214
+ chosen = by_name.get(runs_on) if runs_on else None
215
+ if chosen is not None and not serves(chosen):
216
+ return {**out, "status": "cannot_run", "ok": False,
217
+ "reasons": _why_not(chosen, assay_type, max_bsl)
218
+ + [f"Instruments that can: {', '.join(eligible)}." if eligible else "No instrument in the pool can."]}
219
+ if pick is not None and runs_on and pick != runs_on:
220
+ return {**out, "status": "other_instrument", "ok": False,
221
+ "reasons": [f"{pick} could run it, but this campaign runs on {runs_on}"]}
222
+ flags = []
223
+ if pick is not None and by_name[pick]["simulated"] and any(
224
+ by_name[n]["hardware_validated"] for n in eligible):
225
+ flags.append("simulated_over_validated")
226
+ if chosen is not None and not chosen["assay_types"]:
227
+ return {**out, "status": "unverified", "ok": True, "flags": flags,
228
+ "reasons": [f"{runs_on} declares no assay list, so this could not be checked"]}
229
+ return {**out, "status": "ok" if pick else "unstated", "ok": True, "flags": flags}
230
+
231
+
232
+ CATALOG_PATH = Path(__file__).parent / "instruments.json"
233
+
234
+
235
+ def load_catalog() -> dict:
236
+ return json.loads(CATALOG_PATH.read_text())
237
+
238
+
239
+ # Ids that existed under the project's former name. Programs and recorded runs reference them, so
240
+ # they stay valid: they resolve to the current id and are never written again.
241
+ LEGACY_IDS = {"bionexus-virtual-lab": "proef-virtual-lab"}
242
+
243
+
244
+ def canonical_id(instrument_id: str) -> str:
245
+ return LEGACY_IDS.get(instrument_id, instrument_id)
246
+
247
+
248
+ def _catalog_entry(instrument_id: str) -> dict:
249
+ instrument_id = canonical_id(instrument_id)
250
+ for e in load_catalog()["instruments"]:
251
+ if e["id"] == instrument_id:
252
+ return e
253
+ known = ", ".join(x["id"] for x in load_catalog()["instruments"])
254
+ raise ValueError(f"unknown instrument {instrument_id!r}; "
255
+ f"catalog ids: {known}")
256
+
257
+
258
+ def available_instruments() -> list[dict]:
259
+ """The picker view: every catalog instrument, whether it is
260
+ installable/reachable HERE, and what it declares. Availability is an
261
+ INSTALL check; capability truth comes from the live handshake at
262
+ selection time, the list never overstates what an instrument is."""
263
+ import importlib.util
264
+ import shutil
265
+ out = []
266
+ for e in load_catalog()["instruments"]:
267
+ kind = e["kind"]
268
+ if kind == "simulator":
269
+ installed = True
270
+ elif kind == "mcp":
271
+ exe0 = e.get("availability_executable") or e["command"][0]
272
+ import sys as _s
273
+ installed = (exe0 == "{python}" or bool(shutil.which(exe0))
274
+ or (Path(_s.executable).parent / exe0).exists())
275
+ else:
276
+ mod = e["adapter"].rsplit(":", 1)[0]
277
+ installed = importlib.util.find_spec(mod) is not None
278
+ out.append({**{k: e.get(k) for k in (
279
+ "id", "kind", "name", "vendor",
280
+ "hardware_validated", "assay_types", "readouts",
281
+ "note", "homepage", "requires_network",
282
+ "config_schema")},
283
+ "simulated": bool(e.get("simulated")
284
+ or e.get("simulated_by_default")),
285
+ "installed": bool(installed),
286
+ "profile_read_tool": (e.get("profile") or {}).get(
287
+ "read_tool")})
288
+ return out
289
+
290
+
291
+ def _config_args(cat: dict, config: dict) -> list[str]:
292
+ """Translate an instrument's connection config into server flags per
293
+ its declared config_schema (e.g. labmcp's --simulate / --address).
294
+ simulate defaults TRUE: a campaign must opt INTO hardware, never
295
+ accidentally touch it."""
296
+ args = []
297
+ simulate_omitted = True
298
+ for f in cat.get("config_schema") or []:
299
+ v = config.get(f["key"], f.get("default"))
300
+ if f["key"] == "simulate":
301
+ simulate_omitted = False
302
+ if v:
303
+ args += ["--simulate"]
304
+ elif f["type"] == "bool" and v:
305
+ args += [f"--{f['key']}"]
306
+ elif v not in (None, ""):
307
+ args += [f"--{f['key']}", str(v)]
308
+ if simulate_omitted and "config_schema" in [f.get("key") for f in
309
+ cat.get("config_schema") or []]:
310
+ pass
311
+ return args
312
+
313
+
314
+ def _resolve_cmd(cmd: list[str]) -> list[str]:
315
+ """Executables ship next to the running interpreter (venv/bin) and
316
+ are not always on PATH in subprocess contexts."""
317
+ import shutil
318
+ import sys
319
+ from pathlib import Path
320
+ exe = cmd[0]
321
+ if shutil.which(exe):
322
+ return cmd
323
+ beside = Path(sys.executable).parent / exe
324
+ if beside.exists():
325
+ return [str(beside), *cmd[1:]]
326
+ return cmd
327
+
328
+
329
+ def build_pool(entries: list[dict]) -> list:
330
+ """Operator-declared pool. The happy path references the catalog:
331
+ {"instrument": "<id>"} (commands + profiles come from data)
332
+ Escape hatches for instruments not yet catalogued:
333
+ {"simulator": {...}} | {"adapter": "pkg:Class", "options": {...}}
334
+ {"mcp": {"command": [...], "profile": {<full profile dict>}}}
335
+ """
336
+ import sys
337
+ from proef.core.registry import import_string
338
+ pool = []
339
+ for i, e in enumerate(entries or []):
340
+ if "instrument" in e:
341
+ cat = _catalog_entry(e["instrument"])
342
+ opts = {**(cat.get("options") or {}), **(e.get("options") or {})}
343
+ if cat["kind"] == "simulator":
344
+ from proef.adapters.lab.simulator import SimulatorLab
345
+ pool.append((f"{cat['id']}-{i}", SimulatorLab(**opts)))
346
+ elif cat["kind"] == "mcp":
347
+ from proef.mcp_instrument import McpLabAdapter
348
+ cmd = _resolve_cmd([c.replace("{python}", sys.executable)
349
+ for c in cat["command"]])
350
+ cmd += _config_args(cat, e.get("config") or {})
351
+ cmd += [str(a) for a in (e.get("args") or [])]
352
+ pool.append((f"{cat['id']}-{i}",
353
+ McpLabAdapter(command=cmd,
354
+ profile=dict(cat["profile"]))))
355
+ else:
356
+ cls = import_string(cat["adapter"])
357
+ pool.append((f"{cat['id']}-{i}", cls(**opts)))
358
+ elif "simulator" in e:
359
+ from proef.adapters.lab.simulator import SimulatorLab
360
+ opts = dict(e.get("options") or {})
361
+ opts.update(e["simulator"] or {})
362
+ pool.append((f"simulator-{i}", SimulatorLab(**opts)))
363
+ elif "adapter" in e:
364
+ cls = import_string(e["adapter"])
365
+ name = e.get("name") or e["adapter"].rsplit(":", 1)[-1]
366
+ pool.append((f"{name}-{i}", cls(**(e.get("options") or {}))))
367
+ elif "mcp" in e:
368
+ from proef.mcp_instrument import McpLabAdapter
369
+ m = e["mcp"]
370
+ if not isinstance(m.get("profile"), dict):
371
+ raise ValueError(
372
+ "inline mcp entries need a full profile dict, named "
373
+ "profiles live in instruments.json; add the instrument "
374
+ "to the catalog (one data edit, then use its id)")
375
+ label = str(m.get("command", ["mcp"])[0]).rsplit("/", 1)[-1]
376
+ pool.append((f"{label}-{i}",
377
+ McpLabAdapter(command=list(m["command"]),
378
+ profile=m["profile"])))
379
+ else:
380
+ raise ValueError(f"unrecognized lab pool entry: {e!r}")
381
+ return pool
382
+
383
+
384
+ def fence_info(labs_entries: list | None) -> list[dict]:
385
+ """Human-facing view of a program's fence: which instruments the
386
+ creator permitted, by name, with honest status. This is DECLARATION
387
+ data (what the fence allows), not a live probe of the devices."""
388
+ out = []
389
+ for e in labs_entries or []:
390
+ iid = canonical_id(e["instrument"]) if e.get("instrument") else None
391
+ if iid:
392
+ try:
393
+ cat = _catalog_entry(iid)
394
+ except ValueError:
395
+ out.append({"id": iid, "name": iid, "installed": False,
396
+ "unknown": True})
397
+ continue
398
+ installed = any(x["id"] == iid and x["installed"]
399
+ for x in available_instruments())
400
+ out.append({"id": iid, "name": cat.get("name", iid),
401
+ "vendor": cat.get("vendor"),
402
+ "simulated": bool(cat.get("simulated")
403
+ or cat.get("simulated_by_default")),
404
+ "hardware_validated":
405
+ bool(cat.get("hardware_validated", False)),
406
+ "installed": installed,
407
+ # operator-declared identity patterns (upload
408
+ # enforcement): part of the fence, not the catalog
409
+ "match": e.get("match") or []})
410
+ elif "simulator" in e:
411
+ out.append({"id": "proef-virtual-lab",
412
+ "name": "Virtual lab (simulator)",
413
+ "simulated": True, "installed": True})
414
+ return out
415
+
416
+
417
+ def fence_declared_caps(labs_entries: list | None) -> dict[str, set]:
418
+ """Union of the capability vocabulary DECLARED by a program's fence
419
+ instruments (from the catalog). Vocabulary-agnostic: the readiness
420
+ check treats unmet declared readouts as blockers, failing closed."""
421
+ ids = [e.get("instrument") for e in labs_entries or []
422
+ if e.get("instrument")]
423
+ readouts, assay_types = set(), set()
424
+ for iid in ids:
425
+ try:
426
+ cat = _catalog_entry(iid)
427
+ except ValueError:
428
+ continue
429
+ readouts |= {str(r) for r in cat.get("readouts") or []}
430
+ assay_types |= {str(a) for a in cat.get("assay_types") or []}
431
+ return {"readouts": readouts, "assay_types": assay_types}
proef/materials.py ADDED
@@ -0,0 +1,140 @@
1
+ """Materials DMTA runner — Design-of-experiments property sweep.
2
+
3
+ For material modality programs: Design a formulation sweep, Make each
4
+ formulation, Test it on the sweep rig, Analyze the best against the
5
+ program gate. Produces the same provenance shape as every other
6
+ campaign (problem_defined -> lab_run -> verdict -> review), so the
7
+ workbench, `proef prove`, and the reviewer treat it identically.
8
+
9
+ Gate direction is honored: for max-metrics (tensile strength, t_half,
10
+ yield) a sweep is validated when its best value MEETS OR EXCEEDS the
11
+ gate; the reviewer reads the recorded direction.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import random
16
+ import uuid
17
+ from pathlib import Path
18
+
19
+ from proef.assays.properties import read_property_sweep
20
+ from proef.assays.simulate import simulate_property_sweep
21
+ from proef.core.contracts import (Envelope, EventType, Artifact,
22
+ ArtifactKind)
23
+ from proef.core.interfaces import record_for, system_actor
24
+
25
+
26
+ def run_materials_sweep(objective: str, formulations: list[float],
27
+ gate: float, unit: str = "MPa",
28
+ metric: str = "tensile_strength_mpa",
29
+ param: str = "crosslinker_pct",
30
+ direction: str = "max",
31
+ store=None, exports_dir: str = ".data/exports",
32
+ seed: int | None = None,
33
+ notify=None) -> dict:
34
+ say = notify or (lambda m: print(f"[materials] {m}"))
35
+ store = store if store is not None else __import__(
36
+ "proef.adapters.store.sqlite",
37
+ fromlist=["SqliteProvenanceStore"]).SqliteProvenanceStore()
38
+ problem_id = f"mat-{uuid.uuid4().hex[:6]}"
39
+ branch = f"problem/{problem_id}"
40
+ rng = random.Random(seed if seed is not None else uuid.uuid4().hex)
41
+
42
+ def rec(event_type, decision, actor="materials"):
43
+ return store.append(record_for(
44
+ Envelope(experiment_branch_id=branch),
45
+ EventType(event_type) if isinstance(event_type, str)
46
+ else event_type, system_actor(actor), decision=decision))
47
+
48
+ # Design: the registered problem, in the SAME shape every campaign
49
+ # uses (single-node problem tree) so the workspace, navigator and
50
+ # breadcrumb treat materials runs as first-class trees
51
+ from proef.problem_tree import ProblemNode, ProblemTree
52
+ sweep_tree = ProblemTree(
53
+ root=ProblemNode(id=problem_id, objective=objective,
54
+ metric=metric, direction=direction, gate=gate),
55
+ nodes={problem_id: ProblemNode(
56
+ id=problem_id, objective=objective, metric=metric,
57
+ direction=direction, gate=gate)},
58
+ modality="material", run_budget=len(formulations))
59
+ rec("problem_defined", {
60
+ "problem_id": problem_id, "objective": objective,
61
+ "modality": "material",
62
+ "constraints": [{"name": metric,
63
+ "description": f"{metric} {direction} {gate:g}",
64
+ "kind": "hard", "limit": gate, "unit": unit}],
65
+ "success_metric": f"best {metric} meets the {gate:g} {unit} gate",
66
+ "environment": {"kind": "problem-tree",
67
+ "tree": sweep_tree.model_dump(),
68
+ "run_budget": len(formulations)}})
69
+
70
+ cand = f"{metric} {direction} {gate:g} {unit}"
71
+ rec("hypothesis_proposed", {
72
+ "hypothesis_id": f"hyp-{problem_id}", "candidate": cand,
73
+ "statement": f"{objective} — best formulation reaches {metric} "
74
+ f"{direction} {gate:g} {unit}",
75
+ "rationale": "formulation sweep around the program gate"},
76
+ actor="materials")
77
+
78
+ # Make + Test: produce and measure each formulation (hidden true
79
+ # optimum lives in the rig's seed — the analysis must find it)
80
+ hidden_optimum = rng.choice(formulations) + rng.uniform(-0.4, 0.4)
81
+ rows, truth = simulate_property_sweep(
82
+ formulations, optimum=round(hidden_optimum, 3), seed=rng.randint(
83
+ 0, 10 ** 6), metric=metric, param=param)
84
+ exports = Path(exports_dir)
85
+ exports.mkdir(parents=True, exist_ok=True)
86
+ sweep_file = exports / f"{problem_id}-sweep.csv"
87
+ keys = list(rows[0].keys())
88
+ sweep_file.write_text(",".join(keys) + "\n" + "\n".join(
89
+ ",".join(str(r[k]) for k in keys) for r in rows) + "\n")
90
+ for i, (row, x) in enumerate(zip(rows, formulations)):
91
+ rec("lab_run", {
92
+ "run_id": f"sweep-{i + 1:03d}",
93
+ "title": f"formulation {x:g} {param}",
94
+ "assay": f"{metric} sweep",
95
+ "n_samples": 1, "replicates": 1, "n_controls": 0,
96
+ "concentrations": [x],
97
+ "instrument": "materials-sweep-rig",
98
+ "instrument_version": "sweep-v1",
99
+ "export": str(sweep_file)}, actor="materials-rig")
100
+ say(f"produced and measured formulation {x:g} {param} "
101
+ f"-> {row[metric]} {unit}")
102
+
103
+ # Analyze: best formulation vs the gate (direction-aware)
104
+ result = read_property_sweep(sweep_file, param=param, metric=metric)
105
+ best = result["best"]
106
+ meets = (best["value"] >= gate) if direction == "max" \
107
+ else (best["value"] <= gate)
108
+ verdict = "validated" if meets else "invalidated"
109
+ rec("hypothesis_tested", {
110
+ "hypothesis_id": f"hyp-{problem_id}", "candidate": cand,
111
+ "verdict": None, "run_id": f"sweep-{len(formulations):03d}",
112
+ "observed": best["value"]}, actor="analysis")
113
+ rec("hypothesis_validated" if verdict == "validated"
114
+ else "hypothesis_invalidated", {
115
+ "hypothesis_id": f"hyp-{problem_id}", "candidate": cand,
116
+ "verdict": verdict,
117
+ "observed": best["value"],
118
+ "observed_ci": None, "threshold": gate, "direction": direction,
119
+ "evidence_run_id": f"sweep-{formulations.index(best['param']) + 1:03d}",
120
+ "derivation": {"method": "property-sweep best-of",
121
+ "measured_by": "materials-sweep-rig",
122
+ "raw": f"{metric} per formulation",
123
+ "derived": {"metric": metric,
124
+ "best_param": best["param"]}},
125
+ "note": result["note"]}, actor="analysis")
126
+ say(f"best: {best['param']:g} {param} at {best['value']:g} {unit} "
127
+ f"vs gate {gate:g} -> {verdict}"
128
+ + (f" ({result['note']})" if result["note"] else ""))
129
+
130
+ # Reviewer: same independent audit as every other campaign
131
+ from proef.reviewer import review_campaign
132
+ review = review_campaign(store.branch_records(branch))
133
+ rec("stage_transition", {"kind": "review_report", **review},
134
+ actor="reviewer")
135
+ say(f"reviewer: {review['critical']} critical / "
136
+ f"{review['warnings']} warnings")
137
+
138
+ return {"problem_id": problem_id, "branch": branch, "verdict": verdict,
139
+ "best": best, "review": review,
140
+ "truth": {"hidden_optimum": truth["true_optimum"]}}