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/figures.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Computed story figures — the claims on the Story page, drawn from code.
|
|
2
|
+
|
|
3
|
+
Every figure regenerates deterministically from shipped modules
|
|
4
|
+
(adaptive.DoseDesigner, labread.fit_ic50_ci, plots.dose_response_svg) and
|
|
5
|
+
caches to assets/fig/. Same math as the eval tasks, so the site and the
|
|
6
|
+
suite can never disagree.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
import random
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
FIG_DIR = Path("assets/fig")
|
|
15
|
+
|
|
16
|
+
INK, TEAL, CORAL, DIM, GRID = "#2a2823", "#1f7a86", "#d94f30", "#8a8272", "#e3ded2"
|
|
17
|
+
RMAX, SIGMA, GATE = 500.0, 15.0, 20.0
|
|
18
|
+
TRUES = [10 ** random.Random(11).uniform(math.log10(0.3), math.log10(150))
|
|
19
|
+
for _ in range(60)]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _chart(series, xlab, ylab, title, w=560, h=340, ymax=1.0, xfmt="{:g}"):
|
|
23
|
+
ml, mb, mt = 58, 44, 34
|
|
24
|
+
pw, ph = w - ml - 24, h - mt - 40
|
|
25
|
+
xmax = max(s[1][-1] for s in series) or 1
|
|
26
|
+
|
|
27
|
+
def X(x): return ml + x / xmax * pw
|
|
28
|
+
def Y(y): return mt + (1 - y / ymax) * ph
|
|
29
|
+
s = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}"'
|
|
30
|
+
f' width="{w}" height="{h}"'
|
|
31
|
+
f' font-family="ui-sans-serif,system-ui,sans-serif">',
|
|
32
|
+
f'<rect width="{w}" height="{h}" fill="#faf8f2"/>',
|
|
33
|
+
f'<text x="{ml}" y="20" font-size="13" font-weight="700"'
|
|
34
|
+
f' fill="{INK}">{title}</text>']
|
|
35
|
+
for gv in (0, .25, .5, .75, 1.0):
|
|
36
|
+
y = Y(gv * ymax)
|
|
37
|
+
s.append(f'<line x1="{ml}" y1="{y:.0f}" x2="{w-24}" y2="{y:.0f}"'
|
|
38
|
+
f' stroke="{GRID}"/>')
|
|
39
|
+
s.append(f'<text x="{ml-6}" y="{y+4:.0f}" text-anchor="end"'
|
|
40
|
+
f' font-size="10.5" fill="{DIM}">{gv * ymax:.0%}</text>')
|
|
41
|
+
for name, xs, ys, color in series:
|
|
42
|
+
pts = " ".join(f"{X(x):.1f},{Y(y):.1f}" for x, y in zip(xs, ys))
|
|
43
|
+
s.append(f'<polyline points="{pts}" fill="none" stroke="{color}"'
|
|
44
|
+
f' stroke-width="2.6"/>')
|
|
45
|
+
for x, y in zip(xs, ys):
|
|
46
|
+
s.append(f'<circle cx="{X(x):.1f}" cy="{Y(y):.1f}" r="3"'
|
|
47
|
+
f' fill="{color}"/>')
|
|
48
|
+
step = max(1, len(series[0][1]) // 5)
|
|
49
|
+
for i in range(0, len(series[0][1]), step):
|
|
50
|
+
x = series[0][1][i]
|
|
51
|
+
s.append(f'<text x="{X(x):.0f}" y="{h-mb+18}" text-anchor="middle"'
|
|
52
|
+
f' font-size="10.5" fill="{DIM}">{xfmt.format(x)}</text>')
|
|
53
|
+
s.append(f'<text x="{w/2}" y="{h-6}" text-anchor="middle" font-size="11"'
|
|
54
|
+
f' fill="{DIM}">{xlab}</text>')
|
|
55
|
+
s.append(f'<text x="14" y="{h/2}" font-size="11" fill="{DIM}"'
|
|
56
|
+
f' transform="rotate(-90 14 {h/2})" text-anchor="middle">'
|
|
57
|
+
f'{ylab}</text>')
|
|
58
|
+
lx, ly = ml + 8, mt + 8
|
|
59
|
+
for name, _, _, color in series:
|
|
60
|
+
s.append(f'<rect x="{lx}" y="{ly-8}" width="10" height="10"'
|
|
61
|
+
f' fill="{color}"/>')
|
|
62
|
+
s.append(f'<text x="{lx+15}" y="{ly}" font-size="11" fill="{INK}">'
|
|
63
|
+
f'{name}</text>')
|
|
64
|
+
ly += 16
|
|
65
|
+
s.append("</svg>")
|
|
66
|
+
return "\n".join(s)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _decidable(est, ci, gate=GATE):
|
|
70
|
+
return 1 if (ci[0] > gate and ci[1] > gate) or (ci[0] < gate and ci[1] < gate) else 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def recovery_curve_svg() -> str:
|
|
74
|
+
"""Decision confidence vs assay wells: adaptive vs fixed vs random."""
|
|
75
|
+
from proef.adaptive import DoseDesigner
|
|
76
|
+
conf_a, conf_f, conf_r = [0] * 7, [0] * 7, [0] * 7
|
|
77
|
+
for idx, t in enumerate(TRUES):
|
|
78
|
+
d = DoseDesigner(rmax=RMAX, sigma=SIGMA)
|
|
79
|
+
nr = DoseDesigner(rmax=RMAX, sigma=SIGMA)
|
|
80
|
+
for w in range(6):
|
|
81
|
+
noise = random.Random(1000 + idx * 10 + w).gauss(0, SIGMA)
|
|
82
|
+
c = d.next_dose()
|
|
83
|
+
if c is not None:
|
|
84
|
+
d.observe(c, max(0.0, RMAX / (1 + t / c) + noise))
|
|
85
|
+
est, ci = d.estimate()
|
|
86
|
+
conf_a[w + 1] += _decidable(est, ci)
|
|
87
|
+
fixed_c = (0.5, 2, 10, 40)[min(w, 3)]
|
|
88
|
+
nr.observe(fixed_c, max(0.0, RMAX / (1 + t / fixed_c) + noise))
|
|
89
|
+
est, ci = nr.estimate()
|
|
90
|
+
conf_f[w + 1] += _decidable(est, ci)
|
|
91
|
+
dd = DoseDesigner(rmax=RMAX, sigma=SIGMA,
|
|
92
|
+
doses=(0.25, 0.5, 1, 2, 5, 10, 20, 40, 80))
|
|
93
|
+
rr = random.Random(idx)
|
|
94
|
+
for w in range(6):
|
|
95
|
+
c = (0.5, 2, 10, 40, 80, 1)[w]
|
|
96
|
+
dd.observe(c, max(0.0, RMAX / (1 + t / c) + rr.gauss(0, SIGMA)))
|
|
97
|
+
est, ci = dd.estimate()
|
|
98
|
+
conf_r[w + 1] += _decidable(est, ci)
|
|
99
|
+
n = len(TRUES)
|
|
100
|
+
return _chart([("adaptive (Bayesian)", list(range(1, 7)),
|
|
101
|
+
[c / n for c in conf_a], TEAL),
|
|
102
|
+
("fixed 4-point series", list(range(1, 7)),
|
|
103
|
+
[c / n for c in conf_f], INK),
|
|
104
|
+
("random doses", list(range(1, 7)),
|
|
105
|
+
[c / n for c in conf_r], CORAL)],
|
|
106
|
+
"assay wells spent", "confident decisions",
|
|
107
|
+
"Decision confidence vs assay budget — 60 simulated compounds,"
|
|
108
|
+
" gate at 20 µM")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def abstention_rate_svg() -> str:
|
|
112
|
+
"""Abstention (inconclusive) rate vs distance from the gate."""
|
|
113
|
+
from proef.adaptive import DoseDesigner
|
|
114
|
+
from proef.core.hypothesis import SuccessCriteria
|
|
115
|
+
crit = SuccessCriteria(metric="ic50_um", threshold=GATE)
|
|
116
|
+
bins: list[list[float]] = [[] for _ in range(5)]
|
|
117
|
+
for idx, t in enumerate(TRUES):
|
|
118
|
+
b = min(4, int(abs(math.log10(t / GATE)) / 0.3))
|
|
119
|
+
flips = 0
|
|
120
|
+
for nv in range(3):
|
|
121
|
+
d = DoseDesigner(rmax=RMAX, sigma=SIGMA)
|
|
122
|
+
for c in (0.5, 2, 10, 40):
|
|
123
|
+
d.observe(c, max(0.0, RMAX / (1 + t / c)
|
|
124
|
+
+ random.Random(idx * 7 + nv * 100 + c)
|
|
125
|
+
.gauss(0, SIGMA)))
|
|
126
|
+
est, ci = d.estimate()
|
|
127
|
+
if crit.classify(est, tuple(ci)) == "inconclusive":
|
|
128
|
+
flips += 1
|
|
129
|
+
bins[b].append(flips / 3)
|
|
130
|
+
xs = [0.05, 0.35, 0.65, 0.95, 1.25]
|
|
131
|
+
ys = [sum(b) / len(b) if b else 0.0 for b in bins]
|
|
132
|
+
return _chart([("abstention rate", xs, ys, TEAL)],
|
|
133
|
+
"distance from gate |log₁₀(true IC50 / gate)|",
|
|
134
|
+
"verdicts abstained",
|
|
135
|
+
"Honesty by design: abstention rate vs distance from the gate")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def evidence_panel_svg() -> str:
|
|
139
|
+
"""Three dose-response curves with CI bands: hit / narrow margin / miss."""
|
|
140
|
+
from proef.labread import fit_ic50_ci
|
|
141
|
+
from proef.plots import dose_response_svg
|
|
142
|
+
combo = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1092 250"'
|
|
143
|
+
' width="100%"><rect width="1092" height="250" fill="#faf8f2"/>')
|
|
144
|
+
for i, (t, lab) in enumerate([(2.4, "clear hit"), (18.9, "narrow margin"),
|
|
145
|
+
(47.3, "clear miss")]):
|
|
146
|
+
rr = random.Random(i)
|
|
147
|
+
pts = [(c, max(0.0, RMAX / (1 + t / c) + rr.gauss(0, SIGMA)))
|
|
148
|
+
for c in (0.5, 2, 10, 40)]
|
|
149
|
+
f = fit_ic50_ci(pts, None)
|
|
150
|
+
svg = dose_response_svg(
|
|
151
|
+
pts, ic50=f["ic50"], ci=(f["ci_low"], f["ci_high"]),
|
|
152
|
+
title=f"{lab}: fit {f['ic50']:.1f} µM"
|
|
153
|
+
f" (CI {f['ci_low']:.1f}–{f['ci_high']:.1f})",
|
|
154
|
+
width=360, height=230)
|
|
155
|
+
inner = svg[svg.index(">") + 1:svg.rindex("</svg>")]
|
|
156
|
+
combo += (f'<g transform="translate({i*364},8)">'
|
|
157
|
+
f'{inner.replace(chr(34)+"360"+chr(34), chr(34)+"360"+chr(34))}'
|
|
158
|
+
f'</g>')
|
|
159
|
+
return combo + "</svg>"
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def run_evidence_svg(items: list[dict]) -> str:
|
|
163
|
+
"""REAL evidence panels: one per recorded plate file, fitted from the
|
|
164
|
+
actual readings — never synthetic. `items` = [{"path", "label",
|
|
165
|
+
"verdict"}]. Returns "" when nothing is plottable (honest empty)."""
|
|
166
|
+
from proef.labread import read_plate, fit_ic50_ci
|
|
167
|
+
from proef.plots import dose_response_svg
|
|
168
|
+
panels = []
|
|
169
|
+
for it in items:
|
|
170
|
+
try:
|
|
171
|
+
pr = read_plate(it["path"])
|
|
172
|
+
except Exception:
|
|
173
|
+
continue
|
|
174
|
+
pts = sorted({(r["conc_um"], r["value"]) for r in pr.records
|
|
175
|
+
if not r.get("control") and r.get("conc_um")})
|
|
176
|
+
if len(pts) < 3:
|
|
177
|
+
continue
|
|
178
|
+
try:
|
|
179
|
+
f = fit_ic50_ci(pts, None)
|
|
180
|
+
except Exception:
|
|
181
|
+
continue
|
|
182
|
+
label = it.get("label") or Path(it["path"]).stem
|
|
183
|
+
title = (f"{label}: fit {f['ic50']:.1f} "
|
|
184
|
+
f"{pr.response_unit or 'µM'}"
|
|
185
|
+
f" (CI {f['ci_low']:.1f}\u2013{f['ci_high']:.1f})")
|
|
186
|
+
verdict = it.get("verdict")
|
|
187
|
+
if verdict in ("validated", "confirmed"):
|
|
188
|
+
title += " \u00b7 pass"
|
|
189
|
+
elif verdict == "inconclusive":
|
|
190
|
+
title += " \u00b7 abstain"
|
|
191
|
+
elif verdict in ("refuted", "invalidated"):
|
|
192
|
+
title += " \u00b7 fail"
|
|
193
|
+
svg = dose_response_svg(
|
|
194
|
+
pts, ic50=f["ic50"], ci=(f["ci_low"], f["ci_high"]),
|
|
195
|
+
title=title, width=360, height=230)
|
|
196
|
+
inner = svg[svg.index(">") + 1:svg.rindex("</svg>")]
|
|
197
|
+
panels.append(inner)
|
|
198
|
+
if not panels:
|
|
199
|
+
return ""
|
|
200
|
+
width = max(360, len(panels) * 364)
|
|
201
|
+
combo = (f'<svg xmlns="http://www.w3.org/2000/svg" '
|
|
202
|
+
f'viewBox="0 0 {width} 250" width="100%">'
|
|
203
|
+
f'<rect width="{width}" height="250" fill="#faf8f2"/>')
|
|
204
|
+
for i, inner in enumerate(panels):
|
|
205
|
+
combo += (f'<g transform="translate({i * 364},8)">{inner}</g>')
|
|
206
|
+
return combo + "</svg>"
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def get(name: str) -> str:
|
|
210
|
+
"""Cached figure: 'recovery' | 'stability' | 'evidence'."""
|
|
211
|
+
FIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
212
|
+
path = FIG_DIR / f"{name}.svg"
|
|
213
|
+
if path.exists():
|
|
214
|
+
return path.read_text()
|
|
215
|
+
svg = {"recovery": recovery_curve_svg, "stability": abstention_rate_svg,
|
|
216
|
+
"evidence": evidence_panel_svg}[name]()
|
|
217
|
+
path.write_text(svg)
|
|
218
|
+
return svg
|
proef/fitting.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Single source of truth for the dose-response curve model.
|
|
2
|
+
|
|
3
|
+
Every IC50 path (the plate-reader fit, the adaptive dose designer, the
|
|
4
|
+
simulators, the eval generators) uses the SAME forward model — a logistic in
|
|
5
|
+
log10(conc) with slope fixed at 1 and bottom at 0:
|
|
6
|
+
|
|
7
|
+
r(c) = rmax / (1 + IC50 / c)
|
|
8
|
+
|
|
9
|
+
— and the same search window, so two entry points cannot disagree about
|
|
10
|
+
what an IC50 means or where "out of range" begins.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import math
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
# IC50 search window (log10 uM): 0.001 .. ~316 uM. A fit pinned at either
|
|
18
|
+
# edge is a range statement ("<=" / ">"), never a measured IC50.
|
|
19
|
+
GRID_LOG_LO = -3.0
|
|
20
|
+
GRID_LOG_HI = 2.5
|
|
21
|
+
GRID_FLOOR_UM = 10 ** GRID_LOG_LO
|
|
22
|
+
GRID_CEIL_UM = 10 ** GRID_LOG_HI
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def hill_response(conc: float, ic50: float, rmax: float = 100.0,
|
|
26
|
+
eps: float = 1e-9) -> float:
|
|
27
|
+
"""Response at `conc` for the slope-1 / bottom-0 model. `eps` only guards
|
|
28
|
+
conc=0 (simulators historically use 1e-6; the fit uses 1e-9)."""
|
|
29
|
+
return rmax / (1.0 + ic50 / max(conc, eps))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# two-sided 95% Student-t critical values, indexed by degrees of freedom
|
|
33
|
+
_T975 = {2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571, 6: 2.447, 7: 2.365,
|
|
34
|
+
8: 2.306}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def replicate_ci(values: list[float | None], seed: int = 7,
|
|
38
|
+
n_boot: int = 200) -> tuple[float, float] | None:
|
|
39
|
+
"""Bootstrap CI (95%) of the MEAN over replicate well readings at one
|
|
40
|
+
dose. This is how a property metric (potency_pct, tensile MPa, t_half)
|
|
41
|
+
gets an interval: well-level variance, same abstention rule as the
|
|
42
|
+
Hill IC50. Returns None below 3 usable wells — a single reading has
|
|
43
|
+
no measurable spread, and inventing one is not honesty. Below 10
|
|
44
|
+
wells the interval is a Student-t one (the bootstrap under-covers)."""
|
|
45
|
+
vals = [v for v in values if isinstance(v, (int, float))]
|
|
46
|
+
if len(vals) < 3:
|
|
47
|
+
return None
|
|
48
|
+
xs = [float(v) for v in vals]
|
|
49
|
+
if len(xs) < 10:
|
|
50
|
+
# small n: a percentile bootstrap badly under-covers (n=3 has only
|
|
51
|
+
# 10 distinct resamples) -> Student-t interval of the mean instead
|
|
52
|
+
n = len(xs)
|
|
53
|
+
mean = sum(xs) / n
|
|
54
|
+
sd = (sum((x - mean) ** 2 for x in xs) / (n - 1)) ** 0.5
|
|
55
|
+
half = _T975[n - 1] * sd / n ** 0.5
|
|
56
|
+
return (round(mean - half, 4), round(mean + half, 4))
|
|
57
|
+
from proef.benchmark import bootstrap_ci
|
|
58
|
+
lo, hi = bootstrap_ci(xs, n_boot=n_boot, seed=seed)
|
|
59
|
+
return (lo, hi)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _spearman(xs: list[float], ys: list[float]) -> float:
|
|
63
|
+
n = len(xs)
|
|
64
|
+
if n < 3:
|
|
65
|
+
return float("nan")
|
|
66
|
+
|
|
67
|
+
def rank(x):
|
|
68
|
+
order = sorted(range(n), key=lambda i: x[i])
|
|
69
|
+
r = [0.0] * n
|
|
70
|
+
i = 0
|
|
71
|
+
while i < n:
|
|
72
|
+
j = i
|
|
73
|
+
while j + 1 < n and x[order[j + 1]] == x[order[i]]:
|
|
74
|
+
j += 1
|
|
75
|
+
avg = (i + j) / 2 + 1
|
|
76
|
+
for k in range(i, j + 1):
|
|
77
|
+
r[order[k]] = avg
|
|
78
|
+
i = j + 1
|
|
79
|
+
return r
|
|
80
|
+
|
|
81
|
+
rx, ry = rank(xs), rank(ys)
|
|
82
|
+
mx, my = sum(rx) / n, sum(ry) / n
|
|
83
|
+
num = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
|
|
84
|
+
dx = sum((a - mx) ** 2 for a in rx) ** 0.5
|
|
85
|
+
dy = sum((b - my) ** 2 for b in ry) ** 0.5
|
|
86
|
+
return num / (dx * dy) if dx and dy else 0.0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def classify_curve(pts: list[tuple[float, float]]) -> dict[str, Any]:
|
|
90
|
+
"""qHTS-lite SHAPE taxonomy (registered, blind; a documented
|
|
91
|
+
simplification of the class taxonomies NCATS/Incyte screening floors
|
|
92
|
+
use — monotonic sigmoids vs flat vs noisy vs falling).
|
|
93
|
+
|
|
94
|
+
WHY shape, not numbers, in self-normalized frames: those tables had
|
|
95
|
+
their plate references divided out before deposition, so the 50%-of-
|
|
96
|
+
what line is undefined — but affine re-normalization preserves
|
|
97
|
+
monotonicity, span structure, and WITHIN-CURVE midpoints. So the only
|
|
98
|
+
honest claims available there are relative: is there a
|
|
99
|
+
concentration-dependent rise (RISE-*), is the 50%-of-span crossing
|
|
100
|
+
inside the window (a midpoint AC50-estimate in µM), or is this a
|
|
101
|
+
flatline artifact / falling curve our physics rejects? These
|
|
102
|
+
claims CANNOT become IC50s — that would smuggle a frame back in.
|
|
103
|
+
"""
|
|
104
|
+
pts = sorted(pts)
|
|
105
|
+
vals = [v for _, v in pts]
|
|
106
|
+
if len(pts) < 4:
|
|
107
|
+
return {"class": "insufficient", "trend": None, "span": None,
|
|
108
|
+
"midpoint_uM": None}
|
|
109
|
+
lo, hi = min(vals), max(vals)
|
|
110
|
+
span = hi - lo
|
|
111
|
+
trend = _spearman([c for c, _ in pts], vals)
|
|
112
|
+
out: dict[str, Any] = {"class": "", "trend": round(trend, 2),
|
|
113
|
+
"span": round(span, 1), "midpoint_uM": None}
|
|
114
|
+
if span < 25:
|
|
115
|
+
out["class"] = "flat" # no response (or floor-pinned artifact)
|
|
116
|
+
return out
|
|
117
|
+
if trend <= -0.4:
|
|
118
|
+
out["class"] = "falling" # opposite of inhibition physics
|
|
119
|
+
return out
|
|
120
|
+
if trend < 0.4:
|
|
121
|
+
out["class"] = "noisy" # not concentration dependent
|
|
122
|
+
return out
|
|
123
|
+
mid = lo + 0.5 * span
|
|
124
|
+
n_below = sum(1 for v in vals if v < mid)
|
|
125
|
+
n_above = len(vals) - n_below
|
|
126
|
+
if n_below >= 2 and n_above >= 2:
|
|
127
|
+
for (c0, v0), (c1, v1) in zip(pts, pts[1:]):
|
|
128
|
+
if v0 < mid <= v1 and v1 > v0:
|
|
129
|
+
out["midpoint_uM"] = round(
|
|
130
|
+
c0 + (c1 - c0) * (mid - v0) / (v1 - v0), 5)
|
|
131
|
+
break
|
|
132
|
+
out["class"] = "rise-complete" # full S inside the window
|
|
133
|
+
elif min(vals) >= mid:
|
|
134
|
+
out["class"] = "rise-partial-low" # every dose past mid: potent
|
|
135
|
+
# below the measured window
|
|
136
|
+
else:
|
|
137
|
+
out["class"] = "rise-partial-high" # hasn't reached mid by top dose
|
|
138
|
+
return out
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _hill_sse(log_ic50: float, pts: list[tuple[float, float]],
|
|
143
|
+
max_response: float) -> float:
|
|
144
|
+
ic50 = 10 ** log_ic50
|
|
145
|
+
sse = 0.0
|
|
146
|
+
for c, v in pts:
|
|
147
|
+
pred = hill_response(c, ic50, max_response)
|
|
148
|
+
sse += (v - pred) ** 2
|
|
149
|
+
return sse
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _hill_fit_params(pts: list[tuple[float, float]],
|
|
153
|
+
max_response: float | None
|
|
154
|
+
) -> tuple[float, float] | None:
|
|
155
|
+
"""Least-squares Hill fit by grid search, refined once.
|
|
156
|
+
|
|
157
|
+
max_response given -> 2-param fit (IC50 only).
|
|
158
|
+
max_response None -> 3-param fit: the plateau is ALSO unknown, so we
|
|
159
|
+
grid-search the max multiplier over the observed top response (1x–4x).
|
|
160
|
+
Pretending the observed max is the true max biases IC50 toward the
|
|
161
|
+
potent side — the classic right-censoring trap.
|
|
162
|
+
Returns (IC50 in µM, fitted top) or None."""
|
|
163
|
+
import math
|
|
164
|
+
|
|
165
|
+
if len(pts) < 2:
|
|
166
|
+
return None
|
|
167
|
+
top = max(v for _, v in pts)
|
|
168
|
+
if top <= 0:
|
|
169
|
+
return None
|
|
170
|
+
lo, hi = GRID_LOG_LO, GRID_LOG_HI # 0.001 – ~316 µM
|
|
171
|
+
n = 60
|
|
172
|
+
step = (hi - lo) / n
|
|
173
|
+
if max_response is None: # 3-param: unknown plateau
|
|
174
|
+
mults = [1.0 + 3.0 * j / 12 for j in range(13)] # 1x .. 4x
|
|
175
|
+
best = (None, None, float("inf"))
|
|
176
|
+
for m in mults:
|
|
177
|
+
for i in range(n + 1):
|
|
178
|
+
g = lo + step * i
|
|
179
|
+
s = _hill_sse(g, pts, top * m)
|
|
180
|
+
if s < best[2]:
|
|
181
|
+
best = (g, m, s)
|
|
182
|
+
if best[0] is None:
|
|
183
|
+
return None
|
|
184
|
+
g0, m0, sse0 = best
|
|
185
|
+
for m in [max(1.0, m0 - 0.25 + 0.5 * k / 4) for k in range(5)]:
|
|
186
|
+
for i in range(-8, 9):
|
|
187
|
+
g = g0 + i * step / 8
|
|
188
|
+
s = _hill_sse(g, pts, top * m)
|
|
189
|
+
if s < sse0:
|
|
190
|
+
sse0, g0, m0 = s, g, m
|
|
191
|
+
return 10 ** g0, top * m0
|
|
192
|
+
if max_response <= 0:
|
|
193
|
+
return None
|
|
194
|
+
best, best_sse = None, float("inf")
|
|
195
|
+
for i in range(n + 1):
|
|
196
|
+
g = lo + step * i
|
|
197
|
+
s = _hill_sse(g, pts, max_response)
|
|
198
|
+
if s < best_sse:
|
|
199
|
+
best, best_sse = g, s
|
|
200
|
+
for i in range(-8, 9): # refine
|
|
201
|
+
g = best + i * step / 8
|
|
202
|
+
s = _hill_sse(g, pts, max_response)
|
|
203
|
+
if s < best_sse:
|
|
204
|
+
best, best_sse = g, s
|
|
205
|
+
if best_sse >= float("inf"):
|
|
206
|
+
return None
|
|
207
|
+
return 10 ** best, max_response
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _hill_fit_ic50(pts: list[tuple[float, float]],
|
|
211
|
+
max_response: float | None) -> float | None:
|
|
212
|
+
"""IC50 (µM) of the least-squares Hill fit, or None."""
|
|
213
|
+
fit = _hill_fit_params(pts, max_response)
|
|
214
|
+
return fit[0] if fit else None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def hill_fit(points: list[tuple[float, float]],
|
|
218
|
+
max_response: float | None = 100.0) -> dict[str, float] | None:
|
|
219
|
+
"""{ic50, top} of the slope-1 / bottom-0 fit — what a plot needs to draw
|
|
220
|
+
the fitted curve (top is the known maximum, or the fitted plateau)."""
|
|
221
|
+
pts = sorted((c, v) for c, v in points if v is not None)
|
|
222
|
+
fit = _hill_fit_params(pts, max_response)
|
|
223
|
+
return {"ic50": fit[0], "top": fit[1]} if fit else None
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def fit_ic50(points: list[tuple[float, float]], max_response: float = 100.0) -> float | None:
|
|
227
|
+
"""IC50 from (conc, response) points — Hill fit, with legacy linear
|
|
228
|
+
interpolation (in log10 conc) as the fallback for sparse data."""
|
|
229
|
+
import math
|
|
230
|
+
pts = sorted((c, v) for c, v in points if v is not None)
|
|
231
|
+
if len(pts) < 2:
|
|
232
|
+
return None
|
|
233
|
+
hill = _hill_fit_ic50(pts, max_response)
|
|
234
|
+
if hill is not None and len(pts) >= 3:
|
|
235
|
+
return round(hill, 3)
|
|
236
|
+
if max_response is None:
|
|
237
|
+
return None # 3-param declined (or too few points) -> honest censoring
|
|
238
|
+
target = max_response / 2.0
|
|
239
|
+
for (c0, v0), (c1, v1) in zip(pts, pts[1:]):
|
|
240
|
+
if min(v0, v1) <= target <= max(v0, v1):
|
|
241
|
+
frac = 0.0 if v1 == v0 else (target - v0) / (v1 - v0)
|
|
242
|
+
if c0 > 0 and c1 > 0:
|
|
243
|
+
# dose-response is ~linear in log10(conc), not in conc
|
|
244
|
+
lc = math.log10(c0) + frac * (math.log10(c1) - math.log10(c0))
|
|
245
|
+
return round(10 ** lc, 3)
|
|
246
|
+
return round(c0 + frac * (c1 - c0), 3)
|
|
247
|
+
return None # right-censored within this concentration range
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def fit_ic50_ci(points: list[tuple[float, float]], max_response: float = 100.0,
|
|
251
|
+
n_boot: int = 300, seed: int = 7) -> dict[str, float] | None:
|
|
252
|
+
"""Residual bootstrap CI for the Hill IC50.
|
|
253
|
+
|
|
254
|
+
Refits on resampled residuals around the fitted curve; returns
|
|
255
|
+
{ic50, ci_low, ci_high} (95%, log-scale percentiles) or None.
|
|
256
|
+
Deterministic given the seed — reproducible verdicts, same as everything
|
|
257
|
+
else in Proef.
|
|
258
|
+
"""
|
|
259
|
+
import math
|
|
260
|
+
import random
|
|
261
|
+
|
|
262
|
+
pts = sorted((c, v) for c, v in points if v is not None)
|
|
263
|
+
if len(pts) < 3 or (max_response is not None and max_response <= 0):
|
|
264
|
+
return None
|
|
265
|
+
base = _hill_fit_ic50(pts, max_response)
|
|
266
|
+
if base is None:
|
|
267
|
+
return None
|
|
268
|
+
rng = random.Random(seed)
|
|
269
|
+
boots: list[float] = []
|
|
270
|
+
if max_response is None:
|
|
271
|
+
# residual bootstrap around the best 3-param fit, at its implied max
|
|
272
|
+
top = max(v for _, v in pts)
|
|
273
|
+
mults = [1.0 + 3.0 * j / 12 for j in range(13)]
|
|
274
|
+
best_m = min(mults, key=lambda m: _hill_sse(math.log10(base), pts,
|
|
275
|
+
top * m))
|
|
276
|
+
fitted = [hill_response(c, base, top * best_m) for c, _ in pts]
|
|
277
|
+
else:
|
|
278
|
+
fitted = [hill_response(c, base, max_response) for c, _ in pts]
|
|
279
|
+
# df-corrected residuals: raw residuals of a fitted curve understate the
|
|
280
|
+
# noise by sqrt((n-p)/n); with 3-5 points that is a large optimism
|
|
281
|
+
n_par = 1 if max_response is not None else 2
|
|
282
|
+
scale = (len(pts) / max(1, len(pts) - n_par)) ** 0.5
|
|
283
|
+
residuals = [(v - f) * scale for (_, v), f in zip(pts, fitted)]
|
|
284
|
+
for _ in range(n_boot):
|
|
285
|
+
sample = [(c, max(0.0, f + rng.choice(residuals)))
|
|
286
|
+
for (c, _v), f in zip(pts, fitted)]
|
|
287
|
+
est = _hill_fit_ic50(sample, max_response)
|
|
288
|
+
if est:
|
|
289
|
+
boots.append(math.log10(est))
|
|
290
|
+
if len(boots) < 30: # too few successful refits
|
|
291
|
+
return {"ic50": round(base, 3), "ci_low": None, "ci_high": None,
|
|
292
|
+
"method": "hill-no-ci"}
|
|
293
|
+
boots.sort()
|
|
294
|
+
q = lambda p: boots[max(0, min(len(boots) - 1, int(p * (len(boots) - 1))))]
|
|
295
|
+
return {"ic50": round(base, 3), "ci_low": round(10 ** q(0.025), 3),
|
|
296
|
+
"ci_high": round(10 ** q(0.975), 3), "method": "hill-bootstrap"}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def std_dev(values: list[float]) -> float:
|
|
300
|
+
"""Sample standard deviation (n-1 denominator). NOT a Z'-factor —
|
|
301
|
+
the old name invited that mistake; the plate QC heuristic lives in
|
|
302
|
+
analyze_records and is labeled there."""
|
|
303
|
+
import math
|
|
304
|
+
|
|
305
|
+
if len(values) < 2:
|
|
306
|
+
return float("nan")
|
|
307
|
+
mean = sum(values) / len(values)
|
|
308
|
+
var = sum((v - mean) ** 2 for v in values) / (len(values) - 1)
|
|
309
|
+
return math.sqrt(var)
|
proef/fixtures.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Case-study data fixtures — byte-reproducible reproductions.
|
|
2
|
+
|
|
3
|
+
The blind-reproduction studies depend on live ChEMBL data; databases move,
|
|
4
|
+
and "we reproduced the paper" quietly rots. Freeze captures the exact bytes
|
|
5
|
+
used (checksummed manifest + files committed under
|
|
6
|
+
case-studies/<study>/fixtures/); materialize restores them into the caches
|
|
7
|
+
the study scripts read, so a fresh clone reproduces offline, identically.
|
|
8
|
+
|
|
9
|
+
proef fixtures freeze <study-dir> # capture current caches (dev)
|
|
10
|
+
proef fixtures verify <study-dir> # checksum audit (CI)
|
|
11
|
+
proef fixtures materialize <study-dir> # restore caches if missing (run.py)
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import shutil
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
MANIFEST = "manifest.json"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _sha(p: Path) -> str:
|
|
24
|
+
return _sha_bytes(p.read_bytes())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _sha_bytes(b: bytes) -> str:
|
|
28
|
+
return hashlib.sha256(b).hexdigest()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _entries(study: Path) -> list[dict]:
|
|
32
|
+
if not (study / "fixtures" / MANIFEST).exists():
|
|
33
|
+
return []
|
|
34
|
+
doc = json.loads((study / "fixtures" / MANIFEST).read_text())
|
|
35
|
+
if isinstance(doc, dict):
|
|
36
|
+
# manifests come in two dialects; a dict without "entries" is the
|
|
37
|
+
# CS07 (source/derived) shape, handled by verify() directly
|
|
38
|
+
return doc.get("entries", [])
|
|
39
|
+
return doc
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ------------------------------------------------------------------ freeze
|
|
43
|
+
|
|
44
|
+
def freeze(study_dir: str | Path, sources: list[tuple[str, Path]]) -> dict:
|
|
45
|
+
"""sources: [(relpath_in_fixtures, live_path)] — copies + manifests.
|
|
46
|
+
Live paths are recorded repo-root-relative when possible."""
|
|
47
|
+
study = Path(study_dir)
|
|
48
|
+
root = study.resolve().parents[1]
|
|
49
|
+
fx = study / "fixtures"
|
|
50
|
+
fx.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
entries = []
|
|
52
|
+
for rel, src in sources:
|
|
53
|
+
if not src.exists():
|
|
54
|
+
print(f" skip (missing): {src}")
|
|
55
|
+
continue
|
|
56
|
+
dst = fx / (rel + ".gz")
|
|
57
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
import gzip
|
|
59
|
+
dst.write_bytes(gzip.compress(src.read_bytes(), compresslevel=9))
|
|
60
|
+
try:
|
|
61
|
+
target = str(Path(src).resolve().relative_to(root))
|
|
62
|
+
except ValueError:
|
|
63
|
+
target = str(src)
|
|
64
|
+
entries.append({"path": rel, "sha256": _sha(src),
|
|
65
|
+
"bytes": src.stat().st_size, "target": target})
|
|
66
|
+
manifest = {"frozen_at": __import__("time").strftime("%Y-%m-%dT%H:%M:%S"),
|
|
67
|
+
"entries": sorted(entries, key=lambda e: e["path"])}
|
|
68
|
+
(fx / MANIFEST).write_text(json.dumps(manifest, indent=1))
|
|
69
|
+
return manifest
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# ------------------------------------------------------------------ verify
|
|
73
|
+
|
|
74
|
+
def verify(study_dir: str | Path) -> tuple[bool, list[str]]:
|
|
75
|
+
study = Path(study_dir)
|
|
76
|
+
problems = []
|
|
77
|
+
import gzip
|
|
78
|
+
entries = _entries(study)
|
|
79
|
+
if entries:
|
|
80
|
+
for e in entries:
|
|
81
|
+
p = study / "fixtures" / (e["path"] + ".gz")
|
|
82
|
+
if not p.exists():
|
|
83
|
+
problems.append(f"missing: {e['path']}")
|
|
84
|
+
elif _sha_bytes(gzip.decompress(p.read_bytes())) != e["sha256"]:
|
|
85
|
+
problems.append(f"CHECKSUM MISMATCH: {e['path']}")
|
|
86
|
+
return not problems, problems
|
|
87
|
+
# second manifest dialect (CS07-style MANIFEST.json: source + derived
|
|
88
|
+
# files with raw sha256 and row counts) — both shapes must verify
|
|
89
|
+
m = study / "fixtures" / "MANIFEST.json"
|
|
90
|
+
if m.exists():
|
|
91
|
+
doc = json.loads(m.read_text())
|
|
92
|
+
for name, spec in (doc.get("derived") or {}).items():
|
|
93
|
+
p = study / "fixtures" / (name + ".gz")
|
|
94
|
+
if not p.exists():
|
|
95
|
+
problems.append(f"missing: {name}")
|
|
96
|
+
continue
|
|
97
|
+
raw = gzip.decompress(p.read_bytes())
|
|
98
|
+
if _sha_bytes(raw) != spec["sha256_raw"]:
|
|
99
|
+
problems.append(f"CHECKSUM MISMATCH: {name}")
|
|
100
|
+
elif spec.get("rows") and raw.count(b"\n") - 1 != spec["rows"]:
|
|
101
|
+
problems.append(f"ROW COUNT: {name}")
|
|
102
|
+
src_sha = (doc.get("source") or {}).get("sha256")
|
|
103
|
+
return (not problems), problems
|
|
104
|
+
return False, ["no manifest — run `proef fixtures freeze`"]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ------------------------------------------------------------- materialize
|
|
108
|
+
|
|
109
|
+
def materialize(study_dir: str | Path) -> int:
|
|
110
|
+
"""Restore frozen fixtures to their live cache locations. The frozen
|
|
111
|
+
copy is CHECKSUM-VERIFIED against the manifest before and after
|
|
112
|
+
materializing — a corrupt or edited .gz never becomes a cache file,
|
|
113
|
+
and an existing cache file that does not match the manifest is
|
|
114
|
+
replaced, not trusted. Returns the number of cache files written."""
|
|
115
|
+
import gzip
|
|
116
|
+
study = Path(study_dir)
|
|
117
|
+
root = study.resolve().parents[1]
|
|
118
|
+
entries = _entries(study)
|
|
119
|
+
if not entries:
|
|
120
|
+
raise FileNotFoundError("no fixtures manifest — run "
|
|
121
|
+
"`proef fixtures freeze` first")
|
|
122
|
+
# 1. verify every frozen file BEFORE restoring any of it
|
|
123
|
+
ok, problems = verify(study)
|
|
124
|
+
if not ok:
|
|
125
|
+
raise ValueError("fixture integrity check failed: "
|
|
126
|
+
+ "; ".join(problems[:4]))
|
|
127
|
+
n = 0
|
|
128
|
+
for e in entries:
|
|
129
|
+
if not e.get("target"):
|
|
130
|
+
continue
|
|
131
|
+
target = root / e["target"]
|
|
132
|
+
src = study / "fixtures" / (e["path"] + ".gz")
|
|
133
|
+
data = gzip.decompress(src.read_bytes())
|
|
134
|
+
if _sha_bytes(data) != e["sha256"]:
|
|
135
|
+
raise ValueError(f"fixture decompress mismatch: {e['path']}")
|
|
136
|
+
if not target.exists() or target.read_bytes() != data:
|
|
137
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
138
|
+
target.write_bytes(data)
|
|
139
|
+
n += 1
|
|
140
|
+
return n
|