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
proef/watch.py
ADDED
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
"""Lab awareness, agents notice device outputs instead of being pointed at them.
|
|
2
|
+
|
|
3
|
+
Three pieces:
|
|
4
|
+
|
|
5
|
+
1. `DeviceMonitor` , watches an instrument "outbox"/inbox directory (the
|
|
6
|
+
universal convention: every real instrument exports a file when a run
|
|
7
|
+
completes) and emits `LabEvent`s as files appear.
|
|
8
|
+
2. `AutoAnalysisAgent`, consumes those events: reads the result
|
|
9
|
+
(read_plate), updates any hypotheses whose candidate was measured,
|
|
10
|
+
records diary entries into provenance, and queues decisions for the
|
|
11
|
+
scientist. Humans never shuttle files.
|
|
12
|
+
3. `proef watch <inbox>`, runs the loop.
|
|
13
|
+
|
|
14
|
+
The same event interface later maps 1:1 to real push sources (instrument
|
|
15
|
+
webhooks, queue depth on the LabGateway, device SDKs), inbox watching is the
|
|
16
|
+
lowest-common-denominator that works with every existing instrument.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import logging
|
|
21
|
+
import time
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Callable, Iterator
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class LabEvent:
|
|
29
|
+
kind: str # "plate_ready" | "file_seen"
|
|
30
|
+
source: str # device/file path
|
|
31
|
+
path: Path | None = None
|
|
32
|
+
detail: str = ""
|
|
33
|
+
seen_at: float = field(default_factory=time.time)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class DeviceMonitor:
|
|
37
|
+
"""Watch a directory instruments write into; yield events for new files."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, inbox: str | Path, poll_secs: float = 1.0,
|
|
40
|
+
patterns: tuple[str, ...] = ("*.csv", "*.tsv", "*.xlsx", "*.npy")):
|
|
41
|
+
self.inbox = Path(inbox)
|
|
42
|
+
self.inbox.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
self.poll_secs = poll_secs
|
|
44
|
+
self.patterns = patterns
|
|
45
|
+
self._seen: set[Path] = set()
|
|
46
|
+
|
|
47
|
+
def poll(self) -> list[LabEvent]:
|
|
48
|
+
events = []
|
|
49
|
+
for pattern in self.patterns:
|
|
50
|
+
# a FIXED order: directory order differs between filesystems (macOS and Linux), and the order
|
|
51
|
+
# plates are analysed in decides which confirmation run is submitted first, and so which run id
|
|
52
|
+
# (and which simulator noise) each confirmation gets. Unsorted listing made verdicts depend on the machine.
|
|
53
|
+
for f in sorted(self.inbox.glob(pattern)):
|
|
54
|
+
if f in self._seen:
|
|
55
|
+
continue
|
|
56
|
+
self._seen.add(f)
|
|
57
|
+
kind = "plate_ready" if f.suffix.lower() in (".csv", ".tsv", ".xlsx") else "file_seen"
|
|
58
|
+
events.append(LabEvent(kind=kind, source=self.inbox.name, path=f,
|
|
59
|
+
detail=f"instrument output appeared: {f.name}"))
|
|
60
|
+
return events
|
|
61
|
+
|
|
62
|
+
def events(self, stop_after: int | None = None, once: bool = False,
|
|
63
|
+
idle_timeout: float | None = None) -> Iterator[LabEvent]:
|
|
64
|
+
"""Blocking generator. `stop_after` bounds total events (for demos/tests);
|
|
65
|
+
`idle_timeout` ends the stream after that many seconds without a new
|
|
66
|
+
event (for open-ended campaigns)."""
|
|
67
|
+
count = 0
|
|
68
|
+
last_event = time.time()
|
|
69
|
+
while True:
|
|
70
|
+
for ev in self.poll():
|
|
71
|
+
yield ev
|
|
72
|
+
count += 1
|
|
73
|
+
last_event = time.time()
|
|
74
|
+
if stop_after is not None and count >= stop_after:
|
|
75
|
+
return
|
|
76
|
+
if once:
|
|
77
|
+
return
|
|
78
|
+
if idle_timeout is not None and time.time() - last_event > idle_timeout:
|
|
79
|
+
return
|
|
80
|
+
time.sleep(self.poll_secs)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _as_dicts(records):
|
|
84
|
+
"""Records may be dicts (labread) or Measurement models (simulator);
|
|
85
|
+
read both shapes uniformly."""
|
|
86
|
+
for m in records:
|
|
87
|
+
yield m if isinstance(m, dict) else m.model_dump()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class AutoAnalysisAgent:
|
|
91
|
+
"""Reacts to lab events: reads results, updates hypotheses, records decisions.
|
|
92
|
+
|
|
93
|
+
`notify` is how the scientist hears about it (console, MCP message, chat...).
|
|
94
|
+
If `gateway` is provided, recommendations with a clear next experiment are
|
|
95
|
+
AUTO-SUBMITTED through the safety gateway, closing the loop: the agent
|
|
96
|
+
designs and runs the orthogonal confirmation assay itself, still inside the
|
|
97
|
+
SafetyEngine's trust boundary.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
ORTHOGONAL_ASSAY = {"binding": "enzymatic", "enzymatic": "binding",
|
|
101
|
+
"cytotoxicity": "binding"}
|
|
102
|
+
|
|
103
|
+
def __init__(self, store: Any = None, tracker: Any = None,
|
|
104
|
+
notify: Callable[[str], None] | None = None,
|
|
105
|
+
max_response: float | None = None,
|
|
106
|
+
gateway: Any = None, branch_id: str = "autonomous-loop",
|
|
107
|
+
auto_confirm: bool = True,
|
|
108
|
+
export_fn: Callable[..., None] | None = None,
|
|
109
|
+
adaptive: bool = False,
|
|
110
|
+
dose_ladder: tuple[float, ...] = (0.5, 2.0, 10.0, 40.0, 80.0),
|
|
111
|
+
adaptive_wells: int = 3):
|
|
112
|
+
self.store = store
|
|
113
|
+
self.tracker = tracker
|
|
114
|
+
self.notify = notify or (lambda msg: print(f"[agent] {msg}"))
|
|
115
|
+
self.max_response = max_response
|
|
116
|
+
self.gateway = gateway
|
|
117
|
+
self.branch_id = branch_id
|
|
118
|
+
self.auto_confirm = auto_confirm and gateway is not None
|
|
119
|
+
self.export_fn = export_fn # drops the instrument export for a run
|
|
120
|
+
self.adaptive = adaptive and gateway is not None
|
|
121
|
+
self.dose_ladder = dose_ladder
|
|
122
|
+
self.adaptive_wells = adaptive_wells
|
|
123
|
+
self._designers: dict[str, Any] = {}
|
|
124
|
+
self._confirmations: dict[str, dict] = {} # run_id -> confirmation task
|
|
125
|
+
self._confirm_submitted: set[str] = set() # candidates already confirmed
|
|
126
|
+
|
|
127
|
+
_OPEN = ("proposed", "designed", "tested")
|
|
128
|
+
|
|
129
|
+
def handle(self, event: LabEvent) -> dict[str, Any] | None:
|
|
130
|
+
if event.kind != "plate_ready" or event.path is None:
|
|
131
|
+
return None
|
|
132
|
+
try:
|
|
133
|
+
if self.adaptive:
|
|
134
|
+
return self._handle_adaptive(event)
|
|
135
|
+
conf = self._confirmations.get(event.path.stem)
|
|
136
|
+
if conf:
|
|
137
|
+
return self._handle_confirmation(event, conf)
|
|
138
|
+
result, early = self._read_checked(event)
|
|
139
|
+
if early is not None:
|
|
140
|
+
return early
|
|
141
|
+
except Exception as exc:
|
|
142
|
+
return self._unreadable(event, exc)
|
|
143
|
+
if getattr(result, "kind", "") == "measurements":
|
|
144
|
+
self.notify(f"read {len(result.records)} measurements for "
|
|
145
|
+
f"{len({r['sample'] for r in result.records})} sample(s): a table, not a plate, so no Z'")
|
|
146
|
+
else:
|
|
147
|
+
self.notify(f"analyzed: {len(result.analysis['compounds'])} compound(s), "
|
|
148
|
+
f"Z'~{result.z_prime} (heuristic)")
|
|
149
|
+
verdicts = self._update_hypotheses(event, result) if self.tracker else []
|
|
150
|
+
self._recommend(result)
|
|
151
|
+
return {"compounds": len(result.analysis["compounds"]),
|
|
152
|
+
"z_prime": result.z_prime, "verdicts": verdicts}
|
|
153
|
+
|
|
154
|
+
# ---- reading ----------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
def _read_checked(self, event: LabEvent):
|
|
157
|
+
"""Read the export and screen it for PHYSICAL failure modes first.
|
|
158
|
+
Returns (result, None) or (None, early_summary)."""
|
|
159
|
+
from proef.analysis_profiles.measurements import read_plate_or_table
|
|
160
|
+
from proef.physfail import classify as _fm
|
|
161
|
+
self.notify(f"reading instrument output {event.path.name} "
|
|
162
|
+
"(device finished the measurement)")
|
|
163
|
+
result = read_plate_or_table(event.path, max_response=self.max_response)
|
|
164
|
+
phys = _fm([r["value"] for r in result.records])
|
|
165
|
+
if phys["kind"] == "physical":
|
|
166
|
+
self.notify(f"⚠ PHYSICAL failure mode "
|
|
167
|
+
f"({event.path.name}): {phys['evidence']}, "
|
|
168
|
+
f"{phys['action']}; no verdicts derived")
|
|
169
|
+
self._record_failure_mode(event, phys)
|
|
170
|
+
return None, {"failure_mode": phys, "file": event.path.name}
|
|
171
|
+
return result, None
|
|
172
|
+
|
|
173
|
+
def _unreadable(self, event: LabEvent, exc: Exception) -> dict[str, Any]:
|
|
174
|
+
# classify BEFORE the retry reflex: physical failures must not be
|
|
175
|
+
# treated as software hiccups (the foam/retry trap)
|
|
176
|
+
from proef.physfail import classify as _fm
|
|
177
|
+
verdict = _fm([], error=str(exc))
|
|
178
|
+
if verdict["kind"] == "physical":
|
|
179
|
+
self.notify(f"⚠ PHYSICAL failure mode "
|
|
180
|
+
f"({event.path.name}): {verdict['evidence']}, "
|
|
181
|
+
f"{verdict['action']}")
|
|
182
|
+
self._record_failure_mode(event, verdict)
|
|
183
|
+
else:
|
|
184
|
+
self.notify(f"⚠ instrument output unreadable ({event.path.name}): "
|
|
185
|
+
f"{str(exc)[:120]}, flagged for review, no verdicts "
|
|
186
|
+
f"changed")
|
|
187
|
+
return {"error": str(exc)[:200], "file": event.path.name,
|
|
188
|
+
"failure_mode": verdict}
|
|
189
|
+
|
|
190
|
+
# ---- hypotheses -------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
def _update_hypotheses(self, event: LabEvent, result) -> list[tuple]:
|
|
193
|
+
"""Auto-update hypotheses whose candidate appears in this plate."""
|
|
194
|
+
verdicts: list[tuple] = []
|
|
195
|
+
for hyp in self.tracker.hypotheses.values():
|
|
196
|
+
match = result.analysis["compounds"].get(hyp.candidate)
|
|
197
|
+
crit = hyp.criteria
|
|
198
|
+
is_open = hyp.status in self._OPEN
|
|
199
|
+
# property metrics (potency_pct, tensile, ...) read the recorded
|
|
200
|
+
# value at the HIGHEST dose directly; only IC50-style metrics
|
|
201
|
+
# use the Hill fit
|
|
202
|
+
readout = None
|
|
203
|
+
if crit and crit.metric not in ("ic50_um", "value"):
|
|
204
|
+
readout = self._property_readout(hyp, result)
|
|
205
|
+
if readout is not None and readout[0] is not None and is_open:
|
|
206
|
+
verdicts.append(self._verdict_property(event, result, hyp,
|
|
207
|
+
*readout))
|
|
208
|
+
elif match and is_open and (not match["ic50_um"]
|
|
209
|
+
or match.get("right_censored")
|
|
210
|
+
or match.get("left_censored")):
|
|
211
|
+
verdicts.append(self._verdict_censored(event, result, hyp,
|
|
212
|
+
match))
|
|
213
|
+
elif match and is_open and match["ic50_um"]:
|
|
214
|
+
verdicts.append(self._verdict_fitted(event, result, hyp, match))
|
|
215
|
+
return verdicts
|
|
216
|
+
|
|
217
|
+
@staticmethod
|
|
218
|
+
def _property_readout(hyp, result):
|
|
219
|
+
"""(value, ci, n_replicates_at_top_dose, had_dose_series) for a
|
|
220
|
+
property metric; value None when the plate has no reading."""
|
|
221
|
+
from proef.labread import replicate_ci
|
|
222
|
+
cand_vals = []
|
|
223
|
+
any_val = None
|
|
224
|
+
for rec in _as_dicts(result.records):
|
|
225
|
+
if rec.get("sample") != hyp.candidate or rec.get("control"):
|
|
226
|
+
continue
|
|
227
|
+
if any_val is None:
|
|
228
|
+
any_val = rec.get("value")
|
|
229
|
+
conc, val = rec.get("conc_um"), rec.get("value")
|
|
230
|
+
if isinstance(conc, (int, float)) and isinstance(val, (int, float)):
|
|
231
|
+
cand_vals.append((conc, val))
|
|
232
|
+
if cand_vals:
|
|
233
|
+
# replicate-mean at the top dose + well-level CI: property
|
|
234
|
+
# metrics get the SAME abstention machinery as IC50 fits
|
|
235
|
+
top_conc = max(c for c, _ in cand_vals)
|
|
236
|
+
top_vals = [v for c, v in cand_vals if c == top_conc]
|
|
237
|
+
return (sum(top_vals) / len(top_vals), replicate_ci(top_vals),
|
|
238
|
+
len(top_vals), True)
|
|
239
|
+
# no dose series (a property table: conductivity, solubility, yield...): the replicate rows for this
|
|
240
|
+
# candidate ARE the replicates. Judge their mean and its interval, never just the first row.
|
|
241
|
+
flat = [float(r["value"]) for r in _as_dicts(result.records)
|
|
242
|
+
if r.get("sample") == hyp.candidate and not r.get("control") and isinstance(r.get("value"), (int, float))]
|
|
243
|
+
if flat:
|
|
244
|
+
return sum(flat) / len(flat), replicate_ci(flat), len(flat), False
|
|
245
|
+
if any_val is not None:
|
|
246
|
+
return any_val, None, 1, False
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
def _record_derivation(self, hyp, extra_top: dict | None = None, **kw):
|
|
250
|
+
if not hasattr(self.tracker, "record_outcome"):
|
|
251
|
+
return
|
|
252
|
+
from proef.derivation import build
|
|
253
|
+
inst, ver = self._instrument()
|
|
254
|
+
extra = {"derivation": build(instrument=inst, version=ver, **kw)}
|
|
255
|
+
extra.update(extra_top or {})
|
|
256
|
+
self.tracker.record_outcome(hyp, extra=extra)
|
|
257
|
+
|
|
258
|
+
def _attach(self, event, result, hyp, value, ci) -> None:
|
|
259
|
+
from proef.labread import QC_ZPRIME_FLOOR
|
|
260
|
+
hyp.observed_value = value
|
|
261
|
+
hyp.observed_ci = ci
|
|
262
|
+
hyp.evidence_run_id = event.path.stem # run <-> verdict link
|
|
263
|
+
# a table of measurements has no plate to QC: 'not applicable' (None), never a pass and never a fail
|
|
264
|
+
hyp.qc_passed = (None if getattr(result, "no_plate_qc", False)
|
|
265
|
+
else (result.z_prime or 0) >= QC_ZPRIME_FLOOR)
|
|
266
|
+
|
|
267
|
+
def _verdict_property(self, event, result, hyp, value, ci, n_top, _series):
|
|
268
|
+
crit = hyp.criteria
|
|
269
|
+
self._attach(event, result, hyp, value, ci)
|
|
270
|
+
# no interval, no claim: a property reading with fewer than 3 replicates cannot earn a decisive verdict
|
|
271
|
+
hyp.status = crit.classify(value, ci) if ci else "inconclusive"
|
|
272
|
+
self._record_derivation(
|
|
273
|
+
hyp, {"direction": crit.direction},
|
|
274
|
+
quantity=crit.metric,
|
|
275
|
+
counts={"wells": len(result.records),
|
|
276
|
+
"replicates_at_gate_dose": n_top},
|
|
277
|
+
metric=crit.metric,
|
|
278
|
+
method=("property readout: replicate mean at top dose" if ci else
|
|
279
|
+
"property readout at highest dose (single reading, no "
|
|
280
|
+
"variance estimate)"),
|
|
281
|
+
ci="replicate bootstrap 95%" if ci else None,
|
|
282
|
+
criteria_metric=crit.metric, criteria_direction=crit.direction,
|
|
283
|
+
criteria_threshold=crit.threshold)
|
|
284
|
+
unit = next((d.get("unit", "") for d in _as_dicts(result.records)
|
|
285
|
+
if d.get("sample") == hyp.candidate), "")
|
|
286
|
+
self.notify(f"hypothesis {hyp.hypothesis_id} ({hyp.candidate}): "
|
|
287
|
+
f"{hyp.status.upper()}, {crit.metric} {value} {unit} vs "
|
|
288
|
+
f"threshold {crit.threshold}")
|
|
289
|
+
return (hyp.hypothesis_id, hyp.candidate, hyp.status, value)
|
|
290
|
+
|
|
291
|
+
def _verdict_censored(self, event, result, hyp, match):
|
|
292
|
+
# CENSORED = unmeasurable on this ladder: transition above the top
|
|
293
|
+
# (weaker than measurable) or a saturated plateau at the fit-grid
|
|
294
|
+
# floor (stronger than measurable). The fit refuses a number —
|
|
295
|
+
# honest — but a hypothesis left silently 'tested' is an implicit
|
|
296
|
+
# claim. ABSTAIN explicitly, with the censoring as the reason.
|
|
297
|
+
crit = hyp.criteria
|
|
298
|
+
self._attach(event, result, hyp, None, None)
|
|
299
|
+
hyp.status = "inconclusive"
|
|
300
|
+
why = ("left-censored at the fit-grid floor: true IC50 is below the "
|
|
301
|
+
"measurable window (range statement, not an IC50)"
|
|
302
|
+
if match.get("left_censored")
|
|
303
|
+
else "right-censored: no measurable transition below the top "
|
|
304
|
+
"dose (weaker than this ladder resolves)")
|
|
305
|
+
self._record_derivation(
|
|
306
|
+
hyp, quantity=getattr(result, "response_unit", None),
|
|
307
|
+
counts={"wells": len(result.records)},
|
|
308
|
+
metric=crit.metric if crit else None, method=why, ci=None,
|
|
309
|
+
criteria_metric=crit.metric if crit else None,
|
|
310
|
+
criteria_direction=crit.direction if crit else None,
|
|
311
|
+
criteria_threshold=crit.threshold if crit else None)
|
|
312
|
+
self.notify(f"hypothesis {hyp.hypothesis_id} ({hyp.candidate}): "
|
|
313
|
+
f"INCONCLUSIVE, {why}; no claim either way")
|
|
314
|
+
return (hyp.hypothesis_id, hyp.candidate, hyp.status, None)
|
|
315
|
+
|
|
316
|
+
def _verdict_fitted(self, event, result, hyp, match):
|
|
317
|
+
crit = hyp.criteria
|
|
318
|
+
self._attach(event, result, hyp, match["ic50_um"], match.get("ic50_ci"))
|
|
319
|
+
if crit:
|
|
320
|
+
if not match.get("ic50_ci"):
|
|
321
|
+
# NO-USABLE-CI RULE: a fit whose residual bootstrap collapsed
|
|
322
|
+
# (hill-no-ci) or that leans on a 2-point interpolation
|
|
323
|
+
# carries unknown uncertainty — exactly when a binary call is
|
|
324
|
+
# least defensible. Abstain, don't guess.
|
|
325
|
+
hyp.status = "inconclusive"
|
|
326
|
+
else:
|
|
327
|
+
hyp.status = crit.classify(match["ic50_um"], match["ic50_ci"])
|
|
328
|
+
self._record_derivation(
|
|
329
|
+
hyp, quantity=getattr(result, "response_unit", None),
|
|
330
|
+
counts={"wells": len(result.records)},
|
|
331
|
+
metric=crit.metric if crit else None,
|
|
332
|
+
method=match.get("fit_method"),
|
|
333
|
+
ci="residual bootstrap 95%" if match.get("ic50_ci") else None,
|
|
334
|
+
criteria_metric=crit.metric if crit else None,
|
|
335
|
+
criteria_direction=crit.direction if crit else None,
|
|
336
|
+
criteria_threshold=crit.threshold if crit else None)
|
|
337
|
+
ci_txt = (f" (95% CI {match['ic50_ci'][0]}–{match['ic50_ci'][1]})"
|
|
338
|
+
if match.get("ic50_ci") else "")
|
|
339
|
+
self.notify(f"hypothesis {hyp.hypothesis_id} ({hyp.candidate}): "
|
|
340
|
+
f"{hyp.status.upper()} (preliminary, pending orthogonal "
|
|
341
|
+
f"confirmation), IC50 {match['ic50_um']} uM{ci_txt} vs "
|
|
342
|
+
f"threshold {crit.threshold if crit else '?'}")
|
|
343
|
+
return (hyp.hypothesis_id, hyp.candidate, hyp.status, match["ic50_um"])
|
|
344
|
+
|
|
345
|
+
def _recommend(self, result) -> None:
|
|
346
|
+
"""Scientist-facing diary line + (optionally) the confirmation."""
|
|
347
|
+
best = sorted(((c, r["ic50_um"])
|
|
348
|
+
for c, r in result.analysis["compounds"].items()
|
|
349
|
+
if r["ic50_um"]), key=lambda t: t[1])
|
|
350
|
+
if best:
|
|
351
|
+
candidate, ic50 = best[0]
|
|
352
|
+
self.notify(f"recommendation: best binder so far is {candidate} "
|
|
353
|
+
f"(IC50 {ic50} uM), next: confirm with orthogonal assay")
|
|
354
|
+
if self.auto_confirm and candidate not in self._confirm_submitted:
|
|
355
|
+
self._submit_confirmation(candidate, ic50)
|
|
356
|
+
|
|
357
|
+
_TERMINAL = ("validated", "confirmed", "invalidated", "refuted",
|
|
358
|
+
"inconclusive")
|
|
359
|
+
|
|
360
|
+
def _record_failure_mode(self, event, verdict: dict) -> None:
|
|
361
|
+
if self.store is None:
|
|
362
|
+
return
|
|
363
|
+
try:
|
|
364
|
+
from proef.core.contracts import Envelope, EventType
|
|
365
|
+
from proef.core.interfaces import record_for, system_actor
|
|
366
|
+
self.store.append(record_for(
|
|
367
|
+
Envelope(experiment_branch_id=self.branch_id),
|
|
368
|
+
EventType.gate_decision, system_actor("harness"),
|
|
369
|
+
decision={"kind": "failure-mode",
|
|
370
|
+
"file": getattr(event.path, "name", "?"),
|
|
371
|
+
**verdict}))
|
|
372
|
+
except Exception:
|
|
373
|
+
logging.getLogger(__name__).warning(
|
|
374
|
+
"could not record failure-mode provenance", exc_info=True)
|
|
375
|
+
|
|
376
|
+
def _instrument(self) -> tuple[str | None, str | None]:
|
|
377
|
+
lab = getattr(self.gateway, "lab", None) or \
|
|
378
|
+
getattr(getattr(self.gateway, "_gw", None), "lab", None)
|
|
379
|
+
if lab is None:
|
|
380
|
+
return None, None
|
|
381
|
+
return getattr(lab, "name", None), getattr(lab, "version", None)
|
|
382
|
+
|
|
383
|
+
def _handle_adaptive(self, event) -> None:
|
|
384
|
+
"""Bayesian sequential dosing: each well updates the posterior over
|
|
385
|
+
IC50; the next dose is the most informative unused point on the
|
|
386
|
+
ladder; after `adaptive_wells` the posterior median + credible
|
|
387
|
+
interval decide the verdict (CI-aware, same gate as fixed runs)."""
|
|
388
|
+
from proef.adaptive import DoseDesigner
|
|
389
|
+
from proef.labread import read_plate
|
|
390
|
+
from proef.physfail import classify as _fm
|
|
391
|
+
|
|
392
|
+
result = read_plate(event.path, max_response=self.max_response)
|
|
393
|
+
# physical-failure check before ANY posterior update (P1-6):
|
|
394
|
+
# a saturated dark well must not contaminate the belief state
|
|
395
|
+
vals = [r["value"] for r in result.records
|
|
396
|
+
if isinstance(r.get("value"), (int, float))]
|
|
397
|
+
phys = _fm(vals) if vals else _fm([], error="no readings")
|
|
398
|
+
if phys["kind"] == "physical":
|
|
399
|
+
self.notify(f"⚠ physical failure mode on adaptive well "
|
|
400
|
+
f"{event.path.name}: {phys['evidence']}, "
|
|
401
|
+
f"{phys['action']}; well discarded, posterior "
|
|
402
|
+
f"unchanged")
|
|
403
|
+
self._record_failure_mode(event, phys)
|
|
404
|
+
return None
|
|
405
|
+
obs = {}
|
|
406
|
+
for r in result.records:
|
|
407
|
+
if not r.get("control") and r.get("conc_um") is not None:
|
|
408
|
+
obs[r["sample"]] = (r["conc_um"], r["value"])
|
|
409
|
+
for cand, (conc, value) in obs.items():
|
|
410
|
+
hyp = next((h for h in (self.tracker.hypotheses.values()
|
|
411
|
+
if self.tracker else [])
|
|
412
|
+
if h.candidate == cand), None)
|
|
413
|
+
if hyp is None or hyp.status in self._TERMINAL:
|
|
414
|
+
continue
|
|
415
|
+
d = self._designers.get(cand)
|
|
416
|
+
if d is None:
|
|
417
|
+
d = self._designers[cand] = DoseDesigner(
|
|
418
|
+
doses=self.dose_ladder, first_dose=conc)
|
|
419
|
+
if conc not in d.used:
|
|
420
|
+
d.observe(conc, value)
|
|
421
|
+
if len(d.used) == 1:
|
|
422
|
+
self.notify(f"adaptive screen {cand}: {value:.0f} RFU @ "
|
|
423
|
+
f"{conc:g} µM")
|
|
424
|
+
else:
|
|
425
|
+
est0, ci0 = d.estimate()
|
|
426
|
+
self.notify(f"adaptive: {cand} well @ {conc:g} µM -> "
|
|
427
|
+
f"IC50 posterior {est0:.2f} µM "
|
|
428
|
+
f"(CrI {ci0[0]:.2f}–{ci0[1]:.2f})")
|
|
429
|
+
if len(d.used) < self.adaptive_wells:
|
|
430
|
+
nxt = d.next_dose()
|
|
431
|
+
if nxt:
|
|
432
|
+
run_id = self._submit_adaptive_well(cand, nxt, hyp)
|
|
433
|
+
if run_id:
|
|
434
|
+
self.notify(f"adaptive: {cand} next dose {nxt:g} µM "
|
|
435
|
+
f"-> run {run_id} "
|
|
436
|
+
f"({len(d.used)}/{self.adaptive_wells} wells)")
|
|
437
|
+
continue
|
|
438
|
+
est, ci = d.estimate()
|
|
439
|
+
hyp.observed_value = est
|
|
440
|
+
hyp.observed_ci = ci
|
|
441
|
+
hyp.evidence_run_id = event.path.stem
|
|
442
|
+
hyp.qc_passed = True
|
|
443
|
+
hyp.status = (hyp.criteria.classify(est, ci) if hyp.criteria
|
|
444
|
+
else "tested")
|
|
445
|
+
if self.tracker and hasattr(self.tracker, "record_outcome"):
|
|
446
|
+
from proef.derivation import build
|
|
447
|
+
inst, ver = self._instrument()
|
|
448
|
+
self.tracker.record_outcome(hyp, extra={
|
|
449
|
+
"design": {"mode": "adaptive-bayesian",
|
|
450
|
+
"wells": [round(x, 3) for x in d.used]},
|
|
451
|
+
"derivation": build(
|
|
452
|
+
instrument=inst, version=ver,
|
|
453
|
+
quantity=getattr(result, "response_unit", None),
|
|
454
|
+
counts={"wells": len(d.used)},
|
|
455
|
+
metric=hyp.criteria.metric if hyp.criteria else None,
|
|
456
|
+
method="Bayesian grid posterior (adaptive dose series)",
|
|
457
|
+
ci="posterior 95% credible interval",
|
|
458
|
+
criteria_metric=hyp.criteria.metric if hyp.criteria else None,
|
|
459
|
+
criteria_direction=hyp.criteria.direction if hyp.criteria else None,
|
|
460
|
+
criteria_threshold=hyp.criteria.threshold if hyp.criteria else None)})
|
|
461
|
+
self.notify(f"adaptive verdict {cand}: IC50 {est:.2f} µM "
|
|
462
|
+
f"(95% CrI {ci[0]:.2f}–{ci[1]:.2f}) after "
|
|
463
|
+
f"{len(d.used)} wells -> {hyp.status.upper()}")
|
|
464
|
+
self._designers.pop(cand, None)
|
|
465
|
+
return None
|
|
466
|
+
|
|
467
|
+
def _submit_adaptive_well(self, candidate: str, conc: float,
|
|
468
|
+
hyp) -> str | None:
|
|
469
|
+
from proef.core.contracts import (
|
|
470
|
+
Envelope, ProtocolOp, ProtocolStep, ProtocolSubmission,
|
|
471
|
+
ReagentSpec, SampleKind, SampleSpec,
|
|
472
|
+
)
|
|
473
|
+
protocol = ProtocolSubmission(
|
|
474
|
+
envelope=Envelope(experiment_branch_id=self.branch_id),
|
|
475
|
+
title=f"adaptive-{candidate}-{conc:g}uM",
|
|
476
|
+
assay_type=hyp.assay_type or "binding",
|
|
477
|
+
steps=[ProtocolStep(seq=1, op=ProtocolOp.dispense,
|
|
478
|
+
params={"volume_ul": 50})],
|
|
479
|
+
samples=[SampleSpec(sample_id=candidate, kind=SampleKind.compound,
|
|
480
|
+
concentration=f"{conc:g}uM"),
|
|
481
|
+
SampleSpec(sample_id="ctrl-neg", kind=SampleKind.buffer,
|
|
482
|
+
concentration="10uM")],
|
|
483
|
+
reagents=[ReagentSpec(name="assay-buffer", amount="5 mL",
|
|
484
|
+
bsl_level=1)],
|
|
485
|
+
)
|
|
486
|
+
run_id, rejection = self.gateway.submit(protocol)
|
|
487
|
+
if rejection:
|
|
488
|
+
self.notify(f"adaptive well for {candidate} blocked: {rejection}")
|
|
489
|
+
return None
|
|
490
|
+
if self.export_fn:
|
|
491
|
+
self.export_fn(run_id, candidate, [f"{conc:g}uM"])
|
|
492
|
+
if self.tracker:
|
|
493
|
+
self.tracker.attach_test(hyp, protocol, run_id)
|
|
494
|
+
return run_id
|
|
495
|
+
|
|
496
|
+
def _handle_confirmation(self, event, conf: dict) -> dict[str, Any]:
|
|
497
|
+
"""Orthogonal confirmation means AGREEMENT between methods, not just
|
|
498
|
+
a second curve: overlapping 95% intervals (fallback: within 3x when
|
|
499
|
+
a CI is missing) -> the preliminary call is re-tested against the
|
|
500
|
+
pre-registered gate on the SECOND read. Bad QC or a PHYSICAL plate
|
|
501
|
+
failure yields inconclusive, and every confirmation outcome,
|
|
502
|
+
including the property-metric ones, is provenance-recorded with the
|
|
503
|
+
comparison and the rule used."""
|
|
504
|
+
from proef.labread import QC_ZPRIME_FLOOR, read_plate, replicate_ci
|
|
505
|
+
from proef.physfail import classify as _fm
|
|
506
|
+
|
|
507
|
+
cand, primary = conf["candidate"], conf["primary_ic50"]
|
|
508
|
+
primary_ci = conf.get("primary_ci")
|
|
509
|
+
result = read_plate(event.path, max_response=self.max_response)
|
|
510
|
+
recs = [m if isinstance(m, dict) else m.model_dump()
|
|
511
|
+
for m in result.records]
|
|
512
|
+
hyp = next((h for h in (self.tracker.hypotheses.values()
|
|
513
|
+
if self.tracker else [])
|
|
514
|
+
if h.candidate == cand), None)
|
|
515
|
+
crit = hyp.criteria if hyp else None
|
|
516
|
+
property_metric = bool(crit
|
|
517
|
+
and crit.metric not in ("ic50_um", "value"))
|
|
518
|
+
|
|
519
|
+
# a physically failed plate confirms nothing (P1-6): flag for the
|
|
520
|
+
# operator, record the failure mode, abstain — never retry blindly
|
|
521
|
+
vals = [r.get("value") for r in recs
|
|
522
|
+
if isinstance(r.get("value"), (int, float))]
|
|
523
|
+
phys = _fm(vals) if vals else _fm([], error="no readings")
|
|
524
|
+
if phys["kind"] == "physical":
|
|
525
|
+
self.notify(f"\u26a0 physical failure mode on confirmation plate "
|
|
526
|
+
f"{event.path.name}: {phys['evidence']}, "
|
|
527
|
+
f"{phys['action']}; no confirmation verdict")
|
|
528
|
+
self._record_failure_mode(event, phys)
|
|
529
|
+
return self._finish_confirmation(
|
|
530
|
+
event, conf, hyp, secondary=None, secondary_ci=None,
|
|
531
|
+
ratio=None, agreed=False, rule="physical-failure",
|
|
532
|
+
qc_ok=False, force_status="inconclusive", result=result)
|
|
533
|
+
|
|
534
|
+
qc_ok = (result.z_prime or 0) >= QC_ZPRIME_FLOOR
|
|
535
|
+
if property_metric:
|
|
536
|
+
# property metrics are confirmed as they are judged: the
|
|
537
|
+
# SECOND method's readout at the top dose, with its own
|
|
538
|
+
# replicate CI, is decided against the SAME pre-registered
|
|
539
|
+
# gate. No fake 1.0 ratio; agreement = same gate decision
|
|
540
|
+
# (computed in _finish_confirmation via classify)
|
|
541
|
+
pairs = [(r.get("conc_um"), r.get("value")) for r in recs
|
|
542
|
+
if r.get("sample") == cand and not r.get("control")
|
|
543
|
+
and isinstance(r.get("conc_um"), (int, float))
|
|
544
|
+
and isinstance(r.get("value"), (int, float))]
|
|
545
|
+
if pairs:
|
|
546
|
+
top = max(c for c, _ in pairs)
|
|
547
|
+
top_vals = [v for c, v in pairs if c == top]
|
|
548
|
+
secondary = sum(top_vals) / len(top_vals)
|
|
549
|
+
secondary_ci = replicate_ci(top_vals)
|
|
550
|
+
else:
|
|
551
|
+
singles = [r.get("value") for r in recs
|
|
552
|
+
if r.get("sample") == cand
|
|
553
|
+
and not r.get("control")
|
|
554
|
+
and isinstance(r.get("value"), (int, float))]
|
|
555
|
+
secondary = sum(singles) / len(singles) if singles else None
|
|
556
|
+
secondary_ci = None
|
|
557
|
+
ratio = None
|
|
558
|
+
agreed = None # gate-direction agreement decided below
|
|
559
|
+
rule = "gate-direction"
|
|
560
|
+
else:
|
|
561
|
+
match = result.analysis["compounds"].get(cand) or {}
|
|
562
|
+
secondary = match.get("ic50_um")
|
|
563
|
+
secondary_ci = match.get("ic50_ci")
|
|
564
|
+
ratio = (max(primary, secondary) / min(primary, secondary)
|
|
565
|
+
if primary and secondary else None)
|
|
566
|
+
if primary_ci and secondary_ci:
|
|
567
|
+
# interval overlap is a stronger agreement test than a
|
|
568
|
+
# point ratio: two methods whose CIs overlap cannot
|
|
569
|
+
# distinguish each other
|
|
570
|
+
agreed = min(primary_ci[1], secondary_ci[1]) >= max(
|
|
571
|
+
primary_ci[0], secondary_ci[0])
|
|
572
|
+
rule = "ci-overlap"
|
|
573
|
+
else:
|
|
574
|
+
agreed = ratio is not None and ratio <= 3.0
|
|
575
|
+
rule = "3x-ratio"
|
|
576
|
+
return self._finish_confirmation(
|
|
577
|
+
event, conf, hyp, secondary, secondary_ci, ratio, agreed,
|
|
578
|
+
rule, qc_ok, result=result)
|
|
579
|
+
|
|
580
|
+
def _finish_confirmation(self, event, conf: dict, hyp, secondary,
|
|
581
|
+
secondary_ci, ratio, agreed, rule: str,
|
|
582
|
+
qc_ok: bool, force_status: str | None = None,
|
|
583
|
+
result=None) -> dict[str, Any]:
|
|
584
|
+
"""One status machine + one provenance tail for ALL confirmation
|
|
585
|
+
shapes (IC50-fit, property readout, physical failure). Nothing
|
|
586
|
+
that decides a hypothesis leaves without a record."""
|
|
587
|
+
cand = conf["candidate"]
|
|
588
|
+
primary = conf["primary_ic50"]
|
|
589
|
+
primary_ci = conf.get("primary_ci")
|
|
590
|
+
crit = hyp.criteria if hyp else None
|
|
591
|
+
property_metric = bool(crit
|
|
592
|
+
and crit.metric not in ("ic50_um", "value"))
|
|
593
|
+
status, agreed = self._confirmation_status(
|
|
594
|
+
hyp, crit, cand, primary, primary_ci, secondary, secondary_ci,
|
|
595
|
+
agreed, qc_ok, force_status, property_metric)
|
|
596
|
+
self._notify_confirmation(cand, crit, property_metric, primary,
|
|
597
|
+
secondary, ratio, rule, status, result)
|
|
598
|
+
self._record_confirmation(event, cand, crit, property_metric,
|
|
599
|
+
primary, primary_ci, secondary,
|
|
600
|
+
secondary_ci, ratio, agreed, rule, qc_ok,
|
|
601
|
+
status, result)
|
|
602
|
+
return {"confirmation": status, "candidate": cand,
|
|
603
|
+
"primary": primary, "secondary": secondary, "ratio": ratio}
|
|
604
|
+
|
|
605
|
+
def _confirmation_status(self, hyp, crit, cand, primary, primary_ci,
|
|
606
|
+
secondary, secondary_ci, agreed, qc_ok,
|
|
607
|
+
force_status, property_metric):
|
|
608
|
+
"""The confirmation status machine -> (status, agreed)."""
|
|
609
|
+
pri_status = hyp.status if hyp else "tested"
|
|
610
|
+
status = force_status
|
|
611
|
+
if status is None and (not qc_ok or secondary is None):
|
|
612
|
+
status = "inconclusive"
|
|
613
|
+
elif status is None and property_metric:
|
|
614
|
+
# agreement for a property metric = the second method makes the
|
|
615
|
+
# SAME gate decision as the first (direction-aware). A flipped
|
|
616
|
+
# decision is a disagreement, even though both are decisive.
|
|
617
|
+
cls = crit.classify(secondary, secondary_ci)
|
|
618
|
+
pri_hit = pri_status in ("validated", "confirmed")
|
|
619
|
+
if cls == "inconclusive":
|
|
620
|
+
agreed, status = False, "inconclusive"
|
|
621
|
+
elif pri_hit:
|
|
622
|
+
agreed = cls == "validated"
|
|
623
|
+
status = "confirmed" if agreed else "refuted"
|
|
624
|
+
else:
|
|
625
|
+
agreed = cls == "invalidated"
|
|
626
|
+
status = "refuted" if agreed else "confirmed"
|
|
627
|
+
elif status is None and agreed is False:
|
|
628
|
+
# methods disagree: a claimed HIT that doesn't reproduce is
|
|
629
|
+
# refuted; a claimed NON-HIT that disagrees is simply unclear
|
|
630
|
+
status = "refuted" if pri_status in ("validated", "confirmed") \
|
|
631
|
+
else "inconclusive"
|
|
632
|
+
elif status is None:
|
|
633
|
+
# agreement VERIFIES the preliminary verdict's direction —
|
|
634
|
+
# confirmed only for hits, refuted for non-hits, and borderline
|
|
635
|
+
# CIs stay inconclusive no matter how well the methods agree
|
|
636
|
+
cls = (crit.classify(secondary, secondary_ci)
|
|
637
|
+
if (crit and secondary is not None) else "inconclusive")
|
|
638
|
+
pri_cls = (crit.classify(primary, primary_ci) if crit
|
|
639
|
+
else cls)
|
|
640
|
+
if cls == "inconclusive" or pri_cls == "inconclusive":
|
|
641
|
+
status = "inconclusive"
|
|
642
|
+
self.notify(f"gate honesty: {cand} methods agree but a "
|
|
643
|
+
f"borderline CI straddles threshold "
|
|
644
|
+
f"{crit.threshold if crit else '?'} "
|
|
645
|
+
f"-> inconclusive")
|
|
646
|
+
elif pri_status in ("validated", "confirmed"):
|
|
647
|
+
status = "confirmed" if cls == "validated" else "refuted"
|
|
648
|
+
else:
|
|
649
|
+
status = "refuted" if cls == "invalidated" else "confirmed"
|
|
650
|
+
return status, agreed
|
|
651
|
+
|
|
652
|
+
def _notify_confirmation(self, cand, crit, property_metric, primary,
|
|
653
|
+
secondary, ratio, rule, status, result) -> None:
|
|
654
|
+
if property_metric:
|
|
655
|
+
unit = next((r.get("unit", "") for r in
|
|
656
|
+
(m if isinstance(m, dict) else m.model_dump()
|
|
657
|
+
for m in result.records)
|
|
658
|
+
if r.get("sample") == cand), "") if result else ""
|
|
659
|
+
self.notify(f"orthogonal confirmation for {cand}: "
|
|
660
|
+
f"{crit.metric if crit else '?'} {secondary} {unit} "
|
|
661
|
+
f"vs threshold {crit.threshold if crit else '?'} "
|
|
662
|
+
f"-> {status.upper()}")
|
|
663
|
+
elif ratio:
|
|
664
|
+
self.notify(f"orthogonal confirmation for {cand}: primary "
|
|
665
|
+
f"{primary:.2f} vs secondary {secondary:.2f} \u00b5M "
|
|
666
|
+
f"(ratio {ratio:.1f}x, rule {rule}) -> "
|
|
667
|
+
f"{status.upper()}")
|
|
668
|
+
else:
|
|
669
|
+
self.notify(f"orthogonal confirmation for {cand}: no usable "
|
|
670
|
+
f"secondary fit -> {status.upper()}")
|
|
671
|
+
|
|
672
|
+
def _record_confirmation(self, event, cand, crit, property_metric,
|
|
673
|
+
primary, primary_ci, secondary, secondary_ci,
|
|
674
|
+
ratio, agreed, rule, qc_ok, status,
|
|
675
|
+
result) -> None:
|
|
676
|
+
"""Write the verdict + its derivation onto the matching hypothesis
|
|
677
|
+
and into provenance."""
|
|
678
|
+
if self.tracker:
|
|
679
|
+
for h in self.tracker.hypotheses.values():
|
|
680
|
+
if h.candidate != cand:
|
|
681
|
+
continue
|
|
682
|
+
if secondary is not None:
|
|
683
|
+
h.observed_value = secondary
|
|
684
|
+
h.observed_ci = secondary_ci
|
|
685
|
+
elif not property_metric:
|
|
686
|
+
h.observed_value = primary
|
|
687
|
+
h.observed_ci = primary_ci
|
|
688
|
+
# a failed property confirmation keeps the primary's own
|
|
689
|
+
# property readout — the ic50 fit on a property plate is
|
|
690
|
+
# meaningless and must not overwrite evidence
|
|
691
|
+
h.evidence_run_id = event.path.stem
|
|
692
|
+
h.qc_passed = qc_ok
|
|
693
|
+
h.status = status
|
|
694
|
+
if not hasattr(self.tracker, "record_outcome"):
|
|
695
|
+
break
|
|
696
|
+
from proef.derivation import build
|
|
697
|
+
inst, ver = self._instrument()
|
|
698
|
+
_der = build(
|
|
699
|
+
instrument=inst, version=ver,
|
|
700
|
+
quantity=(getattr(result, "response_unit", None)
|
|
701
|
+
if result is not None else None),
|
|
702
|
+
counts={"wells": len(result.records) if result else 0},
|
|
703
|
+
metric=crit.metric if crit else None,
|
|
704
|
+
method=("property orthogonal re-measurement"
|
|
705
|
+
if property_metric else
|
|
706
|
+
"orthogonal re-measurement + fit"),
|
|
707
|
+
ci=("residual bootstrap 95%" if (rule == "ci-overlap")
|
|
708
|
+
else "replicate bootstrap 95%"
|
|
709
|
+
if (property_metric and secondary_ci) else None),
|
|
710
|
+
criteria_metric=crit.metric if crit else None,
|
|
711
|
+
criteria_direction=crit.direction if crit else None,
|
|
712
|
+
criteria_threshold=crit.threshold if crit else None)
|
|
713
|
+
self.tracker.record_outcome(h, extra={
|
|
714
|
+
"derivation": _der,
|
|
715
|
+
"confirmation": {
|
|
716
|
+
"run_id": event.path.stem,
|
|
717
|
+
"primary_ic50": primary,
|
|
718
|
+
"primary_ci": list(primary_ci) if primary_ci else None,
|
|
719
|
+
"secondary_ic50": secondary,
|
|
720
|
+
"secondary_ci": (list(secondary_ci)
|
|
721
|
+
if secondary_ci else None),
|
|
722
|
+
"ratio": round(ratio, 2) if ratio else None,
|
|
723
|
+
"agreed": bool(agreed) if agreed is not None
|
|
724
|
+
else status == "confirmed",
|
|
725
|
+
"rule": rule}})
|
|
726
|
+
break
|
|
727
|
+
|
|
728
|
+
def _submit_confirmation(self, candidate: str, ic50: float) -> str | None:
|
|
729
|
+
"""Close the loop: design + safety-submit the orthogonal confirmation.
|
|
730
|
+
|
|
731
|
+
Orthogonal means a DIFFERENT method: the confirmation assay is
|
|
732
|
+
chosen from the hypothesis's own assay type, an enzymatic primary
|
|
733
|
+
is confirmed by binding, not by repeating enzymatic (P1-1)."""
|
|
734
|
+
from proef.core.contracts import (
|
|
735
|
+
Envelope, ProtocolOp, ProtocolStep, ProtocolSubmission,
|
|
736
|
+
ReagentSpec, SampleKind, SampleSpec,
|
|
737
|
+
)
|
|
738
|
+
|
|
739
|
+
hyp = next((h for h in (self.tracker.hypotheses.values()
|
|
740
|
+
if self.tracker else [])
|
|
741
|
+
if h.candidate == candidate), None)
|
|
742
|
+
primary_assay = (hyp.assay_type if hyp else "") or "binding"
|
|
743
|
+
assay = (self.ORTHOGONAL_ASSAY.get(primary_assay)
|
|
744
|
+
or ("binding" if primary_assay != "binding" else "enzymatic"))
|
|
745
|
+
protocol = ProtocolSubmission(
|
|
746
|
+
envelope=Envelope(experiment_branch_id=self.branch_id),
|
|
747
|
+
title=f"auto-confirmation-{candidate}",
|
|
748
|
+
assay_type=assay,
|
|
749
|
+
steps=[ProtocolStep(seq=1, op=ProtocolOp.dispense, params={"volume_ul": 50})],
|
|
750
|
+
samples=[SampleSpec(sample_id=candidate, kind=SampleKind.compound,
|
|
751
|
+
concentration="10uM"),
|
|
752
|
+
SampleSpec(sample_id="ctrl-neg", kind=SampleKind.buffer,
|
|
753
|
+
concentration="10uM")],
|
|
754
|
+
reagents=[ReagentSpec(name="assay-buffer", amount="5 mL", bsl_level=1)],
|
|
755
|
+
)
|
|
756
|
+
run_id, rejection = self.gateway.submit(protocol)
|
|
757
|
+
if rejection:
|
|
758
|
+
self.notify(f"confirmation assay for {candidate} BLOCKED by safety: {rejection}")
|
|
759
|
+
return None
|
|
760
|
+
self._confirm_submitted.add(candidate)
|
|
761
|
+
primary_ci = None
|
|
762
|
+
if self.tracker:
|
|
763
|
+
for hyp in self.tracker.hypotheses.values():
|
|
764
|
+
if hyp.candidate == candidate:
|
|
765
|
+
primary_ci = hyp.observed_ci
|
|
766
|
+
self._confirmations[run_id] = {"candidate": candidate,
|
|
767
|
+
"primary_ic50": ic50,
|
|
768
|
+
"primary_ci": primary_ci}
|
|
769
|
+
if self.export_fn:
|
|
770
|
+
self.export_fn(run_id, candidate) # confirmation runs get outputs too
|
|
771
|
+
# keep the run↔hypothesis link in provenance, not just in memory
|
|
772
|
+
if self.tracker:
|
|
773
|
+
for hyp in self.tracker.hypotheses.values():
|
|
774
|
+
if hyp.candidate == candidate and self.tracker.hypotheses.get(hyp.hypothesis_id):
|
|
775
|
+
self.tracker.attach_test(hyp, protocol, run_id)
|
|
776
|
+
break
|
|
777
|
+
self.notify(f"sending orthogonal confirmation assay for {candidate} "
|
|
778
|
+
f"(safety-approved) -> run {run_id}")
|
|
779
|
+
return run_id
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def watch(inbox: str | Path, store: Any = None, tracker: Any = None,
|
|
783
|
+
stop_after: int | None = None, poll_secs: float = 1.0,
|
|
784
|
+
notify: Callable[[str], None] | None = None,
|
|
785
|
+
gateway: Any = None, branch_id: str = "autonomous-loop") -> None:
|
|
786
|
+
monitor = DeviceMonitor(inbox, poll_secs=poll_secs)
|
|
787
|
+
agent = AutoAnalysisAgent(store=store, tracker=tracker, notify=notify,
|
|
788
|
+
gateway=gateway, branch_id=branch_id)
|
|
789
|
+
for event in monitor.events(stop_after=stop_after):
|
|
790
|
+
agent.handle(event)
|