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/labread/formats.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Instrument-export format detection and the long / grid / kinetic parsers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from proef.adapters.lab.simulator import parse_concentration_um
|
|
9
|
+
from proef.labread.common import WELL_RE, _channel_from_cell, _header_score, _is_missing, _is_number, _rows_from_csv, _well_columns, is_control, sanitize_label
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def detect_format(path: Path) -> str:
|
|
13
|
+
"""'long' | 'kinetic' | 'grid' | 'npy' | 'xlsx' | 'unknown'."""
|
|
14
|
+
suffix = path.suffix.lower()
|
|
15
|
+
if suffix == ".npy":
|
|
16
|
+
return "npy"
|
|
17
|
+
if suffix == ".xlsx":
|
|
18
|
+
return "xlsx"
|
|
19
|
+
rows = _rows_from_csv(path)
|
|
20
|
+
if not rows:
|
|
21
|
+
return "unknown"
|
|
22
|
+
if rows and rows[0] and rows[0][0].strip() == "PUBCHEM_RESULT_TAG":
|
|
23
|
+
return "pubchem"
|
|
24
|
+
best = 0
|
|
25
|
+
for row in rows[:20]:
|
|
26
|
+
if any(WELL_RE.match(c) for c in row):
|
|
27
|
+
continue # grid data row
|
|
28
|
+
score, _ = _header_score(row)
|
|
29
|
+
best = max(best, score)
|
|
30
|
+
if best >= 3:
|
|
31
|
+
return "long"
|
|
32
|
+
for row in rows:
|
|
33
|
+
if _well_columns(row):
|
|
34
|
+
return "kinetic"
|
|
35
|
+
# grid: any row where first cell is a plate row letter and rest are numbers
|
|
36
|
+
for row in rows:
|
|
37
|
+
if row and WELL_RE.match(row[0] + "1") and len(row) > 2 and all(
|
|
38
|
+
_is_number(c) for c in row[1:] if c.strip()):
|
|
39
|
+
return "grid"
|
|
40
|
+
return "unknown"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _parse_long(rows: list[list[str]], unit_out: dict | None = None
|
|
44
|
+
) -> list[dict[str, Any]]:
|
|
45
|
+
((_, mapping), header_i) = max(((_header_score(r), i) for i, r in enumerate(rows[:20])),
|
|
46
|
+
key=lambda t: (t[0][0], -t[1]))
|
|
47
|
+
if unit_out is not None and "value" in mapping:
|
|
48
|
+
hdr = rows[header_i][mapping["value"]].strip()
|
|
49
|
+
unit_out["unit"] = sanitize_label(hdr, 24) or "instrument response"
|
|
50
|
+
records: list[dict[str, Any]] = []
|
|
51
|
+
for row in rows[header_i + 1:]:
|
|
52
|
+
if len(row) <= max(mapping.values(), default=0):
|
|
53
|
+
continue
|
|
54
|
+
well = row[mapping["well"]].strip() if "well" in mapping else ""
|
|
55
|
+
if well and not WELL_RE.match(well):
|
|
56
|
+
continue
|
|
57
|
+
sample = (sanitize_label(row[mapping["sample"]]) if "sample" in
|
|
58
|
+
mapping else (well or ""))
|
|
59
|
+
value = row[mapping["value"]].strip() if "value" in mapping else ""
|
|
60
|
+
if not _is_number(value):
|
|
61
|
+
continue
|
|
62
|
+
conc = None
|
|
63
|
+
if ("conc" in mapping and len(row) > mapping["conc"]
|
|
64
|
+
and row[mapping["conc"]].strip()):
|
|
65
|
+
# blank conc means UNKNOWN, not the simulator's default 10 uM
|
|
66
|
+
conc = parse_concentration_um(row[mapping["conc"]])
|
|
67
|
+
records.append({"well": well.upper(), "sample": sample, "conc_um": conc,
|
|
68
|
+
"value": float(value), "control": is_control(sample)})
|
|
69
|
+
return records
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _parse_grid(rows: list[list[str]]) -> list[dict[str, Any]]:
|
|
73
|
+
records: list[dict[str, Any]] = []
|
|
74
|
+
for row in rows:
|
|
75
|
+
m = WELL_RE.match((row[0] + "1"))
|
|
76
|
+
if not m or not row[1:]:
|
|
77
|
+
continue
|
|
78
|
+
row_letter = m.group(1).upper()
|
|
79
|
+
if not all(_is_number(c) for c in row[1:] if c.strip()):
|
|
80
|
+
continue
|
|
81
|
+
for j, cell in enumerate(row[1:], start=1):
|
|
82
|
+
if not cell.strip():
|
|
83
|
+
continue
|
|
84
|
+
records.append({"well": f"{row_letter}{j}", "sample": f"{row_letter}{j}",
|
|
85
|
+
"conc_um": None, "value": float(cell), "control": False})
|
|
86
|
+
return records
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _parse_kinetic(rows: list[list[str]], unit_out: dict | None = None,
|
|
90
|
+
cycles: str = "last") -> list[dict[str, Any]]:
|
|
91
|
+
"""Flatten kinetic well-column tables to one record per (channel, well).
|
|
92
|
+
|
|
93
|
+
cycles='last' is endpoint behaviour (default), 'first' initial rate,
|
|
94
|
+
'mean' the average over reads. A table ends at the next well header or
|
|
95
|
+
channel-label row; all-missing rows inside a table are skipped, not fatal.
|
|
96
|
+
"""
|
|
97
|
+
import statistics
|
|
98
|
+
|
|
99
|
+
blocks: dict[str, dict[str, list[float]]] = {}
|
|
100
|
+
label = ""
|
|
101
|
+
i = 0
|
|
102
|
+
while i < len(rows):
|
|
103
|
+
cells = [c.strip() for c in rows[i]]
|
|
104
|
+
nonempty = [c for c in cells if c]
|
|
105
|
+
if len(nonempty) == 1 and _channel_from_cell(nonempty[0]) == nonempty[0]:
|
|
106
|
+
label = nonempty[0]
|
|
107
|
+
i += 1
|
|
108
|
+
continue
|
|
109
|
+
cols = _well_columns(rows[i])
|
|
110
|
+
if cols:
|
|
111
|
+
chan = label or next(
|
|
112
|
+
(c for c in cells[:cols[0][0]] if _channel_from_cell(c)),
|
|
113
|
+
"") or "response"
|
|
114
|
+
if chan == "response" and _channel_from_cell(label):
|
|
115
|
+
chan = _channel_from_cell(label)
|
|
116
|
+
wellmap = blocks.setdefault(chan, {})
|
|
117
|
+
j = i + 1
|
|
118
|
+
while j < len(rows):
|
|
119
|
+
r = [c.strip() for c in rows[j]]
|
|
120
|
+
if _well_columns(r):
|
|
121
|
+
break
|
|
122
|
+
if len([c for c in r if c]) == 1 and _channel_from_cell(
|
|
123
|
+
next(c for c in r if c)):
|
|
124
|
+
break # next block's label row
|
|
125
|
+
present = [(k, w, r[k]) for k, w in cols if k < len(r)
|
|
126
|
+
and not _is_missing(r[k])]
|
|
127
|
+
if not any(_is_number(v) for _, _, v in present):
|
|
128
|
+
j += 1
|
|
129
|
+
continue
|
|
130
|
+
for k, w, v in present:
|
|
131
|
+
if _is_number(v):
|
|
132
|
+
wellmap.setdefault(w, []).append(float(v))
|
|
133
|
+
j += 1
|
|
134
|
+
i = j
|
|
135
|
+
continue
|
|
136
|
+
i += 1
|
|
137
|
+
|
|
138
|
+
records: list[dict[str, Any]] = []
|
|
139
|
+
for chan, wellmap in blocks.items():
|
|
140
|
+
for w, vs in sorted(wellmap.items()):
|
|
141
|
+
v = (vs[-1] if cycles == "last" else vs[0] if cycles == "first"
|
|
142
|
+
else statistics.fmean(vs))
|
|
143
|
+
records.append({"well": w, "sample": w, "conc_um": None,
|
|
144
|
+
"value": v, "control": False, "channel": chan})
|
|
145
|
+
if unit_out is not None and blocks:
|
|
146
|
+
unit_out["unit"] = (sanitize_label(next(iter(blocks)), 24)
|
|
147
|
+
or "instrument response")
|
|
148
|
+
unit_out["channels"] = list(blocks)
|
|
149
|
+
unit_out["reads"] = max((len(v) for wm in blocks.values()
|
|
150
|
+
for v in wm.values()), default=1)
|
|
151
|
+
return records
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
_META_KEY = re.compile(
|
|
155
|
+
r"^(application|device|firmware|software version|reader type|reader serial"
|
|
156
|
+
r" number|serial number|start time|plate type|plate number|plate"
|
|
157
|
+
r"|experiment file path|protocol file path|date|time)\b[: ]*",
|
|
158
|
+
re.IGNORECASE)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def extract_instrument_meta(rows: list[list[str]]) -> dict[str, str]:
|
|
162
|
+
"""Pull reader/device/software/date identity out of the metadata preamble.
|
|
163
|
+
|
|
164
|
+
Honest provenance: the instrument model and firmware are part of the
|
|
165
|
+
measurement, the same way 'instrument_version' is for sim labs. Stops at
|
|
166
|
+
the first kinetic well-header row so header cells like 'Time [s]' are
|
|
167
|
+
never mistaken for metadata.
|
|
168
|
+
"""
|
|
169
|
+
meta: dict[str, str] = {}
|
|
170
|
+
for row in rows[:120]:
|
|
171
|
+
if _well_columns(row):
|
|
172
|
+
break
|
|
173
|
+
cells = [c.strip() for c in row]
|
|
174
|
+
for i, cell in enumerate(cells):
|
|
175
|
+
if not cell:
|
|
176
|
+
continue
|
|
177
|
+
m = _META_KEY.match(cell)
|
|
178
|
+
if not m:
|
|
179
|
+
continue
|
|
180
|
+
key = m.group(0).lower().strip(" :").replace(" ", "_")
|
|
181
|
+
val = cell[m.end():].strip(" :")
|
|
182
|
+
if not val:
|
|
183
|
+
rest = [c for c in cells[i + 1:] if c]
|
|
184
|
+
val = rest[0] if rest else ""
|
|
185
|
+
if not val or val.startswith("["):
|
|
186
|
+
continue
|
|
187
|
+
if "\\" in val: # windows paths: keep the file name only
|
|
188
|
+
val = val.split("\\")[-1]
|
|
189
|
+
meta.setdefault(key, sanitize_label(val, 80))
|
|
190
|
+
return meta
|
proef/labread/layout.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Plate-layout binding and layout-level QC."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from proef.adapters.lab.simulator import parse_concentration_um
|
|
8
|
+
from proef.labread.common import SYNONYMS, WELL_RE, _header_score, _is_missing, _is_number, _rows_from_csv, is_control, sanitize_label
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _layout_sections(rows: list[list[str]]):
|
|
12
|
+
"""Parse a possibly multi-section layout grid.
|
|
13
|
+
|
|
14
|
+
Real plate maps (wellr's own example included) stack named sections:
|
|
15
|
+
'conc' (dose per well), 'sample' (what sits in the well), 'protein', ...
|
|
16
|
+
each introduced by a header row like 'conc,1,2,...'. Returns
|
|
17
|
+
(conc_map, sample_map, extras) where extras keeps the other layers by
|
|
18
|
+
section name — nothing is silently dropped.
|
|
19
|
+
"""
|
|
20
|
+
conc_map: dict[str, float | None] = {}
|
|
21
|
+
sample_map: dict[str, str] = {}
|
|
22
|
+
extras: dict[str, dict[str, Any]] = {}
|
|
23
|
+
section = None
|
|
24
|
+
for row in rows:
|
|
25
|
+
cells = [c.strip() for c in row]
|
|
26
|
+
if not cells or not cells[0]:
|
|
27
|
+
continue
|
|
28
|
+
c0 = cells[0].lower()
|
|
29
|
+
if (not WELL_RE.match(cells[0] + "1") and len(cells[0]) > 1
|
|
30
|
+
and len(cells) > 1 and cells[1] == "1"):
|
|
31
|
+
if any(c0 == n or c0 in n for n in SYNONYMS["conc"]):
|
|
32
|
+
section = "conc"
|
|
33
|
+
elif any(c0 == n or c0 in n for n in SYNONYMS["sample"]):
|
|
34
|
+
section = "sample"
|
|
35
|
+
else:
|
|
36
|
+
section = sanitize_label(c0, 24)
|
|
37
|
+
extras.setdefault(section, {})
|
|
38
|
+
continue
|
|
39
|
+
m = WELL_RE.match(cells[0] + "1")
|
|
40
|
+
if not m or len(cells[0]) > 2:
|
|
41
|
+
continue
|
|
42
|
+
letter = cells[0].upper()
|
|
43
|
+
for j, cell in enumerate(cells[1:], start=1):
|
|
44
|
+
if _is_missing(cell):
|
|
45
|
+
continue
|
|
46
|
+
well = f"{letter}{j}"
|
|
47
|
+
if section == "conc":
|
|
48
|
+
conc_map[well] = (parse_concentration_um(cell)
|
|
49
|
+
if _is_number(cell) else None)
|
|
50
|
+
elif section == "sample":
|
|
51
|
+
sample_map[well] = (sanitize_label(cell) if not _is_number(cell)
|
|
52
|
+
else sanitize_label(f"{c0} {cell}"))
|
|
53
|
+
elif section:
|
|
54
|
+
extras[section][well] = (float(cell) if _is_number(cell)
|
|
55
|
+
else sanitize_label(cell, 40))
|
|
56
|
+
elif _is_number(cell):
|
|
57
|
+
conc_map[well] = float(cell) # headerless single conc grid
|
|
58
|
+
else:
|
|
59
|
+
sample_map[well] = sanitize_label(cell)
|
|
60
|
+
return conc_map, sample_map, extras
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def bind_layout(records: list[dict[str, Any]], layout: str | Path) -> int:
|
|
64
|
+
"""Attach well -> (sample, conc_um) from a plate-layout file.
|
|
65
|
+
|
|
66
|
+
Two layout dialects: a grid ('conc,1..12' header, one lettered row per
|
|
67
|
+
plate row; possibly several named sections stacked — dose, sample,
|
|
68
|
+
reagent), or long ('well,sample,conc_um'). Empty layout cells mean
|
|
69
|
+
'no compound in that well' and leave the record unmapped. Extra
|
|
70
|
+
categorical layers land on each record as r['layout'].
|
|
71
|
+
Returns the number of wells bound (conc or sample).
|
|
72
|
+
"""
|
|
73
|
+
path = Path(layout)
|
|
74
|
+
rows = _rows_from_csv(path)
|
|
75
|
+
if not rows:
|
|
76
|
+
raise ValueError(f"unreadable layout file: {path}")
|
|
77
|
+
dose_map: dict[str, float | None] = {}
|
|
78
|
+
name_map: dict[str, str] = {}
|
|
79
|
+
extra_maps: dict[str, dict[str, Any]] = {}
|
|
80
|
+
|
|
81
|
+
long_score = max((_header_score(r)[0] for r in rows[:10]), default=0)
|
|
82
|
+
if long_score >= 2: # long layout: well + conc (+ optional sample)
|
|
83
|
+
((_, mapping), header_i) = max(
|
|
84
|
+
((_header_score(r), i) for i, r in enumerate(rows[:10])),
|
|
85
|
+
key=lambda t: (t[0][0], -t[1]))
|
|
86
|
+
for row in rows[header_i + 1:]:
|
|
87
|
+
well = (row[mapping["well"]].strip().upper()
|
|
88
|
+
if "well" in mapping and len(row) > mapping["well"] else "")
|
|
89
|
+
if not WELL_RE.match(well):
|
|
90
|
+
continue
|
|
91
|
+
conc = (parse_concentration_um(row[mapping["conc"]])
|
|
92
|
+
if "conc" in mapping and len(row) > mapping["conc"]
|
|
93
|
+
and row[mapping["conc"]].strip() else None)
|
|
94
|
+
dose_map[well] = conc
|
|
95
|
+
if "sample" in mapping and len(row) > mapping["sample"]:
|
|
96
|
+
name_map[well] = sanitize_label(row[mapping["sample"]])
|
|
97
|
+
else:
|
|
98
|
+
dose_map, name_map, extra_maps = _layout_sections(rows)
|
|
99
|
+
|
|
100
|
+
bound = 0
|
|
101
|
+
for r in records:
|
|
102
|
+
w = r["well"].upper()
|
|
103
|
+
hit = False
|
|
104
|
+
if w in dose_map:
|
|
105
|
+
r["conc_um"] = dose_map[w]
|
|
106
|
+
hit = True
|
|
107
|
+
if w in name_map:
|
|
108
|
+
r["sample"] = name_map[w]
|
|
109
|
+
hit = True
|
|
110
|
+
for sec, m in extra_maps.items():
|
|
111
|
+
if w in m:
|
|
112
|
+
r.setdefault("layout", {})[sec] = m[w]
|
|
113
|
+
hit = True
|
|
114
|
+
bound += hit
|
|
115
|
+
for r in records:
|
|
116
|
+
r["control"] = is_control(str(r["sample"]))
|
|
117
|
+
return bound
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _layout_qc(records: list[dict[str, Any]]) -> dict[str, Any] | None:
|
|
121
|
+
"""Edge/column effects from WELL GEOMETRY of non-control wells.
|
|
122
|
+
|
|
123
|
+
Declared, never silently corrected and never gated: a hot perimeter or a
|
|
124
|
+
drifting column is plate metadata the verdict should know about. Edges
|
|
125
|
+
are inferred from the observed grid (A../..last read row, col 1..last
|
|
126
|
+
read col), so partial reads get a conservative 'outer ring' definition.
|
|
127
|
+
Multi-channel plates get one QC dict PER CHANNEL (pooling OD magnitudes
|
|
128
|
+
with luminescence would produce a meaningless statistic).
|
|
129
|
+
"""
|
|
130
|
+
groups: dict[str, list] = {}
|
|
131
|
+
for r in records:
|
|
132
|
+
if r.get("control"):
|
|
133
|
+
continue
|
|
134
|
+
m = WELL_RE.match(str(r.get("well", "")))
|
|
135
|
+
if m:
|
|
136
|
+
chan = r.get("channel") or ""
|
|
137
|
+
groups.setdefault(chan, []).append(
|
|
138
|
+
(ord(m.group(1).upper()) - 65, int(m.group(2)), r["value"]))
|
|
139
|
+
|
|
140
|
+
def _qc(pts) -> dict[str, Any] | None:
|
|
141
|
+
if len(pts) < 24:
|
|
142
|
+
return None
|
|
143
|
+
max_r = max(p[0] for p in pts)
|
|
144
|
+
max_c = max(p[1] for p in pts)
|
|
145
|
+
edge = [v for ri, ci, v in pts if ri in (0, max_r) or ci in (1, max_c)]
|
|
146
|
+
inner = [v for ri, ci, v in pts
|
|
147
|
+
if ri not in (0, max_r) and ci not in (1, max_c)]
|
|
148
|
+
if not edge or not inner:
|
|
149
|
+
return None
|
|
150
|
+
colmeans: dict[int, list[float]] = {}
|
|
151
|
+
for _, ci, v in pts:
|
|
152
|
+
colmeans.setdefault(ci, []).append(v)
|
|
153
|
+
drift = None
|
|
154
|
+
if len(colmeans) >= 3:
|
|
155
|
+
ms = [sum(x) / len(x) for x in colmeans.values()]
|
|
156
|
+
drift = round(max(ms) - min(ms), 6)
|
|
157
|
+
return {"n_edge": len(edge), "n_inner": len(inner),
|
|
158
|
+
"edge_minus_inner": round(
|
|
159
|
+
sum(edge) / len(edge) - sum(inner) / len(inner), 6),
|
|
160
|
+
"column_drift": drift}
|
|
161
|
+
|
|
162
|
+
qcs = {chan: _qc(pts) for chan, pts in groups.items()}
|
|
163
|
+
qcs = {k: v for k, v in qcs.items() if v is not None}
|
|
164
|
+
if not qcs:
|
|
165
|
+
return None
|
|
166
|
+
if len(qcs) == 1:
|
|
167
|
+
return next(iter(qcs.values()))
|
|
168
|
+
return qcs
|
proef/labread/pubchem.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""PubChem / NCATS qHTS deposit parser (self-normalized curve deposits)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from proef.labread.common import _is_number
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
_DOSE_NAME = re.compile(r"at\s+([0-9][0-9.eE+-]*)\s*(nM|uM|\u00b5M)", re.IGNORECASE)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_ASCENDING = ("inhibit",)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_DESCENDING = ("activity", "response", "control", "% ctrl")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _scale_of(name: str) -> str:
|
|
20
|
+
low = name.lower()
|
|
21
|
+
if any(k in low for k in _ASCENDING):
|
|
22
|
+
return "inhibition" # rises with dose: our native effect scale
|
|
23
|
+
if any(k in low for k in _DESCENDING):
|
|
24
|
+
return "activity" # falls with dose: flip to 100 - x
|
|
25
|
+
return "unknown"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _parse_pubchem(rows: list[list[str]],
|
|
29
|
+
unit_out: dict | None = None) -> list[dict[str, Any]]:
|
|
30
|
+
"""Parse a PubChem deposited assay table (the submitter's own upload,
|
|
31
|
+
REST-exported) into standardized records — STRUCTURALLY BLIND: only
|
|
32
|
+
identity columns (SID/CID/SMILES) and the raw percentage value columns
|
|
33
|
+
are read; PUBCHEM_ACTIVITY_OUTCOME and the submitter's IC50/Hill/Fit
|
|
34
|
+
columns are never touched here. Scoring against those answer-key
|
|
35
|
+
columns must happen downstream, explicitly.
|
|
36
|
+
|
|
37
|
+
Two deposition dialects (both real, both seen in the wild):
|
|
38
|
+
A. Jacobs/MLPCN style — dose ladder in `RESULT_ATTR_CONC_*` meta
|
|
39
|
+
rows; the REST header may truncate the value-column NAMES, so
|
|
40
|
+
the meta row is the truth (unit suffix in the tag: MICROMOL or
|
|
41
|
+
NANOMOLAR).
|
|
42
|
+
B. NCATS qHTS style — doses embedded in header names
|
|
43
|
+
('Activity at 0.233 uM'), no usable meta rows, and on a
|
|
44
|
+
PERCENT-**ACTIVITY** scale (decreasing for inhibitors, often
|
|
45
|
+
negative past full inhibition) — detected by the column name and
|
|
46
|
+
flipped onto the ascending effect scale, with the flip DISCLOSED
|
|
47
|
+
in unit_out['scale'].
|
|
48
|
+
Scale polarity by name: 'Inhibit*' -> as-is; 'Activity/Response/
|
|
49
|
+
Control*' -> 100 - x. Unknown-polarity columns are refused (no silent
|
|
50
|
+
inversion — a mis-signed curve is worse than none).
|
|
51
|
+
"""
|
|
52
|
+
header = [c.strip() for c in rows[0]]
|
|
53
|
+
|
|
54
|
+
def col(*names: str) -> int:
|
|
55
|
+
for n in names:
|
|
56
|
+
if n in header:
|
|
57
|
+
return header.index(n)
|
|
58
|
+
return -1
|
|
59
|
+
|
|
60
|
+
sid_i, cid_i, smi_i = col("PUBCHEM_SID"), col("PUBCHEM_CID"), \
|
|
61
|
+
col("PUBCHEM_EXT_DATASOURCE_SMILES", "PUBCHEM_EXT_DATASOURCE_STRUCTures")
|
|
62
|
+
conc_row = unit_row = None
|
|
63
|
+
for r in rows:
|
|
64
|
+
if not r:
|
|
65
|
+
continue
|
|
66
|
+
tag = r[0].strip()
|
|
67
|
+
if tag.startswith("RESULT_ATTR_CONC"):
|
|
68
|
+
if conc_row is None or tag.endswith("MICROMOL"):
|
|
69
|
+
conc_row = r # micromolar preferred if mixed
|
|
70
|
+
elif tag == "RESULT_UNIT" and unit_row is None:
|
|
71
|
+
unit_row = r
|
|
72
|
+
pcols: list[tuple[int, float, str]] = [] # (col, uM, scale-name)
|
|
73
|
+
if conc_row is not None and any(_is_number(c) for c in conc_row[1:]):
|
|
74
|
+
nano = "NANO" in conc_row[0].upper()
|
|
75
|
+
for j, c in enumerate(conc_row):
|
|
76
|
+
if j == 0 or not c.strip() or not _is_number(c):
|
|
77
|
+
continue
|
|
78
|
+
if (unit_row is not None and j < len(unit_row)
|
|
79
|
+
and unit_row[j].strip().upper().startswith("PERCENT")):
|
|
80
|
+
pcols.append((j, float(c) / 1000.0 if nano else float(c),
|
|
81
|
+
_scale_of(header[j] if j < len(header) else "")))
|
|
82
|
+
else: # dialect B: doses in the header names themselves
|
|
83
|
+
for j, name in enumerate(header):
|
|
84
|
+
m = _DOSE_NAME.search(name)
|
|
85
|
+
if m:
|
|
86
|
+
um = float(m.group(1))
|
|
87
|
+
if m.group(2).lower() == "nm":
|
|
88
|
+
um /= 1000.0
|
|
89
|
+
pcols.append((j, um, _scale_of(name)))
|
|
90
|
+
if not pcols or smi_i < 0:
|
|
91
|
+
return []
|
|
92
|
+
# dialect A's REST header truncation leaves SOME value columns unnamed
|
|
93
|
+
# (scale unknown from the name). They belong to the same measured family
|
|
94
|
+
# as the named ones — inherit a single consistent named scale; refuse if
|
|
95
|
+
# the named columns themselves disagree or none are nameable.
|
|
96
|
+
named = {s for _, _, s in pcols if s != "unknown"}
|
|
97
|
+
if len(named) > 1:
|
|
98
|
+
if unit_out is not None:
|
|
99
|
+
unit_out["refused"] = ("mixed scale polarity in one deposition: "
|
|
100
|
+
+ ", ".join(sorted(named)))
|
|
101
|
+
return []
|
|
102
|
+
if len(named) == 1:
|
|
103
|
+
inherit = named.pop()
|
|
104
|
+
pcols = [(j, c, inherit if s == "unknown" else s)
|
|
105
|
+
for j, c, s in pcols]
|
|
106
|
+
unknown = {s for _, _, s in pcols if s == "unknown"}
|
|
107
|
+
if unknown: # wholly anonymous percent columns: no safe polarity
|
|
108
|
+
if unit_out is not None:
|
|
109
|
+
unit_out["refused"] = ("value columns without recognizable "
|
|
110
|
+
"scale polarity: " + ", ".join(sorted(unknown)))
|
|
111
|
+
return []
|
|
112
|
+
scales = sorted({s for _, _, s in pcols})
|
|
113
|
+
if unit_out is not None:
|
|
114
|
+
flipped = [s for s in scales if s == "activity"]
|
|
115
|
+
unit_out["unit"] = ("% inhibition (ascending effect scale"
|
|
116
|
+
+ ("; activity columns flipped: 100 - x)"
|
|
117
|
+
if flipped else ")"))
|
|
118
|
+
unit_out["scale"] = "+".join(scales)
|
|
119
|
+
unit_out["n_doses"] = len(pcols)
|
|
120
|
+
records: list[dict[str, Any]] = []
|
|
121
|
+
for r in rows:
|
|
122
|
+
if not r or not r[0].strip().isdigit():
|
|
123
|
+
continue
|
|
124
|
+
sid = r[sid_i].strip() if 0 <= sid_i < len(r) else ""
|
|
125
|
+
cid = r[cid_i].strip() if 0 <= cid_i < len(r) else ""
|
|
126
|
+
smi = r[smi_i].strip() if smi_i < len(r) else ""
|
|
127
|
+
name = f"SID{sid}" if sid else (f"CID{cid}" if cid else smi[:16])
|
|
128
|
+
for j, um, scale in pcols:
|
|
129
|
+
if j >= len(r) or not _is_number(r[j]):
|
|
130
|
+
continue # sparse curves: unfilled wells stay absent
|
|
131
|
+
raw = float(r[j])
|
|
132
|
+
inh = 100.0 - raw if scale == "activity" else raw
|
|
133
|
+
records.append({"well": "", "sample": name, "conc_um": um,
|
|
134
|
+
"value": round(inh, 3), "control": False,
|
|
135
|
+
"inhibition_pct": round(inh, 3), "smiles": smi,
|
|
136
|
+
"cid": cid})
|
|
137
|
+
return records
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def tag_row_unit(tag: str) -> str:
|
|
141
|
+
return "nano" if "NANO" in tag.upper() else "micro"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _pubchem_frame(records: list[dict[str, Any]]) -> str:
|
|
145
|
+
"""Fingerprint the normalization frame of a deposited percent table.
|
|
146
|
+
|
|
147
|
+
External-reference deposits (Jacobs/MLPCN style; validated by CS05
|
|
148
|
+
against the lab's own calls) start most compounds at the ZERO end of
|
|
149
|
+
the effect scale: the lowest measured dose of each curve reads ~0%
|
|
150
|
+
inhibition (compound present, enzyme still running).
|
|
151
|
+
Internally self-normalized deposits (NCATS qHTS style; CS06 showed a
|
|
152
|
+
fixed 50%-crossing rule CANNOT port to them) start at the collapsed
|
|
153
|
+
assay floor — most curves' lowest dose already sits at/above full
|
|
154
|
+
effect because the plate's own DMSO/bottom references were divided
|
|
155
|
+
out before deposition.
|
|
156
|
+
|
|
157
|
+
Heuristic (documented, deliberately blunt): median lowest-dose
|
|
158
|
+
response > 55 — or > 50% of compounds flat-saturated (range < 25 with
|
|
159
|
+
min > 75) — is a self-normalized fingerprint. This is a refusal
|
|
160
|
+
trigger, not a claim: 'unknown' behaves like self-normalized.
|
|
161
|
+
"""
|
|
162
|
+
by: dict[str, list[tuple[float, float]]] = {}
|
|
163
|
+
for r in records:
|
|
164
|
+
by.setdefault(r["sample"], []).append((r["conc_um"], r["value"]))
|
|
165
|
+
firsts, flat = [], 0
|
|
166
|
+
for pts in by.values():
|
|
167
|
+
pts = sorted(pts)
|
|
168
|
+
if len(pts) >= 3:
|
|
169
|
+
firsts.append(pts[0][1])
|
|
170
|
+
vals = [v for _, v in pts]
|
|
171
|
+
if min(vals) > 75 and max(vals) - min(vals) < 25:
|
|
172
|
+
flat += 1
|
|
173
|
+
if not firsts:
|
|
174
|
+
return "unknown"
|
|
175
|
+
firsts.sort()
|
|
176
|
+
med = firsts[len(firsts) // 2]
|
|
177
|
+
if med > 55 or flat / len(firsts) > 0.5:
|
|
178
|
+
return "self-normalized"
|
|
179
|
+
return "external-reference"
|