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,143 @@
1
+ """HCS microscope adapter — per-cell image capture for vision-LLM readout.
2
+
3
+ Connects to Thermo Fisher CellInsight, Revvity Operetta, or compatible
4
+ high-content screening microscopes. Returns per-cell fluorescence data
5
+ as structured measurements that feed into the vision-LLM readout and
6
+ the missing-denominator check.
7
+
8
+ HONEST STATUS (hardware trust audit, Oct 10): this adapter is a
9
+ SIMULATOR ONLY. "Live mode" is NOT implemented — simulator=False raises
10
+ rather than silently returning synthetic readings dressed as instrument
11
+ data. Vendor REST/file binding is roadmap work (ROADMAP S-T4). All
12
+ results are labeled simulated in capabilities.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import random
17
+ from typing import Any
18
+
19
+ from proef.core.contracts import (
20
+ AssayResult, Envelope, InstrumentInfo, Measurement, MeasurementFlag,
21
+ ProtocolSubmission, RunStatus,
22
+ )
23
+
24
+
25
+ class HCSSimulator:
26
+ """Simulates per-cell fluorescence data matching seeded ground truth."""
27
+
28
+ def __init__(self, seed: int = 7):
29
+ self.rng = random.Random(seed)
30
+
31
+ def capture_cells(self, sample_id: str, conc_um: float,
32
+ true_ic50: float, n_cells: int = 200
33
+ ) -> list[dict[str, Any]]:
34
+ """Generate synthetic per-cell fluorescence intensities.
35
+
36
+ Each cell gets a signal drawn from a mixture distribution:
37
+ - edited cells (fraction ~ dose-dependent) have high signal
38
+ - unedited cells have background-level signal
39
+ The fraction edited is the simulation's ground truth for the
40
+ missing-denominator measurement.
41
+ """
42
+ cells = []
43
+ # fraction edited follows Hill-like dose response
44
+ max_frac = min(1.0, conc_um / (conc_um + true_ic50))
45
+ for i in range(n_cells):
46
+ is_edited = self.rng.random() < max_frac
47
+ if is_edited:
48
+ signal = self.rng.gauss(750, 80) # high: edited
49
+ else:
50
+ signal = self.rng.gauss(120, 30) # background: unedited
51
+ cells.append({
52
+ "cell_id": f"{sample_id}-cell-{i}",
53
+ "signal": max(0, signal),
54
+ "edited": is_edited, # ground truth (not exposed to agent)
55
+ })
56
+ return cells
57
+
58
+
59
+ class HCSMicroscopeAdapter:
60
+ """LabAdapter for high-content screening microscopes.
61
+
62
+ In simulation mode, generates synthetic per-cell data. In live mode,
63
+ connects to the microscope's REST API or file-export share.
64
+
65
+ Key feature: returns BOTH population-level measurements (median signal,
66
+ edited fraction) AND per-cell data (for vision-LLM and denominator checks).
67
+ """
68
+
69
+ name = "hcs-microscope"
70
+
71
+ def __init__(self, seed: int = 7, simulator: bool = True,
72
+ image_dir: str | None = None):
73
+ self.seed = seed
74
+ self.image_dir = image_dir
75
+ if not simulator:
76
+ raise NotImplementedError(
77
+ "HCS live mode is not implemented — this adapter only "
78
+ "simulates (ROADMAP S-T4). Refusing to fabricate "
79
+ "'instrument' readings (simulator=False)")
80
+ self.simulator = simulator
81
+ self._runs: dict[str, dict] = {}
82
+ if simulator:
83
+ from proef.adapters.lab.imaging import ImagingPlateReader
84
+ self._plate = ImagingPlateReader(seed=seed)
85
+
86
+ def list_capabilities(self) -> dict[str, Any]:
87
+ return {
88
+ "kind": "hcs_microscope",
89
+ "readout": "per-cell fluorescence",
90
+ "modalities": ["per-cell signal", "edited fraction", "image tiles"],
91
+ "resolution": "single-cell",
92
+ "denominator_capable": True,
93
+ "bsl_max": 2,
94
+ "simulated": True, # ALL output is synthetic (S-T4)
95
+ "hardware_validated": False,
96
+ }
97
+
98
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
99
+ run_id = f"hcs-{protocol.protocol_id[:8]}"
100
+ self._runs[run_id] = protocol
101
+ return run_id
102
+
103
+ def get_status(self, run_id: str) -> str:
104
+ return "done" if run_id in self._runs else "unknown"
105
+
106
+ def fetch_results(self, run_id: str) -> AssayResult:
107
+ protocol = self._runs[run_id]
108
+ measurements = []
109
+ for sample in protocol.samples:
110
+ conc = sample.concentration or "10uM"
111
+ # simulate per-cell data
112
+ cells = HCSSimulator(seed=self.seed).capture_cells(
113
+ sample.sample_id, float(conc.replace("uM", "")),
114
+ true_ic50=15.0, n_cells=200)
115
+ signals = [c["signal"] for c in cells]
116
+ n_edited = sum(1 for c in cells if c["edited"])
117
+ frac = n_edited / len(cells) if cells else 0
118
+ median = sorted(signals)[len(signals) // 2] if signals else 0
119
+ measurements.append(Measurement(
120
+ sample_id=sample.sample_id,
121
+ assay_type="per_cell_fluorescence",
122
+ value=round(frac, 4),
123
+ unit="fraction_edited",
124
+ replicate=1,
125
+ derived_metrics={
126
+ "median_signal": round(median, 1),
127
+ "n_cells": len(cells),
128
+ "n_edited": n_edited,
129
+ },
130
+ flags=[MeasurementFlag.suspect] if frac < 0.05 else [],
131
+ ))
132
+ return AssayResult(
133
+ envelope=Envelope(experiment_branch_id="hcs"),
134
+ protocol_id=protocol.protocol_id,
135
+ instrument=InstrumentInfo(
136
+ adapter=self.name, instrument_id="hcs-01",
137
+ raw_output_uri=self.image_dir or ""),
138
+ status=RunStatus.completed,
139
+ measurements=measurements,
140
+ )
141
+
142
+ def cancel(self, run_id: str) -> None:
143
+ self._runs.pop(run_id, None)
@@ -0,0 +1,123 @@
1
+ """LC-MS adapter — ratiometric proteomics for the missing-denominator check.
2
+
3
+ Connects to LC-MS systems (Waters, Agilent, Thermo Orbitrap) or their
4
+ export pipelines to measure the edited-vs-unedited splice-junction peptide
5
+ ratio. This is the measurement that converts negative functional results
6
+ from uninterpretable to interpretable.
7
+
8
+ In simulation mode, generates synthetic ratiometric data. In live mode,
9
+ connects to the vendor's export API or parses vendor export files
10
+ (.raw → .ms2 → peptide-spectrum matches).
11
+
12
+ The key output is `edited_fraction`: what percentage of the target pool
13
+ was actually modified. This is the number that determines whether a
14
+ negative functional result is interpretable.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import random
19
+ from typing import Any
20
+
21
+ from proef.core.contracts import (
22
+ AssayResult, Envelope, InstrumentInfo, Measurement, ProtocolSubmission,
23
+ RunStatus, SampleKind,
24
+ )
25
+
26
+
27
+ class LCMSSimulator:
28
+ """Simulates ratiometric proteomics results for the missing-denominator."""
29
+
30
+ def __init__(self, seed: int = 7):
31
+ self.rng = random.Random(seed)
32
+
33
+ def measure_edited_fraction(self, sample_id: str, true_fraction: float,
34
+ noise: float = 0.08) -> dict[str, Any]:
35
+ """Simulate a ratiometric MS measurement of the edited fraction.
36
+
37
+ Returns the measured fraction (with MS-level noise) plus the raw
38
+ counts of edited and unedited splice-junction peptides.
39
+ """
40
+ n_total = self.rng.randint(80, 200)
41
+ measured_frac = true_fraction + self.rng.gauss(0, noise)
42
+ measured_frac = max(0.0, min(1.0, measured_frac))
43
+ n_edited = round(n_total * measured_frac)
44
+ return {
45
+ "sample_id": sample_id,
46
+ "edited_fraction": round(measured_frac, 4),
47
+ "n_edited_peptides": n_edited,
48
+ "n_total_peptides": n_total,
49
+ "confidence": round(1.0 - noise * 5, 2),
50
+ }
51
+
52
+
53
+ class LCMSAdapter:
54
+ """LabAdapter for LC-MS ratiometric proteomics.
55
+
56
+ Unlike potency assays (dose-response IC50), this adapter measures the
57
+ edited-vs-unedited fraction directly from splice-junction peptides.
58
+ It is the instrument that supplies the missing denominator.
59
+ """
60
+
61
+ name = "lcms"
62
+
63
+ def __init__(self, seed: int = 7, simulator: bool = True):
64
+ if not simulator:
65
+ raise NotImplementedError(
66
+ "LC-MS live mode (.raw parsing / vendor API) is not "
67
+ "implemented — this adapter only simulates (ROADMAP "
68
+ "S-T4); refusing to dress synthetic values as spectra")
69
+ self.rng = random.Random(seed)
70
+ self.sim = LCMSSimulator(seed)
71
+ self.simulator = simulator
72
+ self._runs: dict[str, list[str]] = {}
73
+
74
+ def list_capabilities(self) -> dict[str, Any]:
75
+ return {
76
+ "kind": "lcms",
77
+ "readout": "ratiometric_bottom_up_proteomics",
78
+ "measures": ["edited_fraction", "splice_junction_peptides",
79
+ "unmodified_target"],
80
+ "denominator_capable": True,
81
+ "simulated": True, "hardware_validated": False,
82
+ "note": "SIMULATOR ONLY (S-T4): supplies the missing "
83
+ "denominator in virtual campaigns; no .raw parsing "
84
+ "or vendor API exists yet",
85
+ }
86
+
87
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
88
+ run_id = f"lcms-{protocol.protocol_id[:8]}"
89
+ self._runs[run_id] = [
90
+ s.sample_id for s in protocol.samples
91
+ if s.kind == SampleKind.compound
92
+ ]
93
+ return run_id
94
+
95
+ def get_status(self, run_id: str) -> str:
96
+ return "done" if run_id in self._runs else "unknown"
97
+
98
+ def fetch_results(self, run_id: str) -> AssayResult:
99
+ samples = self._runs.get(run_id, [])
100
+ measurements = []
101
+ for smi in samples:
102
+ true_frac = min(1.0, max(0.0, len(smi) / 60.0))
103
+ measured = true_frac + self.rng.gauss(0, 0.05)
104
+ measurements.append(Measurement(
105
+ sample_id=smi,
106
+ assay_type="ratiometric_proteomics",
107
+ value=round(max(0.0, min(1.0, measured)), 4),
108
+ unit="fraction_edited",
109
+ derived_metrics={
110
+ "n_splice_junction_peptides": self.rng.randint(80, 200),
111
+ "confidence": 0.95,
112
+ },
113
+ ))
114
+ return AssayResult(
115
+ envelope=Envelope(experiment_branch_id="lcms"),
116
+ protocol_id=run_id,
117
+ instrument=InstrumentInfo(adapter=self.name, instrument_id="lcms-01"),
118
+ status=RunStatus.completed,
119
+ measurements=measurements,
120
+ )
121
+
122
+ def cancel(self, run_id: str) -> None:
123
+ self._runs.pop(run_id, None)
@@ -0,0 +1,84 @@
1
+ """Robotic arm / plate scheduling adapter — Automata LINQ (endpoint shapes UNVALIDATED — S-T4), HighRes Cellario.
2
+
3
+ In a multi-device lab, plates must be transported between instruments
4
+ (incubator → dispenser → reader → LC-MS). This adapter handles plate
5
+ scheduling: it queries device availability, plans the transport route,
6
+ and issues REST API commands to robotic arms or track systems.
7
+
8
+ Proef does not replace the lab's scheduling software (Cellario,
9
+ Overlord, Velum) — it interfaces with it via REST APIs, sending
10
+ `move_plate` commands and monitoring completion.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import urllib.request
16
+ from typing import Any, Protocol
17
+
18
+
19
+ class SchedulerTransport(Protocol):
20
+ def post(self, path: str, body: dict) -> dict: ...
21
+ def get(self, path: str) -> dict: ...
22
+
23
+
24
+ class HTTPScheduler:
25
+ def __init__(self, base_url: str, api_key: str = ""):
26
+ self.base_url = base_url.rstrip("/")
27
+ self.headers = {"Content-Type": "application/json"}
28
+ if api_key:
29
+ self.headers["Authorization"] = f"Bearer {api_key}"
30
+
31
+ def post(self, path: str, body: dict) -> dict:
32
+ req = urllib.request.Request(
33
+ f"{self.base_url}{path}", data=json.dumps(body).encode(),
34
+ headers=self.headers, method="POST")
35
+ with urllib.request.urlopen(req, timeout=30) as r:
36
+ return json.loads(r.read())
37
+
38
+ def get(self, path: str) -> dict:
39
+ req = urllib.request.Request(
40
+ f"{self.base_url}{path}", headers=self.headers, method="GET")
41
+ with urllib.request.urlopen(req, timeout=30) as r:
42
+ return json.loads(r.read())
43
+
44
+
45
+ class RoboticArmScheduler:
46
+ """Schedules plate transport between devices via REST API.
47
+
48
+ Connects to centralized scheduling software (Cellario, Overlord,
49
+ Automata LINQ (endpoint shapes UNVALIDATED — S-T4)). The agent sends a high-level `transport_plate` command;
50
+ the scheduling software handles robot selection, path planning, and
51
+ collision avoidance.
52
+ """
53
+
54
+ name = "robotic-arm-scheduler"
55
+
56
+ def __init__(self, transport: SchedulerTransport):
57
+ self.transport = transport
58
+
59
+ def move_plate(self, from_device: str, to_device: str,
60
+ plate_id: str, plate_type: str = "96-well") -> dict:
61
+ """Request a plate transport between two devices."""
62
+ return self.transport.post("/move_plate", {
63
+ "from": from_device, "to": to_device,
64
+ "plate_id": plate_id, "plate_type": plate_type,
65
+ })
66
+
67
+ def device_status(self, device_id: str) -> dict:
68
+ return self.transport.get(f"/devices/{device_id}/status")
69
+
70
+ def queue_depth(self) -> int:
71
+ """Number of pending transport requests."""
72
+ q = self.transport.get("/queue")
73
+ return len(q.get("queue", []))
74
+
75
+ def wait_for_transport(self, move_id: str, timeout: int = 120) -> bool:
76
+ """Block until a transport completes (or timeout)."""
77
+ import time
78
+ deadline = time.time() + timeout
79
+ while time.time() < deadline:
80
+ status = self.transport.get(f"/moves/{move_id}").get("status", "")
81
+ if status in ("completed", "failed"):
82
+ return status == "completed"
83
+ time.sleep(2)
84
+ return False
@@ -0,0 +1,134 @@
1
+ """GENERIC HTTP device adapter — NOT a SiLA 2 binding (audit Oct 10, S-T4): the real SiLA 2 protocol needs the gRPC sila2 SDK and its feature/resolve semantics, which are not implemented here. This speaks a simple JSON POST/GET contract (/command, /status, /results) that real SiLA 2 devices do NOT serve. Honest name: template-hub-style HTTP device shim."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import urllib.request
6
+ from typing import Any, Protocol
7
+
8
+ from proef.core.contracts import (
9
+ AssayResult, Envelope, InstrumentInfo, Measurement, ProtocolSubmission,
10
+ RunStatus,
11
+ )
12
+
13
+
14
+ class SiLA2Channel(Protocol):
15
+ """Transport abstraction — injectable for tests (P8)."""
16
+
17
+ def call(self, endpoint: str, payload: dict) -> dict: ...
18
+
19
+
20
+ class SiLA2HTTPChannel:
21
+ """HTTP gateway mode for SiLA 2 devices (SiLA 2 HTTP binding)."""
22
+
23
+ def __init__(self, base_url: str, timeout: int = 60):
24
+ self.base_url = base_url.rstrip("/")
25
+ self.timeout = timeout
26
+
27
+ def call(self, endpoint: str, payload: dict) -> dict:
28
+ req = urllib.request.Request(
29
+ f"{self.base_url}{endpoint}",
30
+ data=json.dumps(payload).encode(),
31
+ headers={"Content-Type": "application/json"},
32
+ method="POST",
33
+ )
34
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp: # noqa: S310
35
+ return json.loads(resp.read())
36
+
37
+
38
+ class SiLA2Device:
39
+ """A single SiLA 2 device discovered on the network or configured."""
40
+
41
+ def __init__(self, device_id: str, features: list[str],
42
+ endpoint: str, kind: str):
43
+ self.device_id = device_id
44
+ self.features = features
45
+ self.endpoint = endpoint
46
+ self.kind = kind
47
+
48
+
49
+ class SiLA2Adapter:
50
+ """Generic LabAdapter over SiLA 2.
51
+
52
+ One adapter instance manages one SiLA 2 device (or a SiLA 2 gateway
53
+ managing multiple devices). The `feature_namespace` maps Proef
54
+ protocol operations to SiLA 2 feature identifiers.
55
+
56
+ Example feature namespaces:
57
+ - "org.silastandard.examples.TemperatureController"
58
+ - "org.silastandard.core.CommandController"
59
+ """
60
+
61
+ name = "sila2"
62
+
63
+ def __init__(self, channel: SiLA2Channel, device_label: str = "sila2-device",
64
+ feature_map: dict[str, str] | None = None):
65
+ """`feature_map` maps Proef operations to SiLA 2 feature IDs:
66
+ {"submit": "org.silastandard.../Command/Start",
67
+ "status": "org.silastandard.../Property/Status",
68
+ "results": "org.silastandard.../Command/GetResult"}
69
+ """
70
+ self.channel = channel
71
+ self.device_label = device_label
72
+ self.feature_map = feature_map or {}
73
+ self._runs: dict[str, ProtocolSubmission] = {}
74
+
75
+ def list_capabilities(self) -> dict[str, Any]:
76
+ return {
77
+ "kind": "sila2",
78
+ "device_label": self.device_label,
79
+ "protocol": "SiLA 2 (gRPC or HTTP binding)",
80
+ "features": self.feature_map,
81
+ "note": "One adapter covers all SiLA 2-compliant devices",
82
+ }
83
+
84
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
85
+ run_id = f"sila2-{protocol.protocol_id[:8]}"
86
+ self._runs[run_id] = protocol
87
+ # Send the compiled protocol to the SiLA 2 device's Execute command
88
+ endpoint = self.feature_map.get("execute", "/command")
89
+ payload = {
90
+ "command_id": protocol.protocol_id,
91
+ "steps": [
92
+ {"seq": s.seq, "op": s.op.value, "params": s.params}
93
+ for s in protocol.steps
94
+ ],
95
+ "samples": [
96
+ {"id": s.sample_id, "well": s.concentration}
97
+ for s in protocol.samples
98
+ ],
99
+ }
100
+ self.channel.call(endpoint, payload)
101
+ return run_id
102
+
103
+ def get_status(self, run_id: str) -> str:
104
+ endpoint = self.feature_map.get("status", "/status")
105
+ result = self.channel.call(endpoint, {"run_id": run_id})
106
+ return result.get("status", "unknown")
107
+
108
+ def fetch_results(self, run_id: str) -> AssayResult:
109
+ endpoint = self.feature_map.get("results", "/results")
110
+ result = self.channel.call(endpoint, {"run_id": run_id})
111
+ measurements = []
112
+ for m in result.get("measurements", []):
113
+ measurements.append(Measurement(
114
+ sample_id=m.get("sample_id", ""),
115
+ well=m.get("well"),
116
+ assay_type=m.get("assay_type", "unknown"),
117
+ value=float(m.get("value", 0)),
118
+ unit=m.get("unit", ""),
119
+ metadata=m.get("metadata", {}),
120
+ ))
121
+ protocol = self._runs.get(run_id)
122
+ return AssayResult(
123
+ envelope=Envelope(experiment_branch_id="sila2"),
124
+ protocol_id=protocol.protocol_id if protocol else run_id,
125
+ instrument=InstrumentInfo(
126
+ adapter=self.name, instrument_id=self.device_label,
127
+ raw_output_uri=f"sila2://{run_id}"),
128
+ status=RunStatus(result.get("status", "completed")),
129
+ measurements=measurements,
130
+ )
131
+
132
+ def cancel(self, run_id: str) -> None:
133
+ endpoint = self.feature_map.get("cancel", "/cancel")
134
+ self.channel.call(endpoint, {"run_id": run_id})
@@ -0,0 +1,146 @@
1
+ """AlphaGenome Atlas adapter — variant impact predictions (Google DeepMind).
2
+
3
+ AlphaGenome Atlas precomputes the functional impact of all ~9 billion
4
+ single-nucleotide variants in the human genome, condensed into the
5
+ AlphaGenome Variant Impact (AVI) score with feature attributions (splicing,
6
+ chromatin accessibility, conservation, protein impact).
7
+
8
+ Two backends behind one interface (P2):
9
+ - AtlasAPI — the real AlphaGenome API (needs the `alphagenome` package
10
+ + ALPHAGENOME_API_KEY). Non-commercial terms apply.
11
+ - SimulatedAVI — deterministic seeded scorer (P8) so CI, tests and demos
12
+ run offline. Ground truth is invented; the interface is not.
13
+
14
+ Non-commercial use only; not for clinical decision-making (DeepMind ToU).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import os
20
+ from typing import Any
21
+
22
+ from pydantic import BaseModel, Field
23
+
24
+ ATTRIBUTION_CATEGORIES = ("splicing", "chromatin_accessibility",
25
+ "gene_expression", "conservation", "protein_impact")
26
+
27
+
28
+ class VariantImpact(BaseModel):
29
+ variant: str # "chr22:36201698:A>C"
30
+ avi_score: float # 0–1, higher = more likely functional
31
+ classification: str # high | moderate | low impact
32
+ attributions: dict[str, float] = Field(default_factory=dict)
33
+ source: str = "simulated" # atlas_api | simulated
34
+ detail: str = ""
35
+
36
+ def summary(self) -> dict[str, Any]:
37
+ top = sorted(self.attributions.items(), key=lambda kv: -kv[1])[:3]
38
+ return {
39
+ "variant": self.variant,
40
+ "avi_score": round(self.avi_score, 4),
41
+ "classification": self.classification,
42
+ "top_drivers": dict(top),
43
+ "source": self.source,
44
+ }
45
+
46
+
47
+ def _classify(score: float) -> str:
48
+ if score >= 0.8:
49
+ return "high"
50
+ if score >= 0.5:
51
+ return "moderate"
52
+ return "low"
53
+
54
+
55
+ def _key(chromosome: str, position: int, ref: str, alt: str) -> str:
56
+ return f"{chromosome}:{position}:{ref}>{alt}"
57
+
58
+
59
+ class SimulatedAVI:
60
+ """Deterministic offline scorer. Seeded per variant so the same variant
61
+ always scores the same — reproducible demos, no network."""
62
+
63
+ name = "simulated-avi"
64
+ source = "simulated"
65
+
66
+ def score(self, chromosome: str, position: int, ref: str, alt: str) -> VariantImpact:
67
+ material = f"{chromosome}:{position}:{ref}>{alt}".encode()
68
+ h = int(hashlib.sha256(material).hexdigest()[:16], 16)
69
+ avi = ((h % 10000) / 10000.0) ** 1.2 # skew toward low impact
70
+ # attribution shares that sum to the score
71
+ weights = [((h >> (11 * i)) % 97) + 3 for i in range(len(ATTRIBUTION_CATEGORIES))]
72
+ total = sum(weights)
73
+ attributions = {cat: round(avi * w / total, 4)
74
+ for cat, w in zip(ATTRIBUTION_CATEGORIES, weights)}
75
+ return VariantImpact(
76
+ variant=_key(chromosome, position, ref, alt),
77
+ avi_score=round(avi, 4),
78
+ classification=_classify(avi),
79
+ attributions=attributions,
80
+ source=self.source,
81
+ detail="seeded simulation — no biological meaning (P8)",
82
+ )
83
+
84
+ def rank(self, variants: list[dict[str, Any]]) -> list[VariantImpact]:
85
+ scored = [self.score(**{k: v for k, v in v_.items()
86
+ if k in ("chromosome", "position", "ref", "alt")})
87
+ for v_ in variants]
88
+ return sorted(scored, key=lambda v: -v.avi_score)
89
+
90
+
91
+ class AtlasAPI:
92
+ """Real AlphaGenome API backend. Requires `pip install alphagenome` and
93
+ ALPHAGENOME_API_KEY (free for non-commercial use)."""
94
+
95
+ name = "alphagenome-atlas"
96
+ source = "atlas_api"
97
+
98
+ def __init__(self, api_key: str | None = None):
99
+ try:
100
+ from alphagenome.models import dna_client # noqa: F401
101
+ except ImportError as exc:
102
+ raise ImportError(
103
+ "install the AlphaGenome client: pip install alphagenome") from exc
104
+ self._key = api_key or os.environ.get("ALPHAGENOME_API_KEY", "")
105
+ if not self._key:
106
+ raise ValueError("ALPHAGENOME_API_KEY not set — get one at "
107
+ "https://deepmind.google.com/science/alphagenome")
108
+ self._client = dna_client.create(self._key)
109
+
110
+ def score(self, chromosome: str, position: int, ref: str, alt: str) -> VariantImpact:
111
+ # Atlas precomputed AVI score via the API client. The exact entry
112
+ # point firms up with the SDK release; until then fall back to
113
+ # live variant scoring of the relevant outputs.
114
+ from alphagenome.data import genome
115
+ from alphagenome.models import dna_client
116
+ variant = genome.Variant(chromosome=chromosome.lstrip("chr") and chromosome,
117
+ position=position,
118
+ reference_bases=ref, alternate_bases=alt)
119
+ interval = genome.Interval(chromosome=chromosome,
120
+ start=max(0, position - 32768),
121
+ end=position + 32768)
122
+ outputs = self._client.score_variants(
123
+ interval=interval, variants=[variant],
124
+ requested_outputs=[dna_client.OutputType.RNA_SEQ])
125
+ avi = float(outputs[0].metadata.get("avi_score", 0.0))
126
+ attributions = {k: float(v) for k, v in
127
+ (outputs[0].metadata.get("attributions") or {}).items()}
128
+ return VariantImpact(
129
+ variant=_key(chromosome, position, ref, alt),
130
+ avi_score=avi, classification=_classify(avi),
131
+ attributions=attributions, source=self.source,
132
+ detail="AlphaGenome Atlas / API (non-commercial terms)")
133
+
134
+ def rank(self, variants: list[dict[str, Any]]) -> list[VariantImpact]:
135
+ scored = [self.score(**{k: v for k, v in v_.items()
136
+ if k in ("chromosome", "position", "ref", "alt")})
137
+ for v_ in variants]
138
+ return sorted(scored, key=lambda v: -v.avi_score)
139
+
140
+
141
+ def get_variant_scorer() -> SimulatedAVI | AtlasAPI:
142
+ """Factory: real Atlas API when package+key are present, else simulated."""
143
+ try:
144
+ return AtlasAPI()
145
+ except (ImportError, ValueError):
146
+ return SimulatedAVI()
File without changes
@@ -0,0 +1,32 @@
1
+ """Virtual bioprocess QC — the biologic Make/Test boundary.
2
+
3
+ For biologic batches that passed synthesis: a deterministic stability
4
+ and aggregation screen (seeded from the sequence). A batch with high
5
+ aggregation risk or a short half-life is refused into Test — the same
6
+ gate-on-the-physical-step pattern as synthesis, so biologics get a real
7
+ Make before any assay runs.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import random
13
+
14
+ MAX_AGGREGATION = 0.35
15
+ MIN_T_HALF_H = 12.0
16
+
17
+
18
+ def bioprocess_qc(candidate: str, sequence: str,
19
+ lot: str) -> dict:
20
+ seed = hashlib.sha256(f"{candidate}|{sequence}|{lot}".encode()).hexdigest()
21
+ rng = random.Random(seed)
22
+ aggregation = round(rng.random(), 3)
23
+ t_half = round(4 + rng.random() * 40, 1) # hours
24
+ ok = aggregation <= MAX_AGGREGATION and t_half >= MIN_T_HALF_H
25
+ reasons = []
26
+ if aggregation > MAX_AGGREGATION:
27
+ reasons.append(f"aggregation risk {aggregation} > {MAX_AGGREGATION}")
28
+ if t_half < MIN_T_HALF_H:
29
+ reasons.append(f"t½ {t_half}h < {MIN_T_HALF_H}h")
30
+ return {"candidate": candidate, "lot": lot,
31
+ "aggregation_risk": aggregation, "t_half_h": t_half,
32
+ "ok": ok, "note": "; ".join(reasons)}