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/api/launch.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Campaign launch (P2.2): the server-side twin of the workbench's
|
|
2
|
+
Launch-program flow. Builds the campaign cfg from the program doc,
|
|
3
|
+
spawns the proef-auto subprocess, and records the relational links."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from proef.paths import APPROVALS_FILE
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from proef.paths import CAMPAIGN_DIR, ensure_dirs
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class LaunchError(Exception):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_cfg(doc: dict) -> dict:
|
|
23
|
+
"""Campaign cfg from a program doc (mirrors the workbench form)."""
|
|
24
|
+
metric = doc.get("metric") or "potency"
|
|
25
|
+
unit = doc.get("unit") or ""
|
|
26
|
+
direction = doc.get("direction", "min")
|
|
27
|
+
cmp_ = "<=" if direction == "min" else ">="
|
|
28
|
+
gval = float(doc.get("gate_value", 1.0))
|
|
29
|
+
objective = doc.get("objective") or f"Optimize {metric}"
|
|
30
|
+
cfg: dict = {
|
|
31
|
+
"problem": {
|
|
32
|
+
"objective": objective,
|
|
33
|
+
"constraints": [{
|
|
34
|
+
"name": metric,
|
|
35
|
+
"description": f"{metric} {cmp_} {gval:g} {unit}".strip(),
|
|
36
|
+
"kind": "hard", "limit": gval, "unit": unit}],
|
|
37
|
+
"success_metric": f"{metric} gate decisions consistent "
|
|
38
|
+
"across replicates"},
|
|
39
|
+
"k": int(doc.get("k", 2)),
|
|
40
|
+
"rounds": int(doc.get("rounds", 2)),
|
|
41
|
+
"autonomy": doc.get("autonomy", "act"),
|
|
42
|
+
"concentrations": ["0.5uM", "2uM", "10uM", "40uM"]}
|
|
43
|
+
for key in ("max_families", "max_variants_per_family"):
|
|
44
|
+
if doc.get(key):
|
|
45
|
+
cfg[key] = int(doc[key])
|
|
46
|
+
if doc.get("budget"):
|
|
47
|
+
cfg["budget"] = dict(doc["budget"])
|
|
48
|
+
if doc.get("prediction_tools"):
|
|
49
|
+
cfg["prediction_tools"] = [str(t) for t in doc["prediction_tools"]] # the operator's fence for prediction tools
|
|
50
|
+
if doc.get("modality"):
|
|
51
|
+
cfg["modality"] = str(doc["modality"]) # selects the domain pack: assays, prompt wording
|
|
52
|
+
candidates = [c.strip() for c in (doc.get("candidates") or "").split(",")
|
|
53
|
+
if c.strip()]
|
|
54
|
+
if candidates:
|
|
55
|
+
from proef.modality import pack_or_default
|
|
56
|
+
assay = pack_or_default(doc.get("modality")).default_assay # domain data in the pack, not a rule here
|
|
57
|
+
cfg["hypotheses"] = [{
|
|
58
|
+
"statement": f"{c} achieves {metric} {cmp_} {gval:g} {unit}".strip(),
|
|
59
|
+
"candidate": c, "assay_type": assay,
|
|
60
|
+
"predicted": f"{metric} {cmp_} {gval:g}",
|
|
61
|
+
"predicted_value": gval, "rationale": ""}
|
|
62
|
+
for c in candidates]
|
|
63
|
+
else:
|
|
64
|
+
cfg["hypothesis_source"] = "agent"
|
|
65
|
+
if doc.get("orchestrator") == "model":
|
|
66
|
+
cfg["orchestrator"] = "model" # a model chooses among the actions the engine allows after each round
|
|
67
|
+
if doc.get("followups"):
|
|
68
|
+
cfg["followups"] = True # the model suggests what to do with abstained hypotheses (validated by code)
|
|
69
|
+
if doc.get("replan"):
|
|
70
|
+
cfg["replan"] = True # the model proposes follow-up hypotheses after each round (a person approves them)
|
|
71
|
+
return cfg
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def spawn_campaign(doc: dict, program_name: str) -> str | None:
|
|
75
|
+
"""Spawn the campaign subprocess + record registry/spec/links.
|
|
76
|
+
decompose=True runs the plan flow instead: the agent splits the
|
|
77
|
+
objective into a guarded problem tree and executes the leaves
|
|
78
|
+
(each leaf links to the program via PROEF_PROGRAM). Returns the
|
|
79
|
+
campaign eid, or None for decomposed launches."""
|
|
80
|
+
from proef import program as program_cfg
|
|
81
|
+
ensure_dirs()
|
|
82
|
+
if doc.get("decompose"):
|
|
83
|
+
return _spawn_plan(doc, program_name)
|
|
84
|
+
cid = f"cmp-{int(time.time())}-{uuid.uuid4().hex[:4]}"
|
|
85
|
+
cfg = build_cfg(doc)
|
|
86
|
+
cfgpath = CAMPAIGN_DIR / f"{cid}.json"
|
|
87
|
+
cfgpath.write_text(json.dumps(cfg, indent=1))
|
|
88
|
+
logf = CAMPAIGN_DIR / f"{cid}.log"
|
|
89
|
+
|
|
90
|
+
env = {**__import__("os").environ, "PROEF_PROGRAM": program_name,
|
|
91
|
+
"PROEF_CAMPAIGN_ID": cid}
|
|
92
|
+
proc = subprocess.Popen(
|
|
93
|
+
[sys.executable, "-u", "-m", "proef.cli", "campaign", "auto", str(cfgpath),
|
|
94
|
+
"--db", "proef.db", "--inbox", str(APPROVALS_FILE),
|
|
95
|
+
"--yes"],
|
|
96
|
+
stdout=open(logf, "ab", buffering=0), stderr=subprocess.STDOUT,
|
|
97
|
+
cwd=str(Path.cwd()), env=env)
|
|
98
|
+
|
|
99
|
+
store = __import__("proef.wizard_store",
|
|
100
|
+
fromlist=["WizardStore"]).WizardStore()
|
|
101
|
+
objective = cfg["problem"]["objective"]
|
|
102
|
+
store.register_agent(cid, objective, str(logf),
|
|
103
|
+
autonomy=cfg.get("autonomy", "act"), pid=proc.pid)
|
|
104
|
+
try:
|
|
105
|
+
store.set_campaign_spec(
|
|
106
|
+
cid, objective=objective,
|
|
107
|
+
program_slug=program_cfg._slug(program_name),
|
|
108
|
+
constraints=cfg["problem"]["constraints"],
|
|
109
|
+
success_metric=cfg["problem"].get("success_metric"),
|
|
110
|
+
k=cfg.get("k"), rounds=cfg.get("rounds"),
|
|
111
|
+
autonomy=cfg.get("autonomy", "act"),
|
|
112
|
+
hypothesis_source=("agent" if cfg.get("hypothesis_source")
|
|
113
|
+
== "agent" else "config"),
|
|
114
|
+
n_candidates=len(cfg.get("hypotheses") or []),
|
|
115
|
+
modality=doc.get("modality") or None)
|
|
116
|
+
except Exception:
|
|
117
|
+
pass
|
|
118
|
+
try:
|
|
119
|
+
program_cfg.link_leaf(program_name, cid, campaign_root=None,
|
|
120
|
+
question=objective, status="executing")
|
|
121
|
+
except Exception:
|
|
122
|
+
pass
|
|
123
|
+
idx = campaign_index()
|
|
124
|
+
idx[cid] = {"pid": proc.pid, "autonomy": cfg.get("autonomy", "act"),
|
|
125
|
+
"objective": objective, "log": str(logf)}
|
|
126
|
+
save_campaign_index(idx)
|
|
127
|
+
return cid
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _spawn_plan(doc: dict, program_name: str) -> None:
|
|
131
|
+
"""Decompose launch: proef campaign plan (agent tree decomposition) runs the
|
|
132
|
+
leaves; PROEF_PROGRAM links every leaf to the program."""
|
|
133
|
+
import os as _os
|
|
134
|
+
cands = ",".join(c.strip() for c in
|
|
135
|
+
(doc.get("candidates") or "").split(",") if c.strip())
|
|
136
|
+
# autonomy comes from the PROGRAM, never hardcoded here: a gate-mode
|
|
137
|
+
# program must not spawn unattended campaigns (audit fix, Oct 10)
|
|
138
|
+
autonomy = doc.get("autonomy") or "gate"
|
|
139
|
+
cmd = [sys.executable, "-u", "-m", "proef.cli", "campaign", "plan",
|
|
140
|
+
"--objective", doc.get("objective") or "optimize",
|
|
141
|
+
"--model", "anthropic", "--run", "--autonomy", autonomy]
|
|
142
|
+
if cands:
|
|
143
|
+
cmd += ["--candidates", cands]
|
|
144
|
+
import json as _j
|
|
145
|
+
cmd += ["--labs-json", _j.dumps(doc.get("labs")
|
|
146
|
+
or [{"instrument":
|
|
147
|
+
"proef-virtual-lab"}])]
|
|
148
|
+
logf = CAMPAIGN_DIR / f"plan-{int(time.time())}.log"
|
|
149
|
+
env = {**_os.environ, "PROEF_PROGRAM": program_name,
|
|
150
|
+
"PYTHONPATH": str(Path.cwd() / "src")}
|
|
151
|
+
# a plan runs many leaves in ONE process: no single PROEF_CAMPAIGN_ID
|
|
152
|
+
# fits; each leaf announces its own branch via run_tree -> announce_branch
|
|
153
|
+
env.pop("PROEF_CAMPAIGN_ID", None)
|
|
154
|
+
subprocess.Popen(cmd, stdout=open(logf, "ab", buffering=0),
|
|
155
|
+
stderr=subprocess.STDOUT, cwd=str(Path.cwd()), env=env)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def save_campaign_index(idx: dict) -> None:
|
|
159
|
+
CAMPAIGN_DIR.mkdir(parents=True, exist_ok=True)
|
|
160
|
+
(CAMPAIGN_DIR / "index.json").write_text(json.dumps(idx, indent=1))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def campaign_index() -> dict:
|
|
164
|
+
path = CAMPAIGN_DIR / "index.json"
|
|
165
|
+
if path.exists():
|
|
166
|
+
try:
|
|
167
|
+
return json.loads(path.read_text())
|
|
168
|
+
except Exception:
|
|
169
|
+
return {}
|
|
170
|
+
return {}
|
proef/api/v1/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Workbench API v1, a resource model over the engine's read-models."""
|
|
2
|
+
from fastapi import APIRouter
|
|
3
|
+
|
|
4
|
+
from proef.api.v1.analyses import router as analyses_router
|
|
5
|
+
from proef.api.v1.campaigns import router as campaigns_router
|
|
6
|
+
from proef.api.v1.evals import router as evals_router
|
|
7
|
+
from proef.api.v1.evidence import router as evidence_router
|
|
8
|
+
from proef.api.v1.governance import router as governance_router
|
|
9
|
+
from proef.api.v1.inbox import router as inbox_router
|
|
10
|
+
from proef.api.v1.lab import router as lab_router
|
|
11
|
+
from proef.api.v1.pauses import router as pauses_router
|
|
12
|
+
from proef.api.v1.programs import router as programs_router
|
|
13
|
+
from proef.api.v1.trees import router as trees_router
|
|
14
|
+
from proef.api.v1.results import router as results_router
|
|
15
|
+
from proef.api.v1.system import router as system_router
|
|
16
|
+
|
|
17
|
+
router = APIRouter(prefix="/api/v1")
|
|
18
|
+
router.include_router(analyses_router)
|
|
19
|
+
router.include_router(campaigns_router)
|
|
20
|
+
router.include_router(evals_router)
|
|
21
|
+
router.include_router(evidence_router)
|
|
22
|
+
router.include_router(governance_router)
|
|
23
|
+
router.include_router(inbox_router)
|
|
24
|
+
router.include_router(lab_router)
|
|
25
|
+
router.include_router(programs_router)
|
|
26
|
+
router.include_router(pauses_router)
|
|
27
|
+
router.include_router(trees_router)
|
|
28
|
+
router.include_router(results_router)
|
|
29
|
+
router.include_router(system_router)
|
proef/api/v1/analyses.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""/api/v1/analyses, drop a plate file, see what the data says, and say what it is evidence for.
|
|
2
|
+
|
|
3
|
+
Thin typed wiring over `experiment_analysis` (all scientific decisions) and
|
|
4
|
+
`analysis_store` (revisions, artifacts). Every step that changes something is
|
|
5
|
+
sealed in the provenance ledger under the acting person.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import uuid
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
|
14
|
+
from fastapi.responses import HTMLResponse, Response
|
|
15
|
+
|
|
16
|
+
from proef import analysis_store as store
|
|
17
|
+
from proef import experiment_analysis as EA
|
|
18
|
+
from proef.api.v1 import schemas as S
|
|
19
|
+
from proef.api.v1.deps import who
|
|
20
|
+
from proef.core.contracts import Actor, ActorKind, Envelope, EventType
|
|
21
|
+
from proef.core.contracts.analysis import (AnalysisState, DispositionAction,
|
|
22
|
+
HumanDisposition)
|
|
23
|
+
from proef.core.interfaces import record_for
|
|
24
|
+
from proef.views import ids as _ids
|
|
25
|
+
|
|
26
|
+
router = APIRouter(prefix="/analyses", tags=["analyze"])
|
|
27
|
+
log = logging.getLogger("proef.analysis")
|
|
28
|
+
|
|
29
|
+
# states from which a fit may run; others are honest holds the scientist must resolve
|
|
30
|
+
RUNNABLE = {AnalysisState.preview_ready, AnalysisState.configured, AnalysisState.analyzed,
|
|
31
|
+
AnalysisState.reviewed, AnalysisState.qc_hold, AnalysisState.unsupported_regime}
|
|
32
|
+
REVIEWABLE = {AnalysisState.analyzed, AnalysisState.qc_hold, AnalysisState.reviewed}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _problem(status: int, type_: str, title: str, detail: str = "") -> HTTPException:
|
|
36
|
+
return HTTPException(status, S.Problem(type=type_, title=title, detail=detail).model_dump())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _seal(aid: str, event: EventType, user: str, decision: dict, branch: str | None = None) -> None:
|
|
40
|
+
"""Provenance must land; a failure is loud in the log, never silent."""
|
|
41
|
+
try:
|
|
42
|
+
from proef.adapters.store.sqlite import get_store
|
|
43
|
+
get_store(str(_ids.PROVENANCE_DB)).append(record_for(
|
|
44
|
+
Envelope(experiment_branch_id=branch or f"analysis/{aid}"), event,
|
|
45
|
+
Actor(kind=ActorKind.human, id=user), decision=decision))
|
|
46
|
+
except Exception as exc: # noqa: BLE001
|
|
47
|
+
log.error("provenance write FAILED for %s: %s: the chain has a gap", aid, exc)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _doc(aid: str) -> dict:
|
|
51
|
+
try:
|
|
52
|
+
return store.get(aid)
|
|
53
|
+
except KeyError:
|
|
54
|
+
raise _problem(404, "analysis-not-found", "Analysis not found", aid) from None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _src(doc: dict) -> dict:
|
|
58
|
+
return (doc.get("artifacts") or {}).get("source") or {}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _verified_src(doc: dict) -> dict:
|
|
62
|
+
"""The stored bytes must still match the digest the ledger holds."""
|
|
63
|
+
src = _src(doc)
|
|
64
|
+
path = src.get("storage_path")
|
|
65
|
+
if not path or not Path(path).exists():
|
|
66
|
+
raise _problem(409, "source-missing", "Source file is missing", doc["id"])
|
|
67
|
+
if src.get("sha256") and store.sha256_of(Path(path)) != src["sha256"]:
|
|
68
|
+
raise _problem(409, "source-changed", "Source changed on disk",
|
|
69
|
+
"The stored file no longer matches its recorded digest. Re-upload to open a new analysis.")
|
|
70
|
+
return src
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _layout(doc: dict) -> str | None:
|
|
74
|
+
return ((doc.get("artifacts") or {}).get("layout") or {}).get("storage_path")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _preview(p: dict) -> S.AnalysisPreview:
|
|
78
|
+
return S.AnalysisPreview(
|
|
79
|
+
kind="measurements" if p.get("kind") == "measurements" else "plate",
|
|
80
|
+
columns=S.MeasurementColumns(**p["columns"]) if p.get("columns") else None,
|
|
81
|
+
n_measurements=int(p.get("n_measurements") or 0),
|
|
82
|
+
format=p.get("format"), n_wells=int(p.get("n_wells") or 0),
|
|
83
|
+
n_controls=int(p.get("controls_detected") or 0),
|
|
84
|
+
z_prime=p.get("z_prime"), z_kind=p.get("z_prime_kind"),
|
|
85
|
+
samples=list(p.get("samples") or []), has_doses=bool(p.get("has_doses")),
|
|
86
|
+
evidence_origin=str(p.get("evidence_origin") or "unknown"),
|
|
87
|
+
needs_confirmation=[str(x) for x in p.get("needs_confirmation") or []],
|
|
88
|
+
diagnostics=[S.AnalysisDiagnostic(**{k: d.get(k, "") for k in ("severity", "code", "message")})
|
|
89
|
+
for d in p.get("diagnostics") or []])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _curve(entity: str, comp: dict, wells: list[dict], max_response) -> S.Curve | None:
|
|
93
|
+
from proef.fitting import hill_fit, hill_response
|
|
94
|
+
pts = sorted((float(w["conc_um"]), float(w["value"])) for w in wells
|
|
95
|
+
if w.get("sample") == entity and not w.get("control")
|
|
96
|
+
and isinstance(w.get("conc_um"), (int, float)) and w["conc_um"] > 0
|
|
97
|
+
and isinstance(w.get("value"), (int, float)))
|
|
98
|
+
if not pts:
|
|
99
|
+
return None
|
|
100
|
+
fit = None
|
|
101
|
+
if comp:
|
|
102
|
+
line: list[S.CurvePoint] = []
|
|
103
|
+
hf = hill_fit(pts, max_response)
|
|
104
|
+
if comp.get("ic50_um") and hf:
|
|
105
|
+
lo, hi = pts[0][0] / 1.6, pts[-1][0] * 1.6
|
|
106
|
+
line = [S.CurvePoint(conc_um=c, value=hill_response(c, comp["ic50_um"], hf["top"]))
|
|
107
|
+
for c in (lo * (hi / lo) ** (i / 59) for i in range(60))]
|
|
108
|
+
ci = comp.get("ic50_ci")
|
|
109
|
+
fit = S.CurveFit(ic50_um=comp.get("ic50_um"), ci=list(ci) if ci else None,
|
|
110
|
+
top=hf["top"] if hf else None, method=comp.get("fit_method"),
|
|
111
|
+
model=comp.get("fit_model"), right_censored=bool(comp.get("right_censored")),
|
|
112
|
+
left_censored=bool(comp.get("left_censored")), line=line)
|
|
113
|
+
return S.Curve(run_id=entity, label=entity,
|
|
114
|
+
points=[S.CurvePoint(conc_um=c, value=v) for c, v in pts], fit=fit)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _measurements_result(r: dict, cfg: dict, calls: dict, comps: dict) -> S.AnalysisResult:
|
|
118
|
+
metric, unit = r.get("metric") or "value", r.get("unit")
|
|
119
|
+
gate = None
|
|
120
|
+
if r.get("threshold_registered") and cfg.get("threshold") is not None:
|
|
121
|
+
t, d = float(cfg["threshold"]), cfg.get("direction", "min")
|
|
122
|
+
gate = S.Gate(metric=metric, direction=d, threshold=t, unit=unit,
|
|
123
|
+
label=f"{metric} {'≤' if d == 'min' else '≥'} {t:g}" + (f" {unit}" if unit else ""))
|
|
124
|
+
out = []
|
|
125
|
+
for entity in sorted(comps):
|
|
126
|
+
c, k = comps[entity], calls.get(entity) or {}
|
|
127
|
+
out.append(S.AnalysisCompound(entity=entity, call=k.get("call"), reason=k.get("reason"), estimate=c.get("mean"),
|
|
128
|
+
ci=list(c["ci"]) if c.get("ci") else None, n=c.get("n"), n_points=c.get("n"),
|
|
129
|
+
sd=c.get("sd"), values=list(c.get("values") or [])))
|
|
130
|
+
return S.AnalysisResult(kind="measurements", metric=metric, unit=unit, method=r.get("method"), state=str(r.get("state")),
|
|
131
|
+
gate=gate, compounds=out)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _result(doc: dict) -> S.AnalysisResult | None:
|
|
135
|
+
r = doc.get("result")
|
|
136
|
+
if not r:
|
|
137
|
+
return None
|
|
138
|
+
cfg = doc.get("config") or {}
|
|
139
|
+
calls = {c["entity"]: c for c in r.get("calls") or []}
|
|
140
|
+
comps = r.get("compounds") or {}
|
|
141
|
+
if r.get("kind") == "measurements":
|
|
142
|
+
return _measurements_result(r, cfg, calls, comps)
|
|
143
|
+
gate = None
|
|
144
|
+
if r.get("threshold_registered") and cfg.get("threshold") is not None:
|
|
145
|
+
t, d = float(cfg["threshold"]), cfg.get("direction", "min")
|
|
146
|
+
gate = S.Gate(metric=cfg.get("metric", "ic50_um"), direction=d, threshold=t, unit="µM",
|
|
147
|
+
label=f"IC50 (µM) {'≤' if d == 'min' else '≥'} {t:g}")
|
|
148
|
+
out = []
|
|
149
|
+
for entity in sorted(set(comps) | set(calls)):
|
|
150
|
+
c, k = comps.get(entity) or {}, calls.get(entity) or {}
|
|
151
|
+
ci = c.get("ic50_ci")
|
|
152
|
+
out.append(S.AnalysisCompound(
|
|
153
|
+
entity=entity, call=k.get("call"), reason=k.get("reason"), ic50_um=c.get("ic50_um"),
|
|
154
|
+
ci=list(ci) if ci else None, n_points=c.get("n_points"),
|
|
155
|
+
top_known=(c.get("fit_quality") == "known-max") if c.get("fit_quality") in ("known-max", "observed-max") else None,
|
|
156
|
+
curve=_curve(entity, c, r.get("wells") or [], cfg.get("max_response"))))
|
|
157
|
+
refused = bool(r.get("regime_refused") or r.get("normalization_refused"))
|
|
158
|
+
return S.AnalysisResult(
|
|
159
|
+
state=str(r.get("state")), z_prime=r.get("z_prime"), z_kind=r.get("z_prime_kind"),
|
|
160
|
+
z_note=r.get("z_prime_note"), qc_hold=bool(r.get("qc_hold")), refused=refused,
|
|
161
|
+
note=r.get("normalization_note") or (r.get("shape_only") if isinstance(r.get("shape_only"), str) else None),
|
|
162
|
+
gate=gate, compounds=out)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _view(doc: dict) -> S.AnalysisView:
|
|
166
|
+
return S.AnalysisView(
|
|
167
|
+
profile=doc.get("profile", "plate_assay"), id=doc["id"], filename=_src(doc).get("original_name"), sha256=_src(doc).get("sha256"),
|
|
168
|
+
state=doc["state"], revision=doc["revision"], preview=_preview(doc.get("preview") or {}),
|
|
169
|
+
result=_result(doc),
|
|
170
|
+
reviews=[S.AnalysisReviewEntry(action=d["action"], reason=d.get("reason", ""),
|
|
171
|
+
target=d.get("target", ""), by=d.get("actor", "?"), ts=d["at"])
|
|
172
|
+
for d in doc.get("dispositions") or []],
|
|
173
|
+
attachments=[S.AnalysisAttachment(**a) for a in doc.get("attachments") or []])
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# ------------------------------------------------------------------ routes
|
|
177
|
+
@router.get("", response_model=list[S.AnalysisSummary])
|
|
178
|
+
def list_analyses() -> list[S.AnalysisSummary]:
|
|
179
|
+
store.ensure_tables()
|
|
180
|
+
out = []
|
|
181
|
+
for a in store.list_recent():
|
|
182
|
+
try:
|
|
183
|
+
name = _src(store.get(a["id"])).get("original_name")
|
|
184
|
+
except KeyError:
|
|
185
|
+
name = None
|
|
186
|
+
out.append(S.AnalysisSummary(id=a["id"], filename=name, state=a["state"],
|
|
187
|
+
updated_at=a["updated_at"]))
|
|
188
|
+
return out
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@router.post("", response_model=S.AnalysisView)
|
|
192
|
+
async def create_analysis(request: Request, file: UploadFile = File(...),
|
|
193
|
+
layout: UploadFile | None = File(None),
|
|
194
|
+
profile: str = Form("auto")) -> S.AnalysisView:
|
|
195
|
+
"""Store the file (bound by digest), detect what it is: a dose-response plate, or a table of measurements
|
|
196
|
+
(`profile` forces one). No fit, no verdict."""
|
|
197
|
+
store.ensure_tables()
|
|
198
|
+
aid = f"an-{uuid.uuid4().hex[:8]}"
|
|
199
|
+
try:
|
|
200
|
+
src = store.store_artifact(aid, "source", file.filename or "upload", await file.read())
|
|
201
|
+
lay = (store.store_artifact(aid, "layout", layout.filename, await layout.read())
|
|
202
|
+
if layout is not None and layout.filename else None)
|
|
203
|
+
except ValueError as exc:
|
|
204
|
+
raise _problem(422, "rejected-upload", "File rejected", str(exc)) from None
|
|
205
|
+
if profile not in ("auto", "plate_assay", "measurements"):
|
|
206
|
+
raise _problem(422, "unknown-profile", "Unknown analysis type", profile)
|
|
207
|
+
if profile == "auto":
|
|
208
|
+
from proef.analysis_profiles import measurements as _M
|
|
209
|
+
profile = "measurements" if lay is None and _M.looks_like_measurements(Path(src.storage_path)) else "plate_assay"
|
|
210
|
+
try:
|
|
211
|
+
preview = EA.preview(profile, Path(src.storage_path), {},
|
|
212
|
+
layout_path=lay.storage_path if lay else None)
|
|
213
|
+
except EA.AnalysisError as exc:
|
|
214
|
+
raise _problem(422, exc.code, "Could not read this file", exc.message) from None
|
|
215
|
+
store.create(aid, profile, {}, src, lay, preview)
|
|
216
|
+
_seal(aid, EventType.experiment_defined, who(request), {
|
|
217
|
+
"kind": "analysis_created", "source_sha256": src.sha256, "original_name": src.original_name,
|
|
218
|
+
"layout_sha256": lay.sha256 if lay else None, "preview_state": preview.get("state")})
|
|
219
|
+
return _view(store.get(aid))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@router.get("/{aid}", response_model=S.AnalysisView)
|
|
223
|
+
def get_analysis(aid: str) -> S.AnalysisView:
|
|
224
|
+
return _view(_doc(aid))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@router.post("/{aid}/run", response_model=S.AnalysisView)
|
|
228
|
+
def run_analysis(aid: str, body: S.AnalysisRun, request: Request) -> S.AnalysisView:
|
|
229
|
+
"""Confirm the interpretation and fit. A changed confirmation opens a new
|
|
230
|
+
immutable revision. QC holds and regime refusals come back as states."""
|
|
231
|
+
doc = _doc(aid)
|
|
232
|
+
measuring = doc["profile"] == "measurements"
|
|
233
|
+
cfg = {k: v for k, v in (doc.get("config") or {}).items()
|
|
234
|
+
if k not in ("metric", "direction", "threshold", "max_response", "unit", "sample_column", "value_column")}
|
|
235
|
+
if measuring:
|
|
236
|
+
cfg.update(metric=body.metric or "value", direction=body.direction, unit=body.unit or None)
|
|
237
|
+
if body.threshold is not None:
|
|
238
|
+
cfg["threshold"] = body.threshold
|
|
239
|
+
if body.sample_column:
|
|
240
|
+
cfg["sample_column"] = body.sample_column
|
|
241
|
+
if body.value_column:
|
|
242
|
+
cfg["value_column"] = body.value_column
|
|
243
|
+
elif body.threshold is not None:
|
|
244
|
+
cfg.update(metric="ic50_um", direction=body.direction, threshold=body.threshold)
|
|
245
|
+
if body.max_response is not None and not measuring:
|
|
246
|
+
cfg["max_response"] = body.max_response
|
|
247
|
+
if body.evidence_origin:
|
|
248
|
+
cfg["evidence_origin"] = body.evidence_origin
|
|
249
|
+
src, user = _verified_src(doc), who(request)
|
|
250
|
+
try:
|
|
251
|
+
preview = EA.preview(doc["profile"], Path(src["storage_path"]), cfg, layout_path=_layout(doc))
|
|
252
|
+
doc = store.reconfigure(aid, cfg, preview)
|
|
253
|
+
state = AnalysisState(doc["state"])
|
|
254
|
+
if state not in RUNNABLE:
|
|
255
|
+
raise _problem(409, "needs-input", "Cannot fit yet",
|
|
256
|
+
"; ".join(d["message"] for d in preview.get("diagnostics") or [])
|
|
257
|
+
or f"state is {doc['state']}")
|
|
258
|
+
result = EA.analyze(doc["profile"], Path(src["storage_path"]), cfg,
|
|
259
|
+
source_sha256=src.get("sha256"), layout_path=_layout(doc))
|
|
260
|
+
except EA.AnalysisError as exc:
|
|
261
|
+
raise _problem(409 if exc.code == "unreadable_source" else 422, exc.code,
|
|
262
|
+
"Analysis failed", exc.message) from None
|
|
263
|
+
out = store.store_result(aid, result)
|
|
264
|
+
_seal(aid, EventType.evaluation, user, {
|
|
265
|
+
"kind": "analysis_complete", "revision": out["revision"], "state": result.get("state"),
|
|
266
|
+
"source_sha256": src.get("sha256"), "config": cfg, "n_calls": len(result.get("calls") or []),
|
|
267
|
+
"z_prime": result.get("z_prime"), "z_prime_kind": result.get("z_prime_kind"),
|
|
268
|
+
"regime_refused": result.get("regime_refused")})
|
|
269
|
+
return _view(out)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@router.post("/{aid}/review", response_model=S.AnalysisView)
|
|
273
|
+
def review(aid: str, body: S.AnalysisReviewIn, request: Request) -> S.AnalysisView:
|
|
274
|
+
"""A human disposition, beside the computed call, never overwriting it."""
|
|
275
|
+
doc = _doc(aid)
|
|
276
|
+
if doc.get("result") is None:
|
|
277
|
+
raise _problem(409, "nothing-to-review", "Nothing to review", "run the analysis first")
|
|
278
|
+
if AnalysisState(doc["state"]) not in REVIEWABLE:
|
|
279
|
+
raise _problem(409, "not-reviewable", "Cannot review", doc["state"])
|
|
280
|
+
user = who(request)
|
|
281
|
+
out = store.add_disposition(aid, HumanDisposition(
|
|
282
|
+
action=DispositionAction(body.action), reason=body.reason, target=body.target, actor=user))
|
|
283
|
+
_seal(aid, EventType.stage_transition, user, {
|
|
284
|
+
"kind": "analysis_reviewed", "action": body.action, "reason": body.reason,
|
|
285
|
+
"target": body.target, "note": "human disposition: the computed call is unchanged"})
|
|
286
|
+
return _view(out)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
@router.post("/{aid}/attach", response_model=S.AnalysisView)
|
|
290
|
+
def attach(aid: str, body: S.AnalysisAttachIn, request: Request) -> S.AnalysisView:
|
|
291
|
+
"""Cite this analysis in a campaign's ledger as supporting evidence. It is
|
|
292
|
+
context for the people reading the campaign: it does not change any
|
|
293
|
+
verdict, and simulated/predicted data cannot be attached as measured."""
|
|
294
|
+
import time
|
|
295
|
+
|
|
296
|
+
from proef.api.v1.campaigns import _load
|
|
297
|
+
doc = _doc(aid)
|
|
298
|
+
r = doc.get("result")
|
|
299
|
+
if r is None:
|
|
300
|
+
raise _problem(409, "nothing-to-attach", "Nothing to attach", "run the analysis first")
|
|
301
|
+
if doc["state"] != AnalysisState.reviewed.value:
|
|
302
|
+
raise _problem(409, "review-first", "Review before attaching",
|
|
303
|
+
"Record a disposition on the result, then attach it.")
|
|
304
|
+
origin = str(r.get("evidence_origin") or "unknown")
|
|
305
|
+
if origin in ("simulated", "predicted", "unknown"):
|
|
306
|
+
raise _problem(409, "proxy-evidence", "Not measured data",
|
|
307
|
+
f"This analysis is marked '{origin}'. Only measured or historical data "
|
|
308
|
+
"can be attached as evidence.")
|
|
309
|
+
_, _, _, branch, _ = _load(body.campaign_id)
|
|
310
|
+
if not branch:
|
|
311
|
+
raise _problem(409, "no-ledger", "Campaign has no ledger branch yet", body.campaign_id)
|
|
312
|
+
user = who(request)
|
|
313
|
+
calls = {c["entity"]: c.get("call") for c in r.get("calls") or []}
|
|
314
|
+
_seal(aid, EventType.gate_decision, user, {
|
|
315
|
+
"kind": "analysis_attached", "analysis_id": aid, "revision": doc["revision"],
|
|
316
|
+
"source_sha256": _src(doc).get("sha256"), "evidence_origin": origin,
|
|
317
|
+
"candidate": body.candidate, "calls": calls, "note": body.note,
|
|
318
|
+
"effect": "context only: no campaign verdict is changed by this record"}, branch=branch)
|
|
319
|
+
att = {"campaign_id": body.campaign_id, "candidate": body.candidate, "by": user, "ts": time.time()}
|
|
320
|
+
out = store.update(aid, doc["state"], lambda d: d.setdefault("attachments", []).append(att))
|
|
321
|
+
return _view(out)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _chain_status(aid: str) -> str:
|
|
325
|
+
from proef.adapters.store.sqlite import get_store
|
|
326
|
+
if not Path(_ids.PROVENANCE_DB).exists():
|
|
327
|
+
return "no provenance records for this analysis"
|
|
328
|
+
s = get_store(str(_ids.PROVENANCE_DB))
|
|
329
|
+
branch = f"analysis/{aid}"
|
|
330
|
+
if not s.branch_records(branch):
|
|
331
|
+
return "no provenance records for this analysis"
|
|
332
|
+
if s.verify_chain(branch_id=branch):
|
|
333
|
+
raise _problem(409, "chain-tampered", "Provenance chain tampered",
|
|
334
|
+
"the report is refused while the analysis branch fails verification")
|
|
335
|
+
return "intact (recomputed)"
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
@router.get("/{aid}/report", response_class=HTMLResponse)
|
|
339
|
+
def report(aid: str) -> HTMLResponse:
|
|
340
|
+
from proef.analysis_report import render_report
|
|
341
|
+
doc = _doc(aid)
|
|
342
|
+
if doc.get("result") is None:
|
|
343
|
+
raise _problem(409, "nothing-to-report", "No result yet", "run the analysis first")
|
|
344
|
+
return HTMLResponse(render_report(doc, _chain_status(aid)))
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@router.get("/{aid}/export.csv")
|
|
348
|
+
def export_csv(aid: str) -> Response:
|
|
349
|
+
"""Raw and normalized values side by side, with the call and reason per row."""
|
|
350
|
+
from proef.analysis_profiles import plate_assay
|
|
351
|
+
from proef.analysis_report import export_csv as _csv
|
|
352
|
+
from proef.analysis_report import export_measurements_csv
|
|
353
|
+
doc = _doc(aid)
|
|
354
|
+
if doc.get("result") is None:
|
|
355
|
+
raise _problem(409, "nothing-to-export", "No result yet", "run the analysis first")
|
|
356
|
+
if doc["profile"] == "measurements":
|
|
357
|
+
return Response(export_measurements_csv(doc["result"]), media_type="text/csv",
|
|
358
|
+
headers={"Content-Disposition": f'attachment; filename="{aid}-export.csv"'})
|
|
359
|
+
try:
|
|
360
|
+
cfg = plate_assay.CONFIG_TYPE(**(doc.get("config") or {}))
|
|
361
|
+
lay = _layout(doc)
|
|
362
|
+
records = plate_assay.records_for(Path(_verified_src(doc)["storage_path"]), cfg,
|
|
363
|
+
layout_path=Path(lay) if lay else None)
|
|
364
|
+
except Exception as exc: # noqa: BLE001
|
|
365
|
+
raise _problem(409, "source-unreadable", "Source no longer parses", str(exc)) from None
|
|
366
|
+
return Response(_csv(doc, records, doc["result"]), media_type="text/csv",
|
|
367
|
+
headers={"Content-Disposition": f'attachment; filename="{aid}-export.csv"'})
|