proef 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- proef/__init__.py +25 -0
- proef/acquisition.py +244 -0
- proef/ad.py +159 -0
- proef/adapters/__init__.py +0 -0
- proef/adapters/admet.py +196 -0
- proef/adapters/bio/__init__.py +0 -0
- proef/adapters/bio/rdkit_ops.py +52 -0
- proef/adapters/bio/safety_rules.json +146 -0
- proef/adapters/bio/seq_alerts.py +79 -0
- proef/adapters/bio/structure_score.py +85 -0
- proef/adapters/bio/tox_alerts.py +99 -0
- proef/adapters/data/__init__.py +0 -0
- proef/adapters/data/admet.py +62 -0
- proef/adapters/data/chembl.py +110 -0
- proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
- proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
- proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
- proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
- proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
- proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
- proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
- proef/adapters/data/moleculenet.py +60 -0
- proef/adapters/databases/__init__.py +0 -0
- proef/adapters/databases/chembl_gates.py +121 -0
- proef/adapters/databases/chembl_lookup.py +35 -0
- proef/adapters/databases/open_targets.py +102 -0
- proef/adapters/databases/pubmed.py +94 -0
- proef/adapters/devices/__init__.py +0 -0
- proef/adapters/devices/ezo_ph.py +251 -0
- proef/adapters/devices/hcs_microscope.py +143 -0
- proef/adapters/devices/lcms.py +123 -0
- proef/adapters/devices/scheduler.py +84 -0
- proef/adapters/devices/sila2.py +134 -0
- proef/adapters/genomics/alphagenome.py +146 -0
- proef/adapters/lab/__init__.py +0 -0
- proef/adapters/lab/bioprocess.py +32 -0
- proef/adapters/lab/devices.py +170 -0
- proef/adapters/lab/imaging.py +226 -0
- proef/adapters/lab/mhs_driver.py +124 -0
- proef/adapters/lab/opentrons.py +222 -0
- proef/adapters/lab/ot2_sim.py +174 -0
- proef/adapters/lab/plate_reader_share.py +108 -0
- proef/adapters/lab/protein_design.py +199 -0
- proef/adapters/lab/recording.py +119 -0
- proef/adapters/lab/replay.py +107 -0
- proef/adapters/lab/simulator.py +282 -0
- proef/adapters/lab/synthesis.py +92 -0
- proef/adapters/models/__init__.py +0 -0
- proef/adapters/models/anthropic_provider.py +157 -0
- proef/adapters/models/assayloop_ranker.py +67 -0
- proef/adapters/models/from_env.py +93 -0
- proef/adapters/models/gp_policy.py +93 -0
- proef/adapters/models/gp_policy_gp.py +36 -0
- proef/adapters/models/llm_policy.py +187 -0
- proef/adapters/models/openai_compat.py +150 -0
- proef/adapters/models/sklearn_policy.py +65 -0
- proef/adapters/retrosynthesis.py +247 -0
- proef/adapters/sandbox/__init__.py +20 -0
- proef/adapters/sandbox/agentenv.py +145 -0
- proef/adapters/sandbox/docker.py +217 -0
- proef/adapters/sandbox/local.py +164 -0
- proef/adapters/sandbox/opensandbox.py +122 -0
- proef/adapters/store/__init__.py +0 -0
- proef/adapters/store/sqlite.py +207 -0
- proef/adaptive.py +108 -0
- proef/advisory.py +76 -0
- proef/analysis_profiles/__init__.py +8 -0
- proef/analysis_profiles/measurements.py +266 -0
- proef/analysis_profiles/plate_assay.py +316 -0
- proef/analysis_report.py +195 -0
- proef/analysis_store.py +183 -0
- proef/anchor.py +154 -0
- proef/api/app.py +107 -0
- proef/api/launch.py +170 -0
- proef/api/v1/__init__.py +29 -0
- proef/api/v1/analyses.py +367 -0
- proef/api/v1/campaigns.py +802 -0
- proef/api/v1/deps.py +10 -0
- proef/api/v1/evals.py +16 -0
- proef/api/v1/evidence.py +132 -0
- proef/api/v1/governance.py +35 -0
- proef/api/v1/inbox.py +119 -0
- proef/api/v1/lab.py +110 -0
- proef/api/v1/pauses.py +77 -0
- proef/api/v1/programs.py +397 -0
- proef/api/v1/results.py +147 -0
- proef/api/v1/schemas.py +932 -0
- proef/api/v1/system.py +79 -0
- proef/api/v1/trees.py +216 -0
- proef/api/wizard_sessions.py +253 -0
- proef/approvals.py +102 -0
- proef/assays/__init__.py +15 -0
- proef/assays/dls.py +114 -0
- proef/assays/dsf.py +81 -0
- proef/assays/elisa.py +58 -0
- proef/assays/properties.py +65 -0
- proef/assays/simulate.py +157 -0
- proef/audit.py +152 -0
- proef/autoloop.py +1620 -0
- proef/benchmark.py +442 -0
- proef/campaign_fsm.py +151 -0
- proef/citations.py +141 -0
- proef/cli.py +1249 -0
- proef/connect.py +74 -0
- proef/core/__init__.py +0 -0
- proef/core/contracts/__init__.py +35 -0
- proef/core/contracts/analysis.py +100 -0
- proef/core/contracts/models.py +395 -0
- proef/core/device_card.py +125 -0
- proef/core/hypothesis.py +720 -0
- proef/core/interfaces.py +164 -0
- proef/core/registry.py +123 -0
- proef/core/safety.py +324 -0
- proef/core/workflow.py +159 -0
- proef/critic.py +62 -0
- proef/demo.py +164 -0
- proef/derivation.py +128 -0
- proef/diary.py +301 -0
- proef/eln.py +87 -0
- proef/evals/__init__.py +1 -0
- proef/evals/hallucination.py +86 -0
- proef/evals/harness.py +358 -0
- proef/evals/orchestration.py +254 -0
- proef/evals/tasks.py +1010 -0
- proef/evals/toolcalls.py +425 -0
- proef/experiment.py +172 -0
- proef/experiment_analysis.py +114 -0
- proef/experiments/__init__.py +0 -0
- proef/experiments/grounding_exp.py +689 -0
- proef/figures.py +218 -0
- proef/fitting.py +309 -0
- proef/fixtures.py +140 -0
- proef/flywheel.py +125 -0
- proef/followup.py +126 -0
- proef/governance.py +290 -0
- proef/groundedness.py +361 -0
- proef/grounding.py +202 -0
- proef/hypothesis_agent.py +369 -0
- proef/ingest.py +157 -0
- proef/instruments.json +173 -0
- proef/interpret.py +95 -0
- proef/kinetic.py +102 -0
- proef/labread/__init__.py +45 -0
- proef/labread/analysis.py +428 -0
- proef/labread/common.py +153 -0
- proef/labread/formats.py +190 -0
- proef/labread/layout.py +168 -0
- proef/labread/pubchem.py +179 -0
- proef/labselect.py +431 -0
- proef/materials.py +140 -0
- proef/mcp_instrument.py +396 -0
- proef/mcp_server.py +283 -0
- proef/modality.py +111 -0
- proef/model_guard.py +245 -0
- proef/output_blocks.py +183 -0
- proef/paths.py +32 -0
- proef/physfail.py +55 -0
- proef/plan.py +160 -0
- proef/plots.py +123 -0
- proef/predictors.py +217 -0
- proef/probes.py +79 -0
- proef/problem_tree.py +581 -0
- proef/program.py +308 -0
- proef/protocol_design.py +42 -0
- proef/proxy.py +78 -0
- proef/readiness.py +259 -0
- proef/reliability.py +49 -0
- proef/report.py +117 -0
- proef/reproduce.py +310 -0
- proef/reviewer.py +254 -0
- proef/sandbox_session.py +247 -0
- proef/sandboxd.py +109 -0
- proef/scaffold.py +195 -0
- proef/series.py +327 -0
- proef/skills.py +203 -0
- proef/sweep.py +83 -0
- proef/taste.py +177 -0
- proef/templates/confirmatory-followup.json +34 -0
- proef/templates/dose-response-screen.json +39 -0
- proef/templates/sar-exploration.json +38 -0
- proef/templates.py +124 -0
- proef/toolkit.py +433 -0
- proef/toolloop.py +133 -0
- proef/tools.py +441 -0
- proef/tpp.py +185 -0
- proef/views/__init__.py +14 -0
- proef/views/counts.py +102 -0
- proef/views/experiment.py +154 -0
- proef/views/ids.py +49 -0
- proef/views/narrative.py +294 -0
- proef/views/pipeline.py +370 -0
- proef/vision.py +165 -0
- proef/watch.py +790 -0
- proef/wizard_chain.py +25 -0
- proef/wizard_store.py +373 -0
- proef-0.2.0.dist-info/METADATA +662 -0
- proef-0.2.0.dist-info/RECORD +200 -0
- proef-0.2.0.dist-info/WHEEL +4 -0
- proef-0.2.0.dist-info/entry_points.txt +14 -0
- proef-0.2.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Analysis profiles — domain interpretation behind the generic lifecycle.
|
|
2
|
+
|
|
3
|
+
Each profile owns parsing, preview, QC, and result interpretation for ONE
|
|
4
|
+
kind of experimental data. The generic lifecycle (experiment_analysis)
|
|
5
|
+
dispatches to exactly the profile the scientist selected; nothing here
|
|
6
|
+
leaks into shared contracts.
|
|
7
|
+
"""
|
|
8
|
+
from proef.analysis_profiles import measurements, plate_assay # noqa: F401
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Measurements analysis profile: a table of values per sample, judged against a gate.
|
|
2
|
+
|
|
3
|
+
The SECOND analysis profile, added because a real second use case needs it: property data that is not a dose
|
|
4
|
+
series (ionic conductivity, solubility, yield, tensile strength, a pH reading). One row per measurement; repeated
|
|
5
|
+
rows for a sample are its replicates. Per sample it reports n, mean, sd and a 95% interval on the mean,
|
|
6
|
+
and, only when a gate is registered, a call by the SAME rule as everywhere else: an interval that straddles the
|
|
7
|
+
gate abstains.
|
|
8
|
+
|
|
9
|
+
What it cannot do, and says so: there is no curve, no plate, so no Z' and no control-based QC. One measurement gives
|
|
10
|
+
no interval and therefore no call. The interval assumes roughly normal replicate scatter on the arithmetic scale
|
|
11
|
+
(a quantity that spans orders of magnitude should be entered as its log10), which is stated in the result.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import csv
|
|
16
|
+
import io
|
|
17
|
+
import math
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from pydantic import BaseModel, ConfigDict
|
|
22
|
+
|
|
23
|
+
from proef.core.contracts.analysis import (AnalysisDiagnostic, AnalysisState, EvidenceOrigin, PreliminaryCall)
|
|
24
|
+
from proef.core.hypothesis import SuccessCriteria
|
|
25
|
+
|
|
26
|
+
PROFILE_NAME = "measurements"
|
|
27
|
+
PROFILE_VERSION = 1
|
|
28
|
+
|
|
29
|
+
SAMPLE_NAMES = ("sample", "sample_id", "sample id", "id", "candidate", "compound", "material", "name", "specimen",
|
|
30
|
+
"entity", "composition", "formulation", "batch_id")
|
|
31
|
+
VALUE_NAMES = ("value", "measurement", "result", "reading", "response", "y", "mean")
|
|
32
|
+
NOT_A_VALUE = ("replicate", "rep", "run", "batch", "n", "index", "row", "plate", "well", "trial", "repeat", "date", "time")
|
|
33
|
+
PLATE_WORDS = {"well", "wells", "conc", "concentration", "dose", "plate", "rfu", "rlu", "od", "absorbance", "fluorescence",
|
|
34
|
+
"luminescence", "cycle", "kinetic"}
|
|
35
|
+
|
|
36
|
+
MIN_REPLICATES = 3 # the repo-wide rule (fitting.replicate_ci): fewer than 3 readings carry no honest interval
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MeasurementsConfig(BaseModel):
|
|
40
|
+
metric: str = "value"
|
|
41
|
+
direction: str = "min" # min = lower is better
|
|
42
|
+
threshold: float | None = None # registered gate; None => estimates only
|
|
43
|
+
unit: str | None = None
|
|
44
|
+
sample_column: str | None = None # None => inferred, and shown for confirmation
|
|
45
|
+
value_column: str | None = None
|
|
46
|
+
evidence_origin: EvidenceOrigin = EvidenceOrigin.measured
|
|
47
|
+
|
|
48
|
+
model_config = ConfigDict(extra="forbid")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
CONFIG_TYPE = MeasurementsConfig
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _engine_version() -> str:
|
|
55
|
+
try:
|
|
56
|
+
from importlib.metadata import version
|
|
57
|
+
return version("proef")
|
|
58
|
+
except Exception: # noqa: BLE001
|
|
59
|
+
return "unknown"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _table(path: Path) -> tuple[list[str], list[list[str]], str]:
|
|
63
|
+
"""(header, rows, delimiter) of a delimited text file. XLSX is read when openpyxl is available."""
|
|
64
|
+
if path.suffix.lower() == ".xlsx":
|
|
65
|
+
try:
|
|
66
|
+
import openpyxl
|
|
67
|
+
except ImportError as exc:
|
|
68
|
+
raise ImportError("reading .xlsx needs openpyxl; export the sheet as CSV instead") from exc
|
|
69
|
+
ws = openpyxl.load_workbook(path, read_only=True, data_only=True).worksheets[0]
|
|
70
|
+
rows = [["" if c is None else str(c) for c in r] for r in ws.iter_rows(values_only=True)]
|
|
71
|
+
rows = [r for r in rows if any(c.strip() for c in r)]
|
|
72
|
+
if not rows:
|
|
73
|
+
raise ValueError("the sheet is empty")
|
|
74
|
+
return [h.strip() for h in rows[0]], rows[1:], "xlsx"
|
|
75
|
+
text = path.read_text(encoding="utf-8-sig", errors="replace")
|
|
76
|
+
sample = text[:4096]
|
|
77
|
+
try:
|
|
78
|
+
delim = csv.Sniffer().sniff(sample, delimiters=",;\t|").delimiter
|
|
79
|
+
except csv.Error:
|
|
80
|
+
delim = "\t" if "\t" in sample else ","
|
|
81
|
+
rows = [r for r in csv.reader(io.StringIO(text), delimiter=delim) if any(c.strip() for c in r)]
|
|
82
|
+
if len(rows) < 2:
|
|
83
|
+
raise ValueError("a measurements table needs a header row and at least one data row")
|
|
84
|
+
return [h.strip() for h in rows[0]], rows[1:], delim
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _num(s: str) -> float | None:
|
|
88
|
+
try:
|
|
89
|
+
x = float(s.strip().replace(",", "") if s.count(",") == 1 and "." in s else s.strip())
|
|
90
|
+
except (ValueError, AttributeError):
|
|
91
|
+
return None
|
|
92
|
+
return x if math.isfinite(x) else None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def looks_like_measurements(path: Path) -> bool:
|
|
96
|
+
"""True only for a plain table: a sample column, numeric values, and nothing that says plate or dose.
|
|
97
|
+
Anything with plate vocabulary in a header (well, conc, dose, plate, RFU...) or a plate-grid shape (numeric
|
|
98
|
+
column headers 1..12) stays a plate, so a real instrument export is never read as a measurements table."""
|
|
99
|
+
import re
|
|
100
|
+
try:
|
|
101
|
+
header, rows, _ = _table(path)
|
|
102
|
+
except Exception: # noqa: BLE001
|
|
103
|
+
return False
|
|
104
|
+
words = {w for h in header for w in re.findall(r"[a-z]+", h.lower())}
|
|
105
|
+
if words & PLATE_WORDS:
|
|
106
|
+
return False
|
|
107
|
+
if sum(bool(re.fullmatch(r"\d{1,2}", h.strip())) for h in header) >= 4: # a plate grid: columns 1, 2, 3...
|
|
108
|
+
return False
|
|
109
|
+
cols = _columns(header, rows, None, None)
|
|
110
|
+
return cols["sample"] is not None and bool(cols["value_candidates"])
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _columns(header: list[str], rows: list[list[str]], sample_col: str | None, value_col: str | None) -> dict[str, Any]:
|
|
114
|
+
low = [h.lower() for h in header]
|
|
115
|
+
numeric = [i for i in range(len(header)) if sum(_num(r[i]) is not None for r in rows if i < len(r)) >= max(1, 0.6 * len(rows))]
|
|
116
|
+
|
|
117
|
+
def pick(names, explicit):
|
|
118
|
+
if explicit and explicit in header:
|
|
119
|
+
return header.index(explicit)
|
|
120
|
+
for n in names:
|
|
121
|
+
if n in low:
|
|
122
|
+
return low.index(n)
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
s = pick(SAMPLE_NAMES, sample_col)
|
|
126
|
+
if s is None:
|
|
127
|
+
text_cols = [i for i in range(len(header)) if i not in numeric]
|
|
128
|
+
s = text_cols[0] if text_cols else None
|
|
129
|
+
v = pick(VALUE_NAMES, value_col)
|
|
130
|
+
cands = [i for i in numeric if i != s and not any(low[i] == t or low[i].startswith(t + "_") for t in NOT_A_VALUE)]
|
|
131
|
+
if v is None and len(cands) == 1:
|
|
132
|
+
v = cands[0]
|
|
133
|
+
return {"sample": s, "value": v, "value_candidates": cands}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _read(path: Path, cfg: MeasurementsConfig) -> dict[str, Any]:
|
|
137
|
+
header, rows, delim = _table(path)
|
|
138
|
+
cols = _columns(header, rows, cfg.sample_column, cfg.value_column)
|
|
139
|
+
out: dict[str, Any] = {"header": header, "delimiter": delim, "cols": cols, "values": {}, "dropped": 0, "n_rows": len(rows)}
|
|
140
|
+
if cols["sample"] is None or cols["value"] is None:
|
|
141
|
+
return out
|
|
142
|
+
s, v = cols["sample"], cols["value"]
|
|
143
|
+
for r in rows:
|
|
144
|
+
name = r[s].strip() if s < len(r) else ""
|
|
145
|
+
x = _num(r[v]) if v < len(r) else None
|
|
146
|
+
if not name or x is None:
|
|
147
|
+
out["dropped"] += 1
|
|
148
|
+
continue
|
|
149
|
+
out["values"].setdefault(name, []).append(x)
|
|
150
|
+
return out
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _stats(vals: list[float]) -> dict[str, Any]:
|
|
154
|
+
"""n, mean, sd and the 95% interval of the mean, from the SAME function the campaigns use for a property metric
|
|
155
|
+
(Student-t below 10 readings, a deterministic bootstrap from 10), and None below 3 readings."""
|
|
156
|
+
from proef.fitting import replicate_ci
|
|
157
|
+
n = len(vals)
|
|
158
|
+
mean = sum(vals) / n
|
|
159
|
+
sd = math.sqrt(sum((x - mean) ** 2 for x in vals) / (n - 1)) if n > 1 else None
|
|
160
|
+
ci = replicate_ci(vals)
|
|
161
|
+
return {"n": n, "mean": mean, "sd": sd, "ci": list(ci) if ci else None, "values": vals}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def preview(source: Path, cfg: MeasurementsConfig, layout_path: Path | None = None) -> dict[str, Any]:
|
|
165
|
+
r = _read(source, cfg)
|
|
166
|
+
header, cols = r["header"], r["cols"]
|
|
167
|
+
diags: list[AnalysisDiagnostic] = []
|
|
168
|
+
D = lambda sev, code, msg: diags.append(AnalysisDiagnostic(severity=sev, code=code, message=msg)) # noqa: E731
|
|
169
|
+
needs: list[str] = []
|
|
170
|
+
if cols["sample"] is None:
|
|
171
|
+
D("blocker", "no_sample_column", "no sample column found: name the column that identifies each sample")
|
|
172
|
+
needs.append("sample_column")
|
|
173
|
+
if cols["value"] is None:
|
|
174
|
+
if len(cols["value_candidates"]) > 1:
|
|
175
|
+
D("blocker", "ambiguous_value_column", "several numeric columns could be the measurement: "
|
|
176
|
+
+ ", ".join(header[i] for i in cols["value_candidates"]) + ". Choose one.")
|
|
177
|
+
else:
|
|
178
|
+
D("blocker", "no_value_column", "no numeric measurement column found")
|
|
179
|
+
needs.append("value_column")
|
|
180
|
+
samples = sorted(r["values"])
|
|
181
|
+
for s_ in samples:
|
|
182
|
+
if len(r["values"][s_]) < MIN_REPLICATES:
|
|
183
|
+
D("warning", "too_few_measurements", f"{s_}: {len(r['values'][s_])} measurement(s). An interval needs at least "
|
|
184
|
+
f"{MIN_REPLICATES}, so there will be no call for it")
|
|
185
|
+
if r["dropped"]:
|
|
186
|
+
D("warning", "rows_dropped", f"{r['dropped']} row(s) had a missing sample or a non-numeric value and were left out")
|
|
187
|
+
if samples and all(len(v) >= MIN_REPLICATES for v in r["values"].values()):
|
|
188
|
+
D("info", "replicates", f"{len(samples)} samples, {min(len(v) for v in r['values'].values())} to "
|
|
189
|
+
f"{max(len(v) for v in r['values'].values())} measurements each")
|
|
190
|
+
D("info", "no_qc", "No plate, so no Z′. Trust rests on the replicates.")
|
|
191
|
+
state = AnalysisState.needs_mapping if any(d.severity == "blocker" for d in diags) else AnalysisState.preview_ready
|
|
192
|
+
return {
|
|
193
|
+
"profile": PROFILE_NAME, "profile_version": PROFILE_VERSION, "state": state.value, "kind": "measurements",
|
|
194
|
+
"format": f"measurements table ({'xlsx' if r['delimiter'] == 'xlsx' else repr(r['delimiter'])[1:-1] if r['delimiter'] != ',' else 'csv'})",
|
|
195
|
+
"n_wells": 0, "n_measurements": sum(len(v) for v in r["values"].values()), "z_prime": None, "z_prime_kind": None,
|
|
196
|
+
"controls_detected": 0, "samples": samples, "has_doses": False,
|
|
197
|
+
"columns": {"sample": header[cols["sample"]] if cols["sample"] is not None else None,
|
|
198
|
+
"value": header[cols["value"]] if cols["value"] is not None else None,
|
|
199
|
+
"candidates": [header[i] for i in cols["value_candidates"]], "all": header},
|
|
200
|
+
"diagnostics": [d.model_dump() for d in diags], "needs_confirmation": needs,
|
|
201
|
+
"evidence_origin": cfg.evidence_origin.value,
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def analyze(source: Path, cfg: MeasurementsConfig, source_sha256: str | None = None,
|
|
206
|
+
layout_path: Path | None = None) -> dict[str, Any]:
|
|
207
|
+
r = _read(source, cfg)
|
|
208
|
+
if r["cols"]["sample"] is None or r["cols"]["value"] is None or not r["values"]:
|
|
209
|
+
raise ValueError("cannot analyze: confirm the sample and value columns first")
|
|
210
|
+
criteria = SuccessCriteria(metric=cfg.metric, direction=cfg.direction, threshold=cfg.threshold) if cfg.threshold is not None else None
|
|
211
|
+
compounds: dict[str, dict] = {}
|
|
212
|
+
calls: list[PreliminaryCall] = []
|
|
213
|
+
for sample in sorted(r["values"]):
|
|
214
|
+
st = _stats(r["values"][sample])
|
|
215
|
+
compounds[sample] = st
|
|
216
|
+
if criteria is None:
|
|
217
|
+
continue
|
|
218
|
+
if st["ci"] is None:
|
|
219
|
+
calls.append(PreliminaryCall(entity=sample, call="no_call", value=st["mean"],
|
|
220
|
+
reason=f"{st['n']} measurement(s): an interval needs at least {MIN_REPLICATES}, so no call"))
|
|
221
|
+
continue
|
|
222
|
+
call = criteria.classify(st["mean"], (st["ci"][0], st["ci"][1]))
|
|
223
|
+
calls.append(PreliminaryCall(
|
|
224
|
+
entity=sample, call=call, value=st["mean"], ci=(st["ci"][0], st["ci"][1]),
|
|
225
|
+
reason="95% interval fully clears the gate" if call != "inconclusive"
|
|
226
|
+
else "95% interval straddles the registered gate: honest abstention"))
|
|
227
|
+
return {
|
|
228
|
+
"profile": PROFILE_NAME, "profile_version": PROFILE_VERSION, "kind": "measurements",
|
|
229
|
+
"state": AnalysisState.analyzed.value, "format": "measurements table", "engine_version": _engine_version(),
|
|
230
|
+
"n_measurements": sum(len(v) for v in r["values"].values()), "compounds": compounds,
|
|
231
|
+
"calls": [c.model_dump() for c in calls], "threshold_registered": cfg.threshold is not None,
|
|
232
|
+
"metric": cfg.metric, "direction": cfg.direction, "unit": cfg.unit, "evidence_origin": cfg.evidence_origin.value,
|
|
233
|
+
"method": "mean with a 95% interval over the replicates (Student-t below 10 readings, bootstrap from 10), arithmetic scale; at least 3 readings per sample",
|
|
234
|
+
"columns": {"sample": r["header"][r["cols"]["sample"]], "value": r["header"][r["cols"]["value"]]},
|
|
235
|
+
"z_prime": None, "qc_hold": False, "source_sha256": source_sha256,
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def records_for(path: Path, cfg: MeasurementsConfig, layout_path: Path | None = None) -> list[dict[str, Any]]:
|
|
240
|
+
r = _read(path, cfg)
|
|
241
|
+
return [{"sample": s, "value": x} for s, vals in sorted(r["values"].items()) for x in vals]
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def as_read_result(path: Path):
|
|
245
|
+
"""A table of measurements in the shape the campaign agent reads a plate in: `.records` of {sample, value}
|
|
246
|
+
(no concentrations, no controls), no Z', and no fitted compounds. `no_plate_qc` tells the verdict code that
|
|
247
|
+
plate QC does not apply here (recorded as 'not applicable', never as a pass or a fail)."""
|
|
248
|
+
from types import SimpleNamespace
|
|
249
|
+
r = _read(path, MeasurementsConfig())
|
|
250
|
+
if r["cols"]["sample"] is None or r["cols"]["value"] is None:
|
|
251
|
+
raise ValueError("this table has no single sample column and measurement column; use Analyze to choose them")
|
|
252
|
+
records = [{"well": "", "sample": s, "conc_um": None, "value": x, "control": False}
|
|
253
|
+
for s, vals in sorted(r["values"].items()) for x in vals]
|
|
254
|
+
return SimpleNamespace(records=records, z_prime=None, z_prime_kind=None, analysis={"compounds": {}},
|
|
255
|
+
format="measurements", channels=[], response_unit=None, instrument={}, regime=None, batch=None,
|
|
256
|
+
kind="measurements", no_plate_qc=True)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def read_plate_or_table(path: Path, max_response: float | None = None):
|
|
260
|
+
"""What a campaign reads a results file with: a plain table of measurements goes through the measurements
|
|
261
|
+
reader; anything else is a plate. (A plain table must never be fed to the plate reader: it would take a
|
|
262
|
+
replicate column for well coordinates.)"""
|
|
263
|
+
if Path(path).suffix.lower() in (".csv", ".tsv", ".txt") and looks_like_measurements(Path(path)):
|
|
264
|
+
return as_read_result(Path(path))
|
|
265
|
+
from proef.labread import read_plate
|
|
266
|
+
return read_plate(path, max_response=max_response)
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Plate-reader assay analysis profile.
|
|
2
|
+
|
|
3
|
+
The FIRST analysis profile: wraps `proef.labread` (auto-detect, parse,
|
|
4
|
+
normalize, Hill fit with bootstrap CI, Z′, regime gate) behind the generic
|
|
5
|
+
analysis lifecycle. Everything plate-specific — wells, control classes,
|
|
6
|
+
%inhibition, dose-response, censoring — stays HERE; the shared contract
|
|
7
|
+
never learns these words.
|
|
8
|
+
|
|
9
|
+
Honesty rules carried over unchanged:
|
|
10
|
+
- a CI straddling the registered threshold ABSTAINS (inconclusive);
|
|
11
|
+
- a fit without a usable CI (unstable bootstrap / linear-interp fallback)
|
|
12
|
+
can NOT earn a decisive call;
|
|
13
|
+
- right-censored / single-dose entities get `no_call` with the reason, not
|
|
14
|
+
a fabricated number;
|
|
15
|
+
- the regime gate (CS06) refuses absolute claims on unvalidated
|
|
16
|
+
normalization frames — `assert_regimes` is NOT configurable here;
|
|
17
|
+
research bypasses belong to declared reproduction studies in case-study
|
|
18
|
+
scripts, never to the scientist workflow.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from pydantic import BaseModel, ConfigDict
|
|
26
|
+
|
|
27
|
+
from proef.core.contracts.analysis import (AnalysisDiagnostic,
|
|
28
|
+
AnalysisState, EvidenceOrigin,
|
|
29
|
+
PreliminaryCall)
|
|
30
|
+
from proef.core.hypothesis import SuccessCriteria
|
|
31
|
+
|
|
32
|
+
PROFILE_NAME = "plate_assay"
|
|
33
|
+
PROFILE_VERSION = 1
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PlateAssayConfig(BaseModel):
|
|
37
|
+
"""Scientist-confirmed interpretation of ONE plate. Every field the
|
|
38
|
+
engine would otherwise infer silently is explicit here."""
|
|
39
|
+
metric: str = "ic50_um"
|
|
40
|
+
direction: str = "min" # min = lower IC50 is better
|
|
41
|
+
threshold: float | None = None # registered gate; None => estimates only
|
|
42
|
+
cycles: str = "last" # kinetic reduction: last | first | mean
|
|
43
|
+
normalize: str | None = None # None | "pct_inhibition"
|
|
44
|
+
max_response: float | None = None # None => 3-param observed-max fit
|
|
45
|
+
positive_controls: list[str] = [] # sample ids FORCED into the pos class
|
|
46
|
+
negative_controls: list[str] = [] # sample ids FORCED into the neg class
|
|
47
|
+
evidence_origin: EvidenceOrigin = EvidenceOrigin.measured
|
|
48
|
+
|
|
49
|
+
model_config = ConfigDict(extra="forbid")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# profile seam: the generic lifecycle reads this (see experiment_analysis)
|
|
53
|
+
CONFIG_TYPE = PlateAssayConfig
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _engine_version() -> str:
|
|
57
|
+
try:
|
|
58
|
+
from importlib.metadata import version
|
|
59
|
+
return version("proef")
|
|
60
|
+
except Exception: # noqa: BLE001 — editable installs may lack metadata
|
|
61
|
+
return "unknown"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _override_map(cfg: PlateAssayConfig) -> dict[str, str] | None:
|
|
65
|
+
"""Scientist-confirmed sample->class map (None when unset)."""
|
|
66
|
+
if not (cfg.positive_controls or cfg.negative_controls):
|
|
67
|
+
return None
|
|
68
|
+
m = {s.strip(): "pos" for s in cfg.positive_controls}
|
|
69
|
+
m.update({s.strip(): "neg" for s in cfg.negative_controls})
|
|
70
|
+
return m
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _read(path: Path, cfg: PlateAssayConfig,
|
|
74
|
+
layout_path: Path | None = None):
|
|
75
|
+
"""read_plate + scientist-confirmed control classes + optional layout
|
|
76
|
+
join, folded in. The override map re-classes wells; normalization
|
|
77
|
+
refusal is RECORDED as a refusal (no silent fall-back to raw values
|
|
78
|
+
dressed as normalized); refused regimes keep their refusal."""
|
|
79
|
+
from proef import labread
|
|
80
|
+
r = labread.read_plate(
|
|
81
|
+
path, max_response=cfg.max_response, cycles=cfg.cycles,
|
|
82
|
+
normalize=None if _override_map(cfg) else cfg.normalize,
|
|
83
|
+
layout=layout_path, assert_regimes=True)
|
|
84
|
+
overrides = _override_map(cfg)
|
|
85
|
+
if not overrides:
|
|
86
|
+
return r
|
|
87
|
+
for rec in r.records:
|
|
88
|
+
if str(rec.get("sample", "")).strip() in overrides:
|
|
89
|
+
rec["control"] = True
|
|
90
|
+
if r.regime and not r.regime.get("validated"):
|
|
91
|
+
return r
|
|
92
|
+
if cfg.normalize == "pct_inhibition":
|
|
93
|
+
if not labread.to_pct_inhibition(r.records,
|
|
94
|
+
control_classes=overrides):
|
|
95
|
+
r.analysis = dict(labread.analyze_records(
|
|
96
|
+
[], cfg.max_response, control_classes=overrides))
|
|
97
|
+
r.analysis["normalization_refused"] = True
|
|
98
|
+
r.analysis["normalization_note"] = (
|
|
99
|
+
"requested %inhibition normalization is impossible on this "
|
|
100
|
+
"plate (needs >=2 wells of BOTH control classes with blank "
|
|
101
|
+
"signal > positive) — fits refused rather than run on "
|
|
102
|
+
"mislabeled raw values")
|
|
103
|
+
return r
|
|
104
|
+
r.analysis = labread.analyze_records(r.records, cfg.max_response,
|
|
105
|
+
control_classes=overrides)
|
|
106
|
+
return r
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def records_for(path: Path, cfg: PlateAssayConfig,
|
|
110
|
+
layout_path: Path | None = None) -> list[dict[str, Any]]:
|
|
111
|
+
"""The exact well records behind a stored analysis (same fold-ins as
|
|
112
|
+
_read), for CSV export. Never mutates the source."""
|
|
113
|
+
return _read(path, cfg, layout_path).records
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _wells(r, cfg: PlateAssayConfig) -> list[dict[str, Any]]:
|
|
117
|
+
"""Compact well view for the plate map: identity, mapping coverage,
|
|
118
|
+
control CLASS (not just is-control), channel. Wells without geometry
|
|
119
|
+
(deposits) simply have no row."""
|
|
120
|
+
from proef import labread
|
|
121
|
+
overrides = _override_map(cfg)
|
|
122
|
+
out = []
|
|
123
|
+
for rec in r.records:
|
|
124
|
+
well = str(rec.get("well") or "")
|
|
125
|
+
if not well:
|
|
126
|
+
continue
|
|
127
|
+
sample = str(rec.get("sample", ""))
|
|
128
|
+
out.append({"well": well, "sample": sample,
|
|
129
|
+
"conc_um": rec.get("conc_um"), "value": rec["value"],
|
|
130
|
+
"control": labread.control_class(sample, overrides),
|
|
131
|
+
"channel": rec.get("channel")})
|
|
132
|
+
return out
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def preview(source: Path, cfg: PlateAssayConfig,
|
|
136
|
+
layout_path: Path | None = None) -> dict[str, Any]:
|
|
137
|
+
"""Parse-level interpretation ONLY: no fits published, no verdicts.
|
|
138
|
+
|
|
139
|
+
Returns the preview payload + the profile's opinion of the session
|
|
140
|
+
state (a regime refusal or missing controls holds the session, it
|
|
141
|
+
does not fabricate a pass)."""
|
|
142
|
+
r = _read(source, cfg, layout_path)
|
|
143
|
+
diags: list[AnalysisDiagnostic] = []
|
|
144
|
+
if r.format in ("unknown", "xlsx-unknown"):
|
|
145
|
+
diags.append(AnalysisDiagnostic(
|
|
146
|
+
severity="blocker", code="unknown_format",
|
|
147
|
+
message="export format not recognized — no rows parsed"))
|
|
148
|
+
if not r.records:
|
|
149
|
+
diags.append(AnalysisDiagnostic(
|
|
150
|
+
severity="blocker", code="no_wells",
|
|
151
|
+
message="no interpretable wells in the export"))
|
|
152
|
+
if r.z_prime is None:
|
|
153
|
+
diags.append(AnalysisDiagnostic(
|
|
154
|
+
severity="warning", code="no_controls",
|
|
155
|
+
message="no control wells detected — QC unavailable; confirm "
|
|
156
|
+
"control classes or supply positive/negative controls"))
|
|
157
|
+
elif r.z_prime_kind != "real":
|
|
158
|
+
diags.append(AnalysisDiagnostic(
|
|
159
|
+
severity="warning", code="heuristic_zprime",
|
|
160
|
+
message="control-spread heuristic Z'~ (real Z' needs BOTH "
|
|
161
|
+
"control classes, >=2 wells each)"))
|
|
162
|
+
has_doses = any(rec.get("conc_um") is not None for rec in r.records)
|
|
163
|
+
if not has_doses and r.format not in ("pubchem",):
|
|
164
|
+
diags.append(AnalysisDiagnostic(
|
|
165
|
+
severity="warning", code="no_layout",
|
|
166
|
+
message="no concentrations bound — pass a plate-layout file "
|
|
167
|
+
"for dose-response fits"))
|
|
168
|
+
needs: list[str] = []
|
|
169
|
+
if cfg.positive_controls or cfg.negative_controls:
|
|
170
|
+
known = {str(rec.get("sample", "")).strip() for rec in r.records}
|
|
171
|
+
for name in cfg.positive_controls + cfg.negative_controls:
|
|
172
|
+
if name.strip() not in known:
|
|
173
|
+
needs.append(name)
|
|
174
|
+
if needs:
|
|
175
|
+
diags.append(AnalysisDiagnostic(
|
|
176
|
+
severity="blocker", code="unknown_control_ids",
|
|
177
|
+
message=f"configured control ids not present on the plate: "
|
|
178
|
+
f"{sorted(set(needs))}"))
|
|
179
|
+
if r.regime and not r.regime.get("validated"):
|
|
180
|
+
state = AnalysisState.unsupported_regime
|
|
181
|
+
elif any(d.severity == "blocker" for d in diags):
|
|
182
|
+
state = AnalysisState.needs_mapping
|
|
183
|
+
else:
|
|
184
|
+
state = AnalysisState.preview_ready
|
|
185
|
+
return {
|
|
186
|
+
"profile": PROFILE_NAME,
|
|
187
|
+
"profile_version": PROFILE_VERSION,
|
|
188
|
+
"state": (state.value if hasattr(state, "value") else state),
|
|
189
|
+
"format": r.format,
|
|
190
|
+
"n_wells": len(r.records),
|
|
191
|
+
"channels": list(r.channels),
|
|
192
|
+
"response_unit": r.response_unit,
|
|
193
|
+
"instrument": dict(r.instrument or {}),
|
|
194
|
+
"z_prime": r.z_prime,
|
|
195
|
+
"z_prime_kind": r.z_prime_kind,
|
|
196
|
+
"controls_detected": r.analysis.get("controls_detected", 0),
|
|
197
|
+
"regime": dict(r.regime) if r.regime else None,
|
|
198
|
+
"samples": sorted({str(rec.get("sample")) for rec in r.records
|
|
199
|
+
if not rec.get("control")}),
|
|
200
|
+
"wells": _wells(r, cfg),
|
|
201
|
+
"has_doses": has_doses,
|
|
202
|
+
"diagnostics": [d.model_dump() for d in diags],
|
|
203
|
+
"needs_confirmation": ["control_classes"] if r.z_prime is None else [],
|
|
204
|
+
"evidence_origin": cfg.evidence_origin.value,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def analyze(source: Path, cfg: PlateAssayConfig,
|
|
209
|
+
source_sha256: str | None = None,
|
|
210
|
+
layout_path: Path | None = None) -> dict[str, Any]:
|
|
211
|
+
"""Deterministic analysis + threshold-conditional preliminary calls.
|
|
212
|
+
|
|
213
|
+
Same bytes + same config => same payload. Verdicts exist ONLY where a
|
|
214
|
+
threshold was registered and the regime/CI physics support a call."""
|
|
215
|
+
r = _read(source, cfg, layout_path)
|
|
216
|
+
from proef import labread
|
|
217
|
+
|
|
218
|
+
compounds = r.analysis.get("compounds", {})
|
|
219
|
+
regime_refused = bool(r.analysis.get("regime_refusal"))
|
|
220
|
+
norm_refused = bool(r.analysis.get("normalization_refused"))
|
|
221
|
+
criteria = None
|
|
222
|
+
if cfg.threshold is not None:
|
|
223
|
+
criteria = SuccessCriteria(metric=cfg.metric, direction=cfg.direction,
|
|
224
|
+
threshold=cfg.threshold)
|
|
225
|
+
|
|
226
|
+
calls: list[PreliminaryCall] = []
|
|
227
|
+
results: dict[str, dict[str, Any]] = {}
|
|
228
|
+
top_dose: dict[str, float] = {}
|
|
229
|
+
for rec in r.records:
|
|
230
|
+
c = rec.get("conc_um")
|
|
231
|
+
s = str(rec.get("sample"))
|
|
232
|
+
if c is not None and (s not in top_dose or c > top_dose[s]):
|
|
233
|
+
top_dose[s] = float(c)
|
|
234
|
+
for sample, comp in compounds.items():
|
|
235
|
+
results[sample] = comp
|
|
236
|
+
if criteria is None or regime_refused or norm_refused:
|
|
237
|
+
continue
|
|
238
|
+
ic50, ci = comp.get("ic50_um"), comp.get("ic50_ci")
|
|
239
|
+
usable_ci = ci is not None and ci[0] is not None and ci[1] is not None
|
|
240
|
+
if comp.get("flagged_single_dose"):
|
|
241
|
+
calls.append(PreliminaryCall(
|
|
242
|
+
entity=sample, call="no_call",
|
|
243
|
+
reason="single-dose — no concentration series"))
|
|
244
|
+
elif comp.get("right_censored") or ic50 is None:
|
|
245
|
+
calls.append(PreliminaryCall(
|
|
246
|
+
entity=sample, call="no_call",
|
|
247
|
+
reason="right-censored: no 50% crossing inside the tested "
|
|
248
|
+
"window — a range statement, not a number"))
|
|
249
|
+
elif top_dose.get(sample) and ic50 > 2.0 * top_dose[sample]:
|
|
250
|
+
calls.append(PreliminaryCall(
|
|
251
|
+
entity=sample, call="no_call", value=ic50,
|
|
252
|
+
reason="no 50% crossing inside the tested window — the fit "
|
|
253
|
+
"extrapolates past the top dose; a range statement, "
|
|
254
|
+
"not a number"))
|
|
255
|
+
elif not usable_ci:
|
|
256
|
+
calls.append(PreliminaryCall(
|
|
257
|
+
entity=sample, call="inconclusive",
|
|
258
|
+
value=ic50,
|
|
259
|
+
reason="fit without a usable CI (unstable bootstrap or "
|
|
260
|
+
"interpolation fallback) — cannot earn a decisive "
|
|
261
|
+
"call"))
|
|
262
|
+
else:
|
|
263
|
+
call = criteria.classify(ic50, (ci[0], ci[1]))
|
|
264
|
+
calls.append(PreliminaryCall(
|
|
265
|
+
entity=sample, call=call, value=ic50, ci=(ci[0], ci[1]),
|
|
266
|
+
reason=("CI fully clears the gate" if call != "inconclusive"
|
|
267
|
+
else "95% CI straddles the registered gate — "
|
|
268
|
+
"honest abstention")))
|
|
269
|
+
|
|
270
|
+
zp = r.z_prime
|
|
271
|
+
# `zp == zp` is the NaN guard: a NaN Z' cannot gate (NaN < x is False,
|
|
272
|
+
# but the explicit check keeps the intent auditable)
|
|
273
|
+
qc_hold = (zp is not None and zp == zp
|
|
274
|
+
and zp < labread.QC_ZPRIME_FLOOR
|
|
275
|
+
and not regime_refused and not norm_refused)
|
|
276
|
+
state = AnalysisState.analyzed
|
|
277
|
+
if regime_refused:
|
|
278
|
+
state = AnalysisState.unsupported_regime
|
|
279
|
+
elif qc_hold:
|
|
280
|
+
state = AnalysisState.qc_hold
|
|
281
|
+
|
|
282
|
+
payload: dict[str, Any] = {
|
|
283
|
+
"profile": PROFILE_NAME,
|
|
284
|
+
"profile_version": PROFILE_VERSION,
|
|
285
|
+
"state": (state.value if hasattr(state, "value") else state),
|
|
286
|
+
"format": r.format,
|
|
287
|
+
"n_wells": len(r.records),
|
|
288
|
+
"response_unit": r.response_unit,
|
|
289
|
+
"instrument": dict(r.instrument or {}),
|
|
290
|
+
"batch": r.batch,
|
|
291
|
+
"z_prime": r.z_prime,
|
|
292
|
+
"z_prime_kind": r.z_prime_kind,
|
|
293
|
+
"z_prime_note": r.analysis.get("z_prime_note"),
|
|
294
|
+
"layout_qc": r.analysis.get("layout_qc"),
|
|
295
|
+
"controls_detected": r.analysis.get("controls_detected", 0),
|
|
296
|
+
"regime": dict(r.regime) if r.regime else None,
|
|
297
|
+
"regime_refused": regime_refused,
|
|
298
|
+
"normalization_refused": norm_refused,
|
|
299
|
+
"normalization_note": r.analysis.get("normalization_note"),
|
|
300
|
+
"shape_only": r.analysis.get("shape_only"),
|
|
301
|
+
"engine_version": _engine_version(),
|
|
302
|
+
"compounds": results,
|
|
303
|
+
"wells": _wells(r, cfg),
|
|
304
|
+
"calls": [c.model_dump() for c in calls],
|
|
305
|
+
"threshold_registered": cfg.threshold is not None,
|
|
306
|
+
"metric": cfg.metric,
|
|
307
|
+
"direction": cfg.direction,
|
|
308
|
+
"evidence_origin": cfg.evidence_origin.value,
|
|
309
|
+
"source_sha256": source_sha256,
|
|
310
|
+
"qc_hold": qc_hold,
|
|
311
|
+
}
|
|
312
|
+
if not compounds and not regime_refused:
|
|
313
|
+
payload["diagnostics"] = [AnalysisDiagnostic(
|
|
314
|
+
severity="blocker", code="analysis_empty",
|
|
315
|
+
message="analysis produced no compound results").model_dump()]
|
|
316
|
+
return payload
|