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,282 @@
|
|
|
1
|
+
"""Virtual Lab Simulator — deterministic, seeded assay outcomes (P4, P8).
|
|
2
|
+
|
|
3
|
+
Implements LabAdapter. Same contract as any hardware adapter; CI runs this.
|
|
4
|
+
Outcome model: per-assay baseline response modulated by a seeded per-sample
|
|
5
|
+
factor + gaussian noise, so workflows are reproducible given a seed.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import random
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from proef.fitting import hill_response
|
|
14
|
+
from proef.core.contracts import (
|
|
15
|
+
AssayResult,
|
|
16
|
+
Envelope,
|
|
17
|
+
InstrumentInfo,
|
|
18
|
+
Measurement,
|
|
19
|
+
MeasurementFlag,
|
|
20
|
+
ProtocolSubmission,
|
|
21
|
+
RunStatus,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# assay -> (max_response, unit, noise_std)
|
|
25
|
+
ASSAY_PROFILE: dict[str, tuple[float, str, float]] = {
|
|
26
|
+
"binding": (100.0, "percent_inhibition", 4.0),
|
|
27
|
+
"enzymatic": (100.0, "percent_inhibition", 5.0),
|
|
28
|
+
"cytotoxicity": (100.0, "percent_viability_loss", 6.0),
|
|
29
|
+
"counterscreen": (100.0, "percent_interference", 3.0),
|
|
30
|
+
"adme": (70.0, "permeability_score", 9.0),
|
|
31
|
+
"plate_reader": (60.0, "od450", 0.15),
|
|
32
|
+
# materials characterization (simulated property curves)
|
|
33
|
+
"tensile": (250.0, "MPa", 12.0),
|
|
34
|
+
"dsc": (145.0, "degC", 3.0),
|
|
35
|
+
"dls": (120.0, "nm", 8.0),
|
|
36
|
+
"ftir": (97.0, "pct_transmittance", 1.5),
|
|
37
|
+
"xrd": (68.0, "pct_crystallinity", 4.0),
|
|
38
|
+
"density": (7.8, "g_per_cm3", 0.15),
|
|
39
|
+
# biologics
|
|
40
|
+
"elisa": (850.0, "ng_per_mL", 40.0),
|
|
41
|
+
"dsf": (62.0, "degC", 1.2),
|
|
42
|
+
"immunogenicity": (35.0, "pct_response", 4.0),
|
|
43
|
+
"aggregation": (8.0, "pct_aggregate", 0.8),
|
|
44
|
+
"thermal_stability": (71.0, "degC", 1.0),
|
|
45
|
+
# cell therapy
|
|
46
|
+
"potency": (88.0, "pct_potency", 5.0),
|
|
47
|
+
"sterility": (99.0, "pct_sterile", 0.5),
|
|
48
|
+
"phenotype_stability": (92.0, "pct_phenotype", 2.5),
|
|
49
|
+
# mRNA
|
|
50
|
+
"expression": (74.0, "pct_expression", 4.5),
|
|
51
|
+
"stability": (80.0, "pct_intact", 3.0),
|
|
52
|
+
# agrochemical
|
|
53
|
+
"organism_dose_response": (100.0, "pct_mortality", 5.0),
|
|
54
|
+
"phytotoxicity": (100.0, "pct_injury", 5.0),
|
|
55
|
+
"custom": (50.0, "signal", 10.0),
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
from proef.modality import DOSE_RESPONSE as DOSE_RESPONSE_ASSAYS # noqa: E402 one definition, in the modality pack
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def parse_concentration_um(conc: str | None, default_um: float = 10.0) -> float:
|
|
62
|
+
"""Parse '10uM'/'500nM'/None -> micromolar."""
|
|
63
|
+
if not conc:
|
|
64
|
+
return default_um
|
|
65
|
+
c = conc.strip().lower()
|
|
66
|
+
if c.endswith("nm"):
|
|
67
|
+
return float(c[:-2]) / 1000.0
|
|
68
|
+
if c.endswith("um"):
|
|
69
|
+
return float(c[:-2])
|
|
70
|
+
if c.endswith("mm"):
|
|
71
|
+
return float(c[:-2]) * 1000.0
|
|
72
|
+
try:
|
|
73
|
+
return float(c)
|
|
74
|
+
except ValueError:
|
|
75
|
+
return default_um
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class SimulatorLab:
|
|
79
|
+
"""Virtual lab with realistic assay semantics (P4/P8):
|
|
80
|
+
|
|
81
|
+
- Dose–response: repeated sample_ids at increasing concentrations produce a
|
|
82
|
+
Hill curve; `ic50_um` is reported in derived_metrics.
|
|
83
|
+
- Replicates: repeated (sample_id, concentration) pairs are independent
|
|
84
|
+
draws; median is the reported value.
|
|
85
|
+
- Counterscreens: 'counterscreen' assay flags assay-interference artifacts
|
|
86
|
+
(PAINS-like): a seeded fraction of compounds shows false signal.
|
|
87
|
+
- Method bias: `method_bias={"<sample>": {"<assay>": factor}}` multiplies a compound's
|
|
88
|
+
apparent IC50 in ONE assay type, a method-specific artifact (an aggregator that looks
|
|
89
|
+
potent in a binding assay and is not active in an enzymatic one). It is how a demo or
|
|
90
|
+
a test engineers "the orthogonal method disagrees" explicitly, instead of hoping the
|
|
91
|
+
noise lands that way.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
name = "simulator"
|
|
95
|
+
version = "sim-v1"
|
|
96
|
+
|
|
97
|
+
def __init__(self, seed: int = 7, instruments: dict[str, Any] | None = None,
|
|
98
|
+
replicates: int = 3, interference_rate: float = 0.25,
|
|
99
|
+
method_bias: dict[str, dict[str, float]] | None = None):
|
|
100
|
+
self.seed = seed
|
|
101
|
+
self.method_bias = {s: dict(b) for s, b in (method_bias or {}).items()}
|
|
102
|
+
self.replicates = replicates
|
|
103
|
+
self.supports_replicates = True # a protocol may ask for its own replicate count (constraints['replicates'])
|
|
104
|
+
self.interference_rate = interference_rate
|
|
105
|
+
self._runs: dict[str, ProtocolSubmission] = {}
|
|
106
|
+
self._capabilities = instruments or {
|
|
107
|
+
"assays": ["binding", "enzymatic", "cytotoxicity", "counterscreen", "adme"],
|
|
108
|
+
"throughput": {"plates_per_day": 20},
|
|
109
|
+
"bsl_max": 2,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
def replay_config(self) -> dict[str, Any]:
|
|
113
|
+
"""Everything about this lab that changes what it measures, as plain data, so a replay can build the same lab."""
|
|
114
|
+
return {"replicates": self.replicates, "interference_rate": self.interference_rate,
|
|
115
|
+
"method_bias": {s: dict(b) for s, b in self.method_bias.items()}, "instruments": dict(self._capabilities)}
|
|
116
|
+
|
|
117
|
+
def replicates_for(self, protocol: ProtocolSubmission) -> int:
|
|
118
|
+
"""The replicate count this run uses: the protocol's own request when it has one (bounded), else the lab's."""
|
|
119
|
+
want = (getattr(protocol, "constraints", None) or {}).get("replicates")
|
|
120
|
+
if isinstance(want, int) and not isinstance(want, bool) and 1 <= want <= 12:
|
|
121
|
+
return want
|
|
122
|
+
return self.replicates
|
|
123
|
+
|
|
124
|
+
def list_capabilities(self) -> dict[str, Any]:
|
|
125
|
+
return dict(self._capabilities)
|
|
126
|
+
|
|
127
|
+
def submit_protocol(self, protocol: ProtocolSubmission) -> str:
|
|
128
|
+
# deterministic run ids (seed + call order): downstream noise seeds
|
|
129
|
+
# derive from run ids, so evals and case studies stay reproducible
|
|
130
|
+
self._seq = getattr(self, "_seq", 0) + 1
|
|
131
|
+
run_id = f"sim-{self.seed}-{self._seq:03d}"
|
|
132
|
+
self._runs[run_id] = protocol
|
|
133
|
+
return run_id
|
|
134
|
+
|
|
135
|
+
def get_status(self, run_id: str) -> str:
|
|
136
|
+
return "done" if run_id in self._runs else "failed"
|
|
137
|
+
|
|
138
|
+
# -- per-compound ground truth (seeded, stable across runs) ----------------
|
|
139
|
+
|
|
140
|
+
def _compound_key(self, protocol_id: str, sample_id: str) -> int:
|
|
141
|
+
# potency is a COMPOUND property, not a run property: key on the
|
|
142
|
+
# seed + sample only, so the same compound has the same ground truth
|
|
143
|
+
# across primary and confirmation runs (protocol_id kept in the
|
|
144
|
+
# signature for call-site stability)
|
|
145
|
+
material = f"{self.seed}:{sample_id}".encode()
|
|
146
|
+
return int(hashlib.sha256(material).hexdigest()[:8], 16)
|
|
147
|
+
|
|
148
|
+
def true_ic50_um(self, protocol_id: str, sample_id: str) -> float:
|
|
149
|
+
"""Seeded true potency for a compound (stable across runs)."""
|
|
150
|
+
key = self._compound_key(protocol_id, sample_id)
|
|
151
|
+
return 0.5 + (key % 1000) / 1000.0 * 49.5 # 0.5 – 50 uM
|
|
152
|
+
|
|
153
|
+
def apparent_ic50_um(self, run_id: str, sample_id: str) -> float:
|
|
154
|
+
"""What the ASSAY RUN reports: the compound's true potency, times its method bias for this run's assay type."""
|
|
155
|
+
proto = self._runs.get(run_id)
|
|
156
|
+
assay = proto.assay_type.value if proto is not None else None
|
|
157
|
+
return self.true_ic50_um(run_id, sample_id) * self.method_bias.get(sample_id, {}).get(assay, 1.0)
|
|
158
|
+
|
|
159
|
+
def is_interferer(self, protocol_id: str, sample_id: str) -> bool:
|
|
160
|
+
key = self._compound_key(protocol_id, sample_id)
|
|
161
|
+
return (key % 100) < self.interference_rate * 100
|
|
162
|
+
|
|
163
|
+
def set_property_gate(self, metric: str, direction: str,
|
|
164
|
+
threshold: float) -> None:
|
|
165
|
+
"""When the campaign's gate is a property metric (potency, Tm,
|
|
166
|
+
expression...), simulate candidate true values that STRADDLE the
|
|
167
|
+
gate — roughly half pass, half fail — instead of arbitrary
|
|
168
|
+
dose-response numbers. Dose-independent readout."""
|
|
169
|
+
self._property_gate = {"metric": metric, "direction": direction,
|
|
170
|
+
"threshold": float(threshold)}
|
|
171
|
+
|
|
172
|
+
def _property_true_value(self, protocol_id: str, sample_id: str) -> float:
|
|
173
|
+
# seeded by CANDIDATE only: a construct's true property value is
|
|
174
|
+
# fixed — replicate/confirmation runs sample noise around it
|
|
175
|
+
key = self._compound_key("property-truth", sample_id)
|
|
176
|
+
gate = self._property_gate["threshold"]
|
|
177
|
+
# spread candidates across 0.55x–1.45x of the gate, seeded/stable
|
|
178
|
+
factor = 0.55 + (key % 1000) / 1000.0 * 0.9
|
|
179
|
+
return gate * factor
|
|
180
|
+
|
|
181
|
+
def fetch_results(self, run_id: str) -> AssayResult:
|
|
182
|
+
protocol = self._runs[run_id]
|
|
183
|
+
assay = protocol.assay_type.value
|
|
184
|
+
max_resp, unit, noise = ASSAY_PROFILE.get(assay, ASSAY_PROFILE["custom"])
|
|
185
|
+
gate = getattr(self, "_property_gate", None)
|
|
186
|
+
property_mode = bool(gate and gate["metric"] not in
|
|
187
|
+
("ic50_um", "value"))
|
|
188
|
+
reps = self.replicates_for(protocol)
|
|
189
|
+
measurements: list[Measurement] = []
|
|
190
|
+
controls_passed = True
|
|
191
|
+
|
|
192
|
+
# group wells: (sample_id, concentration) -> replicate draws
|
|
193
|
+
for sample in protocol.samples:
|
|
194
|
+
is_control = sample.kind.value == "buffer" or sample.sample_id.startswith("ctrl")
|
|
195
|
+
conc = parse_concentration_um(sample.concentration)
|
|
196
|
+
ic50 = self.apparent_ic50_um(run_id, sample.sample_id)
|
|
197
|
+
draws = []
|
|
198
|
+
for rep in range(1, reps + 1):
|
|
199
|
+
rng = random.Random(self._compound_key(run_id + f"r{rep}", sample.sample_id + str(conc)))
|
|
200
|
+
if property_mode and not is_control:
|
|
201
|
+
# property readout: dose-independent true value per
|
|
202
|
+
# candidate, stable across replicates + noise
|
|
203
|
+
true_v = self._property_true_value(run_id, sample.sample_id)
|
|
204
|
+
value = true_v + rng.gauss(0, noise)
|
|
205
|
+
else:
|
|
206
|
+
value = self._response(assay, max_resp, conc, ic50, sample.sample_id, run_id)
|
|
207
|
+
value += rng.gauss(0, noise)
|
|
208
|
+
draws.append(value)
|
|
209
|
+
value = sorted(draws)[len(draws) // 2] # median of replicates
|
|
210
|
+
flags: list[MeasurementFlag] = []
|
|
211
|
+
if is_control:
|
|
212
|
+
value = 0.0 if assay != "plate_reader" else value
|
|
213
|
+
flags.append(MeasurementFlag.control)
|
|
214
|
+
if assay == "counterscreen" and value > 20:
|
|
215
|
+
controls_passed = False
|
|
216
|
+
derived: dict[str, float] = {}
|
|
217
|
+
if not is_control:
|
|
218
|
+
derived["conc_um"] = conc
|
|
219
|
+
if assay in DOSE_RESPONSE_ASSAYS and not is_control:
|
|
220
|
+
derived["ic50_um"] = round(ic50, 3)
|
|
221
|
+
measurements.append(
|
|
222
|
+
Measurement(
|
|
223
|
+
sample_id=sample.sample_id,
|
|
224
|
+
well=f"{sample.sample_id[:4]}-{conc:g}uM",
|
|
225
|
+
assay_type=assay,
|
|
226
|
+
value=round(value, 3),
|
|
227
|
+
unit=unit,
|
|
228
|
+
uncertainty=round(noise, 3),
|
|
229
|
+
replicate=reps,
|
|
230
|
+
derived_metrics=derived,
|
|
231
|
+
flags=flags,
|
|
232
|
+
)
|
|
233
|
+
)
|
|
234
|
+
return AssayResult(
|
|
235
|
+
envelope=Envelope(experiment_branch_id="simulator"),
|
|
236
|
+
protocol_id=protocol.protocol_id,
|
|
237
|
+
instrument=InstrumentInfo(adapter=self.name, instrument_id=f"{self.name}-01"),
|
|
238
|
+
status=RunStatus.completed,
|
|
239
|
+
measurements=measurements,
|
|
240
|
+
qc={"controls_passed": controls_passed},
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
def _response(self, assay: str, max_resp: float, conc: float, ic50: float,
|
|
244
|
+
sample_id: str, run_id: str) -> float:
|
|
245
|
+
"""Hill curve (n=1): response = max / (1 + IC50/C). Counterscreen is not
|
|
246
|
+
dose-dependent: interferers (PAINS-like) show high artifact signal."""
|
|
247
|
+
if assay == "counterscreen":
|
|
248
|
+
return max_resp * 0.9 if self.is_interferer(run_id, sample_id) else max_resp * 0.02
|
|
249
|
+
return hill_response(conc, ic50, max_resp, eps=1e-6)
|
|
250
|
+
|
|
251
|
+
def cancel(self, run_id: str) -> None:
|
|
252
|
+
self._runs.pop(run_id, None)
|
|
253
|
+
|
|
254
|
+
# -- state transport for sandboxed execution (S-T3 1c) ------------------
|
|
255
|
+
|
|
256
|
+
def export_state(self) -> dict:
|
|
257
|
+
"""JSON-safe snapshot of everything a fetch depends on."""
|
|
258
|
+
from proef.core.contracts import ProtocolSubmission as _PS
|
|
259
|
+
return {
|
|
260
|
+
"seed": self.seed, "replicates": self.replicates,
|
|
261
|
+
"interference_rate": self.interference_rate,
|
|
262
|
+
"method_bias": self.method_bias,
|
|
263
|
+
"seq": getattr(self, "_seq", 0),
|
|
264
|
+
"runs": {rid: p.model_dump(mode="json")
|
|
265
|
+
for rid, p in self._runs.items()},
|
|
266
|
+
"capabilities": self._capabilities,
|
|
267
|
+
"property_gate": getattr(self, "_property_gate", None),
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
@classmethod
|
|
271
|
+
def import_state(cls, st: dict) -> "SimulatorLab":
|
|
272
|
+
from proef.core.contracts import ProtocolSubmission as _PS
|
|
273
|
+
lab = cls(seed=st["seed"], instruments=st.get("capabilities"),
|
|
274
|
+
replicates=st["replicates"],
|
|
275
|
+
interference_rate=st["interference_rate"],
|
|
276
|
+
method_bias=st.get("method_bias"))
|
|
277
|
+
lab._seq = st["seq"]
|
|
278
|
+
lab._runs = {rid: _PS.model_validate(d)
|
|
279
|
+
for rid, d in st["runs"].items()}
|
|
280
|
+
if st.get("property_gate"):
|
|
281
|
+
lab._property_gate = st["property_gate"]
|
|
282
|
+
return lab
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Virtual production — Make as a first-class, modality-agnostic step.
|
|
2
|
+
|
|
3
|
+
Design decides the intervention; Make produces it. For small molecules
|
|
4
|
+
that is chemical synthesis; for biologics, expression and purification;
|
|
5
|
+
for other modalities, whatever production means. The QC semantics are
|
|
6
|
+
shared: every batch gets a yield, a purity, and a lot id, and batches
|
|
7
|
+
below spec are refused into Test. Deterministic (seeded from candidate
|
|
8
|
+
+ structure/sequence) so the same design always produces the same batch.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import random
|
|
14
|
+
|
|
15
|
+
MIN_PURITY = 85.0
|
|
16
|
+
MIN_YIELD = 10.0
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class VirtualSynthesizer:
|
|
20
|
+
"""Deterministic virtual synthesis: batch yield and purity from the
|
|
21
|
+
candidate identity. A SMILES (when present) shifts the seed — the
|
|
22
|
+
same structure always synthesizes the same way."""
|
|
23
|
+
|
|
24
|
+
name = "virtual-synthesis"
|
|
25
|
+
|
|
26
|
+
def __init__(self, min_purity: float = MIN_PURITY,
|
|
27
|
+
min_yield: float = MIN_YIELD):
|
|
28
|
+
self.min_purity = min_purity
|
|
29
|
+
self.min_yield = min_yield
|
|
30
|
+
|
|
31
|
+
# how each modality words its production step
|
|
32
|
+
ACTIONS = {"small molecule": "synthesized",
|
|
33
|
+
"": "synthesized",
|
|
34
|
+
"biologic": "expressed and purified",
|
|
35
|
+
"cell therapy": "engineered and expanded",
|
|
36
|
+
"mRNA": "transcribed and encapsulated"}
|
|
37
|
+
|
|
38
|
+
def synthesize(self, candidate: str, smiles: str | None = None,
|
|
39
|
+
modality: str = "", attempt: int = 1,
|
|
40
|
+
route: dict | None = None) -> dict:
|
|
41
|
+
"""attempt > 1 is a REAL re-synthesis: process re-optimization on a
|
|
42
|
+
different route run (its own lot seed), recorded separately. One
|
|
43
|
+
refused batch never silently dooms a candidate that a second
|
|
44
|
+
process run could deliver — and each attempt is provenance.
|
|
45
|
+
|
|
46
|
+
route: a planned RoutePlan.summary() from the retrosynthesis
|
|
47
|
+
adapter. When given, batch yield is drawn from the ROUTE'S MODELED
|
|
48
|
+
overall yield (± seeded process variance) instead of a flat prior —
|
|
49
|
+
Make answers to the plan, and the plan is stamped into the batch."""
|
|
50
|
+
seed = hashlib.sha256(
|
|
51
|
+
f"{candidate}|{smiles or ''}|a{attempt}".encode()).hexdigest()
|
|
52
|
+
rng = random.Random(seed)
|
|
53
|
+
if smiles and route:
|
|
54
|
+
# batch yield is DRAWN FROM THE ROUTE (modeled overall yield ±
|
|
55
|
+
# seeded process variance), not a flat prior
|
|
56
|
+
mu = float(route.get("yield_pct", 50.0))
|
|
57
|
+
yield_pct = round(min(95.0, max(1.0, rng.gauss(mu, mu * 0.25))), 1)
|
|
58
|
+
purity = round(78 + rng.random() * 21.5, 1)
|
|
59
|
+
elif smiles:
|
|
60
|
+
# designed molecules carry real synthetic risk: ~30% of
|
|
61
|
+
# structures fail purity or yield (deterministic per structure).
|
|
62
|
+
# Distribution calibrated to that stated claim: an earlier
|
|
63
|
+
# uniform purity U[60,99.5] against a 85 gate failed ~2/3 of
|
|
64
|
+
# batches — a Make stub should not dominate a real-data study
|
|
65
|
+
# (CS04 caught the intent/behavior mismatch).
|
|
66
|
+
yield_pct = round(5 + rng.random() * 90, 1)
|
|
67
|
+
purity = round(78 + rng.random() * 21.5, 1)
|
|
68
|
+
else:
|
|
69
|
+
# virtual candidates without structures are the lab's
|
|
70
|
+
# abstraction — always synthesizable at high quality
|
|
71
|
+
yield_pct = round(40 + rng.random() * 55, 1)
|
|
72
|
+
purity = round(90 + rng.random() * 9.5, 1)
|
|
73
|
+
ok = purity >= self.min_purity and yield_pct >= self.min_yield
|
|
74
|
+
lot = "lot-" + seed[:8]
|
|
75
|
+
out = {"attempt": attempt,
|
|
76
|
+
"candidate": candidate, "smiles": smiles or "",
|
|
77
|
+
"modality": modality,
|
|
78
|
+
"action": self.ACTIONS.get(modality.lower().strip(),
|
|
79
|
+
"produced"),
|
|
80
|
+
"yield_pct": yield_pct, "purity": purity, "ok": ok,
|
|
81
|
+
"lot": lot,
|
|
82
|
+
"note": "" if ok else
|
|
83
|
+
f"purity {purity} < {self.min_purity} or yield "
|
|
84
|
+
f"{yield_pct} < {self.min_yield} — batch refused into Test"}
|
|
85
|
+
if route: # batch answers to a planned route — stamp everything
|
|
86
|
+
out["route"] = route.get("route", "")
|
|
87
|
+
out["route_steps"] = route.get("steps")
|
|
88
|
+
out["route_yield_model_pct"] = route.get("yield_pct")
|
|
89
|
+
out["route_lead_time_days"] = route.get("lead_time_days")
|
|
90
|
+
out["route_cost_usd"] = route.get("cost_usd")
|
|
91
|
+
out["data_origin"] = route.get("data_origin", "")
|
|
92
|
+
return out
|
|
File without changes
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Anthropic model provider (T4.1, P3).
|
|
2
|
+
|
|
3
|
+
Same contract as OpenAICompatProvider: real API when configured, deterministic
|
|
4
|
+
offline stub otherwise. Stamps model_version on every result (P5).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import urllib.request
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from proef.core.contracts import ToolInvocation, ToolName, ToolResult
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AnthropicProvider:
|
|
18
|
+
name = "anthropic"
|
|
19
|
+
|
|
20
|
+
def __init__(self, model: str | None = None, api_key: str | None = None,
|
|
21
|
+
base_url: str | None = None):
|
|
22
|
+
self.model = (model or os.environ.get("PROEF_LLM_MODEL")
|
|
23
|
+
or os.environ.get("ANTHROPIC_DEFAULT_SONNET_MODEL")
|
|
24
|
+
or os.environ.get("ANTHROPIC_DEFAULT_HAIKU_MODEL")
|
|
25
|
+
or "stub-claude")
|
|
26
|
+
self.model_version = self.model
|
|
27
|
+
self.api_key = api_key or os.environ.get("ANTHROPIC_AUTH_TOKEN")
|
|
28
|
+
self.base_url = (base_url or os.environ.get("PROEF_LLM_BASE_URL")
|
|
29
|
+
or os.environ.get("ANTHROPIC_BASE_URL")
|
|
30
|
+
or "https://api.anthropic.com").rstrip("/")
|
|
31
|
+
# real-API mode only when a key is present; otherwise offline stub
|
|
32
|
+
self.api_key = self.api_key if self.api_key else None
|
|
33
|
+
|
|
34
|
+
def generate(self, invocation: ToolInvocation, prompt: str, system: str | None = None, **kwargs: Any) -> ToolResult:
|
|
35
|
+
if self.api_key is None:
|
|
36
|
+
text = self._stub_generate(prompt, **kwargs)
|
|
37
|
+
else:
|
|
38
|
+
text = self._messages(prompt, system, **kwargs)
|
|
39
|
+
return ToolResult(
|
|
40
|
+
envelope=invocation.envelope.model_copy(),
|
|
41
|
+
invocation_id=invocation.invocation_id,
|
|
42
|
+
status="succeeded",
|
|
43
|
+
output={"text": text},
|
|
44
|
+
model_version=self.model_version,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def predict(self, invocation: ToolInvocation, kind: ToolName, payload: dict[str, Any]) -> ToolResult:
|
|
48
|
+
return ToolResult(
|
|
49
|
+
envelope=invocation.envelope.model_copy(),
|
|
50
|
+
invocation_id=invocation.invocation_id,
|
|
51
|
+
status="rejected",
|
|
52
|
+
rejection_reason=f"{self.name} does not implement structured prediction '{kind}'",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def _messages(self, prompt: str, system: str | None, **kwargs: Any) -> str:
|
|
56
|
+
body: dict[str, Any] = {
|
|
57
|
+
"model": self.model,
|
|
58
|
+
"max_tokens": kwargs.pop("max_tokens", 4000),
|
|
59
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
60
|
+
**kwargs,
|
|
61
|
+
}
|
|
62
|
+
if system:
|
|
63
|
+
body["system"] = system
|
|
64
|
+
# reasoning models can spend the whole budget thinking and return no
|
|
65
|
+
# text — escalate max_tokens rather than fail
|
|
66
|
+
attempts = 0
|
|
67
|
+
while True:
|
|
68
|
+
attempts += 1
|
|
69
|
+
data = self._post(self._request(body))
|
|
70
|
+
text = "".join(c.get("text", "") for c in data.get("content", [])
|
|
71
|
+
if c.get("type") == "text")
|
|
72
|
+
if text:
|
|
73
|
+
return text
|
|
74
|
+
if attempts >= 5 or body["max_tokens"] >= 32000:
|
|
75
|
+
raise ValueError("model returned no text content "
|
|
76
|
+
"(reasoning may have exhausted max_tokens)")
|
|
77
|
+
body["max_tokens"] = min(32000, body["max_tokens"] * 2)
|
|
78
|
+
|
|
79
|
+
def _request(self, body: dict):
|
|
80
|
+
return urllib.request.Request(
|
|
81
|
+
f"{self.base_url}/v1/messages",
|
|
82
|
+
data=json.dumps(body).encode(),
|
|
83
|
+
headers={
|
|
84
|
+
"Content-Type": "application/json",
|
|
85
|
+
"x-api-key": self.api_key or "",
|
|
86
|
+
"anthropic-version": "2023-06-01",
|
|
87
|
+
},
|
|
88
|
+
method="POST",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def _post(self, req, tries: int = 6):
|
|
92
|
+
import time
|
|
93
|
+
import urllib.error
|
|
94
|
+
for i in range(tries):
|
|
95
|
+
try:
|
|
96
|
+
with urllib.request.urlopen(req, timeout=300) as resp: # noqa: S310
|
|
97
|
+
# 300s: reasoning models can pause well past a minute
|
|
98
|
+
# before emitting text
|
|
99
|
+
return json.loads(resp.read())
|
|
100
|
+
except urllib.error.HTTPError as exc:
|
|
101
|
+
if exc.code not in (429, 500, 502, 503) or i == tries - 1:
|
|
102
|
+
raise
|
|
103
|
+
time.sleep(10 * (i + 1))
|
|
104
|
+
except Exception:
|
|
105
|
+
if i == tries - 1:
|
|
106
|
+
raise
|
|
107
|
+
time.sleep(10 * (i + 1))
|
|
108
|
+
|
|
109
|
+
def call_with_tools(self, messages: list[dict], tools: list[dict],
|
|
110
|
+
system: str = "") -> dict:
|
|
111
|
+
"""Send a conversation with tool definitions; returns parsed response
|
|
112
|
+
with tool_calls extracted. Used by the agentic loop."""
|
|
113
|
+
body: dict[str, Any] = {
|
|
114
|
+
"model": self.model,
|
|
115
|
+
"max_tokens": 8000,
|
|
116
|
+
"messages": messages,
|
|
117
|
+
"tools": tools,
|
|
118
|
+
}
|
|
119
|
+
if system:
|
|
120
|
+
body["system"] = system
|
|
121
|
+
req = urllib.request.Request(
|
|
122
|
+
f"{self.base_url}/v1/messages",
|
|
123
|
+
data=json.dumps(body).encode(),
|
|
124
|
+
headers={
|
|
125
|
+
"Content-Type": "application/json",
|
|
126
|
+
"x-api-key": self.api_key or "",
|
|
127
|
+
"anthropic-version": "2023-06-01",
|
|
128
|
+
},
|
|
129
|
+
method="POST",
|
|
130
|
+
)
|
|
131
|
+
data = self._post(req)
|
|
132
|
+
# Parse content blocks
|
|
133
|
+
text_parts = []
|
|
134
|
+
tool_calls = []
|
|
135
|
+
for block in data.get("content", []):
|
|
136
|
+
if block.get("type") == "text":
|
|
137
|
+
text_parts.append(block.get("text", ""))
|
|
138
|
+
elif block.get("type") == "tool_use":
|
|
139
|
+
tool_calls.append({
|
|
140
|
+
"name": block.get("name", ""),
|
|
141
|
+
"arguments": block.get("input", {}),
|
|
142
|
+
})
|
|
143
|
+
stop = data.get("stop_reason", "")
|
|
144
|
+
return {
|
|
145
|
+
"text": "".join(text_parts),
|
|
146
|
+
"tool_calls": tool_calls if stop == "tool_use" else [],
|
|
147
|
+
"raw": json.dumps(data.get("content", []), default=str)[:4000],
|
|
148
|
+
"stop_reason": stop,
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
def _stub_generate(self, prompt: str, n: int = 3, **kwargs: Any) -> str:
|
|
152
|
+
h = hashlib.sha256(("anthropic:" + prompt).encode()).hexdigest()
|
|
153
|
+
proposals = [
|
|
154
|
+
{"smiles": f"N{'C' * (1 + int(h[i:i + 2], 16) % 6)}O", "seed": h[i:i + 8]}
|
|
155
|
+
for i in range(0, 2 * n, 2)
|
|
156
|
+
]
|
|
157
|
+
return json.dumps(proposals)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""AssayLoop bridge — their policy, our loop.
|
|
2
|
+
|
|
3
|
+
Genentech's AssayLoop (MIT) contributes trained acquisition policies for
|
|
4
|
+
screen-style problems (AssayFormer: LLM warm start -> amortized ranker over
|
|
5
|
+
gene libraries). Proef contributes the execution and trust layer: gates,
|
|
6
|
+
instruments, provenance, evals. This adapter plugs an assaybench-style
|
|
7
|
+
policy into a Proef campaign without either repo depending on the other.
|
|
8
|
+
|
|
9
|
+
The policy contract (duck-typed, mirrors assaybench.Model):
|
|
10
|
+
predict(observations, candidates, task_context=None) -> obj.scores: dict
|
|
11
|
+
|
|
12
|
+
observations: iterable of records with .candidate and .label
|
|
13
|
+
(label: {"hit": bool, "relevance_score": float})
|
|
14
|
+
|
|
15
|
+
Use `policy=` with any local object satisfying that contract (tests, your own
|
|
16
|
+
model). With no policy, attempts to load Genentech's released checkpoint —
|
|
17
|
+
requires `pip install assayloop torch huggingface-hub`.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _Obs:
|
|
25
|
+
__slots__ = ("candidate", "label")
|
|
26
|
+
|
|
27
|
+
def __init__(self, candidate: str, label: dict):
|
|
28
|
+
self.candidate = candidate
|
|
29
|
+
self.label = label
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AssayLoopRanker:
|
|
33
|
+
name = "assayloop-ranker"
|
|
34
|
+
|
|
35
|
+
def __init__(self, policy: Any | None = None, checkpoint: str | None = None):
|
|
36
|
+
if policy is None:
|
|
37
|
+
policy = self._load_released(checkpoint)
|
|
38
|
+
self.policy = policy
|
|
39
|
+
|
|
40
|
+
@staticmethod
|
|
41
|
+
def _load_released(checkpoint: str | None):
|
|
42
|
+
try:
|
|
43
|
+
from huggingface_hub import snapshot_download
|
|
44
|
+
from assayloop.models.amortized_ranker import AmortizedRankerModel
|
|
45
|
+
except ImportError as exc:
|
|
46
|
+
raise ImportError(
|
|
47
|
+
"no policy given and assayloop is not installed: "
|
|
48
|
+
"pass policy=<assaybench-style Model> or "
|
|
49
|
+
"pip install assayloop torch huggingface-hub") from exc
|
|
50
|
+
ckpt = checkpoint or snapshot_download("Genentech/assayformer")
|
|
51
|
+
return AmortizedRankerModel(checkpoint=ckpt, ckpt_file="model_last.pt")
|
|
52
|
+
|
|
53
|
+
def rank(self, candidates: list[str],
|
|
54
|
+
observations: list[dict] | None = None) -> list[tuple[str, float]]:
|
|
55
|
+
"""observations: [{candidate, hit, relevance_score}, ...]"""
|
|
56
|
+
obs = [_Obs(o["candidate"],
|
|
57
|
+
{"hit": bool(o.get("hit", False)),
|
|
58
|
+
"relevance_score": float(o.get("relevance_score", 0.0))})
|
|
59
|
+
for o in (observations or [])]
|
|
60
|
+
pred = self.policy.predict(obs, list(candidates))
|
|
61
|
+
scores = getattr(pred, "scores", pred)
|
|
62
|
+
return sorted(((c, float(scores.get(c, 0.0))) for c in candidates),
|
|
63
|
+
key=lambda t: -t[1])
|
|
64
|
+
|
|
65
|
+
def pick_batch(self, candidates: list[str], observations: list[dict] | None,
|
|
66
|
+
n: int) -> list[str]:
|
|
67
|
+
return [c for c, _ in self.rank(candidates, observations)[:n]]
|