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/core/hypothesis.py
ADDED
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
"""First-class hypotheses (P5: proposed → tested → validated/invalidated).
|
|
2
|
+
|
|
3
|
+
A hypothesis is a falsifiable prediction tied to a candidate and an assay.
|
|
4
|
+
Its lifecycle is fully provenance-recorded: proposal, test run, and verdict
|
|
5
|
+
(with evidence) are separate immutable records, so the scientific trail is
|
|
6
|
+
auditable end to end.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import logging
|
|
12
|
+
import uuid
|
|
13
|
+
from typing import Any, Callable
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel, Field
|
|
16
|
+
|
|
17
|
+
from proef.core.contracts import (
|
|
18
|
+
Actor,
|
|
19
|
+
Artifact,
|
|
20
|
+
ArtifactKind,
|
|
21
|
+
AssayResult,
|
|
22
|
+
Envelope,
|
|
23
|
+
EventType,
|
|
24
|
+
ProtocolSubmission,
|
|
25
|
+
ProvenanceRecord,
|
|
26
|
+
)
|
|
27
|
+
from proef.core.interfaces import ProvenanceStore, record_for
|
|
28
|
+
|
|
29
|
+
log = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"Constraint", "ExperimentDesign", "Hypothesis", "HypothesisTracker",
|
|
34
|
+
"PortfolioDecision", "ProblemStatement", "SuccessCriteria",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SuccessCriteria(BaseModel):
|
|
39
|
+
"""Declared BEFORE the experiment runs (pre-registration semantics)."""
|
|
40
|
+
metric: str # e.g. "ic50_um", "percent_inhibition"
|
|
41
|
+
direction: str = "min" # "min" | "max" (which direction is good)
|
|
42
|
+
threshold: float # success boundary on the metric
|
|
43
|
+
min_replicates: int = 1 # minimum evidence required to conclude
|
|
44
|
+
inconclusive_if_qc_failed: bool = True # bad QC -> inconclusive, not invalidated
|
|
45
|
+
proxy_of: str | None = None # the claim this metric proxies (Goodhart
|
|
46
|
+
# guard); empty follows the default ladder
|
|
47
|
+
|
|
48
|
+
def evidence(self) -> dict:
|
|
49
|
+
"""Proxy-chain distance from this metric to the clinical claim."""
|
|
50
|
+
from proef.proxy import distance
|
|
51
|
+
return distance(self.metric, self.proxy_of)
|
|
52
|
+
|
|
53
|
+
def evidence_line(self) -> str:
|
|
54
|
+
from proef.proxy import evidence_line
|
|
55
|
+
return evidence_line(self.metric, self.proxy_of)
|
|
56
|
+
|
|
57
|
+
def met(self, value: float) -> bool:
|
|
58
|
+
return value <= self.threshold if self.direction == "min" else value >= self.threshold
|
|
59
|
+
|
|
60
|
+
def classify(self, value: float,
|
|
61
|
+
ci: tuple[float | None, float | None] | None = None,
|
|
62
|
+
extrapolation: bool = False) -> str:
|
|
63
|
+
"""Point estimate decides; the CI can VETO certainty.
|
|
64
|
+
|
|
65
|
+
If the 95% interval straddles the threshold, the honest verdict is
|
|
66
|
+
'inconclusive' — not a coin-flip dressed as a result.
|
|
67
|
+
|
|
68
|
+
`extrapolation` (applicability domain, proef.ad): a value that
|
|
69
|
+
came from a model OUTSIDE its training chemistry cannot earn a
|
|
70
|
+
claim-grade verdict in EITHER direction — both arrows widen to
|
|
71
|
+
abstention. Local models do not get to make confident negatives
|
|
72
|
+
either; 'not active' from beyond the domain is as unfounded as
|
|
73
|
+
'active'.
|
|
74
|
+
"""
|
|
75
|
+
if extrapolation:
|
|
76
|
+
return "inconclusive"
|
|
77
|
+
if ci is None or ci[0] is None or ci[1] is None:
|
|
78
|
+
return "validated" if self.met(value) else "invalidated"
|
|
79
|
+
lo, hi = ci
|
|
80
|
+
if self.direction == "min":
|
|
81
|
+
if hi <= self.threshold:
|
|
82
|
+
return "validated"
|
|
83
|
+
if lo > self.threshold:
|
|
84
|
+
return "invalidated"
|
|
85
|
+
else:
|
|
86
|
+
if lo >= self.threshold:
|
|
87
|
+
return "validated"
|
|
88
|
+
if hi < self.threshold:
|
|
89
|
+
return "invalidated"
|
|
90
|
+
return "inconclusive"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Constraint(BaseModel):
|
|
94
|
+
"""A hard or soft constraint on the solution space, declared with the problem."""
|
|
95
|
+
name: str
|
|
96
|
+
description: str = ""
|
|
97
|
+
kind: str = "hard" # "hard" | "soft" | "preference"
|
|
98
|
+
limit: float | None = None # numeric bound where applicable
|
|
99
|
+
unit: str | None = None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class ProblemStatement(BaseModel):
|
|
103
|
+
"""Stage 0: what are we trying to achieve, and within what constraints?
|
|
104
|
+
|
|
105
|
+
Everything downstream (hypotheses, experiments, verdicts) traces back here.
|
|
106
|
+
"""
|
|
107
|
+
problem_id: str = Field(default_factory=lambda: f"prob-{uuid.uuid4().hex[:8]}")
|
|
108
|
+
objective: str # the scientific question / goal
|
|
109
|
+
context: str = "" # background, prior evidence
|
|
110
|
+
constraints: list[Constraint] = Field(default_factory=list)
|
|
111
|
+
success_metric: str | None = None # what "solved" means
|
|
112
|
+
proposed_by: str = "scientist"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class PortfolioDecision(BaseModel):
|
|
116
|
+
"""Why a hypothesis made / did not make the cut."""
|
|
117
|
+
hypothesis_id: str
|
|
118
|
+
selected: bool
|
|
119
|
+
score: float = 0.0
|
|
120
|
+
reason: str = ""
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class ExperimentDefinitionRef(BaseModel):
|
|
124
|
+
"""Reference to the scientific experiment definition (see proef.experiment)."""
|
|
125
|
+
experiment_id: str
|
|
126
|
+
scientific_question: str
|
|
127
|
+
claim_type: str
|
|
128
|
+
summary: str = ""
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class ExperimentDesign(BaseModel):
|
|
132
|
+
"""The experiment that will test the hypothesis — specified up-front."""
|
|
133
|
+
assay_type: str
|
|
134
|
+
concentrations: list[str] = Field(default_factory=list)
|
|
135
|
+
replicates: int = 1
|
|
136
|
+
controls: list[str] = Field(default_factory=list)
|
|
137
|
+
design_notes: str = ""
|
|
138
|
+
protocol_id: str | None = None # filled when the protocol is submitted
|
|
139
|
+
run_id: str | None = None
|
|
140
|
+
definition: ExperimentDefinitionRef | None = None # scientific manifest
|
|
141
|
+
readiness_verdict: str | None = None # ready / ready_with_warnings / blocked
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class Hypothesis(BaseModel):
|
|
145
|
+
hypothesis_id: str
|
|
146
|
+
branch_id: str
|
|
147
|
+
statement: str # falsifiable prediction
|
|
148
|
+
rationale: str = "" # why we believe it (prior evidence)
|
|
149
|
+
mechanism: str = "" # the CAUSAL story, not just correlation
|
|
150
|
+
predicted_observables: list[str] = Field(default_factory=list)
|
|
151
|
+
refutation_condition: str = "" # what observation KILLS this hypothesis
|
|
152
|
+
citation: str = "" # PMID/DOI grounding the rationale
|
|
153
|
+
citation_status: str = "unverified" # unverified|verified|invalid|check-failed
|
|
154
|
+
citation_detail: str = ""
|
|
155
|
+
candidate: str # molecule/sample id under test
|
|
156
|
+
assay_type: str = ""
|
|
157
|
+
predicted: str # human-readable prediction
|
|
158
|
+
predicted_value: float | None = None
|
|
159
|
+
round: int = 1
|
|
160
|
+
status: str = "proposed" # proposed | designed | tested | validated | invalidated | inconclusive
|
|
161
|
+
criteria: SuccessCriteria | None = None
|
|
162
|
+
design: ExperimentDesign | None = None
|
|
163
|
+
observed_value: float | None = None
|
|
164
|
+
observed_ci: tuple[float | None, float | None] | None = None
|
|
165
|
+
qc_passed: bool | None = None
|
|
166
|
+
evidence_run_id: str | None = None
|
|
167
|
+
problem_id: str | None = None # root problem this hypothesis addresses
|
|
168
|
+
portfolio_rank: int | None = None # order in the proposed portfolio
|
|
169
|
+
family: str | None = None # mechanistic family (same claim, many variants)
|
|
170
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def explanatory_bonus(h: "Hypothesis") -> float:
|
|
174
|
+
"""Explanatory power is worth a portfolio edge: a hypothesis that says
|
|
175
|
+
WHY (mechanism), HOW IT COULD DIE (refutation condition), and WHERE IT
|
|
176
|
+
COMES FROM (a VERIFIED citation) is more testable science than a bare
|
|
177
|
+
prediction. Capped at 0.2 so it breaks ties, never overrides real
|
|
178
|
+
scores. An INVALID citation is penalized below a bare hypothesis —
|
|
179
|
+
fabricated grounding is worse than none ("never invent" enforced)."""
|
|
180
|
+
bonus = 0.0
|
|
181
|
+
if h.mechanism:
|
|
182
|
+
bonus += 0.10
|
|
183
|
+
if h.refutation_condition:
|
|
184
|
+
bonus += 0.05
|
|
185
|
+
if h.citation_status == "verified":
|
|
186
|
+
bonus += 0.05
|
|
187
|
+
elif h.citation_status == "invalid":
|
|
188
|
+
bonus -= 0.10
|
|
189
|
+
return max(-0.1, min(bonus, 0.2))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class HypothesisTracker:
|
|
193
|
+
"""Records the full hypothesis lifecycle into the provenance store.
|
|
194
|
+
|
|
195
|
+
Stage 0: define_problem -> propose_portfolio -> select_portfolio
|
|
196
|
+
Then each selected hypothesis enters the flow: propose/designed -> tested
|
|
197
|
+
-> validated | invalidated | inconclusive.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
def __init__(self, store: ProvenanceStore, actor: Actor,
|
|
201
|
+
on_verdict: Callable[[Any], None] | None = None):
|
|
202
|
+
self.store = store
|
|
203
|
+
self.actor = actor
|
|
204
|
+
self.hypotheses: dict[str, Hypothesis] = {}
|
|
205
|
+
self.on_verdict = on_verdict # flywheel hook (best-effort)
|
|
206
|
+
|
|
207
|
+
@classmethod
|
|
208
|
+
def resume(cls, store: ProvenanceStore, actor: Actor, branch_id: str,
|
|
209
|
+
on_verdict: Callable[[Any], None] | None = None
|
|
210
|
+
) -> "HypothesisTracker":
|
|
211
|
+
"""Rebuild a campaign's hypotheses from its ledger branch so new
|
|
212
|
+
evidence can be judged by the SAME verdict code a live run uses.
|
|
213
|
+
|
|
214
|
+
Each proposal restores its pre-registered criteria; later verdict
|
|
215
|
+
records restore status/observed value, so a hypothesis that was
|
|
216
|
+
already judged is never silently re-judged (it stays non-open)."""
|
|
217
|
+
t = cls(store, actor, on_verdict=on_verdict)
|
|
218
|
+
verdict_events = {"hypothesis_validated", "hypothesis_invalidated",
|
|
219
|
+
"hypothesis_inconclusive"}
|
|
220
|
+
for r in store.branch_records(branch_id):
|
|
221
|
+
ev, d = r.event_type.value, r.decision or {}
|
|
222
|
+
hid = r.artifact.artifact_id if r.artifact else None
|
|
223
|
+
if ev == "hypothesis_proposed" and hid and d.get("criteria"):
|
|
224
|
+
meta = r.artifact.metadata or {}
|
|
225
|
+
h = Hypothesis(
|
|
226
|
+
hypothesis_id=hid, branch_id=branch_id,
|
|
227
|
+
statement=d.get("statement", ""), mechanism=d.get("mechanism", ""),
|
|
228
|
+
refutation_condition=d.get("refutation_condition", ""),
|
|
229
|
+
candidate=str(meta.get("candidate") or d.get("candidate") or ""),
|
|
230
|
+
assay_type=str(meta.get("assay") or ""),
|
|
231
|
+
predicted=d.get("predicted", ""),
|
|
232
|
+
criteria=SuccessCriteria(**d["criteria"]),
|
|
233
|
+
problem_id=branch_id.split("/", 1)[-1],
|
|
234
|
+
family=d.get("family") or None,
|
|
235
|
+
metadata={"criteria_source": d.get("criteria_source", "explicit")})
|
|
236
|
+
t.hypotheses[hid] = h
|
|
237
|
+
elif ev == "gate_decision" and d.get("kind") == "criteria_assigned" and d.get("hypothesis_id") in t.hypotheses:
|
|
238
|
+
h = t.hypotheses[d["hypothesis_id"]] # recency wins: the gate replaces what the proposal carried
|
|
239
|
+
h.criteria = SuccessCriteria(**d["criteria"])
|
|
240
|
+
h.metadata = {**(h.metadata or {}), "criteria_source": d.get("source", "gate")}
|
|
241
|
+
elif ev in verdict_events and hid in t.hypotheses:
|
|
242
|
+
h = t.hypotheses[hid]
|
|
243
|
+
h.status = d.get("verdict") or h.status
|
|
244
|
+
h.observed_value = d.get("observed")
|
|
245
|
+
ci = d.get("observed_ci")
|
|
246
|
+
h.observed_ci = tuple(ci) if ci else None
|
|
247
|
+
h.evidence_run_id = d.get("evidence_run_id")
|
|
248
|
+
return t
|
|
249
|
+
|
|
250
|
+
def define_experiment(
|
|
251
|
+
self,
|
|
252
|
+
problem: ProblemStatement,
|
|
253
|
+
definition: Any,
|
|
254
|
+
review: Any = None,
|
|
255
|
+
) -> Any:
|
|
256
|
+
"""Register a scientific ExperimentDefinition (proef.experiment)
|
|
257
|
+
with its readiness review before any protocol is submitted.
|
|
258
|
+
`definition` is an ExperimentDefinition; `review` is the readiness
|
|
259
|
+
review result if already computed."""
|
|
260
|
+
branch = f"problem/{problem.problem_id}"
|
|
261
|
+
env = Envelope(experiment_branch_id=branch)
|
|
262
|
+
verdict = review.verdict.value if review is not None else None
|
|
263
|
+
self.store.append(self._record(
|
|
264
|
+
env, EventType.experiment_defined, self.actor,
|
|
265
|
+
decision={
|
|
266
|
+
"experiment_id": definition.experiment_id,
|
|
267
|
+
"scientific_question": definition.scientific_question,
|
|
268
|
+
"claim_type": definition.claim_type.value,
|
|
269
|
+
"target": definition.intervention.target,
|
|
270
|
+
"verdict": verdict,
|
|
271
|
+
}))
|
|
272
|
+
self.store.append(record_for(
|
|
273
|
+
env, EventType.experiment_readiness_reviewed, self.actor,
|
|
274
|
+
decision={
|
|
275
|
+
"experiment_id": definition.experiment_id,
|
|
276
|
+
"verdict": verdict,
|
|
277
|
+
"warnings": [f.message for f in review.warnings] if review else [],
|
|
278
|
+
"blockers": [b.message for b in review.blockers] if review else [],
|
|
279
|
+
}))
|
|
280
|
+
return definition
|
|
281
|
+
|
|
282
|
+
# ------------------------------------------- stage 0: problem & portfolio
|
|
283
|
+
|
|
284
|
+
def define_problem(self, problem: ProblemStatement,
|
|
285
|
+
environment: dict | None = None) -> ProblemStatement:
|
|
286
|
+
"""Record the problem + constraints + execution environment.
|
|
287
|
+
The environment block (lab adapter name/version/seed, concentrations,
|
|
288
|
+
autonomy) is what makes `proef campaign reproduce` possible — without it recorded,
|
|
289
|
+
reproducibility would be a claim, not a command."""
|
|
290
|
+
self.store.append(self._record(
|
|
291
|
+
Envelope(experiment_branch_id=f"problem/{problem.problem_id}"),
|
|
292
|
+
EventType.problem_defined, None,
|
|
293
|
+
decision={
|
|
294
|
+
"problem_id": problem.problem_id,
|
|
295
|
+
"objective": problem.objective,
|
|
296
|
+
"constraints": [c.model_dump() for c in problem.constraints],
|
|
297
|
+
"success_metric": problem.success_metric,
|
|
298
|
+
"environment": environment or {},
|
|
299
|
+
},
|
|
300
|
+
))
|
|
301
|
+
return problem
|
|
302
|
+
|
|
303
|
+
def propose_portfolio(
|
|
304
|
+
self,
|
|
305
|
+
problem: ProblemStatement,
|
|
306
|
+
hypotheses: list[dict[str, Any]],
|
|
307
|
+
) -> list[Hypothesis]:
|
|
308
|
+
"""Register a batch of candidate hypotheses addressing the problem.
|
|
309
|
+
Each dict: statement, candidate, assay_type, predicted, rationale,
|
|
310
|
+
predicted_value, optional criteria/design. All recorded; selection next."""
|
|
311
|
+
proposed: list[Hypothesis] = []
|
|
312
|
+
for i, spec in enumerate(hypotheses, start=1):
|
|
313
|
+
h = self.propose(
|
|
314
|
+
branch_id=f"problem/{problem.problem_id}",
|
|
315
|
+
statement=spec["statement"],
|
|
316
|
+
candidate=spec["candidate"],
|
|
317
|
+
assay_type=spec.get("assay_type", "binding"),
|
|
318
|
+
predicted=spec.get("predicted", spec["statement"]),
|
|
319
|
+
predicted_value=spec.get("predicted_value"),
|
|
320
|
+
rationale=spec.get("rationale", ""),
|
|
321
|
+
mechanism=spec.get("mechanism", ""),
|
|
322
|
+
refutation_condition=spec.get("refutation_condition", ""),
|
|
323
|
+
predicted_observables=spec.get("predicted_observables"),
|
|
324
|
+
citation=spec.get("citation", ""),
|
|
325
|
+
citation_status=spec.get("citation_status", "unverified"),
|
|
326
|
+
citation_detail=spec.get("citation_detail", ""),
|
|
327
|
+
round_no=0,
|
|
328
|
+
criteria=spec.get("criteria"),
|
|
329
|
+
design=spec.get("design"),
|
|
330
|
+
# structure keys must ride IN the recorded decision — the
|
|
331
|
+
# chain is hash-immutable, patching h.metadata afterwards
|
|
332
|
+
# would leave the provenance record chemotype-blind
|
|
333
|
+
**({"smiles": spec["smiles"]} if spec.get("smiles") else {}),
|
|
334
|
+
**({"family": spec["family"]} if spec.get("family") else {}),
|
|
335
|
+
**({"predicted_by": spec["predicted_by"]}
|
|
336
|
+
if spec.get("predicted_by") else {}),
|
|
337
|
+
**{k: v for k, v in (spec.get("metadata") or {}).items()
|
|
338
|
+
if k not in ("smiles", "family")},
|
|
339
|
+
)
|
|
340
|
+
h.problem_id = problem.problem_id
|
|
341
|
+
h.portfolio_rank = i
|
|
342
|
+
h.family = spec.get("family")
|
|
343
|
+
if spec.get("smiles"):
|
|
344
|
+
h.metadata["smiles"] = spec["smiles"]
|
|
345
|
+
for key in ("modality", "sequence", "description",
|
|
346
|
+
"source_candidate"):
|
|
347
|
+
if (spec.get("metadata") or {}).get(key):
|
|
348
|
+
h.metadata[key] = spec["metadata"][key]
|
|
349
|
+
h.branch_id = f"problem/{problem.problem_id}"
|
|
350
|
+
self.hypotheses[h.hypothesis_id] = h
|
|
351
|
+
proposed.append(h)
|
|
352
|
+
return proposed
|
|
353
|
+
|
|
354
|
+
def propose_families(
|
|
355
|
+
self,
|
|
356
|
+
problem: ProblemStatement,
|
|
357
|
+
families: list[dict[str, Any]],
|
|
358
|
+
) -> list[Hypothesis]:
|
|
359
|
+
"""Register mechanistically DISTINCT hypothesis families, each with
|
|
360
|
+
variant hypotheses (same claim, different parameterizations — e.g.
|
|
361
|
+
analogs of one warhead). Each family dict:
|
|
362
|
+
{family, parent_statement, kind, rationale,
|
|
363
|
+
variants: [variant-spec dicts as in propose_portfolio]}
|
|
364
|
+
Returns flat variant list, each tagged with its family; the family
|
|
365
|
+
parent claim itself is provenance-recorded."""
|
|
366
|
+
all_variants: list[Hypothesis] = []
|
|
367
|
+
for fam in families:
|
|
368
|
+
fid = fam.get("family") or (
|
|
369
|
+
"fam-" + hashlib.sha1(
|
|
370
|
+
fam["parent_statement"].encode()).hexdigest()[:8])
|
|
371
|
+
self.store.append(self._record(
|
|
372
|
+
Envelope(experiment_branch_id=f"problem/{problem.problem_id}"),
|
|
373
|
+
EventType.hypothesis_proposed, None,
|
|
374
|
+
decision={
|
|
375
|
+
"family_id": fid,
|
|
376
|
+
"parent_statement": fam["parent_statement"],
|
|
377
|
+
"kind": fam.get("kind", "mechanistic"),
|
|
378
|
+
"retain_fold": fam.get("retain_fold", 3.2),
|
|
379
|
+
"rationale": fam.get("rationale", ""),
|
|
380
|
+
"n_variants": len(fam.get("variants", [])),
|
|
381
|
+
}))
|
|
382
|
+
for spec in fam.get("variants", []):
|
|
383
|
+
spec = dict(spec)
|
|
384
|
+
spec.setdefault("rationale", fam.get("rationale", ""))
|
|
385
|
+
for k in ("mechanism", "refutation_condition", "citation"):
|
|
386
|
+
spec.setdefault(k, fam.get(k, ""))
|
|
387
|
+
h = self.propose(
|
|
388
|
+
branch_id=f"problem/{problem.problem_id}",
|
|
389
|
+
statement=spec["statement"],
|
|
390
|
+
candidate=spec["candidate"],
|
|
391
|
+
assay_type=spec.get("assay_type", "binding"),
|
|
392
|
+
predicted=spec.get("predicted", spec["statement"]),
|
|
393
|
+
predicted_value=spec.get("predicted_value"),
|
|
394
|
+
rationale=spec.get("rationale", ""),
|
|
395
|
+
mechanism=spec.get("mechanism", ""),
|
|
396
|
+
refutation_condition=spec.get("refutation_condition", ""),
|
|
397
|
+
predicted_observables=spec.get("predicted_observables"),
|
|
398
|
+
citation=spec.get("citation", ""),
|
|
399
|
+
citation_status=spec.get("citation_status", "unverified"),
|
|
400
|
+
citation_detail=spec.get("citation_detail", ""),
|
|
401
|
+
round_no=0,
|
|
402
|
+
criteria=spec.get("criteria"),
|
|
403
|
+
design=spec.get("design"),
|
|
404
|
+
# family tag + structure key ride IN the recorded decision:
|
|
405
|
+
# series claims derive their verdicts FROM the chain
|
|
406
|
+
family=fid,
|
|
407
|
+
**({"predicted_by": spec["predicted_by"]}
|
|
408
|
+
if spec.get("predicted_by") else {}),
|
|
409
|
+
**({"smiles": spec["smiles"]} if spec.get("smiles") else {}),
|
|
410
|
+
**{k: v for k, v in (spec.get("metadata") or {}).items()
|
|
411
|
+
if k not in ("smiles", "family")},
|
|
412
|
+
)
|
|
413
|
+
h.problem_id = problem.problem_id
|
|
414
|
+
h.family = fid
|
|
415
|
+
self.hypotheses[h.hypothesis_id] = h
|
|
416
|
+
all_variants.append(h)
|
|
417
|
+
return all_variants
|
|
418
|
+
|
|
419
|
+
def select_portfolio(self, problem: ProblemStatement,
|
|
420
|
+
proposed: list[Hypothesis],
|
|
421
|
+
score_fn: Callable[[Hypothesis], float],
|
|
422
|
+
k: int = 2,
|
|
423
|
+
max_per_family: int | None = None) -> list[Hypothesis]:
|
|
424
|
+
"""Analyze + filter the portfolio to the k hypotheses worth testing.
|
|
425
|
+
With max_per_family, selection enforces DIVERSITY: at most N variants
|
|
426
|
+
of the same mechanistic family are taken (a sweep of one idea cannot
|
|
427
|
+
crowd out different ideas). Every accept/reject decision is
|
|
428
|
+
provenance-recorded with its reason."""
|
|
429
|
+
def _total(h: Hypothesis) -> float:
|
|
430
|
+
return score_fn(h) + explanatory_bonus(h)
|
|
431
|
+
scored = sorted(proposed, key=_total, reverse=True)
|
|
432
|
+
selected, decisions = [], []
|
|
433
|
+
family_counts: dict[str, int] = {}
|
|
434
|
+
for h in scored:
|
|
435
|
+
sel = len(selected) < k
|
|
436
|
+
reason = "top-k by score"
|
|
437
|
+
if sel and max_per_family is not None and h.family:
|
|
438
|
+
if family_counts.get(h.family, 0) >= max_per_family:
|
|
439
|
+
sel = False
|
|
440
|
+
reason = (f"family '{h.family}' already has "
|
|
441
|
+
f"{max_per_family} selected (diversity cap)")
|
|
442
|
+
if sel:
|
|
443
|
+
selected.append(h)
|
|
444
|
+
if h.family:
|
|
445
|
+
family_counts[h.family] = family_counts.get(h.family, 0) + 1
|
|
446
|
+
bonus = explanatory_bonus(h)
|
|
447
|
+
decisions.append(PortfolioDecision(
|
|
448
|
+
hypothesis_id=h.hypothesis_id, selected=sel,
|
|
449
|
+
score=round(score_fn(h) + bonus, 4),
|
|
450
|
+
reason=(reason + (f" (+{bonus:.2f} explanatory power)"
|
|
451
|
+
if bonus else ""))))
|
|
452
|
+
self.store.append(self._record(
|
|
453
|
+
Envelope(experiment_branch_id=f"problem/{problem.problem_id}"),
|
|
454
|
+
EventType.hypotheses_filtered, None,
|
|
455
|
+
decision={
|
|
456
|
+
"problem_id": problem.problem_id,
|
|
457
|
+
"k": k,
|
|
458
|
+
"decisions": [d.model_dump() for d in decisions],
|
|
459
|
+
},
|
|
460
|
+
))
|
|
461
|
+
return selected
|
|
462
|
+
|
|
463
|
+
def propose(self, statement: str, candidate: str, assay_type: str,
|
|
464
|
+
predicted: str, predicted_value: float | None = None,
|
|
465
|
+
rationale: str = "", round_no: int = 1,
|
|
466
|
+
mechanism: str = "", refutation_condition: str = "",
|
|
467
|
+
predicted_observables: list[str] | None = None,
|
|
468
|
+
citation: str = "", citation_status: str = "unverified",
|
|
469
|
+
citation_detail: str = "",
|
|
470
|
+
criteria: SuccessCriteria | None = None,
|
|
471
|
+
design: ExperimentDesign | None = None,
|
|
472
|
+
branch_id: str | None = None, **meta: Any) -> Hypothesis:
|
|
473
|
+
env = Envelope(experiment_branch_id=branch_id or f"hyp/{round_no}")
|
|
474
|
+
criteria_source = "explicit"
|
|
475
|
+
if criteria is None:
|
|
476
|
+
# derive explicit criteria from the point prediction (min-direction:
|
|
477
|
+
# IC50-style assays). Callers should override for max-direction. The record says where the
|
|
478
|
+
# criterion came from. With no gate and no prediction it is a PLACEHOLDER: the program's gate is expected
|
|
479
|
+
# to replace it before any data, and a verdict on a placeholder abstains, never judges against 0.0.
|
|
480
|
+
criteria_source = "prediction" if predicted_value is not None else "placeholder"
|
|
481
|
+
criteria = SuccessCriteria(metric="ic50_um", direction="min",
|
|
482
|
+
threshold=predicted_value if predicted_value is not None else 0.0)
|
|
483
|
+
if design is None:
|
|
484
|
+
design = ExperimentDesign(assay_type=assay_type)
|
|
485
|
+
h = Hypothesis(
|
|
486
|
+
hypothesis_id="hyp-" + hashlib.sha1(
|
|
487
|
+
f"{statement}\x00{candidate}\x00{round_no}".encode()
|
|
488
|
+
).hexdigest()[:8],
|
|
489
|
+
branch_id=env.experiment_branch_id,
|
|
490
|
+
statement=statement,
|
|
491
|
+
rationale=rationale,
|
|
492
|
+
mechanism=mechanism,
|
|
493
|
+
refutation_condition=refutation_condition,
|
|
494
|
+
predicted_observables=predicted_observables or [],
|
|
495
|
+
citation=citation,
|
|
496
|
+
citation_status=citation_status,
|
|
497
|
+
citation_detail=citation_detail,
|
|
498
|
+
candidate=candidate,
|
|
499
|
+
assay_type=assay_type,
|
|
500
|
+
predicted=predicted,
|
|
501
|
+
predicted_value=predicted_value,
|
|
502
|
+
round=round_no,
|
|
503
|
+
criteria=criteria,
|
|
504
|
+
design=design,
|
|
505
|
+
metadata={**meta, "criteria_source": criteria_source},
|
|
506
|
+
)
|
|
507
|
+
self.hypotheses[h.hypothesis_id] = h
|
|
508
|
+
self.store.append(self._record(env, EventType.hypothesis_proposed, h,
|
|
509
|
+
decision={"statement": statement,
|
|
510
|
+
"predicted": predicted,
|
|
511
|
+
"criteria": h.criteria.model_dump(),
|
|
512
|
+
"criteria_source": criteria_source,
|
|
513
|
+
"lab_check": (h.metadata or {}).get("lab_check"),
|
|
514
|
+
"predictions": (h.metadata or {}).get("predictions"),
|
|
515
|
+
"followup_of": (h.metadata or {}).get("followup_of"),
|
|
516
|
+
"replicates": (h.metadata or {}).get("replicates"),
|
|
517
|
+
"design": h.design.model_dump(),
|
|
518
|
+
"rationale": rationale,
|
|
519
|
+
"mechanism": mechanism,
|
|
520
|
+
"refutation_condition":
|
|
521
|
+
refutation_condition,
|
|
522
|
+
"citation": citation,
|
|
523
|
+
"citation_status":
|
|
524
|
+
citation_status,
|
|
525
|
+
"predicted_by":
|
|
526
|
+
(h.metadata or {}).get(
|
|
527
|
+
"predicted_by"),
|
|
528
|
+
"smiles":
|
|
529
|
+
(h.metadata or {}).get(
|
|
530
|
+
"smiles", ""),
|
|
531
|
+
"family":
|
|
532
|
+
h.family or
|
|
533
|
+
(h.metadata or {}).get(
|
|
534
|
+
"family", ""),
|
|
535
|
+
"citation_detail":
|
|
536
|
+
citation_detail,
|
|
537
|
+
"predicted_observables":
|
|
538
|
+
h.predicted_observables}))
|
|
539
|
+
return h
|
|
540
|
+
|
|
541
|
+
def specify_design(self, h: Hypothesis, design: ExperimentDesign) -> Hypothesis:
|
|
542
|
+
"""Declare the experiment design before running it (designed state)."""
|
|
543
|
+
h.design = design
|
|
544
|
+
h.status = "designed"
|
|
545
|
+
self.hypotheses[h.hypothesis_id] = h
|
|
546
|
+
self.store.append(self._record(
|
|
547
|
+
Envelope(experiment_branch_id=h.branch_id), EventType.stage_transition,
|
|
548
|
+
self.actor, # design event; keeps stage_transition for workflow linkage
|
|
549
|
+
artifact=self._artifact(h),
|
|
550
|
+
decision={"designed_for": h.hypothesis_id, "design": design.model_dump()},
|
|
551
|
+
))
|
|
552
|
+
return h
|
|
553
|
+
|
|
554
|
+
def attach_test(self, h: Hypothesis, protocol: ProtocolSubmission, run_id: str) -> None:
|
|
555
|
+
h.design = h.design or ExperimentDesign(assay_type=protocol.assay_type.value)
|
|
556
|
+
h.design.protocol_id = protocol.protocol_id
|
|
557
|
+
h.design.run_id = run_id
|
|
558
|
+
h.status = "tested" if h.status in ("proposed", "designed") else h.status
|
|
559
|
+
self.hypotheses[h.hypothesis_id] = h
|
|
560
|
+
env = Envelope(experiment_branch_id=h.branch_id)
|
|
561
|
+
self.store.append(self._record(env, EventType.hypothesis_tested, h,
|
|
562
|
+
decision={"run_id": run_id,
|
|
563
|
+
"protocol_id": protocol.protocol_id,
|
|
564
|
+
"assay": getattr(
|
|
565
|
+
protocol.assay_type, "value",
|
|
566
|
+
str(protocol.assay_type))}))
|
|
567
|
+
|
|
568
|
+
def verdict(self, h: Hypothesis, result: AssayResult,
|
|
569
|
+
threshold: float | None = None) -> Hypothesis:
|
|
570
|
+
"""Assess against the pre-declared criteria. QC-failed or missing-evidence
|
|
571
|
+
runs yield 'inconclusive', never a silent invalidate."""
|
|
572
|
+
placeholder = (h.metadata or {}).get("criteria_source") == "placeholder"
|
|
573
|
+
preregistered = h.criteria is not None and not placeholder
|
|
574
|
+
if threshold is not None and h.criteria is None:
|
|
575
|
+
h.criteria = SuccessCriteria(metric="ic50_um", threshold=threshold)
|
|
576
|
+
criteria = h.criteria or SuccessCriteria(metric="value", threshold=threshold or 0.0)
|
|
577
|
+
qc_ok = getattr(result.qc, "controls_passed", True)
|
|
578
|
+
rows = [m for m in result.measurements if m.sample_id == h.candidate]
|
|
579
|
+
src = next((m for m in rows
|
|
580
|
+
if criteria.metric == "value"
|
|
581
|
+
or criteria.metric in m.derived_metrics
|
|
582
|
+
or m.unit == criteria.metric), None)
|
|
583
|
+
if src is None and criteria.metric not in ("ic50_um", "value"):
|
|
584
|
+
# property metric: read the recorded value at the HIGHEST
|
|
585
|
+
# dose (dose ladders carry conc_um in derived metrics)
|
|
586
|
+
doses = [m for m in rows if isinstance(
|
|
587
|
+
m.derived_metrics.get("conc_um"), (int, float))]
|
|
588
|
+
src = (max(doses, key=lambda m: (m.derived_metrics["conc_um"],
|
|
589
|
+
m.value))
|
|
590
|
+
if doses else (rows[0] if rows else None))
|
|
591
|
+
value = src.value if src is not None else None
|
|
592
|
+
h.observed_value = value
|
|
593
|
+
h.qc_passed = qc_ok
|
|
594
|
+
h.evidence_run_id = result.run_id
|
|
595
|
+
# the CI must come from the SAME row as the value, under the metric's
|
|
596
|
+
# own keys ("<metric>_ci_low") with the legacy IC50 keys as fallback
|
|
597
|
+
ci = None
|
|
598
|
+
if src is not None:
|
|
599
|
+
dm = src.derived_metrics
|
|
600
|
+
stem = criteria.metric.removesuffix("_um")
|
|
601
|
+
for prefix in dict.fromkeys((criteria.metric, stem)):
|
|
602
|
+
low, high = dm.get(f"{prefix}_ci_low"), dm.get(f"{prefix}_ci_high")
|
|
603
|
+
if low is not None and high is not None:
|
|
604
|
+
ci = (low, high)
|
|
605
|
+
break
|
|
606
|
+
h.observed_ci = ci
|
|
607
|
+
if not qc_ok:
|
|
608
|
+
h.status = "inconclusive"
|
|
609
|
+
elif value is None:
|
|
610
|
+
h.status = "inconclusive" # no usable evidence (right-censored etc.)
|
|
611
|
+
elif placeholder:
|
|
612
|
+
h.status = "inconclusive" # nothing was registered to judge against: abstain, never refute against 0.0
|
|
613
|
+
else:
|
|
614
|
+
h.status = criteria.classify(value, ci)
|
|
615
|
+
event = {
|
|
616
|
+
"validated": EventType.hypothesis_validated,
|
|
617
|
+
"invalidated": EventType.hypothesis_invalidated,
|
|
618
|
+
"inconclusive": EventType.hypothesis_inconclusive,
|
|
619
|
+
}.get(h.status, EventType.hypothesis_tested)
|
|
620
|
+
env = Envelope(experiment_branch_id=h.branch_id)
|
|
621
|
+
from proef.derivation import build
|
|
622
|
+
meas = next((m for m in result.measurements
|
|
623
|
+
if m.sample_id == h.candidate), None)
|
|
624
|
+
inst = getattr(result, "instrument", None)
|
|
625
|
+
self.store.append(self._record(env, event, h, decision={
|
|
626
|
+
"metric": criteria.metric, "threshold": criteria.threshold,
|
|
627
|
+
"direction": criteria.direction,
|
|
628
|
+
"observed": value, "observed_ci": list(ci) if ci else None,
|
|
629
|
+
"qc_passed": qc_ok,
|
|
630
|
+
"evidence_run_id": result.run_id,
|
|
631
|
+
"verdict": h.status,
|
|
632
|
+
"criteria_preregistered": preregistered,
|
|
633
|
+
"evidence": criteria.evidence(),
|
|
634
|
+
"derivation": build(
|
|
635
|
+
instrument=(inst.adapter if inst else None),
|
|
636
|
+
version=(getattr(inst, "instrument_id", None)
|
|
637
|
+
if inst else None),
|
|
638
|
+
quantity=(meas.unit if meas else None),
|
|
639
|
+
counts=({"replicates": meas.replicate}
|
|
640
|
+
if meas and meas.replicate else None),
|
|
641
|
+
metric=criteria.metric,
|
|
642
|
+
method=("assay pipeline derived" if meas and
|
|
643
|
+
meas.derived_metrics else "reported value"),
|
|
644
|
+
criteria_metric=criteria.metric,
|
|
645
|
+
criteria_direction=criteria.direction,
|
|
646
|
+
criteria_threshold=criteria.threshold),
|
|
647
|
+
}))
|
|
648
|
+
self._fire_on_verdict(h)
|
|
649
|
+
return h
|
|
650
|
+
|
|
651
|
+
def _fire_on_verdict(self, h: Hypothesis) -> None:
|
|
652
|
+
"""The flywheel must never break a run — but a broken flywheel must
|
|
653
|
+
not be invisible either: log it (negative results stop compounding)."""
|
|
654
|
+
if self.on_verdict is None:
|
|
655
|
+
return
|
|
656
|
+
try:
|
|
657
|
+
self.on_verdict(h)
|
|
658
|
+
except Exception:
|
|
659
|
+
log.warning("on_verdict hook failed for hypothesis %s; "
|
|
660
|
+
"this verdict was NOT fed to the flywheel",
|
|
661
|
+
h.hypothesis_id, exc_info=True)
|
|
662
|
+
|
|
663
|
+
def _artifact(self, h: Hypothesis) -> Artifact:
|
|
664
|
+
return Artifact(
|
|
665
|
+
artifact_id=h.hypothesis_id,
|
|
666
|
+
kind=ArtifactKind.hypothesis,
|
|
667
|
+
uri=f"mem://{h.branch_id}/{h.hypothesis_id}",
|
|
668
|
+
metadata={"candidate": h.candidate, "assay": h.assay_type,
|
|
669
|
+
"statement": h.statement,
|
|
670
|
+
**({"mechanism": h.mechanism} if h.mechanism else {}),
|
|
671
|
+
**({"citation": h.citation,
|
|
672
|
+
"citation_status": h.citation_status}
|
|
673
|
+
if h.citation else {})},
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
def record_outcome(self, h: Hypothesis, extra: dict | None = None) -> Hypothesis:
|
|
677
|
+
"""Provenance-record a verdict already determined on `h` (e.g. by the
|
|
678
|
+
auto-analysis agent fitting a device export). Same event shape as
|
|
679
|
+
`verdict()` — observed, CI, threshold, qc, evidence run — so the pipeline
|
|
680
|
+
view and diary see agent-side and lab-side verdicts identically.
|
|
681
|
+
Event type follows the VERDICT, never the workflow: a confirmation that
|
|
682
|
+
refutes lands as hypothesis_invalidated, an abstention as
|
|
683
|
+
hypothesis_inconclusive. Nothing that decides is ever recorded as a
|
|
684
|
+
bare 'tested' — readers trust the payload, and so should the chain."""
|
|
685
|
+
event = {
|
|
686
|
+
"validated": EventType.hypothesis_validated,
|
|
687
|
+
"confirmed": EventType.hypothesis_validated,
|
|
688
|
+
"invalidated": EventType.hypothesis_invalidated,
|
|
689
|
+
"refuted": EventType.hypothesis_invalidated,
|
|
690
|
+
"inconclusive": EventType.hypothesis_inconclusive,
|
|
691
|
+
}.get(h.status, EventType.hypothesis_tested)
|
|
692
|
+
env = Envelope(experiment_branch_id=h.branch_id)
|
|
693
|
+
decision = {
|
|
694
|
+
"metric": h.criteria.metric if h.criteria else "value",
|
|
695
|
+
"direction": h.criteria.direction if h.criteria else "min",
|
|
696
|
+
"threshold": h.criteria.threshold if h.criteria else None,
|
|
697
|
+
"observed": h.observed_value,
|
|
698
|
+
"observed_ci": list(h.observed_ci) if h.observed_ci else None,
|
|
699
|
+
"qc_passed": h.qc_passed,
|
|
700
|
+
"evidence_run_id": h.evidence_run_id,
|
|
701
|
+
"verdict": h.status,
|
|
702
|
+
}
|
|
703
|
+
if extra:
|
|
704
|
+
decision.update(extra)
|
|
705
|
+
self.store.append(self._record(env, event, h, decision=decision))
|
|
706
|
+
self._fire_on_verdict(h)
|
|
707
|
+
return h
|
|
708
|
+
|
|
709
|
+
def _record(self, env: Envelope, event: EventType, h: Any,
|
|
710
|
+
decision: dict) -> ProvenanceRecord:
|
|
711
|
+
artifact = self._artifact(h) if isinstance(h, Hypothesis) else None
|
|
712
|
+
return record_for(env, event, self.actor, artifact=artifact, decision=decision)
|
|
713
|
+
|
|
714
|
+
def summary(self) -> dict[str, int]:
|
|
715
|
+
counts = {"proposed": len(self.hypotheses), "validated": 0,
|
|
716
|
+
"invalidated": 0, "inconclusive": 0}
|
|
717
|
+
for h in self.hypotheses.values():
|
|
718
|
+
if h.status in ("validated", "invalidated", "inconclusive"):
|
|
719
|
+
counts[h.status] += 1
|
|
720
|
+
return counts
|