proef 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. proef/__init__.py +25 -0
  2. proef/acquisition.py +244 -0
  3. proef/ad.py +159 -0
  4. proef/adapters/__init__.py +0 -0
  5. proef/adapters/admet.py +196 -0
  6. proef/adapters/bio/__init__.py +0 -0
  7. proef/adapters/bio/rdkit_ops.py +52 -0
  8. proef/adapters/bio/safety_rules.json +146 -0
  9. proef/adapters/bio/seq_alerts.py +79 -0
  10. proef/adapters/bio/structure_score.py +85 -0
  11. proef/adapters/bio/tox_alerts.py +99 -0
  12. proef/adapters/data/__init__.py +0 -0
  13. proef/adapters/data/admet.py +62 -0
  14. proef/adapters/data/chembl.py +110 -0
  15. proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
  16. proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
  17. proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
  18. proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
  19. proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
  20. proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
  21. proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
  22. proef/adapters/data/moleculenet.py +60 -0
  23. proef/adapters/databases/__init__.py +0 -0
  24. proef/adapters/databases/chembl_gates.py +121 -0
  25. proef/adapters/databases/chembl_lookup.py +35 -0
  26. proef/adapters/databases/open_targets.py +102 -0
  27. proef/adapters/databases/pubmed.py +94 -0
  28. proef/adapters/devices/__init__.py +0 -0
  29. proef/adapters/devices/ezo_ph.py +251 -0
  30. proef/adapters/devices/hcs_microscope.py +143 -0
  31. proef/adapters/devices/lcms.py +123 -0
  32. proef/adapters/devices/scheduler.py +84 -0
  33. proef/adapters/devices/sila2.py +134 -0
  34. proef/adapters/genomics/alphagenome.py +146 -0
  35. proef/adapters/lab/__init__.py +0 -0
  36. proef/adapters/lab/bioprocess.py +32 -0
  37. proef/adapters/lab/devices.py +170 -0
  38. proef/adapters/lab/imaging.py +226 -0
  39. proef/adapters/lab/mhs_driver.py +124 -0
  40. proef/adapters/lab/opentrons.py +222 -0
  41. proef/adapters/lab/ot2_sim.py +174 -0
  42. proef/adapters/lab/plate_reader_share.py +108 -0
  43. proef/adapters/lab/protein_design.py +199 -0
  44. proef/adapters/lab/recording.py +119 -0
  45. proef/adapters/lab/replay.py +107 -0
  46. proef/adapters/lab/simulator.py +282 -0
  47. proef/adapters/lab/synthesis.py +92 -0
  48. proef/adapters/models/__init__.py +0 -0
  49. proef/adapters/models/anthropic_provider.py +157 -0
  50. proef/adapters/models/assayloop_ranker.py +67 -0
  51. proef/adapters/models/from_env.py +93 -0
  52. proef/adapters/models/gp_policy.py +93 -0
  53. proef/adapters/models/gp_policy_gp.py +36 -0
  54. proef/adapters/models/llm_policy.py +187 -0
  55. proef/adapters/models/openai_compat.py +150 -0
  56. proef/adapters/models/sklearn_policy.py +65 -0
  57. proef/adapters/retrosynthesis.py +247 -0
  58. proef/adapters/sandbox/__init__.py +20 -0
  59. proef/adapters/sandbox/agentenv.py +145 -0
  60. proef/adapters/sandbox/docker.py +217 -0
  61. proef/adapters/sandbox/local.py +164 -0
  62. proef/adapters/sandbox/opensandbox.py +122 -0
  63. proef/adapters/store/__init__.py +0 -0
  64. proef/adapters/store/sqlite.py +207 -0
  65. proef/adaptive.py +108 -0
  66. proef/advisory.py +76 -0
  67. proef/analysis_profiles/__init__.py +8 -0
  68. proef/analysis_profiles/measurements.py +266 -0
  69. proef/analysis_profiles/plate_assay.py +316 -0
  70. proef/analysis_report.py +195 -0
  71. proef/analysis_store.py +183 -0
  72. proef/anchor.py +154 -0
  73. proef/api/app.py +107 -0
  74. proef/api/launch.py +170 -0
  75. proef/api/v1/__init__.py +29 -0
  76. proef/api/v1/analyses.py +367 -0
  77. proef/api/v1/campaigns.py +802 -0
  78. proef/api/v1/deps.py +10 -0
  79. proef/api/v1/evals.py +16 -0
  80. proef/api/v1/evidence.py +132 -0
  81. proef/api/v1/governance.py +35 -0
  82. proef/api/v1/inbox.py +119 -0
  83. proef/api/v1/lab.py +110 -0
  84. proef/api/v1/pauses.py +77 -0
  85. proef/api/v1/programs.py +397 -0
  86. proef/api/v1/results.py +147 -0
  87. proef/api/v1/schemas.py +932 -0
  88. proef/api/v1/system.py +79 -0
  89. proef/api/v1/trees.py +216 -0
  90. proef/api/wizard_sessions.py +253 -0
  91. proef/approvals.py +102 -0
  92. proef/assays/__init__.py +15 -0
  93. proef/assays/dls.py +114 -0
  94. proef/assays/dsf.py +81 -0
  95. proef/assays/elisa.py +58 -0
  96. proef/assays/properties.py +65 -0
  97. proef/assays/simulate.py +157 -0
  98. proef/audit.py +152 -0
  99. proef/autoloop.py +1620 -0
  100. proef/benchmark.py +442 -0
  101. proef/campaign_fsm.py +151 -0
  102. proef/citations.py +141 -0
  103. proef/cli.py +1249 -0
  104. proef/connect.py +74 -0
  105. proef/core/__init__.py +0 -0
  106. proef/core/contracts/__init__.py +35 -0
  107. proef/core/contracts/analysis.py +100 -0
  108. proef/core/contracts/models.py +395 -0
  109. proef/core/device_card.py +125 -0
  110. proef/core/hypothesis.py +720 -0
  111. proef/core/interfaces.py +164 -0
  112. proef/core/registry.py +123 -0
  113. proef/core/safety.py +324 -0
  114. proef/core/workflow.py +159 -0
  115. proef/critic.py +62 -0
  116. proef/demo.py +164 -0
  117. proef/derivation.py +128 -0
  118. proef/diary.py +301 -0
  119. proef/eln.py +87 -0
  120. proef/evals/__init__.py +1 -0
  121. proef/evals/hallucination.py +86 -0
  122. proef/evals/harness.py +358 -0
  123. proef/evals/orchestration.py +254 -0
  124. proef/evals/tasks.py +1010 -0
  125. proef/evals/toolcalls.py +425 -0
  126. proef/experiment.py +172 -0
  127. proef/experiment_analysis.py +114 -0
  128. proef/experiments/__init__.py +0 -0
  129. proef/experiments/grounding_exp.py +689 -0
  130. proef/figures.py +218 -0
  131. proef/fitting.py +309 -0
  132. proef/fixtures.py +140 -0
  133. proef/flywheel.py +125 -0
  134. proef/followup.py +126 -0
  135. proef/governance.py +290 -0
  136. proef/groundedness.py +361 -0
  137. proef/grounding.py +202 -0
  138. proef/hypothesis_agent.py +369 -0
  139. proef/ingest.py +157 -0
  140. proef/instruments.json +173 -0
  141. proef/interpret.py +95 -0
  142. proef/kinetic.py +102 -0
  143. proef/labread/__init__.py +45 -0
  144. proef/labread/analysis.py +428 -0
  145. proef/labread/common.py +153 -0
  146. proef/labread/formats.py +190 -0
  147. proef/labread/layout.py +168 -0
  148. proef/labread/pubchem.py +179 -0
  149. proef/labselect.py +431 -0
  150. proef/materials.py +140 -0
  151. proef/mcp_instrument.py +396 -0
  152. proef/mcp_server.py +283 -0
  153. proef/modality.py +111 -0
  154. proef/model_guard.py +245 -0
  155. proef/output_blocks.py +183 -0
  156. proef/paths.py +32 -0
  157. proef/physfail.py +55 -0
  158. proef/plan.py +160 -0
  159. proef/plots.py +123 -0
  160. proef/predictors.py +217 -0
  161. proef/probes.py +79 -0
  162. proef/problem_tree.py +581 -0
  163. proef/program.py +308 -0
  164. proef/protocol_design.py +42 -0
  165. proef/proxy.py +78 -0
  166. proef/readiness.py +259 -0
  167. proef/reliability.py +49 -0
  168. proef/report.py +117 -0
  169. proef/reproduce.py +310 -0
  170. proef/reviewer.py +254 -0
  171. proef/sandbox_session.py +247 -0
  172. proef/sandboxd.py +109 -0
  173. proef/scaffold.py +195 -0
  174. proef/series.py +327 -0
  175. proef/skills.py +203 -0
  176. proef/sweep.py +83 -0
  177. proef/taste.py +177 -0
  178. proef/templates/confirmatory-followup.json +34 -0
  179. proef/templates/dose-response-screen.json +39 -0
  180. proef/templates/sar-exploration.json +38 -0
  181. proef/templates.py +124 -0
  182. proef/toolkit.py +433 -0
  183. proef/toolloop.py +133 -0
  184. proef/tools.py +441 -0
  185. proef/tpp.py +185 -0
  186. proef/views/__init__.py +14 -0
  187. proef/views/counts.py +102 -0
  188. proef/views/experiment.py +154 -0
  189. proef/views/ids.py +49 -0
  190. proef/views/narrative.py +294 -0
  191. proef/views/pipeline.py +370 -0
  192. proef/vision.py +165 -0
  193. proef/watch.py +790 -0
  194. proef/wizard_chain.py +25 -0
  195. proef/wizard_store.py +373 -0
  196. proef-0.2.0.dist-info/METADATA +662 -0
  197. proef-0.2.0.dist-info/RECORD +200 -0
  198. proef-0.2.0.dist-info/WHEEL +4 -0
  199. proef-0.2.0.dist-info/entry_points.txt +14 -0
  200. proef-0.2.0.dist-info/licenses/LICENSE +202 -0
