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.
- proef/__init__.py +25 -0
- proef/acquisition.py +244 -0
- proef/ad.py +159 -0
- proef/adapters/__init__.py +0 -0
- proef/adapters/admet.py +196 -0
- proef/adapters/bio/__init__.py +0 -0
- proef/adapters/bio/rdkit_ops.py +52 -0
- proef/adapters/bio/safety_rules.json +146 -0
- proef/adapters/bio/seq_alerts.py +79 -0
- proef/adapters/bio/structure_score.py +85 -0
- proef/adapters/bio/tox_alerts.py +99 -0
- proef/adapters/data/__init__.py +0 -0
- proef/adapters/data/admet.py +62 -0
- proef/adapters/data/chembl.py +110 -0
- proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
- proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
- proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
- proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
- proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
- proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
- proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
- proef/adapters/data/moleculenet.py +60 -0
- proef/adapters/databases/__init__.py +0 -0
- proef/adapters/databases/chembl_gates.py +121 -0
- proef/adapters/databases/chembl_lookup.py +35 -0
- proef/adapters/databases/open_targets.py +102 -0
- proef/adapters/databases/pubmed.py +94 -0
- proef/adapters/devices/__init__.py +0 -0
- proef/adapters/devices/ezo_ph.py +251 -0
- proef/adapters/devices/hcs_microscope.py +143 -0
- proef/adapters/devices/lcms.py +123 -0
- proef/adapters/devices/scheduler.py +84 -0
- proef/adapters/devices/sila2.py +134 -0
- proef/adapters/genomics/alphagenome.py +146 -0
- proef/adapters/lab/__init__.py +0 -0
- proef/adapters/lab/bioprocess.py +32 -0
- proef/adapters/lab/devices.py +170 -0
- proef/adapters/lab/imaging.py +226 -0
- proef/adapters/lab/mhs_driver.py +124 -0
- proef/adapters/lab/opentrons.py +222 -0
- proef/adapters/lab/ot2_sim.py +174 -0
- proef/adapters/lab/plate_reader_share.py +108 -0
- proef/adapters/lab/protein_design.py +199 -0
- proef/adapters/lab/recording.py +119 -0
- proef/adapters/lab/replay.py +107 -0
- proef/adapters/lab/simulator.py +282 -0
- proef/adapters/lab/synthesis.py +92 -0
- proef/adapters/models/__init__.py +0 -0
- proef/adapters/models/anthropic_provider.py +157 -0
- proef/adapters/models/assayloop_ranker.py +67 -0
- proef/adapters/models/from_env.py +93 -0
- proef/adapters/models/gp_policy.py +93 -0
- proef/adapters/models/gp_policy_gp.py +36 -0
- proef/adapters/models/llm_policy.py +187 -0
- proef/adapters/models/openai_compat.py +150 -0
- proef/adapters/models/sklearn_policy.py +65 -0
- proef/adapters/retrosynthesis.py +247 -0
- proef/adapters/sandbox/__init__.py +20 -0
- proef/adapters/sandbox/agentenv.py +145 -0
- proef/adapters/sandbox/docker.py +217 -0
- proef/adapters/sandbox/local.py +164 -0
- proef/adapters/sandbox/opensandbox.py +122 -0
- proef/adapters/store/__init__.py +0 -0
- proef/adapters/store/sqlite.py +207 -0
- proef/adaptive.py +108 -0
- proef/advisory.py +76 -0
- proef/analysis_profiles/__init__.py +8 -0
- proef/analysis_profiles/measurements.py +266 -0
- proef/analysis_profiles/plate_assay.py +316 -0
- proef/analysis_report.py +195 -0
- proef/analysis_store.py +183 -0
- proef/anchor.py +154 -0
- proef/api/app.py +107 -0
- proef/api/launch.py +170 -0
- proef/api/v1/__init__.py +29 -0
- proef/api/v1/analyses.py +367 -0
- proef/api/v1/campaigns.py +802 -0
- proef/api/v1/deps.py +10 -0
- proef/api/v1/evals.py +16 -0
- proef/api/v1/evidence.py +132 -0
- proef/api/v1/governance.py +35 -0
- proef/api/v1/inbox.py +119 -0
- proef/api/v1/lab.py +110 -0
- proef/api/v1/pauses.py +77 -0
- proef/api/v1/programs.py +397 -0
- proef/api/v1/results.py +147 -0
- proef/api/v1/schemas.py +932 -0
- proef/api/v1/system.py +79 -0
- proef/api/v1/trees.py +216 -0
- proef/api/wizard_sessions.py +253 -0
- proef/approvals.py +102 -0
- proef/assays/__init__.py +15 -0
- proef/assays/dls.py +114 -0
- proef/assays/dsf.py +81 -0
- proef/assays/elisa.py +58 -0
- proef/assays/properties.py +65 -0
- proef/assays/simulate.py +157 -0
- proef/audit.py +152 -0
- proef/autoloop.py +1620 -0
- proef/benchmark.py +442 -0
- proef/campaign_fsm.py +151 -0
- proef/citations.py +141 -0
- proef/cli.py +1249 -0
- proef/connect.py +74 -0
- proef/core/__init__.py +0 -0
- proef/core/contracts/__init__.py +35 -0
- proef/core/contracts/analysis.py +100 -0
- proef/core/contracts/models.py +395 -0
- proef/core/device_card.py +125 -0
- proef/core/hypothesis.py +720 -0
- proef/core/interfaces.py +164 -0
- proef/core/registry.py +123 -0
- proef/core/safety.py +324 -0
- proef/core/workflow.py +159 -0
- proef/critic.py +62 -0
- proef/demo.py +164 -0
- proef/derivation.py +128 -0
- proef/diary.py +301 -0
- proef/eln.py +87 -0
- proef/evals/__init__.py +1 -0
- proef/evals/hallucination.py +86 -0
- proef/evals/harness.py +358 -0
- proef/evals/orchestration.py +254 -0
- proef/evals/tasks.py +1010 -0
- proef/evals/toolcalls.py +425 -0
- proef/experiment.py +172 -0
- proef/experiment_analysis.py +114 -0
- proef/experiments/__init__.py +0 -0
- proef/experiments/grounding_exp.py +689 -0
- proef/figures.py +218 -0
- proef/fitting.py +309 -0
- proef/fixtures.py +140 -0
- proef/flywheel.py +125 -0
- proef/followup.py +126 -0
- proef/governance.py +290 -0
- proef/groundedness.py +361 -0
- proef/grounding.py +202 -0
- proef/hypothesis_agent.py +369 -0
- proef/ingest.py +157 -0
- proef/instruments.json +173 -0
- proef/interpret.py +95 -0
- proef/kinetic.py +102 -0
- proef/labread/__init__.py +45 -0
- proef/labread/analysis.py +428 -0
- proef/labread/common.py +153 -0
- proef/labread/formats.py +190 -0
- proef/labread/layout.py +168 -0
- proef/labread/pubchem.py +179 -0
- proef/labselect.py +431 -0
- proef/materials.py +140 -0
- proef/mcp_instrument.py +396 -0
- proef/mcp_server.py +283 -0
- proef/modality.py +111 -0
- proef/model_guard.py +245 -0
- proef/output_blocks.py +183 -0
- proef/paths.py +32 -0
- proef/physfail.py +55 -0
- proef/plan.py +160 -0
- proef/plots.py +123 -0
- proef/predictors.py +217 -0
- proef/probes.py +79 -0
- proef/problem_tree.py +581 -0
- proef/program.py +308 -0
- proef/protocol_design.py +42 -0
- proef/proxy.py +78 -0
- proef/readiness.py +259 -0
- proef/reliability.py +49 -0
- proef/report.py +117 -0
- proef/reproduce.py +310 -0
- proef/reviewer.py +254 -0
- proef/sandbox_session.py +247 -0
- proef/sandboxd.py +109 -0
- proef/scaffold.py +195 -0
- proef/series.py +327 -0
- proef/skills.py +203 -0
- proef/sweep.py +83 -0
- proef/taste.py +177 -0
- proef/templates/confirmatory-followup.json +34 -0
- proef/templates/dose-response-screen.json +39 -0
- proef/templates/sar-exploration.json +38 -0
- proef/templates.py +124 -0
- proef/toolkit.py +433 -0
- proef/toolloop.py +133 -0
- proef/tools.py +441 -0
- proef/tpp.py +185 -0
- proef/views/__init__.py +14 -0
- proef/views/counts.py +102 -0
- proef/views/experiment.py +154 -0
- proef/views/ids.py +49 -0
- proef/views/narrative.py +294 -0
- proef/views/pipeline.py +370 -0
- proef/vision.py +165 -0
- proef/watch.py +790 -0
- proef/wizard_chain.py +25 -0
- proef/wizard_store.py +373 -0
- proef-0.2.0.dist-info/METADATA +662 -0
- proef-0.2.0.dist-info/RECORD +200 -0
- proef-0.2.0.dist-info/WHEEL +4 -0
- proef-0.2.0.dist-info/entry_points.txt +14 -0
- proef-0.2.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Simulated lab devices — liquid handler and sequencer (7).
|
|
2
|
+
|
|
3
|
+
Like the imaging plate reader: seeded physics, realistic failure modes, and raw
|
|
4
|
+
evidence on disk. Agents see executed logs / FASTQ files, not oracles.
|
|
5
|
+
|
|
6
|
+
Requires numpy (extra `lab-imaging`).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import random
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
import numpy as np
|
|
17
|
+
except ImportError as exc: # pragma: no cover
|
|
18
|
+
raise ImportError("device sims require numpy: pip install proef[lab-imaging]") from exc
|
|
19
|
+
|
|
20
|
+
from proef.core.contracts import ProtocolSubmission
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _seed(*parts: Any) -> int:
|
|
24
|
+
return int(hashlib.sha256(":".join(str(p) for p in parts).encode()).hexdigest()[:8], 16)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ------------------------------------------------------------- liquid handler
|
|
28
|
+
|
|
29
|
+
class LiquidHandlerSim:
|
|
30
|
+
"""Simulated 8-channel liquid handler (Opentrons-class).
|
|
31
|
+
|
|
32
|
+
Physics: requested volume -> delivered volume with percent error growing as
|
|
33
|
+
volume shrinks (real pipettes are worst at low volumes), optional carryover
|
|
34
|
+
when a tip is reused after a concentrated reagent.
|
|
35
|
+
|
|
36
|
+
`execute(protocol)` returns the *executed* transfer log — the ground truth
|
|
37
|
+
of what actually landed in each well, not what was requested.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
name = "liquid-handler-sim"
|
|
41
|
+
|
|
42
|
+
def __init__(self, seed: int = 7, cv_percent: float = 5.0, carryover_prob: float = 0.03,
|
|
43
|
+
min_volume_ul: float = 2.0):
|
|
44
|
+
self.seed = seed
|
|
45
|
+
self.cv = cv_percent
|
|
46
|
+
self.carryover_prob = carryover_prob
|
|
47
|
+
self.min_volume_ul = min_volume_ul
|
|
48
|
+
|
|
49
|
+
def execute(self, protocol: ProtocolSubmission) -> dict[str, Any]:
|
|
50
|
+
rng = random.Random(_seed("lh", self.seed, protocol.protocol_id))
|
|
51
|
+
transfers: list[dict[str, Any]] = []
|
|
52
|
+
carryover = 0.0
|
|
53
|
+
for step in sorted(protocol.steps, key=lambda s: s.seq):
|
|
54
|
+
if step.op.value != "dispense":
|
|
55
|
+
continue
|
|
56
|
+
requested = float(step.params.get("volume_ul", 10.0))
|
|
57
|
+
delivered = requested * (1.0 + rng.gauss(0, self.cv / 100.0))
|
|
58
|
+
# low-volume penalty: below min spec, systematic under-delivery
|
|
59
|
+
if requested < self.min_volume_ul:
|
|
60
|
+
delivered *= requested / self.min_volume_ul
|
|
61
|
+
if carryover and rng.random() < self.carryover_prob:
|
|
62
|
+
delivered += carryover * rng.uniform(0.01, 0.05)
|
|
63
|
+
carryover = delivered
|
|
64
|
+
transfers.append({
|
|
65
|
+
"step": step.seq,
|
|
66
|
+
"requested_ul": round(requested, 3),
|
|
67
|
+
"delivered_ul": round(delivered, 3),
|
|
68
|
+
"error_percent": round(100 * (delivered - requested) / max(requested, 1e-9), 2),
|
|
69
|
+
"carryover": carryover > requested * 0.05,
|
|
70
|
+
"below_spec": requested < self.min_volume_ul,
|
|
71
|
+
})
|
|
72
|
+
executed_vol = sum(t["delivered_ul"] for t in transfers)
|
|
73
|
+
requested_vol = sum(t["requested_ul"] for t in transfers)
|
|
74
|
+
return {
|
|
75
|
+
"transfers": transfers,
|
|
76
|
+
"total_requested_ul": round(requested_vol, 2),
|
|
77
|
+
"total_delivered_ul": round(executed_vol, 2),
|
|
78
|
+
"global_error_percent": round(100 * (executed_vol - requested_vol)
|
|
79
|
+
/ max(requested_vol, 1e-9), 2),
|
|
80
|
+
"evidence": f"transfers={len(transfers)}, cv={self.cv}%",
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# ------------------------------------------------------------------- sequencer
|
|
85
|
+
|
|
86
|
+
COMPLEMENT = str.maketrans("ACGT", "TGCA")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class SequencerSim:
|
|
90
|
+
"""Simulated short-read sequencer: sample -> reads -> variant calling.
|
|
91
|
+
|
|
92
|
+
Given a reference and a true genotype (list of (position, alt) mutations,
|
|
93
|
+
0-based), emits seeded reads with substitution errors and configurable
|
|
94
|
+
coverage, writes FASTQ, then `call_variants` re-derives the genotype from
|
|
95
|
+
the reads. Agents get FASTQ evidence; the truth stays in the device.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
name = "sequencer-sim"
|
|
99
|
+
|
|
100
|
+
def __init__(self, seed: int = 7, read_length: int = 50, error_rate: float = 0.01):
|
|
101
|
+
self.seed = seed
|
|
102
|
+
self.read_length = read_length
|
|
103
|
+
self.error_rate = error_rate
|
|
104
|
+
|
|
105
|
+
def sequence(self, sample_id: str, reference: str,
|
|
106
|
+
mutations: list[tuple[int, str]], coverage: int = 30) -> dict[str, Any]:
|
|
107
|
+
truth = list(reference)
|
|
108
|
+
for pos, alt in mutations:
|
|
109
|
+
truth[pos] = alt
|
|
110
|
+
truth_genome = "".join(truth)
|
|
111
|
+
rng = random.Random(_seed("seq", self.seed, sample_id))
|
|
112
|
+
reads: list[dict[str, Any]] = []
|
|
113
|
+
n_reads = max(1, coverage * len(reference) // self.read_length)
|
|
114
|
+
for _ in range(n_reads):
|
|
115
|
+
start = rng.randrange(0, max(1, len(truth_genome) - self.read_length + 1))
|
|
116
|
+
seq = truth_genome[start:start + self.read_length]
|
|
117
|
+
seq = "".join(
|
|
118
|
+
c if rng.random() >= self.error_rate else rng.choice("ACGT")
|
|
119
|
+
for c in seq
|
|
120
|
+
)
|
|
121
|
+
qual = "".join(chr(33 + max(20, min(40, int(rng.gauss(35, 4))))) for _ in seq)
|
|
122
|
+
reads.append({"seq": seq, "qual": qual, "start": start})
|
|
123
|
+
fq = self.write_fastq(sample_id, reads)
|
|
124
|
+
return {"sample_id": sample_id, "fastq": fq, "reads": reads,
|
|
125
|
+
"reference": reference, "coverage": coverage}
|
|
126
|
+
|
|
127
|
+
def write_fastq(self, sample_id: str, reads: list[dict], path: str | Path | None = None) -> str:
|
|
128
|
+
lines: list[str] = []
|
|
129
|
+
for i, r in enumerate(reads):
|
|
130
|
+
# alignment start embedded in the header (poor-man's SAM tag)
|
|
131
|
+
lines += [f"@{sample_id}:{i} start={r['start']}", r["seq"], "+", r["qual"]]
|
|
132
|
+
text = "\n".join(lines) + "\n"
|
|
133
|
+
if path:
|
|
134
|
+
Path(path).write_text(text)
|
|
135
|
+
return text
|
|
136
|
+
|
|
137
|
+
@staticmethod
|
|
138
|
+
def call_variants(fastq: str, reference: str,
|
|
139
|
+
min_var_fraction: float = 0.2) -> list[dict[str, Any]]:
|
|
140
|
+
"""Pileup variant caller: reads align via the `start=` header tag."""
|
|
141
|
+
lines = fastq.splitlines()
|
|
142
|
+
piles: list[dict[str, int]] = [dict() for _ in reference]
|
|
143
|
+
for i in range(0, len(lines) - 3, 4):
|
|
144
|
+
header, seq = lines[i], lines[i + 1]
|
|
145
|
+
if not set(seq) <= set("ACGT"):
|
|
146
|
+
continue
|
|
147
|
+
start = 0
|
|
148
|
+
for tok in header.split():
|
|
149
|
+
if tok.startswith("start="):
|
|
150
|
+
start = int(tok.split("=")[1])
|
|
151
|
+
for off, base in enumerate(seq):
|
|
152
|
+
pos = start + off
|
|
153
|
+
if pos >= len(reference):
|
|
154
|
+
break
|
|
155
|
+
piles[pos][base] = piles[pos].get(base, 0) + 1
|
|
156
|
+
calls: list[dict[str, Any]] = []
|
|
157
|
+
for pos, pile in enumerate(piles):
|
|
158
|
+
total = sum(pile.values())
|
|
159
|
+
if total == 0:
|
|
160
|
+
continue
|
|
161
|
+
ref_base = reference[pos]
|
|
162
|
+
alt_base = max((b for b in pile if b != ref_base),
|
|
163
|
+
key=lambda b: pile[b], default=None)
|
|
164
|
+
if alt_base is None:
|
|
165
|
+
continue
|
|
166
|
+
frac = pile[alt_base] / total
|
|
167
|
+
if frac >= min_var_fraction:
|
|
168
|
+
calls.append({"position": pos, "ref": ref_base, "alt": alt_base,
|
|
169
|
+
"fraction": round(frac, 3)})
|
|
170
|
+
return calls
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Simulated lab devices with image-based readouts (optional extra: numpy).
|
|
2
|
+
|
|
3
|
+
Layered realism — raw data first, analysis second:
|
|
4
|
+
|
|
5
|
+
1. DEVICE: `ImagingPlateReader` exposes a 96-well plate. Each well is a
|
|
6
|
+
synthetic fluorescence micrograph (tile x tile pixels) whose intensity
|
|
7
|
+
encodes the seeded, dose-dependent ground truth (Hill curve over IC50),
|
|
8
|
+
plus noise, vignetting, and per-well artifacts (edge effect, pipetting
|
|
9
|
+
spike, bubble).
|
|
10
|
+
2. ANALYSIS: `analyze_plate` computes per-well background-corrected median
|
|
11
|
+
intensity, fits dose-response IC50 per compound, and computes assay QC.
|
|
12
|
+
|
|
13
|
+
`ImagingSimulatorLab` implements the LabAdapter contract on top, so agents get
|
|
14
|
+
AssayResults whose raw evidence is an actual image file — same shape as a real
|
|
15
|
+
plate reader with image capture.
|
|
16
|
+
|
|
17
|
+
Requires numpy (extra: `pip install proef[lab-imaging]`).
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hashlib
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from proef.fitting import hill_response as _hill
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
import numpy as np
|
|
29
|
+
except ImportError as exc: # pragma: no cover
|
|
30
|
+
raise ImportError("lab-imaging extra requires numpy: pip install proef[lab-imaging]") from exc
|
|
31
|
+
|
|
32
|
+
from proef.adapters.lab.simulator import (
|
|
33
|
+
AssayResult,
|
|
34
|
+
Envelope,
|
|
35
|
+
InstrumentInfo,
|
|
36
|
+
Measurement,
|
|
37
|
+
MeasurementFlag,
|
|
38
|
+
ProtocolSubmission,
|
|
39
|
+
RunStatus,
|
|
40
|
+
parse_concentration_um,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
PLATE_ROWS, PLATE_COLS = 8, 12 # 96-well
|
|
44
|
+
TILE = 24 # pixels per well micrograph
|
|
45
|
+
BONDS_PLACEHOLDER = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _seed(*parts: Any) -> int:
|
|
49
|
+
return int(hashlib.sha256(":".join(str(p) for p in parts).encode()).hexdigest()[:8], 16)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def true_ic50_um(protocol_seed: int, sample_id: str) -> float:
|
|
53
|
+
"""Seeded true potency (0.5-50 uM), stable across runs."""
|
|
54
|
+
return 0.5 + (_seed(protocol_seed, sample_id) % 1000) / 1000.0 * 49.5
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def hill_response(conc_um: float, ic50_um: float, max_resp: float = 100.0) -> float:
|
|
58
|
+
return _hill(conc_um, ic50_um, max_resp, eps=1e-6)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ImagingPlateReader:
|
|
62
|
+
"""Synthetic 96-well fluorescence plate with image capture."""
|
|
63
|
+
|
|
64
|
+
def __init__(self, seed: int = 7, tile: int = TILE, noise: float = 6.0,
|
|
65
|
+
artifact_rate: float = 0.04):
|
|
66
|
+
self.seed = seed
|
|
67
|
+
self.tile = tile
|
|
68
|
+
self.noise = noise
|
|
69
|
+
self.artifact_rate = artifact_rate
|
|
70
|
+
|
|
71
|
+
def capture(self, run_id: str, well_spec: list[tuple[str, str, float]]) -> dict[str, dict]:
|
|
72
|
+
"""well_spec: (well_id, sample_id, conc_um). Returns {well_id: {image, ...}}.
|
|
73
|
+
|
|
74
|
+
Pixel intensity = response-scaled cell blobs + background, with shot
|
|
75
|
+
noise and vignetting; occasional well artifacts.
|
|
76
|
+
"""
|
|
77
|
+
rng_art = random.Random(_seed("artifacts", run_id))
|
|
78
|
+
yy, xx = np.mgrid[0:self.tile, 0:self.tile]
|
|
79
|
+
vignette = 1.0 - 0.15 * (((yy - self.tile / 2) ** 2 + (xx - self.tile / 2) ** 2)
|
|
80
|
+
/ (self.tile / 2) ** 2)
|
|
81
|
+
wells: dict[str, dict] = {}
|
|
82
|
+
for well_id, sample_id, conc in well_spec:
|
|
83
|
+
ic50 = true_ic50_um(self.seed, sample_id)
|
|
84
|
+
response = hill_response(conc, ic50)
|
|
85
|
+
# homogeneous whole-well fluorescence: uniform signal + cell texture
|
|
86
|
+
rng = np.random.default_rng(_seed("img", run_id, well_id))
|
|
87
|
+
img = rng.normal(0, self.noise, (self.tile, self.tile)) * vignette + 20.0
|
|
88
|
+
img += response * 0.9 # the measured signal
|
|
89
|
+
n_cells = max(4, int(rng.normal(18, 5)))
|
|
90
|
+
for _ in range(n_cells): # texture, response-independent
|
|
91
|
+
cy = int(rng.integers(3, self.tile - 3))
|
|
92
|
+
cx = int(rng.integers(3, self.tile - 3))
|
|
93
|
+
img[cy - 2:cy + 3, cx - 2:cx + 3] += 3.0 * rng.uniform(0.6, 1.4)
|
|
94
|
+
artifact = ""
|
|
95
|
+
if rng_art.random() < self.artifact_rate:
|
|
96
|
+
artifact = rng_art.choice(["edge_effect", "pipetting_spike", "bubble"])
|
|
97
|
+
if artifact == "edge_effect":
|
|
98
|
+
img[:, :4] *= 0.4
|
|
99
|
+
elif artifact == "pipetting_spike":
|
|
100
|
+
img[2:6, 2:6] += 400.0
|
|
101
|
+
else:
|
|
102
|
+
img[10:18, 10:18] += 250.0
|
|
103
|
+
wells[well_id] = {"image": img, "sample_id": sample_id,
|
|
104
|
+
"conc_um": conc, "artifact": artifact}
|
|
105
|
+
return wells
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def analyze_plate(plate: dict[str, dict]) -> dict[str, Any]:
|
|
109
|
+
"""Image analysis: background-corrected median intensity per well ->
|
|
110
|
+
per-compound dose-response IC50 fit + assay QC."""
|
|
111
|
+
raw: dict[str, list[tuple[str, float, float, str]]] = {}
|
|
112
|
+
for well_id, v in plate.items():
|
|
113
|
+
img = v["image"]
|
|
114
|
+
raw.setdefault(v["sample_id"], []).append(
|
|
115
|
+
(well_id, v["conc_um"], float(np.median(img)), v["artifact"]))
|
|
116
|
+
# plate background = baseline of control wells (whole-well uniform signal
|
|
117
|
+
# raises a well's own corners, so per-well subtraction would cancel it)
|
|
118
|
+
ctrl_medians = [med for sample, vals in raw.items() if sample.startswith("ctrl")
|
|
119
|
+
for _, _, med, _ in vals]
|
|
120
|
+
bg = float(np.median(ctrl_medians)) if ctrl_medians else 20.0
|
|
121
|
+
intensities: dict[str, list[tuple[float, float, str]]] = {}
|
|
122
|
+
for sample, vals in raw.items():
|
|
123
|
+
intensities[sample] = [(conc, med - bg, artifact) for _, conc, med, artifact in vals]
|
|
124
|
+
|
|
125
|
+
ctrl_vals = [s for sample, vals in intensities.items() if sample.startswith("ctrl")
|
|
126
|
+
for _, s, _ in vals]
|
|
127
|
+
all_vals = [s for vals in intensities.values() for _, s, _ in vals]
|
|
128
|
+
z_prime = 0.5
|
|
129
|
+
if len(ctrl_vals) >= 2:
|
|
130
|
+
sigma_all = float(np.std(all_vals)) or 1.0
|
|
131
|
+
spread = abs(float(np.mean(all_vals)) - float(np.mean(ctrl_vals)))
|
|
132
|
+
z_prime = max(-1.0, min(1.0, 1 - 3 * (float(np.std(ctrl_vals)) + 1.0)
|
|
133
|
+
/ (spread + sigma_all)))
|
|
134
|
+
|
|
135
|
+
compounds: dict[str, dict] = {}
|
|
136
|
+
for sample, vals in intensities.items():
|
|
137
|
+
if sample.startswith("ctrl"):
|
|
138
|
+
continue
|
|
139
|
+
pts = sorted((c, s / 0.9) for c, s, _ in vals) # undo capture gain -> % response
|
|
140
|
+
artifacts_used = sorted({a for _, _, a in vals if a})
|
|
141
|
+
top = max((s for _, s in pts), default=0.0)
|
|
142
|
+
ic50 = None
|
|
143
|
+
if top > 10.0:
|
|
144
|
+
target = 50.0 # half of the assay's known maximal response (100%)
|
|
145
|
+
for (c0, s0), (c1, s1) in zip(pts, pts[1:]):
|
|
146
|
+
if s0 <= target <= s1:
|
|
147
|
+
frac = 0.0 if s1 == s0 else (target - s0) / (s1 - s0)
|
|
148
|
+
ic50 = round(c0 + frac * (c1 - c0), 2)
|
|
149
|
+
break
|
|
150
|
+
if ic50 is None and pts[-1][1] >= target:
|
|
151
|
+
ic50 = round(pts[-1][0], 2)
|
|
152
|
+
compounds[sample] = {"ic50_um": ic50, "max_signal": round(top, 1),
|
|
153
|
+
"curve": pts, "artifacts": artifacts_used}
|
|
154
|
+
return {"z_prime": round(z_prime, 3), "compounds": compounds}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class ImagingSimulatorLab:
|
|
158
|
+
"""LabAdapter: raw plate images in, analyzed AssayResults out."""
|
|
159
|
+
|
|
160
|
+
name = "imaging-simulator"
|
|
161
|
+
|
|
162
|
+
def __init__(self, seed: int = 7, image_dir: str | Path = ".data/images",
|
|
163
|
+
artifact_rate: float = 0.04):
|
|
164
|
+
self.device = ImagingPlateReader(seed=seed, artifact_rate=artifact_rate)
|
|
165
|
+
self.image_dir = Path(image_dir)
|
|
166
|
+
self.image_dir.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
self._runs: dict[str, ProtocolSubmission] = {}
|
|
168
|
+
|
|
169
|
+
def list_capabilities(self) -> dict[str, Any]:
|
|
170
|
+
return {"assays": ["binding", "enzymatic", "cytotoxicity", "counterscreen"],
|
|
171
|
+
"readout": "fluorescence-imaging", "plate": "96-well",
|
|
172
|
+
"tile_px": self.device.tile, "bsl_max": 2,
|
|
173
|
+
"throughput": {"plates_per_day": 12}}
|
|
174
|
+
|
|
175
|
+
def submit_protocol(self, protocol: ProtocolSubmission) -> str:
|
|
176
|
+
run_id = f"img-{protocol.protocol_id[:8]}"
|
|
177
|
+
self._runs[run_id] = protocol
|
|
178
|
+
return run_id
|
|
179
|
+
|
|
180
|
+
def get_status(self, run_id: str) -> str:
|
|
181
|
+
return "done" if run_id in self._runs else "failed"
|
|
182
|
+
|
|
183
|
+
def fetch_results(self, run_id: str) -> AssayResult:
|
|
184
|
+
protocol = self._runs[run_id]
|
|
185
|
+
well_spec: list[tuple[str, str, float]] = []
|
|
186
|
+
for i, sample in enumerate(protocol.samples):
|
|
187
|
+
conc = parse_concentration_um(sample.concentration)
|
|
188
|
+
well_id = f"{chr(ord('A') + (i // PLATE_COLS))}{(i % PLATE_COLS) + 1}"
|
|
189
|
+
is_control = sample.kind.value == "buffer" or sample.sample_id.startswith("ctrl")
|
|
190
|
+
if is_control and protocol.assay_type.value != "plate_reader":
|
|
191
|
+
conc = 1e-3 # negative-control wells: effectively no compound
|
|
192
|
+
well_spec.append((well_id, "ctrl" if is_control else sample.sample_id, conc))
|
|
193
|
+
plate = self.device.capture(run_id, well_spec)
|
|
194
|
+
for well_id, v in plate.items(): # persist raw evidence (agents can open these)
|
|
195
|
+
np.save(self.image_dir / f"{run_id}_{well_id}.npy", v["image"])
|
|
196
|
+
analysis = analyze_plate(plate)
|
|
197
|
+
measurements = []
|
|
198
|
+
for sample_id, r in analysis["compounds"].items():
|
|
199
|
+
if r["ic50_um"] is not None:
|
|
200
|
+
measurements.append(Measurement(
|
|
201
|
+
sample_id=sample_id,
|
|
202
|
+
assay_type=protocol.assay_type.value,
|
|
203
|
+
value=r["ic50_um"], unit="uM",
|
|
204
|
+
derived_metrics={"ic50_um": r["ic50_um"],
|
|
205
|
+
"max_signal": r["max_signal"],
|
|
206
|
+
"z_prime": analysis["z_prime"]},
|
|
207
|
+
flags=[MeasurementFlag.suspect] if r["artifacts"] else [],
|
|
208
|
+
))
|
|
209
|
+
sample_image = next(iter(plate))
|
|
210
|
+
return AssayResult(
|
|
211
|
+
envelope=Envelope(experiment_branch_id="imaging-simulator"),
|
|
212
|
+
run_id=run_id, protocol_id=protocol.protocol_id,
|
|
213
|
+
instrument=InstrumentInfo(
|
|
214
|
+
adapter=self.name, instrument_id="img-reader-01",
|
|
215
|
+
raw_output_uri=str(self.image_dir / f"{run_id}_{sample_image}.npy")),
|
|
216
|
+
status=RunStatus.completed,
|
|
217
|
+
measurements=measurements,
|
|
218
|
+
qc={"controls_passed": analysis["z_prime"] >= 0.3,
|
|
219
|
+
"z_prime": analysis["z_prime"]},
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
def cancel(self, run_id: str) -> None:
|
|
223
|
+
self._runs.pop(run_id, None)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
import random # noqa: E402 (kept last to keep the device imports obvious)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""MHS (machine/hardware standard) driver adapter — experimental.
|
|
2
|
+
|
|
3
|
+
Wraps an MHS-compliant driver endpoint as a Proef LabAdapter. MHS
|
|
4
|
+
translates devices into read/write primitives plus a standard discovery
|
|
5
|
+
format; this adapter maps those onto our protocol/result lifecycle so any
|
|
6
|
+
MHS-compatible instrument becomes usable without bespoke code.
|
|
7
|
+
|
|
8
|
+
config (YAML/JSON passed to proef campaign auto, or constructor kwargs):
|
|
9
|
+
mhs_url: http://bench-host:8900 # driver endpoint (required)
|
|
10
|
+
device_id: incubator-01
|
|
11
|
+
name: Bench incubator
|
|
12
|
+
|
|
13
|
+
Status: skeleton. The MHS driver SDK is not public yet; endpoints follow
|
|
14
|
+
the published shape (discovery reference file, read/write commands) and
|
|
15
|
+
will be firmed up against the real spec.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import urllib.request
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from proef.core.device_card import DeviceCard, builtin_card, load_card, to_agent_text
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MhsDriverLab:
|
|
28
|
+
"""LabAdapter over an MHS driver. Follows the SimulatorLab surface:
|
|
29
|
+
submit_protocol / get_status / fetch_results / list_capabilities."""
|
|
30
|
+
|
|
31
|
+
name = "mhs-driver"
|
|
32
|
+
|
|
33
|
+
def __init__(self, mhs_url: str | None = None, device_id: str = "mhs-device",
|
|
34
|
+
name: str = "MHS device", timeout_s: int = 30, **_: Any) -> None:
|
|
35
|
+
self.mhs_url = (mhs_url or os.environ.get("MHS_URL", "")).rstrip("/")
|
|
36
|
+
if not self.mhs_url:
|
|
37
|
+
raise ValueError(
|
|
38
|
+
"MHS adapter needs `mhs_url` (or MHS_URL env) pointing at the "
|
|
39
|
+
"driver endpoint — e.g. http://bench-host:8900")
|
|
40
|
+
self.device_id = device_id
|
|
41
|
+
self.device_name = name
|
|
42
|
+
self.timeout_s = timeout_s
|
|
43
|
+
|
|
44
|
+
# -- driver communication -------------------------------------------------
|
|
45
|
+
|
|
46
|
+
def _call(self, path: str, payload: dict | None = None) -> dict:
|
|
47
|
+
url = f"{self.mhs_url}/{path.lstrip('/')}"
|
|
48
|
+
data = json.dumps(payload).encode() if payload is not None else None
|
|
49
|
+
req = urllib.request.Request(
|
|
50
|
+
url, data=data, method="POST" if data else "GET",
|
|
51
|
+
headers={"Content-Type": "application/json"})
|
|
52
|
+
with urllib.request.urlopen(req, timeout=self.timeout_s) as r: # noqa: S310
|
|
53
|
+
return json.loads(r.read())
|
|
54
|
+
|
|
55
|
+
# -- discovery: the reference file is the agent's manual -------------------
|
|
56
|
+
|
|
57
|
+
def reference_file(self) -> dict:
|
|
58
|
+
return self._call("reference")
|
|
59
|
+
|
|
60
|
+
def list_capabilities(self) -> dict[str, Any]:
|
|
61
|
+
try:
|
|
62
|
+
ref = self.reference_file()
|
|
63
|
+
except Exception as exc:
|
|
64
|
+
return {"assays": [], "error": f"driver unreachable: {exc}"}
|
|
65
|
+
return {
|
|
66
|
+
"assays": ref.get("protocols", []),
|
|
67
|
+
"measures": ref.get("measures", []),
|
|
68
|
+
"adjusts": ref.get("adjusts", []),
|
|
69
|
+
"safety_limits": ref.get("safety_limits", []),
|
|
70
|
+
"notes": ref.get("notes", []),
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
def agent_reference_text(self) -> str:
|
|
74
|
+
"""MHS-style reference file as agent-readable text, with operator
|
|
75
|
+
tags layered in from any local device card."""
|
|
76
|
+
try:
|
|
77
|
+
ref = self.reference_file()
|
|
78
|
+
card = DeviceCard(
|
|
79
|
+
device_id=self.device_id, name=self.device_name,
|
|
80
|
+
protocols=ref.get("protocols", []),
|
|
81
|
+
measures=[m for m in ref.get("measures", [])],
|
|
82
|
+
adjusts=[a for a in ref.get("adjusts", [])],
|
|
83
|
+
safety_limits=[s for s in ref.get("safety_limits", [])],
|
|
84
|
+
notes=ref.get("notes", []),
|
|
85
|
+
source="builtin")
|
|
86
|
+
except Exception:
|
|
87
|
+
card = builtin_card(self.device_id, self.device_name, {})
|
|
88
|
+
card = load_card(self.device_id, base=card) or card
|
|
89
|
+
return to_agent_text(card)
|
|
90
|
+
|
|
91
|
+
# -- control: write to operate, read to observe ----------------------------
|
|
92
|
+
|
|
93
|
+
def submit_protocol(self, protocol: Any) -> str:
|
|
94
|
+
out = self._call("write", {
|
|
95
|
+
"device": self.device_id,
|
|
96
|
+
"command": "run_protocol",
|
|
97
|
+
"params": {"protocol": protocol.model_dump(mode="json")},
|
|
98
|
+
})
|
|
99
|
+
return str(out.get("run_id", out.get("handle", "")))
|
|
100
|
+
|
|
101
|
+
def get_status(self, run_id: str) -> str:
|
|
102
|
+
out = self._call("read", {"device": self.device_id,
|
|
103
|
+
"command": "status", "params": {"run_id": run_id}})
|
|
104
|
+
return str(out.get("status", "unknown"))
|
|
105
|
+
|
|
106
|
+
def fetch_results(self, run_id: str) -> Any:
|
|
107
|
+
from proef.core.contracts import AssayResult, Envelope
|
|
108
|
+
out = self._call("read", {"device": self.device_id,
|
|
109
|
+
"command": "results", "params": {"run_id": run_id}})
|
|
110
|
+
# driver returns measurements in our contract shape; wrap if bare
|
|
111
|
+
if isinstance(out, dict) and "measurements" in out:
|
|
112
|
+
out.setdefault("envelope", {})
|
|
113
|
+
out.setdefault("status", "completed")
|
|
114
|
+
return AssayResult.model_validate(out)
|
|
115
|
+
return AssayResult(
|
|
116
|
+
envelope=Envelope(experiment_branch_id=f"mhs/{run_id}"),
|
|
117
|
+
protocol_id=run_id,
|
|
118
|
+
status="completed",
|
|
119
|
+
measurements=[],
|
|
120
|
+
raw=out)
|
|
121
|
+
|
|
122
|
+
def cancel(self, run_id: str) -> None:
|
|
123
|
+
self._call("write", {"device": self.device_id,
|
|
124
|
+
"command": "cancel", "params": {"run_id": run_id}})
|