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,428 @@
|
|
|
1
|
+
"""Compound IC50 table + Z', PlateResult and the read_plate entry point."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from proef.fitting import GRID_CEIL_UM, GRID_FLOOR_UM, classify_curve, fit_ic50, fit_ic50_ci
|
|
8
|
+
from proef.labread.common import WELL_RE, _header_score, _is_number, _rows_from_csv, _well_columns, control_class, is_control, sanitize_label
|
|
9
|
+
from proef.labread.formats import _parse_grid, _parse_kinetic, _parse_long, detect_format, extract_instrument_meta
|
|
10
|
+
from proef.labread.layout import _layout_qc, bind_layout
|
|
11
|
+
from proef.labread.pubchem import _parse_pubchem, _pubchem_frame
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def to_pct_inhibition(records: list[dict[str, Any]],
|
|
15
|
+
control_classes: dict[str, str] | None = None) -> bool:
|
|
16
|
+
"""Normalize non-control values to % inhibition against BOTH control
|
|
17
|
+
classes: %I = 100*(blank - v)/(blank - positive). Requires >=2 wells of
|
|
18
|
+
each class and the right orientation; otherwise REFUSES (returns False,
|
|
19
|
+
values untouched) — a fabricated normalized unit is worse than raw RFU.
|
|
20
|
+
Keeps r['value_raw'] alongside the transformed r['value']."""
|
|
21
|
+
neg = [r["value"] for r in records if r.get("control")
|
|
22
|
+
and control_class(r["sample"], control_classes) == "neg"]
|
|
23
|
+
pos = [r["value"] for r in records if r.get("control")
|
|
24
|
+
and control_class(r["sample"], control_classes) == "pos"]
|
|
25
|
+
if len(neg) < 2 or len(pos) < 2:
|
|
26
|
+
return False
|
|
27
|
+
b = sum(neg) / len(neg)
|
|
28
|
+
p = sum(pos) / len(pos)
|
|
29
|
+
if not (b > p): # blanks must out-signal full-inhibition wells
|
|
30
|
+
return False
|
|
31
|
+
for r in records:
|
|
32
|
+
if r.get("control"):
|
|
33
|
+
continue
|
|
34
|
+
r["value_raw"] = r["value"]
|
|
35
|
+
r["value"] = 100.0 * (b - r["value"]) / (b - p)
|
|
36
|
+
return True
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def analyze_records(records: list[dict[str, Any]],
|
|
40
|
+
max_response: float | None = None,
|
|
41
|
+
control_classes: dict[str, str] | None = None) -> dict[str, Any]:
|
|
42
|
+
"""Compound IC50 table + Z' factor. Controls drive Z'; compounds get fits.
|
|
43
|
+
`control_classes`: explicit scientist-confirmed sample->class overrides
|
|
44
|
+
(win over name sniffing)."""
|
|
45
|
+
import math
|
|
46
|
+
|
|
47
|
+
by_sample: dict[str, list[tuple[float | None, float]]] = {}
|
|
48
|
+
for r in records:
|
|
49
|
+
by_sample.setdefault(r["sample"], []).append((r["conc_um"], r["value"]))
|
|
50
|
+
|
|
51
|
+
ctrl_wells = [r for r in records if r["control"]]
|
|
52
|
+
neg_vals = [r["value"] for r in ctrl_wells
|
|
53
|
+
if control_class(r["sample"], control_classes) == "neg"]
|
|
54
|
+
pos_vals = [r["value"] for r in ctrl_wells
|
|
55
|
+
if control_class(r["sample"], control_classes) == "pos"]
|
|
56
|
+
all_vals = [r["value"] for r in records]
|
|
57
|
+
|
|
58
|
+
def _std(v):
|
|
59
|
+
m = sum(v) / len(v)
|
|
60
|
+
return (sum((x - m) ** 2 for x in v) / (len(v) - 1)) ** 0.5 if len(v) > 1 else 0.0
|
|
61
|
+
|
|
62
|
+
zp = float("nan")
|
|
63
|
+
zp_kind = None
|
|
64
|
+
if len(neg_vals) >= 2 and len(pos_vals) >= 2:
|
|
65
|
+
# REAL Z' (Zhang 1999): needs both control classes, nothing else.
|
|
66
|
+
denom = abs(sum(neg_vals) / len(neg_vals) - sum(pos_vals) / len(pos_vals))
|
|
67
|
+
if denom > 0:
|
|
68
|
+
zp = max(-1.0, min(1.0,
|
|
69
|
+
1 - 3 * (_std(neg_vals) + _std(pos_vals)) / denom))
|
|
70
|
+
zp_kind = "real"
|
|
71
|
+
if zp_kind is None and len(ctrl_wells) >= 2:
|
|
72
|
+
ctrl_vals = [r["value"] for r in ctrl_wells]
|
|
73
|
+
sigma_all = _std(all_vals) or 1.0
|
|
74
|
+
spread = abs(sum(all_vals) / len(all_vals) - sum(ctrl_vals) / len(ctrl_vals))
|
|
75
|
+
zp = max(-1.0, min(1.0, 1 - 3 * (_std(ctrl_vals) + 1.0) / (spread + sigma_all)))
|
|
76
|
+
zp_kind = "heuristic"
|
|
77
|
+
|
|
78
|
+
compounds: dict[str, Any] = {}
|
|
79
|
+
for sample, vals in by_sample.items():
|
|
80
|
+
if control_class(sample, control_classes) is not None:
|
|
81
|
+
continue
|
|
82
|
+
pts = [(c, v) for c, v in vals if c is not None]
|
|
83
|
+
flagged = max_response is None
|
|
84
|
+
ic50 = fit_ic50(pts, max_response)
|
|
85
|
+
ci = fit_ic50_ci(pts, max_response) if len(pts) >= 3 else None
|
|
86
|
+
if ci:
|
|
87
|
+
ic50 = ci["ic50"]
|
|
88
|
+
# LEFT-censoring: saturated plateau, transition below the measurable
|
|
89
|
+
# window (estimate or CI floor pinned at the grid edge / rounded to
|
|
90
|
+
# 0.0). A number at the floor is a range statement, not an IC50.
|
|
91
|
+
left_censored = bool(ic50 is not None and pts) and (
|
|
92
|
+
ic50 <= GRID_FLOOR_UM * 1.05
|
|
93
|
+
or bool(ci and ci.get("ci_low") is not None
|
|
94
|
+
and ci["ci_low"] <= GRID_FLOOR_UM * 1.05))
|
|
95
|
+
# RIGHT-censoring at the grid ceiling: an estimate (or CI top)
|
|
96
|
+
# pinned at the search-grid edge is "> range", not a measured IC50.
|
|
97
|
+
at_ceiling = bool(ic50 is not None and pts) and (
|
|
98
|
+
ic50 >= GRID_CEIL_UM * 0.95
|
|
99
|
+
or bool(ci and ci.get("ci_high") is not None
|
|
100
|
+
and ci["ci_high"] >= GRID_CEIL_UM * 0.95))
|
|
101
|
+
compounds[sample] = {
|
|
102
|
+
"ic50_um": ic50,
|
|
103
|
+
"ic50_ci": (ci["ci_low"], ci["ci_high"]) if ci and ci.get("ci_low")
|
|
104
|
+
is not None else None,
|
|
105
|
+
"fit_method": (ci or {}).get("method", "linear-interp"),
|
|
106
|
+
# what the curve model actually is: slope fixed at 1, bottom at 0
|
|
107
|
+
"fit_model": ("1-parameter logistic (IC50 only; slope=1, "
|
|
108
|
+
"bottom=0, top known)" if max_response else
|
|
109
|
+
"2-parameter logistic (IC50 + top; slope=1, "
|
|
110
|
+
"bottom=0)"),
|
|
111
|
+
"n_points": len(pts) or len(vals),
|
|
112
|
+
"right_censored": bool(pts) and (ic50 is None or at_ceiling),
|
|
113
|
+
"left_censored": left_censored,
|
|
114
|
+
"fit_quality": "known-max" if max_response else ("observed-max" if pts else "n/a"),
|
|
115
|
+
"flagged_single_dose": not pts,
|
|
116
|
+
}
|
|
117
|
+
return {"z_prime": (round(zp, 3) if zp == zp else None),
|
|
118
|
+
"z_prime_kind": zp_kind,
|
|
119
|
+
"z_prime_note": (
|
|
120
|
+
"real Z' (Zhang): both control classes, >=2 wells each"
|
|
121
|
+
if zp_kind == "real" else
|
|
122
|
+
"approximation: control spread vs global dynamic range with "
|
|
123
|
+
"a constant positive-control term (real Z' needs a positive "
|
|
124
|
+
"control class); QC heuristic, gated at QC_ZPRIME_FLOOR"),
|
|
125
|
+
"controls_detected": len(ctrl_wells),
|
|
126
|
+
"layout_qc": _layout_qc(records),
|
|
127
|
+
"compounds": compounds}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class PlateResult:
|
|
131
|
+
"""Scientist-facing result of read_plate: records + fits + QC + table."""
|
|
132
|
+
|
|
133
|
+
def __init__(self, path: Path, fmt: str, records: list[dict], analysis: dict,
|
|
134
|
+
response_unit: str | None = None, instrument: dict | None = None,
|
|
135
|
+
channels: list[str] | None = None, reads: int | None = None,
|
|
136
|
+
batch: str = "", regime: dict | None = None):
|
|
137
|
+
self.source = str(path)
|
|
138
|
+
self.format = fmt
|
|
139
|
+
self.records = records
|
|
140
|
+
self.analysis = analysis
|
|
141
|
+
self.instrument = instrument or {}
|
|
142
|
+
self.channels = channels or []
|
|
143
|
+
self.reads = reads
|
|
144
|
+
self.batch = batch
|
|
145
|
+
self.regime = regime
|
|
146
|
+
self.response_unit = response_unit or {
|
|
147
|
+
"npy": "mean pixel intensity", "grid": "well value",
|
|
148
|
+
"xlsx-grid": "well value"}.get(fmt, "instrument response")
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def z_prime(self) -> float | None:
|
|
152
|
+
return self.analysis["z_prime"]
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def z_prime_kind(self) -> str | None:
|
|
156
|
+
return self.analysis.get("z_prime_kind")
|
|
157
|
+
|
|
158
|
+
def table(self) -> str:
|
|
159
|
+
compounds = self.analysis["compounds"]
|
|
160
|
+
single_dose = all(r["flagged_single_dose"] for r in compounds.values())
|
|
161
|
+
if single_dose:
|
|
162
|
+
vals = [self._record_value(r) for r in self.records if not r["control"]]
|
|
163
|
+
med = sorted(vals)[len(vals) // 2] if vals else float("nan")
|
|
164
|
+
return (f"single-dose plate: {len(vals)} wells, median signal {med:.1f}\n"
|
|
165
|
+
"(no concentration series in export — dose-response fit unavailable;\n"
|
|
166
|
+
" pass a concentration-mapped long-format export for IC50 fits)")
|
|
167
|
+
lines = [f"{'compound':<14} {'IC50 (uM)':>10} {'points':>7} note"]
|
|
168
|
+
for sample, r in compounds.items():
|
|
169
|
+
ic50 = (f"{r['ic50_um']:.2f}" if r["ic50_um"] is not None else
|
|
170
|
+
("> range" if r["right_censored"] else "<=0.001"))
|
|
171
|
+
note = ("single-dose" if r["flagged_single_dose"] else
|
|
172
|
+
"right-censored" if r["right_censored"] else
|
|
173
|
+
"left-censored (below measurable window)"
|
|
174
|
+
if r["left_censored"] else r["fit_quality"])
|
|
175
|
+
lines.append(f"{sample:<14} {ic50:>10} {r['n_points']:>7} {note}")
|
|
176
|
+
return "\n".join(lines)
|
|
177
|
+
|
|
178
|
+
def _record_value(self, r: dict) -> float:
|
|
179
|
+
return r["value"]
|
|
180
|
+
|
|
181
|
+
def to_csv(self, path: str | Path) -> Path:
|
|
182
|
+
"""Export the standardized records + fitted IC50s for Excel/GraphPad."""
|
|
183
|
+
import csv as _csv
|
|
184
|
+
from pathlib import Path as _P
|
|
185
|
+
|
|
186
|
+
out = _P(path)
|
|
187
|
+
with out.open("w", newline="") as f:
|
|
188
|
+
w = _csv.writer(f)
|
|
189
|
+
w.writerow(["well", "sample", "conc_um", "value", "control", "ic50_um",
|
|
190
|
+
"batch", "channel", "value_raw"])
|
|
191
|
+
for r in self.records:
|
|
192
|
+
ic50 = self.analysis["compounds"].get(r["sample"], {}).get("ic50_um", "")
|
|
193
|
+
w.writerow([r["well"], r["sample"], r["conc_um"], r["value"],
|
|
194
|
+
r["control"], ic50, r.get("batch", ""),
|
|
195
|
+
r.get("channel", ""), r.get("value_raw", "")])
|
|
196
|
+
return out
|
|
197
|
+
|
|
198
|
+
def curve_svg(self, sample: str, width: int = 560, height: int = 340) -> str:
|
|
199
|
+
"""Dose-response SVG for one compound (from this plate's records)."""
|
|
200
|
+
from proef.plots import dose_response_svg
|
|
201
|
+
|
|
202
|
+
pts = [(r["conc_um"], r["value"]) for r in self.records
|
|
203
|
+
if r["sample"] == sample and r.get("conc_um") is not None]
|
|
204
|
+
comp = self.analysis["compounds"].get(sample, {})
|
|
205
|
+
return dose_response_svg(pts, ic50=comp.get("ic50_um"),
|
|
206
|
+
ci=comp.get("ic50_ci"),
|
|
207
|
+
title=f"{sample} — {self.source}",
|
|
208
|
+
width=width, height=height)
|
|
209
|
+
|
|
210
|
+
def __str__(self) -> str:
|
|
211
|
+
reader = (self.instrument.get("device")
|
|
212
|
+
or self.instrument.get("reader_type")
|
|
213
|
+
or self.instrument.get("application") or "")
|
|
214
|
+
serial = (self.instrument.get("serial_number")
|
|
215
|
+
or self.instrument.get("reader_serial_number") or "")
|
|
216
|
+
ident = f" | reader: {reader}{' (' + serial + ')' if serial else ''}" if reader else ""
|
|
217
|
+
real = self.z_prime_kind == "real"
|
|
218
|
+
zlabel = (f"Z' {self.z_prime} (real: pos+neg control classes)"
|
|
219
|
+
if real else f"Z'~ {self.z_prime} (control-spread heuristic)")
|
|
220
|
+
lq = self.analysis.get("layout_qc") or {}
|
|
221
|
+
if "edge_minus_inner" in lq:
|
|
222
|
+
edge = f" | edge-effect {lq['edge_minus_inner']:+.1f}"
|
|
223
|
+
elif lq: # per-channel layout QC: declare the first channel
|
|
224
|
+
first = next(iter(lq.values()))
|
|
225
|
+
edge = f" | edge-effect {first['edge_minus_inner']:+.1f} ({next(iter(lq))})"
|
|
226
|
+
else:
|
|
227
|
+
edge = ""
|
|
228
|
+
batch = f" | batch: {self.batch}" if self.batch else ""
|
|
229
|
+
if self.regime:
|
|
230
|
+
if self.regime.get("validated"):
|
|
231
|
+
ident += " | regime: pubchem/{} — validated (CS05)".format(
|
|
232
|
+
self.regime["frame"])
|
|
233
|
+
elif self.regime.get("mode") == "shape-only":
|
|
234
|
+
ident += (" | regime: pubchem/{} — SHAPE-ONLY admits "
|
|
235
|
+
"(no IC50 claims; CS06)".format(
|
|
236
|
+
self.regime["frame"]))
|
|
237
|
+
else:
|
|
238
|
+
ident += (" | regime: pubchem/{} — NOT VALIDATED, verdicts "
|
|
239
|
+
"refused (CS06)".format(self.regime["frame"]))
|
|
240
|
+
head = (f"plate: {self.source} [{self.format}] | "
|
|
241
|
+
f"wells: {len(self.records)} | controls: {self.analysis['controls_detected']} | "
|
|
242
|
+
f"{zlabel}{ident}{batch}{edge}")
|
|
243
|
+
return head + "\n" + self.table()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _read_pubchem(path, _unit: dict):
|
|
247
|
+
"""PubChem submitter table: blind by construction; returns the records,
|
|
248
|
+
instrument stub and the normalization-regime fingerprint."""
|
|
249
|
+
rows = _rows_from_csv(path)
|
|
250
|
+
records = _parse_pubchem(rows, _unit) # blind by construction
|
|
251
|
+
frame = _pubchem_frame(records) if records else "unknown"
|
|
252
|
+
instrument = {"deposition": "PubChem submitter table",
|
|
253
|
+
"n_doses": _unit.get("n_doses")}
|
|
254
|
+
regime = {"dialect": "pubchem", "frame": frame,
|
|
255
|
+
"validated": frame == "external-reference",
|
|
256
|
+
"validation_source": ("CS05 (case-studies/05-paper-pilot): "
|
|
257
|
+
"98.9% decisive agreement, "
|
|
258
|
+
"0 false actives"
|
|
259
|
+
if frame == "external-reference"
|
|
260
|
+
else "CS06 (case-studies/06-ncats-"
|
|
261
|
+
"deposit): FAILED reproduction "
|
|
262
|
+
"(rho=0.107)")}
|
|
263
|
+
return records, instrument, regime
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _read_npy(path) -> PlateResult:
|
|
267
|
+
"""Imaging tiles (.npy): analyzed by the imaging plate reader."""
|
|
268
|
+
from proef.adapters.lab.imaging import analyze_plate, ImagingPlateReader
|
|
269
|
+
dev = ImagingPlateReader(seed=0)
|
|
270
|
+
plate = {p.stem: {"image": __import__("numpy").load(p), "sample_id": p.stem,
|
|
271
|
+
"conc_um": None, "artifact": ""}
|
|
272
|
+
for p in sorted(path.parent.glob("*.npy"))}
|
|
273
|
+
analysis = analyze_plate(plate)
|
|
274
|
+
records = [{"well": w, "sample": sanitize_label(v["sample_id"]),
|
|
275
|
+
"conc_um": v["conc_um"],
|
|
276
|
+
"value": v["image"].mean(),
|
|
277
|
+
"control": is_control(v["sample_id"])}
|
|
278
|
+
for w, v in plate.items()]
|
|
279
|
+
return PlateResult(path, "npy", records, analysis)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _read_xlsx(path, _unit: dict, cycles: str):
|
|
283
|
+
"""Excel export: sniff long / kinetic / grid on the extracted rows.
|
|
284
|
+
Returns (format label, records, instrument)."""
|
|
285
|
+
try:
|
|
286
|
+
import openpyxl
|
|
287
|
+
except ImportError as exc:
|
|
288
|
+
raise ImportError("pip install openpyxl to read .xlsx exports") from exc
|
|
289
|
+
ws = openpyxl.load_workbook(path, data_only=True).active
|
|
290
|
+
rows = [[("" if c is None else str(c)) for c in row] for row in ws.iter_rows(values_only=True)]
|
|
291
|
+
# reuse the CSV sniffing on the extracted rows
|
|
292
|
+
long_score = max((_header_score(r)[0] for r in rows[:20]), default=0)
|
|
293
|
+
kinetic_hit = any(_well_columns(r) for r in rows)
|
|
294
|
+
grid_hit = any(r and WELL_RE.match(r[0] + "1") and
|
|
295
|
+
all(_is_number(c) for c in r[1:] if c.strip())
|
|
296
|
+
for r in rows)
|
|
297
|
+
instrument = extract_instrument_meta(rows)
|
|
298
|
+
if long_score >= 3:
|
|
299
|
+
records = _parse_long(rows, _unit)
|
|
300
|
+
fmt = "xlsx-long"
|
|
301
|
+
elif kinetic_hit:
|
|
302
|
+
records = _parse_kinetic(rows, _unit, cycles=cycles)
|
|
303
|
+
fmt = "xlsx-kinetic"
|
|
304
|
+
elif grid_hit:
|
|
305
|
+
records = _parse_grid(rows)
|
|
306
|
+
fmt = "xlsx-grid"
|
|
307
|
+
else:
|
|
308
|
+
records = []
|
|
309
|
+
fmt = "xlsx-unknown"
|
|
310
|
+
return fmt, records, instrument
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _refuse_regime(analysis: dict, records: list, regime: dict) -> None:
|
|
314
|
+
"""Regime gate (CS06): an unvalidated normalization frame gets no
|
|
315
|
+
dose-response claims; self-normalized deposits get SHAPE-ONLY ones."""
|
|
316
|
+
analysis["regime_refusal"] = True
|
|
317
|
+
if regime["frame"] == "self-normalized":
|
|
318
|
+
# SHAPE-ONLY ADMISSION (CS06 re-admission ladder): absolute
|
|
319
|
+
# IC50 semantics need an external reference this frame does
|
|
320
|
+
# not have; shape classes are invariant under affine
|
|
321
|
+
# renormalization, so they are the ONLY claims made here.
|
|
322
|
+
bys: dict[str, list[tuple[float, float]]] = {}
|
|
323
|
+
for r in records:
|
|
324
|
+
bys.setdefault(r["sample"], []).append((r["conc_um"],
|
|
325
|
+
r["value"]))
|
|
326
|
+
analysis["shape_only"] = {s: classify_curve(p)
|
|
327
|
+
for s, p in bys.items()}
|
|
328
|
+
regime["mode"] = "shape-only"
|
|
329
|
+
regime["note"] = (
|
|
330
|
+
"REGIME SHAPE-ONLY — absolute IC50/verdict claims are "
|
|
331
|
+
"refused on self-normalized deposits (no external "
|
|
332
|
+
"reference); concentration-dependence SHAPE classes "
|
|
333
|
+
"(rise-complete/partial/flat/noisy/falling) with "
|
|
334
|
+
"within-curve midpoints are admitted and labeled. "
|
|
335
|
+
"Never merge shape admits with validated IC50 verdicts.")
|
|
336
|
+
else: # unknown frame: no claim at all survives
|
|
337
|
+
regime["note"] = (
|
|
338
|
+
"REGIME NOT VALIDATED — no dose-response assertions issued "
|
|
339
|
+
"on this normalization frame (CS06: fixed-reference "
|
|
340
|
+
"crossing rules do not port to unvalidated deposits). "
|
|
341
|
+
"Research mode (assert_regimes=False) is for declared "
|
|
342
|
+
"reproduction studies, never campaign verdicts.")
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def read_plate(path: str | Path, max_response: float | None = None,
|
|
346
|
+
layout: str | Path | None = None,
|
|
347
|
+
cycles: str = "last",
|
|
348
|
+
normalize: str | None = None,
|
|
349
|
+
assert_regimes: bool = True) -> PlateResult:
|
|
350
|
+
"""Auto-detect, parse, fit and QC an instrument/lab result file.
|
|
351
|
+
|
|
352
|
+
layout: optional well->(sample, conc_um) plate-layout file to join onto
|
|
353
|
+
grid/kinetic exports that carry no compound identity (dose-response fits
|
|
354
|
+
become possible). cycles: kinetic reduction per well — 'last' (endpoint),
|
|
355
|
+
'first', or 'mean'. normalize='pct_inhibition': rescale non-control
|
|
356
|
+
values against the plate's own blank + full-inhibition controls.
|
|
357
|
+
|
|
358
|
+
Regime gate (CS06's lesson): deposited percent tables are fingerprinted
|
|
359
|
+
for their normalization frame; only frames validated by an external
|
|
360
|
+
reproduction (pubchem/external-reference — CS05, 98.9% agreement,
|
|
361
|
+
zero false actives) get dose-response assertions. Self-normalized
|
|
362
|
+
qHTS deposits REFUSE the surface — no fabricated verdicts, and the
|
|
363
|
+
refusal names its regime. assert_regimes=False is a RESEARCH bypass
|
|
364
|
+
(used by the CS06 negative-result study); never for campaign verdicts.
|
|
365
|
+
"""
|
|
366
|
+
path = Path(path)
|
|
367
|
+
if not path.exists():
|
|
368
|
+
raise FileNotFoundError(path)
|
|
369
|
+
fmt = detect_format(path)
|
|
370
|
+
_unit: dict = {}
|
|
371
|
+
instrument: dict = {}
|
|
372
|
+
regime: dict | None = None
|
|
373
|
+
if fmt == "long":
|
|
374
|
+
rows = _rows_from_csv(path)
|
|
375
|
+
records = _parse_long(rows, _unit)
|
|
376
|
+
instrument = extract_instrument_meta(rows)
|
|
377
|
+
elif fmt == "grid":
|
|
378
|
+
rows = _rows_from_csv(path)
|
|
379
|
+
records = _parse_grid(rows)
|
|
380
|
+
instrument = extract_instrument_meta(rows)
|
|
381
|
+
elif fmt == "kinetic":
|
|
382
|
+
rows = _rows_from_csv(path)
|
|
383
|
+
records = _parse_kinetic(rows, _unit, cycles=cycles)
|
|
384
|
+
instrument = extract_instrument_meta(rows)
|
|
385
|
+
elif fmt == "pubchem":
|
|
386
|
+
records, instrument, regime = _read_pubchem(path, _unit)
|
|
387
|
+
elif fmt == "npy":
|
|
388
|
+
return _read_npy(path)
|
|
389
|
+
elif fmt == "xlsx":
|
|
390
|
+
fmt, records, instrument = _read_xlsx(path, _unit, cycles)
|
|
391
|
+
else:
|
|
392
|
+
raise ValueError(f"unrecognized plate format: {path}")
|
|
393
|
+
|
|
394
|
+
if layout is not None:
|
|
395
|
+
bind_layout(records, layout)
|
|
396
|
+
channels = _unit.get("channels") or []
|
|
397
|
+
if len(channels) > 1: # keep channels as separate samples, never pooled
|
|
398
|
+
first = channels[0]
|
|
399
|
+
for r in records:
|
|
400
|
+
ch = r.get("channel") or first
|
|
401
|
+
if ch != first:
|
|
402
|
+
r["sample"] = f"{r['sample']}·{sanitize_label(ch, 12)}"
|
|
403
|
+
|
|
404
|
+
if normalize == "pct_inhibition":
|
|
405
|
+
if not to_pct_inhibition(records):
|
|
406
|
+
raise ValueError(
|
|
407
|
+
"cannot normalize to %inhibition: need >=2 blank (negative-"
|
|
408
|
+
"class) AND >=2 full-inhibition (positive-class) control "
|
|
409
|
+
"wells with blank signal > positive — raw values kept")
|
|
410
|
+
_unit["unit"] = "% inhibition"
|
|
411
|
+
|
|
412
|
+
batch = " · ".join(x for x in (
|
|
413
|
+
instrument.get("plate_number") or "",
|
|
414
|
+
instrument.get("date") or "", instrument.get("time") or "") if x)
|
|
415
|
+
for r in records:
|
|
416
|
+
if batch:
|
|
417
|
+
r.setdefault("batch", batch) # batch/date: first-class covariate
|
|
418
|
+
|
|
419
|
+
refuse = regime is not None and not regime["validated"] and assert_regimes
|
|
420
|
+
analysis = analyze_records([] if refuse else records, max_response)
|
|
421
|
+
if refuse:
|
|
422
|
+
_refuse_regime(analysis, records, regime)
|
|
423
|
+
|
|
424
|
+
analysis_out = analysis
|
|
425
|
+
return PlateResult(path, fmt, records, analysis_out,
|
|
426
|
+
response_unit=_unit.get("unit"), instrument=instrument,
|
|
427
|
+
channels=channels, reads=_unit.get("reads"), batch=batch,
|
|
428
|
+
regime=regime)
|
proef/labread/common.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Shared constants and cell/row helpers for the plate-reader parsers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import csv
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
WELL_RE = re.compile(r"^([A-P])(\d{1,2})$", re.IGNORECASE)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# QC acceptance floor for the plate-level z'-style heuristic below. Named in
|
|
14
|
+
# ONE place because it gates verdicts everywhere (watch, autoloop).
|
|
15
|
+
QC_ZPRIME_FLOOR = 0.5
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
SYNONYMS: dict[str, list[str]] = {
|
|
19
|
+
"well": ["well", "position", "pos", "site", "well_id", "wellid"],
|
|
20
|
+
"sample": ["sample", "sample_id", "sampleid", "compound", "compound_id",
|
|
21
|
+
"name", "id", "molecule", "analyte"],
|
|
22
|
+
"conc": ["conc", "concentration", "conc_um", "concentration_um", "conc(uM)",
|
|
23
|
+
"dose", "uM"],
|
|
24
|
+
"value": ["value", "rfu", "od", "abs", "absorbance", "reading", "signal",
|
|
25
|
+
"measurement", "counts", "response", "value_mean", "median"],
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
CONTROL_IDS = {"ctrl", "control", "blank", "neg", "negative", "vehicle",
|
|
30
|
+
"ntc", "standard", "dmso", "medium", "mock"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
POS_CONTROL_IDS = {"pos", "positive", "max_inhibition", "full_inhibition",
|
|
34
|
+
"dead", "killed"}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def is_control(sample_id: str) -> bool:
|
|
38
|
+
return control_class(sample_id) is not None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def control_class(sample_id: str, overrides: dict[str, str] | None = None
|
|
42
|
+
) -> str | None:
|
|
43
|
+
"""'pos' | 'neg' | None. A real Z' needs BOTH classes; conflating them
|
|
44
|
+
would print a QC number that means nothing. `overrides` maps explicit
|
|
45
|
+
sample ids to classes — a scientist-confirmed classification wins over
|
|
46
|
+
label sniffing."""
|
|
47
|
+
if overrides:
|
|
48
|
+
o = overrides.get(str(sample_id).strip())
|
|
49
|
+
if o in ("pos", "neg"):
|
|
50
|
+
return o
|
|
51
|
+
s = sample_id.strip().lower().replace(" ", "_")
|
|
52
|
+
if any(s.startswith(c) or s == c for c in POS_CONTROL_IDS):
|
|
53
|
+
return "pos"
|
|
54
|
+
if any(s.startswith(c) or s == c for c in CONTROL_IDS):
|
|
55
|
+
return "neg"
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def sanitize_label(text: Any, cap: int = 60) -> str:
|
|
60
|
+
"""Instrument-file labels are UNTRUSTED data: strip control characters,
|
|
61
|
+
collapse whitespace, cap length. They flow into logs, prompts and table
|
|
62
|
+
keys — they must never carry structure or instructions."""
|
|
63
|
+
s = "".join(ch for ch in str(text) if ch.isprintable())
|
|
64
|
+
s = " ".join(s.split())
|
|
65
|
+
return s[:cap]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _rows_from_csv(path: Path) -> list[list[str]]:
|
|
69
|
+
# vendor exports are frequently Windows-1252/latin-1 (°, µ in metadata);
|
|
70
|
+
# a strict utf-8 read of e.g. a BioTek Gen5 .txt throws and the file is
|
|
71
|
+
# mislabeled 'unknown'. And the delimiter must be CHOSEN, not guessed
|
|
72
|
+
# first-come: a tab-delimited Gen5 line containing 'tht:440/30,485/20'
|
|
73
|
+
# 'succeeds' under the comma dialect as width-3 confetti. Pick the
|
|
74
|
+
# (encoding, delimiter) whose MEDIAN row width is largest.
|
|
75
|
+
best_rows: list[list[str]] = []
|
|
76
|
+
best_width = 0
|
|
77
|
+
for encoding in ("utf-8-sig", "latin-1"):
|
|
78
|
+
for dialect in (",", "\t", ";"):
|
|
79
|
+
try:
|
|
80
|
+
with path.open(newline="", encoding=encoding) as f:
|
|
81
|
+
rows = [r for r in csv.reader(f, delimiter=dialect)
|
|
82
|
+
if any(c.strip() for c in r)]
|
|
83
|
+
except (OSError, UnicodeDecodeError, csv.Error):
|
|
84
|
+
continue
|
|
85
|
+
if not rows:
|
|
86
|
+
continue
|
|
87
|
+
widths = sorted(len(r) for r in rows)
|
|
88
|
+
median = widths[len(widths) // 2]
|
|
89
|
+
if median > best_width:
|
|
90
|
+
best_rows, best_width = rows, median
|
|
91
|
+
return best_rows if best_width >= 2 else []
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _header_score(header: list[str]) -> tuple[int, dict[str, int]]:
|
|
95
|
+
"""How many recognized columns, and their index map."""
|
|
96
|
+
mapping: dict[str, int] = {}
|
|
97
|
+
for i, col in enumerate(header):
|
|
98
|
+
c = col.strip().lower()
|
|
99
|
+
for field, names in SYNONYMS.items():
|
|
100
|
+
if field in mapping:
|
|
101
|
+
continue
|
|
102
|
+
if any(c == n or c.replace(" ", "_") == n or n in c for n in names):
|
|
103
|
+
mapping[field] = i
|
|
104
|
+
break
|
|
105
|
+
return len(mapping), mapping
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _is_number(s: str) -> bool:
|
|
109
|
+
try:
|
|
110
|
+
float(s)
|
|
111
|
+
return True
|
|
112
|
+
except ValueError:
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
MISSING_TOKENS = {"?", "??", "???", "?????", "----", "---", "*", "n/a", "na",
|
|
117
|
+
"nan", "none", "null", "over range", "error", "overflow"}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
_CHANNEL_RE = re.compile(r"[A-Za-z0-9_\-]{2,24}:[A-Za-z0-9_/,\.\-]{2,24}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _is_missing(cell: str) -> bool:
|
|
124
|
+
c = cell.strip().lower()
|
|
125
|
+
return (not c or c in MISSING_TOKENS or set(c) <= {"?", "-"})
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _channel_from_cell(cell: str) -> str:
|
|
129
|
+
m = _CHANNEL_RE.search(cell)
|
|
130
|
+
return m.group(0) if m else ""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _well_columns(row: list[str]) -> list[tuple[int, str]]:
|
|
134
|
+
"""Longest contiguous run (>=8) of well-name cells: the kinetic header.
|
|
135
|
+
|
|
136
|
+
Returns (column_index, WELL) pairs. Column-major layout lets us map data
|
|
137
|
+
rows back to wells even when Time/Temp/Cycle prefix columns vary — and
|
|
138
|
+
ignores trailing summary columns like Gen5's 'Max V [...]'.
|
|
139
|
+
"""
|
|
140
|
+
hits = [(i, c.strip().upper()) for i, c in enumerate(row)
|
|
141
|
+
if WELL_RE.match(c.strip())]
|
|
142
|
+
best: list[tuple[int, str]] = []
|
|
143
|
+
cur: list[tuple[int, str]] = []
|
|
144
|
+
for item in hits:
|
|
145
|
+
if cur and item[0] == cur[-1][0] + 1:
|
|
146
|
+
cur.append(item)
|
|
147
|
+
else:
|
|
148
|
+
if len(cur) > len(best):
|
|
149
|
+
best = cur
|
|
150
|
+
cur = [item]
|
|
151
|
+
if len(cur) > len(best):
|
|
152
|
+
best = cur
|
|
153
|
+
return best if len(best) >= 8 else []
|