proef/core/workflow.py ADDED
@@ -0,0 +1,159 @@
1
+ """Stage graph + hypothesis tournament engine (P2: consumes only core interfaces).
2
+
3
+ The stage graph is deliberately boring: a list of Stages run in order, each a
4
+ callable StageTask -> StageResult, with optional human gates between stages and
5
+ round-based looping for the active-learning cycle. The tournament runs
6
+ generate->reflect->rank->evolve waves inside a stage.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+
14
+ from proef.core.contracts import (
15
+ Actor,
16
+ Envelope,
17
+ EventType,
18
+ GateType,
19
+ StageName,
20
+ StageResult,
21
+ StageStatus,
22
+ StageTask,
23
+ )
24
+ from proef.core.interfaces import ProvenanceStore, record_for
25
+
26
+
27
+ @dataclass
28
+ class Gate:
29
+ """A human review point. `approver` returns True/False/redirect-dict."""
30
+ gate_type: GateType
31
+ approver: Callable[[StageResult], bool]
32
+
33
+
34
+ @dataclass
35
+ class Stage:
36
+ name: StageName
37
+ run: Callable[[StageTask], StageResult]
38
+ gate: Gate | None = None
39
+ max_rounds: int = 1 # >1 enables the active-learning loop
40
+
41
+
42
+ @dataclass
43
+ class StageGraph:
44
+ """Ordered stages; each stage may loop rounds. Provenance on every transition."""
45
+ stages: list[Stage]
46
+ store: ProvenanceStore
47
+ actor: Actor
48
+ branch_id: str
49
+ results: dict[str, list[StageResult]] = field(default_factory=dict)
50
+
51
+ def execute(self, context: dict[str, Any] | None = None) -> dict[str, Any]:
52
+ context = context or {}
53
+ carry: dict[str, Any] = {}
54
+ for stage in self.stages:
55
+ carry = self._run_stage(stage, context, carry)
56
+ return carry
57
+
58
+ def _run_stage(self, stage: Stage, context: dict[str, Any], carry: dict[str, Any]) -> dict[str, Any]:
59
+ out: list[StageResult] = []
60
+ for round_no in range(1, stage.max_rounds + 1):
61
+ task = StageTask(
62
+ envelope=Envelope(experiment_branch_id=self.branch_id),
63
+ stage=stage.name,
64
+ attempt=round_no,
65
+ context={**context, **carry, "round": round_no},
66
+ )
67
+ result = stage.run(task)
68
+ out.append(result)
69
+ self.store.append(
70
+ record_for(
71
+ task.envelope,
72
+ EventType.stage_transition,
73
+ self.actor,
74
+ decision={
75
+ "stage": stage.name.value,
76
+ "round": round_no,
77
+ "status": result.status.value,
78
+ },
79
+ )
80
+ )
81
+ if result.status in (StageStatus.failed_terminal, StageStatus.needs_human):
82
+ break
83
+ carry = {
84
+ "artifacts": [a.model_dump() for a in result.output_artifacts],
85
+ "proposals": [p.model_dump() for p in result.next_round_proposals],
86
+ }
87
+ if round_no < stage.max_rounds:
88
+ # feed proposals back as next-round context (active learning)
89
+ context = {**context, "prev_proposals": carry["proposals"]}
90
+ self.results[stage.name.value] = out
91
+
92
+ if stage.gate is not None:
93
+ last = out[-1]
94
+ approved = stage.gate.approver(last)
95
+ self.store.append(
96
+ record_for(
97
+ Envelope(experiment_branch_id=self.branch_id),
98
+ EventType.gate_decision,
99
+ self.actor,
100
+ decision={
101
+ "gate": stage.gate.gate_type.value,
102
+ "approved": approved,
103
+ },
104
+ )
105
+ )
106
+ if not approved:
107
+ carry["gate_rejected"] = stage.gate.gate_type.value
108
+ return carry
109
+
110
+
111
+ # ------------------------------------------------------------- tournament
112
+
113
+ @dataclass
114
+ class TournamentConfig:
115
+ population: int = 8 # proposals per wave
116
+ survivors: int = 3 # top-k carried into the next wave
117
+ waves: int = 2 # generation rounds
118
+ score_fn: Callable[[dict[str, Any]], float] = lambda p: p.get("score", 0.0)
119
+
120
+
121
+ class HypothesisTournament:
122
+ """Generate -> Reflect -> Rank -> Evolve (P2: only needs a ModelProvider +
123
+ optional reflection/ranking callables). Deterministic given deterministic
124
+ inputs; scores come from the Evaluation side (user-supplied or BioTools)."""
125
+
126
+ def __init__(
127
+ self,
128
+ model: Any,
129
+ config: TournamentConfig | None = None,
130
+ reflect_fn: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
131
+ evolve_fn: Callable[[list[dict[str, Any]]], list[dict[str, Any]]] | None = None,
132
+ ):
133
+ self.model = model
134
+ self.cfg = config or TournamentConfig()
135
+ self.reflect_fn = reflect_fn
136
+ self.evolve_fn = evolve_fn
137
+
138
+ def run(
139
+ self,
140
+ branch_id: str,
141
+ seed_context: dict[str, Any],
142
+ generate_fn: Callable[[dict[str, Any]], list[dict[str, Any]]],
143
+ score_fn: Callable[[dict[str, Any]], float],
144
+ ) -> list[dict[str, Any]]:
145
+ """Returns ranked survivors (best first), scored by `score_fn`."""
146
+ population = generate_fn(seed_context)[: self.cfg.population]
147
+ for wave in range(self.cfg.waves):
148
+ if self.reflect_fn:
149
+ population = [self.reflect_fn(p) for p in population]
150
+ population.sort(key=score_fn, reverse=True)
151
+ survivors = population[: self.cfg.survivors]
152
+ if wave < self.cfg.waves - 1:
153
+ if self.evolve_fn:
154
+ population = self.evolve_fn(survivors)
155
+ else:
156
+ population = survivors # simple truncation evolve
157
+ else:
158
+ population = survivors
159
+ return sorted(population, key=score_fn, reverse=True)
proef/critic.py ADDED
@@ -0,0 +1,62 @@
1
+ """A second agent that reads the plan before the person does.
2
+
3
+ The hypothesis lead proposes; the critic only criticises. It looks for what a careful colleague would catch in
4
+ review (near-duplicate hypotheses, a claim the gate's metric cannot test, a "refuted if" that cannot be observed,
5
+ an assay that does not match the claim) and returns short notes. It is advisory by construction: it cannot remove
6
+ a hypothesis, change a gate or approve anything, and a failed or malformed reply yields no notes rather than an
7
+ error. Run it on a DIFFERENT model than the proposer when you can (PROEF_LLM_CRITIC_MODEL): two instances of one
8
+ model share blind spots. The notes, and which model wrote them, are recorded in the ledger.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+ from typing import Any
15
+
16
+ MAX_NOTES = 8
17
+
18
+ PROMPT = """You are the critic on a research team. A colleague proposed this plan; you do not run experiments and you
19
+ decide nothing. Find the weaknesses a careful reviewer would raise BEFORE any lab time is spent.
20
+
21
+ OBJECTIVE: {objective}
22
+ THE GATE (the only thing the experiments will measure): {gate}
23
+
24
+ PLAN
25
+ {plan}
26
+
27
+ Look for: near-duplicate hypotheses that waste runs; a claim the gate's metric cannot test (it would be judged on
28
+ the metric only); a "refuted if" that no experiment here could observe; an assay that does not match the claim;
29
+ a confidence that looks unearned; a missing or unverifiable citation relied upon.
30
+
31
+ Reply ONLY with JSON: {{"notes": [{{"target": "family id or candidate id, or 'plan'", "severity": "concern|note",
32
+ "text": "one or two sentences, specific"}}]}}. At most {max_notes} notes. If the plan is sound, return {{"notes": []}}."""
33
+
34
+
35
+ def _plan_text(plan: dict) -> str:
36
+ lines = []
37
+ for f in plan.get("families", []):
38
+ lines.append(f"- family {f.get('id')} (confidence {f.get('confidence')}): {f.get('claim')}")
39
+ lines.append(f" mechanism: {f.get('mechanism')}; refuted if: {f.get('refuted_if')}; citation: {f.get('citation_status') or 'none'}")
40
+ for v in f.get("variants", []):
41
+ lines.append(f" * {v.get('candidate')}: {v.get('statement')} [assay {v.get('assay')}]")
42
+ return "\n".join(lines)[:6000]
43
+
44
+
45
+ def critique_plan(model: Any, plan: dict, objective: str, gate: str = "") -> list[dict]:
46
+ """Advisory notes on a plan: [{target, severity, text}]. Never raises."""
47
+ from proef.core.contracts import Envelope, ToolInvocation
48
+ try:
49
+ prompt = PROMPT.format(objective=objective, gate=gate or "the program's gate", plan=_plan_text(plan), max_notes=MAX_NOTES)
50
+ inv = ToolInvocation(envelope=Envelope(experiment_branch_id="critic"), tool="c.fm.generate_molecules")
51
+ raw = model.generate(inv, prompt).output["text"]
52
+ m = re.search(r"\{.*\}", raw, re.S)
53
+ notes = json.loads(m.group(0)).get("notes", []) if m else []
54
+ except Exception: # noqa: BLE001 - a critic that fails must never block the plan
55
+ return []
56
+ out = []
57
+ for n in notes[:MAX_NOTES] if isinstance(notes, list) else []:
58
+ if isinstance(n, dict) and str(n.get("text", "")).strip():
59
+ out.append({"target": str(n.get("target") or "plan")[:60],
60
+ "severity": "concern" if n.get("severity") == "concern" else "note",
61
+ "text": str(n["text"]).strip()[:300]})
62
+ return out
proef/demo.py ADDED
@@ -0,0 +1,164 @@
1
+ """proef demo — onboarding that engineers THE moment (S-T2).
2
+
3
+ Scientists adopt pre-registration discipline at the speed they feel it
4
+ save them. This demo runs a curated, scripted campaign THROUGH THE REAL
5
+ MACHINERY (HypothesisTracker, SimulatorLab, AutoAnalysisAgent orthogonal
6
+ confirmation, CI-aware verdicts, hash-chained provenance) so that the
7
+ first screen shows the two moments no competitor ships:
8
+
9
+ BORDER — IC50 with a 95% CI straddling the gate: the system ABSTAINS,
10
+ visibly, and abstains again when the second method agrees
11
+ on the number but not the decision.
12
+ FALSER — a clean-looking preliminary hit (4.9 uM, CI well under the
13
+ gate) that the orthogonal method DISAGREES with: REFUTED,
14
+ on the record, with the comparison and the rule used.
15
+
16
+ Numbers are simulated (seeded — the same demo every run) and labeled
17
+ simulated. The discipline they demonstrate is the production discipline.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import tempfile
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ DEMO_GATE_UM = 10.0
26
+ DEMO_SEED = 19
27
+ DEMO_SMILES = {
28
+ "WINNER": "Cc1ccc(NC(=O)c2ccc(O)cc2)cc1",
29
+ "FALSER": "COc1ccc(NC(=O)c2ccccc2F)cc1",
30
+ "BORDER": "Cc1cccc(NC(=O)c2ccc(F)cc2)c1",
31
+ }
32
+ EXPECTED = {"WINNER": "confirmed", "FALSER": "refuted", "BORDER": "inconclusive"}
33
+ # FALSER is an assay artifact: it looks potent in the binding assay and is inactive by the orthogonal enzymatic method.
34
+ # Engineered explicitly (not left to simulator noise), so the moment lands on every machine, in any run order.
35
+ DEMO_METHOD_BIAS = {"FALSER": {"enzymatic": 4.0}}
36
+
37
+
38
+ def _campaign_config():
39
+ from proef.autoloop import CampaignConfig
40
+ from proef.core.hypothesis import Constraint, ProblemStatement
41
+
42
+ problem = ProblemStatement(
43
+ objective="SER-DEMO: three compounds, one gate (IC50 <= 10 uM), "
44
+ "pre-registered before measurement",
45
+ constraints=[Constraint(name="potency", description="<= 10 uM",
46
+ kind="hard", limit=DEMO_GATE_UM, unit="uM")])
47
+ hyps = [{"statement": f"{c} inhibits the demo target", "candidate": c,
48
+ "assay_type": "binding", "predicted": "<= 10",
49
+ "predicted_value": DEMO_GATE_UM, "rationale": "demo (simulated)",
50
+ "mechanism": "reversible binding",
51
+ "refutation_condition": f"orthogonal method disagrees (no CI "
52
+ f"overlap) or IC50 CI sits above "
53
+ f"{DEMO_GATE_UM} uM",
54
+ "citation": "demo — no real prior art claimed",
55
+ "smiles": smi}
56
+ for c, smi in DEMO_SMILES.items()]
57
+ return CampaignConfig(
58
+ problem=problem, hypotheses=hyps, k=3, rounds=1, autonomy="act",
59
+ concentrations=["0.1uM", "0.3uM", "1uM", "3uM", "10uM"],
60
+ inbox=tempfile.mkdtemp(prefix="proef-demo-"), poll_secs=0.02)
61
+
62
+
63
+ def _moments(recs) -> dict[str, Any]:
64
+ """Pull the two engineered moments + the hero out of the chain —
65
+ straight from provenance decisions, not the in-memory report."""
66
+ out: dict[str, Any] = {}
67
+ prelim: dict[str, dict] = {}
68
+ for r in recs:
69
+ d = r.decision or {}
70
+ cand = d.get("candidate") or (
71
+ (r.artifact.metadata if r.artifact else {}) or {}).get("candidate")
72
+ v = d.get("verdict")
73
+ if not cand or not v:
74
+ continue
75
+ obs = d.get("observed") or d.get("ic50_um")
76
+ ci = d.get("observed_ci") or d.get("ic50_ci")
77
+ if cand == "BORDER" and "abstain" not in out and ci \
78
+ and ci[0] < DEMO_GATE_UM < ci[1]:
79
+ out["abstain"] = {"candidate": cand, "observed_uM": obs,
80
+ "ci95": list(ci), "gate_uM": DEMO_GATE_UM}
81
+ if cand == "FALSER":
82
+ conf = d.get("confirmation") or {}
83
+ if v == "validated" and "fake_hit" not in prelim:
84
+ prelim["fake_hit"] = {"observed_uM": obs, "ci95": list(ci)}
85
+ if v == "refuted" and conf:
86
+ out["refutation"] = {
87
+ "candidate": cand, "rule": conf.get("rule"),
88
+ "primary_uM": conf.get("primary_ic50"),
89
+ "secondary_uM": conf.get("secondary_ic50"),
90
+ "agreed": conf.get("agreed"),
91
+ "preliminary": prelim.get("fake_hit", {})}
92
+ if cand == "WINNER" and v == "confirmed":
93
+ out["hero"] = {"observed_uM": obs, "ci95": list(ci)}
94
+ return out
95
+
96
+
97
+ def run_demo(db_path: str | Path | None = None,
98
+ html_path: str | Path | None = None,
99
+ echo: bool = False) -> dict[str, Any]:
100
+ """Execute the scripted campaign. Chain lands in db_path (default
101
+ .data/demo.db, overwritten fresh); diary HTML optional. Returns
102
+ {verdicts, moments, branch, records, db, chain_ok, lines}."""
103
+ from proef.adapters.lab.simulator import SimulatorLab
104
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
105
+ from proef.autoloop import run_campaign
106
+ from proef.paths import DATA_DIR
107
+
108
+ db = Path(db_path) if db_path else DATA_DIR / "demo.db"
109
+ db.parent.mkdir(parents=True, exist_ok=True)
110
+ db.unlink(missing_ok=True) # idempotent: the demo is stateless
111
+ store = SqliteProvenanceStore(str(db))
112
+ lines: list[str] = []
113
+ rep = run_campaign(_campaign_config(), SimulatorLab(seed=DEMO_SEED, method_bias=DEMO_METHOD_BIAS),
114
+ store,
115
+ notify=(lambda m: (lines.append(str(m)),
116
+ print(f" [demo] {m}")
117
+ if echo else None)))
118
+ branch = f"problem/{rep.problem_id}"
119
+ recs = store.branch_records(branch)
120
+ moments = _moments(recs)
121
+ verdicts = dict(rep.verdicts)
122
+ chain_problems = store.verify_chain(branch)
123
+
124
+ if html_path:
125
+ from proef.diary import build_diary_html
126
+ p = Path(html_path)
127
+ p.parent.mkdir(parents=True, exist_ok=True)
128
+ p.write_text(build_diary_html(recs, branch))
129
+
130
+ return {"verdicts": verdicts, "moments": moments, "branch": branch,
131
+ "records": len(recs), "db": str(db),
132
+ "chain_ok": not chain_problems,
133
+ "lines": [l for l in lines if l.strip()],
134
+ "simulated": True,
135
+ "narration": narration(verdicts, moments)}
136
+
137
+
138
+ def narration(verdicts: dict, moments: dict) -> list[str]:
139
+ """The story beat — what to point at first."""
140
+ out: list[str] = []
141
+ ab = moments.get("abstain")
142
+ if ab:
143
+ out.append(
144
+ f"BORDER measured IC50 {ab['observed_uM']:.2f} uM, 95% CI "
145
+ f"{ab['ci95'][0]:.2f}-{ab['ci95'][1]:.2f} uM — the interval "
146
+ f"straddles the {ab['gate_uM']:.0f} uM gate, so the system "
147
+ "ABSTAINS: \"we do not claim this\". And it abstains AGAIN when "
148
+ "the orthogonal method agrees on the number but not the decision.")
149
+ rf = moments.get("refutation")
150
+ if rf:
151
+ pre = rf.get("preliminary", {})
152
+ out.append(
153
+ f"FALSER looked like a hit ({pre.get('observed_uM', 0):.2f} uM, "
154
+ f"CI {pre.get('ci95', [0, 0])[0]:.2f}-{pre.get('ci95', [0, 0])[1]:.2f} "
155
+ f"uM) — the kind of number that gets a slide. The orthogonal "
156
+ f"method read {rf['secondary_uM']:.2f} uM; intervals do not "
157
+ f"overlap (rule: {rf['rule']}), so the preliminary call was "
158
+ "REFUTED — on the record, with the comparison kept.")
159
+ if verdicts.get("WINNER") == "confirmed":
160
+ out.append("WINNER: both methods inside the gate with overlapping "
161
+ "CIs — CONFIRMED. That is the whole pitch: agree -> "
162
+ "claim, disagree -> kill, unsure -> abstain. All "
163
+ "hash-chained (proef prove the branch).")
164
+ return out
proef/derivation.py ADDED
@@ -0,0 +1,128 @@
1
+ """Derivation records — how a number was made, as DATA not prose.
2
+
3
+ The framework is instrument-generic: a plate reader's IC50, a qPCR fold
4
+ change, a sequencer's variant call and a microscope's cell count are made by
5
+ different chains. So no UI caption may hard-code one chain. Instead, every
6
+ analysis path attaches a `derivation` dict to its verdict, and the UI simply
7
+ renders whatever the record says.
8
+
9
+ Shape (all keys optional, so any domain can fill what it knows):
10
+ measured_by: "instrument (version)"
11
+ raw: {quantity, wells|reads|images|..., replicates}
12
+ derived: {metric, method, ci}
13
+ decided_by: {criteria}
14
+ """
15
+ from __future__ import annotations
16
+
17
+
18
+ _UNIT_SUFFIX = {"um": "µM", "nm": "nM", "us": "µs", "ct": "Ct",
19
+ "mpa": "MPa", "pct": "%", "nm2": "nm²"}
20
+
21
+ # machine metric -> human wording (verdicts read like the program's goal)
22
+ _METRIC_WORDS = {
23
+ "potency_pct": "potency",
24
+ "potency": "potency",
25
+ "tensile_strength_mpa": "tensile strength",
26
+ "tensile": "tensile strength",
27
+ "strength_mpa": "strength",
28
+ "conductivity": "conductivity",
29
+ "density": "density",
30
+ "thermal_stability": "thermal stability",
31
+ "stability": "stability",
32
+ "aggregation": "aggregation",
33
+ "immunogenicity": "immunogenicity",
34
+ "expression": "expression",
35
+ "sterility": "sterility",
36
+ "phenotype_stability": "phenotype stability",
37
+ "organism_dose_response": "organism response",
38
+ "phytotoxicity": "phytotoxicity",
39
+ "fold_change": "fold change",
40
+ "ic50_um": "IC50",
41
+ "ic50": "IC50",
42
+ }
43
+
44
+
45
+ def metric_label(metric: str | None) -> str:
46
+ """Machine metric -> human wording: ic50_um -> 'IC50 (µM)';
47
+ potency_pct -> 'potency (%)'; tensile_strength_mpa ->
48
+ 'tensile strength (MPa)'. Unknown metrics prettify."""
49
+ if not metric:
50
+ return "value"
51
+ m = metric.strip().lower()
52
+ if m in _METRIC_WORDS:
53
+ base = _METRIC_WORDS[m]
54
+ suffix = m.split("_")[-1]
55
+ if suffix in _UNIT_SUFFIX and suffix not in ("ct",):
56
+ return f"{base} ({_UNIT_SUFFIX[suffix]})"
57
+ return base
58
+ parts = metric.split("_")
59
+ if len(parts) > 1 and parts[-1].lower() in _UNIT_SUFFIX:
60
+ return (f"{'_'.join(parts[:-1]).upper()} "
61
+ f"({_UNIT_SUFFIX[parts[-1].lower()]})")
62
+ return metric.replace("_", " ")
63
+
64
+
65
+ def criteria_label(metric: str | None, direction: str | None,
66
+ threshold) -> str:
67
+ if metric is None or threshold is None:
68
+ return ""
69
+ op = "≤" if direction == "min" else "≥" if direction == "max" else "="
70
+ return f"{metric_label(metric)} {op} {threshold:g}"
71
+
72
+
73
+ def describe(der: dict | None) -> str:
74
+ """One generic line from a derivation dict. Unknown => says so."""
75
+ if not der:
76
+ return "derivation not recorded for this verdict"
77
+ parts = []
78
+ raw = der.get("raw") or {}
79
+ obs = []
80
+ if raw.get("quantity"):
81
+ obs.append(f"measured {raw['quantity']}")
82
+ for unit_key, label in (("wells", "wells"), ("reads", "reads"),
83
+ ("images", "images"), ("peaks", "peaks"),
84
+ ("records", "records"), ("replicates", "replicates")):
85
+ if raw.get(unit_key):
86
+ obs.append(f"{raw[unit_key]} {label}")
87
+ clause = " ".join(obs)
88
+ if clause and der.get("measured_by"):
89
+ clause += f" on {der['measured_by']}"
90
+ if clause:
91
+ parts.append(clause)
92
+ d = der.get("derived") or {}
93
+ if d.get("metric") or d.get("method"):
94
+ line = f"{metric_label(d.get('metric'))}"
95
+ line += f" by {d['method']}" if d.get("method") else "derived"
96
+ if d.get("ci"):
97
+ line += f", {d['ci']}"
98
+ parts.append(line)
99
+ dec = der.get("decided_by") or {}
100
+ crit = (criteria_label(dec.get("metric"), dec.get("direction"),
101
+ dec.get("threshold"))
102
+ or dec.get("criteria") or "")
103
+ if crit:
104
+ parts.append(f"gate: {crit}")
105
+ return " → ".join(p for p in parts if p) or "derivation not recorded"
106
+
107
+
108
+ def build(instrument: str | None = None, version: str | None = None,
109
+ quantity: str | None = None, counts: dict | None = None,
110
+ metric: str | None = None, method: str | None = None,
111
+ ci: str | None = None, criteria: str | None = None,
112
+ criteria_metric: str | None = None,
113
+ criteria_direction: str | None = None,
114
+ criteria_threshold=None) -> dict:
115
+ """Convenience builder used by the analysis paths. Pass criteria as
116
+ structured parts when available (renders humanely); a plain string still
117
+ works for legacy callers."""
118
+ return {
119
+ "measured_by": (f"{instrument} ({version})" if instrument and version
120
+ else instrument),
121
+ "raw": {"quantity": quantity, **(counts or {})},
122
+ "derived": {"metric": metric, "method": method, "ci": ci},
123
+ "decided_by": ({"metric": criteria_metric,
124
+ "direction": criteria_direction,
125
+ "threshold": criteria_threshold}
126
+ if criteria_metric is not None
127
+ else {"criteria": criteria}),
128
+ }