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.
Files changed (200) hide show
  1. proef/__init__.py +25 -0
  2. proef/acquisition.py +244 -0
  3. proef/ad.py +159 -0
  4. proef/adapters/__init__.py +0 -0
  5. proef/adapters/admet.py +196 -0
  6. proef/adapters/bio/__init__.py +0 -0
  7. proef/adapters/bio/rdkit_ops.py +52 -0
  8. proef/adapters/bio/safety_rules.json +146 -0
  9. proef/adapters/bio/seq_alerts.py +79 -0
  10. proef/adapters/bio/structure_score.py +85 -0
  11. proef/adapters/bio/tox_alerts.py +99 -0
  12. proef/adapters/data/__init__.py +0 -0
  13. proef/adapters/data/admet.py +62 -0
  14. proef/adapters/data/chembl.py +110 -0
  15. proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
  16. proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
  17. proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
  18. proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
  19. proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
  20. proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
  21. proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
  22. proef/adapters/data/moleculenet.py +60 -0
  23. proef/adapters/databases/__init__.py +0 -0
  24. proef/adapters/databases/chembl_gates.py +121 -0
  25. proef/adapters/databases/chembl_lookup.py +35 -0
  26. proef/adapters/databases/open_targets.py +102 -0
  27. proef/adapters/databases/pubmed.py +94 -0
  28. proef/adapters/devices/__init__.py +0 -0
  29. proef/adapters/devices/ezo_ph.py +251 -0
  30. proef/adapters/devices/hcs_microscope.py +143 -0
  31. proef/adapters/devices/lcms.py +123 -0
  32. proef/adapters/devices/scheduler.py +84 -0
  33. proef/adapters/devices/sila2.py +134 -0
  34. proef/adapters/genomics/alphagenome.py +146 -0
  35. proef/adapters/lab/__init__.py +0 -0
  36. proef/adapters/lab/bioprocess.py +32 -0
  37. proef/adapters/lab/devices.py +170 -0
  38. proef/adapters/lab/imaging.py +226 -0
  39. proef/adapters/lab/mhs_driver.py +124 -0
  40. proef/adapters/lab/opentrons.py +222 -0
  41. proef/adapters/lab/ot2_sim.py +174 -0
  42. proef/adapters/lab/plate_reader_share.py +108 -0
  43. proef/adapters/lab/protein_design.py +199 -0
  44. proef/adapters/lab/recording.py +119 -0
  45. proef/adapters/lab/replay.py +107 -0
  46. proef/adapters/lab/simulator.py +282 -0
  47. proef/adapters/lab/synthesis.py +92 -0
  48. proef/adapters/models/__init__.py +0 -0
  49. proef/adapters/models/anthropic_provider.py +157 -0
  50. proef/adapters/models/assayloop_ranker.py +67 -0
  51. proef/adapters/models/from_env.py +93 -0
  52. proef/adapters/models/gp_policy.py +93 -0
  53. proef/adapters/models/gp_policy_gp.py +36 -0
  54. proef/adapters/models/llm_policy.py +187 -0
  55. proef/adapters/models/openai_compat.py +150 -0
  56. proef/adapters/models/sklearn_policy.py +65 -0
  57. proef/adapters/retrosynthesis.py +247 -0
  58. proef/adapters/sandbox/__init__.py +20 -0
  59. proef/adapters/sandbox/agentenv.py +145 -0
  60. proef/adapters/sandbox/docker.py +217 -0
  61. proef/adapters/sandbox/local.py +164 -0
  62. proef/adapters/sandbox/opensandbox.py +122 -0
  63. proef/adapters/store/__init__.py +0 -0
  64. proef/adapters/store/sqlite.py +207 -0
  65. proef/adaptive.py +108 -0
  66. proef/advisory.py +76 -0
  67. proef/analysis_profiles/__init__.py +8 -0
  68. proef/analysis_profiles/measurements.py +266 -0
  69. proef/analysis_profiles/plate_assay.py +316 -0
  70. proef/analysis_report.py +195 -0
  71. proef/analysis_store.py +183 -0
  72. proef/anchor.py +154 -0
  73. proef/api/app.py +107 -0
  74. proef/api/launch.py +170 -0
  75. proef/api/v1/__init__.py +29 -0
  76. proef/api/v1/analyses.py +367 -0
  77. proef/api/v1/campaigns.py +802 -0
  78. proef/api/v1/deps.py +10 -0
  79. proef/api/v1/evals.py +16 -0
  80. proef/api/v1/evidence.py +132 -0
  81. proef/api/v1/governance.py +35 -0
  82. proef/api/v1/inbox.py +119 -0
  83. proef/api/v1/lab.py +110 -0
  84. proef/api/v1/pauses.py +77 -0
  85. proef/api/v1/programs.py +397 -0
  86. proef/api/v1/results.py +147 -0
  87. proef/api/v1/schemas.py +932 -0
  88. proef/api/v1/system.py +79 -0
  89. proef/api/v1/trees.py +216 -0
  90. proef/api/wizard_sessions.py +253 -0
  91. proef/approvals.py +102 -0
  92. proef/assays/__init__.py +15 -0
  93. proef/assays/dls.py +114 -0
  94. proef/assays/dsf.py +81 -0
  95. proef/assays/elisa.py +58 -0
  96. proef/assays/properties.py +65 -0
  97. proef/assays/simulate.py +157 -0
  98. proef/audit.py +152 -0
  99. proef/autoloop.py +1620 -0
  100. proef/benchmark.py +442 -0
  101. proef/campaign_fsm.py +151 -0
  102. proef/citations.py +141 -0
  103. proef/cli.py +1249 -0
  104. proef/connect.py +74 -0
  105. proef/core/__init__.py +0 -0
  106. proef/core/contracts/__init__.py +35 -0
  107. proef/core/contracts/analysis.py +100 -0
  108. proef/core/contracts/models.py +395 -0
  109. proef/core/device_card.py +125 -0
  110. proef/core/hypothesis.py +720 -0
  111. proef/core/interfaces.py +164 -0
  112. proef/core/registry.py +123 -0
  113. proef/core/safety.py +324 -0
  114. proef/core/workflow.py +159 -0
  115. proef/critic.py +62 -0
  116. proef/demo.py +164 -0
  117. proef/derivation.py +128 -0
  118. proef/diary.py +301 -0
  119. proef/eln.py +87 -0
  120. proef/evals/__init__.py +1 -0
  121. proef/evals/hallucination.py +86 -0
  122. proef/evals/harness.py +358 -0
  123. proef/evals/orchestration.py +254 -0
  124. proef/evals/tasks.py +1010 -0
  125. proef/evals/toolcalls.py +425 -0
  126. proef/experiment.py +172 -0
  127. proef/experiment_analysis.py +114 -0
  128. proef/experiments/__init__.py +0 -0
  129. proef/experiments/grounding_exp.py +689 -0
  130. proef/figures.py +218 -0
  131. proef/fitting.py +309 -0
  132. proef/fixtures.py +140 -0
  133. proef/flywheel.py +125 -0
  134. proef/followup.py +126 -0
  135. proef/governance.py +290 -0
  136. proef/groundedness.py +361 -0
  137. proef/grounding.py +202 -0
  138. proef/hypothesis_agent.py +369 -0
  139. proef/ingest.py +157 -0
  140. proef/instruments.json +173 -0
  141. proef/interpret.py +95 -0
  142. proef/kinetic.py +102 -0
  143. proef/labread/__init__.py +45 -0
  144. proef/labread/analysis.py +428 -0
  145. proef/labread/common.py +153 -0
  146. proef/labread/formats.py +190 -0
  147. proef/labread/layout.py +168 -0
  148. proef/labread/pubchem.py +179 -0
  149. proef/labselect.py +431 -0
  150. proef/materials.py +140 -0
  151. proef/mcp_instrument.py +396 -0
  152. proef/mcp_server.py +283 -0
  153. proef/modality.py +111 -0
  154. proef/model_guard.py +245 -0
  155. proef/output_blocks.py +183 -0
  156. proef/paths.py +32 -0
  157. proef/physfail.py +55 -0
  158. proef/plan.py +160 -0
  159. proef/plots.py +123 -0
  160. proef/predictors.py +217 -0
  161. proef/probes.py +79 -0
  162. proef/problem_tree.py +581 -0
  163. proef/program.py +308 -0
  164. proef/protocol_design.py +42 -0
  165. proef/proxy.py +78 -0
  166. proef/readiness.py +259 -0
  167. proef/reliability.py +49 -0
  168. proef/report.py +117 -0
  169. proef/reproduce.py +310 -0
  170. proef/reviewer.py +254 -0
  171. proef/sandbox_session.py +247 -0
  172. proef/sandboxd.py +109 -0
  173. proef/scaffold.py +195 -0
  174. proef/series.py +327 -0
  175. proef/skills.py +203 -0
  176. proef/sweep.py +83 -0
  177. proef/taste.py +177 -0
  178. proef/templates/confirmatory-followup.json +34 -0
  179. proef/templates/dose-response-screen.json +39 -0
  180. proef/templates/sar-exploration.json +38 -0
  181. proef/templates.py +124 -0
  182. proef/toolkit.py +433 -0
  183. proef/toolloop.py +133 -0
  184. proef/tools.py +441 -0
  185. proef/tpp.py +185 -0
  186. proef/views/__init__.py +14 -0
  187. proef/views/counts.py +102 -0
  188. proef/views/experiment.py +154 -0
  189. proef/views/ids.py +49 -0
  190. proef/views/narrative.py +294 -0
  191. proef/views/pipeline.py +370 -0
  192. proef/vision.py +165 -0
  193. proef/watch.py +790 -0
  194. proef/wizard_chain.py +25 -0
  195. proef/wizard_store.py +373 -0
  196. proef-0.2.0.dist-info/METADATA +662 -0
  197. proef-0.2.0.dist-info/RECORD +200 -0
  198. proef-0.2.0.dist-info/WHEEL +4 -0
  199. proef-0.2.0.dist-info/entry_points.txt +14 -0
  200. proef-0.2.0.dist-info/licenses/LICENSE +202 -0
proef/assays/dls.py ADDED
@@ -0,0 +1,114 @@
1
+ """DLS analysis — hydrodynamic radius from autocorrelation exports.
2
+
3
+ Parses dynamic-light-scattering autocorrelation curves (tau vs g2) and
4
+ computes, per measurement:
5
+
6
+ - translational decay rate Gamma from a linear cumulant fit of
7
+ ln(g2 - 1) over the first half-decade of tau
8
+ - hydrodynamic radius Rh via the Stokes-Einstein relation:
9
+ Rh = k_B * T / (6 * pi * eta * Gamma)
10
+ (water defaults: T = 298.15 K, eta = 0.890 cP; configurable)
11
+ - a polydispersity flag from the late-tau residual: multi-modal
12
+ (aggregated) samples bend the tail upward and fail the linear fit
13
+
14
+ Rh is an intensity-weighted estimate, not a distribution reconstruction
15
+ (CONTIN/regularized inversion needs the full correlation matrix and is
16
+ out of scope for a dependency-light core). Aggregation screening — the
17
+ biologics Make/Test boundary — is exactly what this estimate is for.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import csv
22
+ import math
23
+ from pathlib import Path
24
+
25
+ # water, 25 C
26
+ K_B = 1.380649e-23 # J/K
27
+ TEMP_K = 298.15
28
+ ETA = 0.00089 # Pa*s
29
+ # standard optical configuration: 660 nm laser, n = 1.33, 173 deg
30
+ # backscatter — q = 4*pi*n*sin(theta/2)/lambda
31
+ WAVELENGTH_NM = 660.0
32
+ N_MEDIUM = 1.33
33
+ ANGLE_DEG = 173.0
34
+
35
+
36
+ def _q_scattering() -> float:
37
+ import math
38
+ theta = math.radians(ANGLE_DEG)
39
+ return 4 * math.pi * N_MEDIUM * math.sin(theta / 2) / \
40
+ (WAVELENGTH_NM * 1e-9) # 1/m
41
+
42
+
43
+ def _num(v):
44
+ try:
45
+ return float(str(v).strip())
46
+ except (TypeError, ValueError):
47
+ return None
48
+
49
+
50
+ def read_dls(path: str | Path, temp_k: float = TEMP_K,
51
+ viscosity: float = ETA) -> dict:
52
+ curves: dict[str, list[tuple[float, float]]] = {}
53
+ with open(path, newline="", encoding="utf-8", errors="replace") as fh:
54
+ reader = csv.DictReader(fh)
55
+ fields = {k.lower().strip(): k for k in (reader.fieldnames or [])}
56
+ tau_col = next((fields[s] for s in ("tau", "time", "lag", "t")
57
+ if s in fields), None)
58
+ g2_col = next((fields[s] for s in ("g2", "correlation",
59
+ "autocorrelation", "g2-1")
60
+ if s in fields), None)
61
+ if not tau_col or not g2_col:
62
+ raise ValueError("DLS export needs tau + correlation columns; "
63
+ f"saw {reader.fieldnames}")
64
+ id_col = next((fields[s] for s in ("sample", "measurement", "well",
65
+ "id") if s in fields), None)
66
+ for row in reader:
67
+ tau, g2 = _num(row.get(tau_col)), _num(row.get(g2_col))
68
+ if tau is None or g2 is None or tau <= 0:
69
+ continue
70
+ key = str(row.get(id_col, "measurement")) if id_col else "meas"
71
+ curves.setdefault(key, []).append((tau, g2))
72
+
73
+ results = []
74
+ for name, pts in sorted(curves.items()):
75
+ pts.sort()
76
+ # cumulant-style linear fit on ln(g2-1) for tau in the first
77
+ # decade where g2 > baseline
78
+ # fit where the signal is still decaying: g2-1 above 10% of its
79
+ # dynamic range — late taus are pure baseline and skew the slope
80
+ g2max = max(g2 for _t, g2 in pts)
81
+ fit_pts = [(t, math.log(max(g2 - 1.0, 1e-9))) for t, g2 in pts
82
+ if g2 > 1.0 + 0.1 * (g2max - 1.0)]
83
+ fit_pts = fit_pts[:max(3, len(fit_pts))]
84
+ if len(fit_pts) < 3:
85
+ results.append({"measurement": name, "rh_nm": None,
86
+ "pdi_flag": None, "points": len(pts),
87
+ "note": "no decaying correlation above "
88
+ "baseline — no particles detected"})
89
+ continue
90
+ xs = [t for t, _y in fit_pts] # linear tau
91
+ ys = [y for _t, y in fit_pts]
92
+ n = len(xs)
93
+ sx, sy = sum(xs), sum(ys)
94
+ sxx = sum(x * x for x in xs)
95
+ sxy = sum(x * y for x, y in zip(xs, ys))
96
+ denom = n * sxx - sx * sx
97
+ slope = (n * sxy - sx * sy) / denom if denom else 0.0
98
+ gamma = max(-slope / 2.0, 1e-6) # decay rate, 1/s (g2 model)
99
+ # Stokes-Einstein with the standard q: Rh = k_B*T*q^2 / (6*pi*eta*Gamma)
100
+ q = _q_scattering()
101
+ rh_m = (K_B * temp_k * q * q) / (6 * math.pi * viscosity * gamma)
102
+ rh_nm = round(rh_m * 1e9, 2)
103
+ # polydispersity: residual of the tail against the linear fit
104
+ tail = pts[int(len(pts) * 0.6):]
105
+ pred = {t: 1 + math.exp(-2 * gamma * t) for t, _g in pts}
106
+ tail_dev = [abs(g2 - pred.get(t, g2)) for t, g2 in tail
107
+ if t in pred]
108
+ pdi = (sum(tail_dev) / len(tail_dev)) if tail_dev else 0.0
109
+ results.append({"measurement": name, "rh_nm": rh_nm,
110
+ "pdi_flag": "aggregated" if pdi > 0.1
111
+ else "monodisperse",
112
+ "points": len(pts), "note": ""})
113
+ return {"source": str(path), "temp_k": temp_k,
114
+ "viscosity_pa_s": viscosity, "curves": results}
proef/assays/dsf.py ADDED
@@ -0,0 +1,81 @@
1
+ """DSF analysis — thermal shifts from qPCR-style melt exports.
2
+
3
+ Parses long-format thermal melt data (temperature vs fluorescence per
4
+ well/curve — the export shape of qPCR instruments and DSF reader
5
+ attachments) and computes the melting temperature Tm per curve:
6
+
7
+ - Tm = temperature of the minimum of dF/dT (the fluorescence drop at
8
+ the unfolding transition), on a lightly smoothed curve
9
+ - span (F_max - F_min) is reported as a curve-quality flag: a flat
10
+ curve means no transition was observed, and that is reported rather
11
+ than guessed
12
+
13
+ Quantitative thermodynamics (DeltaH, DeltaS via Boltzmann fitting) is
14
+ deliberately out of scope here — Tm is the decision variable for
15
+ comparing construct stability.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from pathlib import Path
20
+ import csv
21
+
22
+ TempSynonyms = ("temperature", "temp", "t", "celsius")
23
+ ValueSynonyms = ("fluorescence", "fluor", "rfu", "value", "f")
24
+
25
+
26
+ def _num(v):
27
+ try:
28
+ return float(str(v).strip())
29
+ except (TypeError, ValueError):
30
+ return None
31
+
32
+
33
+ def read_dsf(path: str | Path) -> dict:
34
+ """Parses long-format rows: id-ish column, temperature, fluorescence.
35
+ Returns {"source", "curves": [{curve, tm, span, points}]}."""
36
+ curves: dict[str, list[tuple[float, float]]] = {}
37
+ with open(path, newline="", encoding="utf-8", errors="replace") as fh:
38
+ reader = csv.DictReader(fh)
39
+ fields = {k.lower().strip(): k for k in (reader.fieldnames or [])}
40
+ temp_col = next((fields[s] for s in TempSynonyms
41
+ if s in fields), None)
42
+ val_col = next((fields[s] for s in ValueSynonyms if s in fields),
43
+ None)
44
+ if not temp_col or not val_col:
45
+ raise ValueError("DSF export needs temperature + fluorescence "
46
+ f"columns; saw {reader.fieldnames}")
47
+ id_col = next((fields[s] for s in ("well", "sample", "curve", "id")
48
+ if s in fields), None)
49
+ for row in reader:
50
+ t, v = _num(row.get(temp_col)), _num(row.get(val_col))
51
+ if t is None or v is None:
52
+ continue
53
+ key = str(row.get(id_col, "curve")) if id_col else "curve"
54
+ curves.setdefault(key, []).append((t, v))
55
+
56
+ results = []
57
+ for name, pts in sorted(curves.items()):
58
+ pts.sort()
59
+ if len(pts) < 5:
60
+ results.append({"curve": name, "tm": None, "span": None,
61
+ "points": len(pts),
62
+ "note": "too few points for a transition"})
63
+ continue
64
+ vals = [v for _t, v in pts]
65
+ span = max(vals) - min(vals)
66
+ if span <= 0:
67
+ results.append({"curve": name, "tm": None, "span": round(span, 3),
68
+ "points": len(pts),
69
+ "note": "flat curve — no transition observed"})
70
+ continue
71
+ # Tm = the steepest point of the transition (peak |dF/dT| on a
72
+ # 3-point window) — works for rising and falling transitions
73
+ tm, best = None, -1.0
74
+ for i in range(1, len(pts) - 1):
75
+ deriv = abs((pts[i - 1][1] - pts[i + 1][1]) / 2.0)
76
+ if deriv > best:
77
+ best, tm = deriv, pts[i][0]
78
+ results.append({"curve": name, "tm": round(tm, 2),
79
+ "span": round(span, 3), "points": len(pts),
80
+ "note": ""})
81
+ return {"source": str(path), "curves": results}
proef/assays/elisa.py ADDED
@@ -0,0 +1,58 @@
1
+ """ELISA analysis — immunogenicity/serology from plate-reader files.
2
+
3
+ Parses the same long/grid formats as `labread.read_plate` (any vendor
4
+ CSV/XLSX: Molecular Devices, Tecan, ...), then computes:
5
+
6
+ - cutoff = mean(blank) + 3 x sd(blank) (standard serology rule)
7
+ - per sample: max OD, endpoint titer (highest dilution with OD >= cutoff,
8
+ when a dilution column is present), and a positive/negative call
9
+
10
+ Honest scope: a qualitative screen and titer, not a calibrated
11
+ concentration — that needs a validated standard curve on the same plate.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+
17
+ from proef.labread import read_plate
18
+
19
+
20
+ def read_elisa(path: str | Path, blank_pattern: str = "blank") -> dict:
21
+ pr = read_plate(path)
22
+ records = [r for r in pr.records if r.get("value") is not None]
23
+ blanks = [float(r["value"]) for r in records
24
+ if r.get("control") or blank_pattern in
25
+ str(r.get("sample", "")).lower()]
26
+ samples = [r for r in records
27
+ if r.get("value") is not None and not r.get("control")
28
+ and blank_pattern not in str(r.get("sample", "")).lower()]
29
+ if blanks:
30
+ mean_b = sum(blanks) / len(blanks)
31
+ sd_b = (sum((v - mean_b) ** 2 for v in blanks)
32
+ / max(1, len(blanks) - 1)) ** 0.5 if len(blanks) > 1 else 0.0
33
+ cutoff = mean_b + 3 * sd_b
34
+ else:
35
+ vals = sorted(float(r["value"]) for r in records)
36
+ cutoff = vals[len(vals) // 2] if vals else 0.0 # no blanks: median
37
+
38
+ per_sample: dict[str, list[dict]] = {}
39
+ for r in samples:
40
+ per_sample.setdefault(str(r.get("sample")), []).append(r)
41
+
42
+ rows = []
43
+ for sample, rs in sorted(per_sample.items()):
44
+ rs_sorted = sorted(rs, key=lambda r: float(r.get("conc_um") or 0))
45
+ max_od = max(float(r["value"]) for r in rs)
46
+ positive = max_od >= cutoff
47
+ titer = None
48
+ if len(rs) > 1 and any(r.get("conc_um") for r in rs):
49
+ # dilution series: titer = highest dilution still >= cutoff
50
+ above = [float(r["conc_um"]) for r in rs_sorted
51
+ if float(r["value"]) >= cutoff]
52
+ titer = max(above) if above else None
53
+ rows.append({"sample": sample, "max_od": round(max_od, 3),
54
+ "titer": titer,
55
+ "call": "positive" if positive else "negative"})
56
+ return {"source": str(path), "cutoff": round(cutoff, 4),
57
+ "n_blanks": len(blanks), "results": rows,
58
+ "response_unit": pr.response_unit}
@@ -0,0 +1,65 @@
1
+ """Property-sweep analysis — the materials Analyze phase.
2
+
3
+ Reads a formulation sweep export (param vs measured property), finds the
4
+ best-performing formulation, and reports how sharply the property peaks
5
+ (so a flat sweep is reported honestly as 'no optimum found' instead of a
6
+ spurious winner).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+ import csv
12
+
13
+
14
+ def _num(v):
15
+ try:
16
+ return float(str(v).strip())
17
+ except (TypeError, ValueError):
18
+ return None
19
+
20
+
21
+ def read_property_sweep(path: str | Path, param: str | None = None,
22
+ metric: str | None = None) -> dict:
23
+ """Parses rows with a parameter column and a metric column; returns
24
+ the best formulation, the peak sharpness, and all points."""
25
+ with open(path, newline="", encoding="utf-8", errors="replace") as fh:
26
+ reader = csv.DictReader(fh)
27
+ fields = {k.lower().strip(): k for k in (reader.fieldnames or [])}
28
+ param_col = fields.get((param or "").lower()) or next(
29
+ (fields[s] for s in ("crosslinker_pct", "dopant", "param",
30
+ "concentration", "value")
31
+ if s in fields), None)
32
+ metric_col = fields.get((metric or "").lower()) or next(
33
+ (fields[s] for s in ("tensile_strength_mpa", "conductivity",
34
+ "property", "strength", "metric")
35
+ if s in fields), None)
36
+ if not param_col or not metric_col:
37
+ raise ValueError("sweep export needs a parameter column and a "
38
+ f"metric column; saw {reader.fieldnames}")
39
+ id_col = next((fields[s] for s in ("sample", "id", "formulation")
40
+ if s in fields), None)
41
+ pts = []
42
+ for row in reader:
43
+ x, y = _num(row.get(param_col)), _num(row.get(metric_col))
44
+ if x is None or y is None:
45
+ continue
46
+ pts.append((x, y, str(row.get(id_col, f"F{len(pts) + 1}"))))
47
+ if len(pts) < 3:
48
+ raise ValueError("need at least 3 sweep points")
49
+
50
+ pts.sort()
51
+ best_x, best_y, best_id = max(pts, key=lambda p: p[1])
52
+ xs = [p[0] for p in pts]
53
+ span = max(xs) - min(xs)
54
+ # sharpness: how much better the best is vs the sweep mean
55
+ mean_y = sum(p[1] for p in pts) / len(pts)
56
+ sharpness = (best_y - mean_y) / max(span / max(len(pts) - 1, 1), 1e-9)
57
+ return {"source": str(path), "param": param_col, "metric": metric_col,
58
+ "points": [{"param": x, "value": y, "sample": sid}
59
+ for x, y, sid in pts],
60
+ "best": {"param": best_x, "value": round(best_y, 3),
61
+ "sample": best_id},
62
+ "peak_sharpness": round(sharpness, 3),
63
+ "note": "" if sharpness > 1.0 else
64
+ "flat sweep — no optimum stands out; do not over-read the "
65
+ "best point"}
@@ -0,0 +1,157 @@
1
+ """Simulate the biologics readouts — synthetic instrument exports with
2
+ known ground truth, for pipeline validation without physical machines.
3
+
4
+ - DLS: Brownian motion + scattering physics per the Raynals approach —
5
+ each particle size contributes exp(-Gamma_i * tau) to the FIELD
6
+ correlation; g2 = 1 + beta * |sum(w_i g1_i)|^2. A distribution of
7
+ sizes produces a Tikhonov-style multi-exponential decay. Deterministic
8
+ under a seed; noise is Gaussian.
9
+ - ELISA: 4-parameter logistic (4PL) antigen-antibody saturation —
10
+ response = bottom + (top - bottom) / (1 + (conc/ec50)^hill), plus
11
+ blank wells and Gaussian noise.
12
+ - DSF: two-state Boltzmann unfolding — fraction folded = 1/(1 +
13
+ exp((T - Tm)/steepness)), folded + unfolded baselines, Gaussian noise.
14
+
15
+ Every simulator returns (rows, truth): `rows` are CSV-ready instrument
16
+ lines, `truth` is the ground truth the matching analysis adapter must
17
+ recover. roundtrip tests assert exactly that.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ import random
23
+
24
+ # water, 25 C, standard 660 nm / 173 deg backscatter (matches assays.dls)
25
+ K_B = 1.380649e-23
26
+ TEMP_K = 298.15
27
+ ETA = 0.00089
28
+ Q_SCATTERING = 2.528e7 # 1/m (see assays.dls._q_scattering)
29
+
30
+
31
+ def _gamma_for_rh(rh_nm: float) -> float:
32
+ """Translational decay rate of a particle with hydrodynamic radius
33
+ rh_nm: Gamma = D * q^2, D = k_B*T / (6*pi*eta*Rh)."""
34
+ d = (K_B * TEMP_K) / (6 * math.pi * ETA * (rh_nm * 1e-9))
35
+ return d * Q_SCATTERING ** 2
36
+
37
+
38
+ # ------------------------------------------------------------------- DLS
39
+
40
+ def simulate_dls(species: list[tuple[float, float]],
41
+ beta: float = 0.8,
42
+ n_points: int = 60,
43
+ tau_start_s: float = 1e-6,
44
+ tau_growth: float = 1.15,
45
+ noise: float = 0.004,
46
+ seed: int = 7,
47
+ sample_id: str = "M1") -> tuple[list[dict], dict]:
48
+ """species = [(rh_nm, weight), ...] (weights need not sum to 1).
49
+ Returns (rows, truth)."""
50
+ rh_list = [rh for rh, _w in species]
51
+ truth = {
52
+ "rh_intensity_weighted_nm": round(
53
+ sum(rh * w for rh, w in species) / sum(w for _r, w in species),
54
+ 3),
55
+ "gammas": [round(_gamma_for_rh(rh), 1) for rh, _w in species],
56
+ "species": species, "seed": seed}
57
+ rng = random.Random(seed)
58
+ rows = []
59
+ tau = tau_start_s
60
+ for _i in range(n_points):
61
+ g1 = sum(w * math.exp(-_gamma_for_rh(rh) * tau)
62
+ for rh, w in species)
63
+ g2 = 1.0 + beta * g1 * g1 + rng.gauss(0, noise)
64
+ rows.append({"Sample": sample_id, "Tau": f"{tau:.3e}",
65
+ "Correlation": f"{max(g2, 1.0):.6f}"})
66
+ tau *= tau_growth
67
+ return rows, truth
68
+
69
+
70
+ # ----------------------------------------------------------------- ELISA
71
+
72
+ def simulate_elisa(top: float = 1.5, bottom: float = 0.08,
73
+ ec50: float = 120.0, hill: float = 1.2,
74
+ dilutions: list[int] | None = None,
75
+ n_blanks: int = 3, blank_od: float = 0.08,
76
+ noise: float = 0.01,
77
+ seed: int = 11,
78
+ sample_id: str = "S1") -> tuple[list[dict], dict]:
79
+ """4PL antigen-antibody saturation over a dilution series. The
80
+ dilution column is 1/dilution-factor order as in real serology
81
+ exports (lowest concentration first)."""
82
+ dilutions = dilutions or [0.001, 0.01, 0.1, 1.0, 10.0]
83
+ rng = random.Random(seed)
84
+
85
+ def well(i: int) -> str:
86
+ # standard 96-well coordinates: A1.. row-major (12 columns)
87
+ return f"{chr(65 + i // 12)}{i % 12 + 1}"
88
+
89
+ rows = [{"Well": well(i), "Sample": "blank", "Conc": "0",
90
+ "OD": f"{blank_od + rng.gauss(0, noise):.4f}"}
91
+ for i in range(n_blanks)]
92
+ truth = {"top": top, "bottom": bottom, "ec50": ec50, "hill": hill,
93
+ "seed": seed}
94
+ for i, dil in enumerate(dilutions):
95
+ resp = bottom + (top - bottom) / (1 + (dil / ec50) ** hill)
96
+ rows.append({"Well": well(n_blanks + i), "Sample": sample_id,
97
+ "Conc": str(dil),
98
+ "OD": f"{max(resp + rng.gauss(0, noise), 0):.4f}"})
99
+ return rows, truth
100
+
101
+
102
+ # ------------------------------------------------- materials property sweep
103
+
104
+ def simulate_property_sweep(formulations: list[float],
105
+ optimum: float = 6.0,
106
+ peak_value: float = 85.0,
107
+ width: float = 2.5,
108
+ noise: float = 1.5,
109
+ seed: int = 13,
110
+ metric: str = "tensile_strength_mpa",
111
+ param: str = "crosslinker_pct") -> tuple[
112
+ list[dict], dict]:
113
+ """Materials Design-of-Experiments: a property responds to a
114
+ formulation parameter through a smooth peak (quadratic around the
115
+ optimum) — tensile strength vs crosslinker density, conductivity vs
116
+ dopant ratio, etc. Deterministic; truth carries the true optimum so
117
+ the analysis adapter can be checked against it."""
118
+ rng = random.Random(seed)
119
+ rows, values = [], []
120
+ for i, x in enumerate(formulations):
121
+ v = peak_value - ((x - optimum) / width) ** 2 * 10
122
+ v = max(0.0, v + rng.gauss(0, noise))
123
+ values.append(v)
124
+ rows.append({"Sample": f"F{i + 1}", param: f"{x:g}",
125
+ metric: f"{v:.2f}"})
126
+ return rows, {"true_optimum": optimum, "peak_value": peak_value,
127
+ "metric": metric, "param": param,
128
+ "measured_best": formulations[max(range(len(values)),
129
+ key=values.__getitem__)],
130
+ "measured_best_value": round(max(values), 2),
131
+ "seed": seed}
132
+
133
+
134
+ # ------------------------------------------------------------------ DSF
135
+
136
+ def simulate_dsf(tm: float = 65.0, steepness: float = 2.0,
137
+ folded_baseline: float = 20.0,
138
+ unfolded_baseline: float = 100.0,
139
+ t_range: tuple[float, float] = (40.0, 90.0),
140
+ n_points: int = 100, noise: float = 0.6,
141
+ seed: int = 3,
142
+ well: str = "A1") -> tuple[list[dict], dict]:
143
+ """Two-state Boltzmann unfolding: fraction folded =
144
+ 1 / (1 + exp((T - Tm)/steepness)); signal = folded*base_f +
145
+ unfolded*base_u + noise."""
146
+ rng = random.Random(seed)
147
+ rows, truth = [], {"tm": tm, "steepness": steepness, "seed": seed}
148
+ lo, hi = t_range
149
+ for i in range(n_points):
150
+ t = lo + (hi - lo) * i / (n_points - 1)
151
+ folded = 1.0 / (1.0 + math.exp((t - tm) / steepness))
152
+ signal = (folded_baseline * folded
153
+ + unfolded_baseline * (1 - folded)
154
+ + rng.gauss(0, noise))
155
+ rows.append({"Well": well, "Temperature": f"{t:.2f}",
156
+ "Fluorescence": f"{signal:.3f}"})
157
+ return rows, truth
proef/audit.py ADDED
@@ -0,0 +1,152 @@
1
+ """The checkpoint audit: read a finished campaign's ledger and list every place a checkpoint did not hold.
2
+
3
+ Each rule is an invariant the engine is supposed to keep whatever drove it: a fixed loop, a model orchestrator, a rogue tool, a halt in
4
+ the middle. The audit reads only the ledger (plus, optionally, the store to verify the hash chain), so it also works on a campaign
5
+ someone else ran. The evals count violations over many campaigns and the number must be zero. A rule that has never been seen to
6
+ fire is not trusted: every rule has a synthetic violation in `tests/test_audit.py` that it must catch.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ VERDICT_EVENTS = ("hypothesis_validated", "hypothesis_invalidated", "hypothesis_inconclusive")
14
+
15
+
16
+ @dataclass
17
+ class Violation:
18
+ rule: str
19
+ detail: str
20
+
21
+ def __str__(self) -> str:
22
+ return f"{self.rule}: {self.detail}"
23
+
24
+
25
+ def _kind(r: Any) -> str:
26
+ return (getattr(r, "decision", None) or {}).get("kind", "")
27
+
28
+
29
+ def _et(r: Any) -> str:
30
+ return getattr(getattr(r, "event_type", None), "value", str(getattr(r, "event_type", "")))
31
+
32
+
33
+ def audit_campaign(recs: list, store: Any = None, branch: str | None = None) -> list[Violation]:
34
+ """Every checkpoint violation in these records, or [] when all hold."""
35
+ v: list[Violation] = []
36
+ problem = next((r.decision for r in recs if _et(r) == "problem_defined"), None) or {}
37
+ env = problem.get("environment") or {}
38
+ limit = next((c.get("limit") for c in problem.get("constraints", []) if c.get("kind") == "hard" and c.get("limit") is not None), None)
39
+
40
+ runs = [(i, r) for i, r in enumerate(recs) if _et(r) == "lab_run"]
41
+ run_ids = {(r.decision or {}).get("run_id") for _, r in runs}
42
+
43
+ # 0. a campaign with failed model calls says so (it ran on fallbacks, so it did not run as configured)
44
+ errs = [r.decision for r in recs if _kind(r) == "model_error"]
45
+ if env and errs:
46
+ from proef.model_guard import failure_effect
47
+ dep = [e for e in errs if failure_effect(str(e.get("purpose") or e.get("role")), env) == "dependency"]
48
+ if dep and not any(_kind(r) == "campaign_degraded" for r in recs):
49
+ v.append(Violation("degradation_reported", f"{len(dep)} model call(s) the campaign depends on failed and it does not say it ran degraded"))
50
+ if len(dep) < len(errs) and not any(_kind(r) in ("model_advisory_failures", "campaign_degraded") for r in recs):
51
+ v.append(Violation("degradation_reported", "an advisory model call failed and the campaign does not note it"))
52
+
53
+ # 1. observe submits nothing
54
+ if env.get("autonomy") == "observe" and runs:
55
+ v.append(Violation("observe_runs_nothing", f"{len(runs)} lab run(s) under observe"))
56
+
57
+ # 2. under approvals, a plan-covered run is recorded as covered (confirmation assays follow their own gate)
58
+ if env.get("autonomy") == "gate" and env.get("plan_review"):
59
+ covered = sum(1 for r in recs if _kind(r) == "covered_by_plan")
60
+ tests = [r for _, r in runs if not str((r.decision or {}).get("title", "")).startswith("auto-confirmation")]
61
+ if tests and covered < len(tests):
62
+ v.append(Violation("gated_runs_are_covered", f"{len(tests)} test run(s) but only {covered} covered_by_plan record(s)"))
63
+
64
+ # 3. a person's decision is a person's: the engine never writes one
65
+ for r in recs:
66
+ if _kind(r) == "human_review" and getattr(getattr(r, "actor", None), "kind", None) is not None and r.actor.kind.value != "human":
67
+ v.append(Violation("no_decision_by_a_machine", f"human_review recorded by {r.actor.id} ({r.actor.kind.value})"))
68
+
69
+ # 4. every verdict is judged by the program's gate, and a placeholder only ever abstains
70
+ for r in recs:
71
+ if _et(r) in VERDICT_EVENTS:
72
+ d = r.decision or {}
73
+ if d.get("criteria_preregistered") is False and _et(r) != "hypothesis_inconclusive":
74
+ v.append(Violation("placeholder_abstains", f"{_et(r)} on a criterion nobody registered"))
75
+ if d.get("criteria_preregistered") and limit is not None and d.get("threshold") is not None \
76
+ and d.get("metric") == "ic50_um" and not _same(d["threshold"], limit):
77
+ v.append(Violation("gate_is_the_programs", f"verdict judged at {d['threshold']}, the program's gate is {limit}"))
78
+ ev = d.get("evidence_run_id")
79
+ if ev and run_ids and ev not in run_ids and not str(ev).startswith("hand"):
80
+ v.append(Violation("verdict_has_evidence", f"evidence run {ev} is not a run in this branch"))
81
+ if "free-text" in str(d.get("declared_by", "")):
82
+ v.append(Violation("no_free_text_verdict", "a verdict declared by an agent in free text"))
83
+
84
+ # 5. an orchestrator can only choose what was allowed
85
+ for r in recs:
86
+ if _kind(r) == "orchestrator_choice":
87
+ d = r.decision
88
+ if d.get("chosen") not in (d.get("allowed") or []):
89
+ v.append(Violation("choice_is_allowed", f"round {d.get('round')}: chose {d.get('chosen')!r}, allowed {d.get('allowed')}"))
90
+
91
+ # 6. nothing runs after the campaign was ended. A stop by the switch or the wall clock also spends no more model calls; a stop the
92
+ # orchestrator chose ends the ROUNDS, and the advisory review of what was learned still runs, so only its calls are allowed
93
+ stop_at = next((i for i, r in enumerate(recs) if _kind(r) == "campaign_stopped"), None)
94
+ if stop_at is not None:
95
+ why = recs[stop_at].decision.get("why")
96
+ later = [r for r in recs[stop_at + 1:]
97
+ if _et(r) == "lab_run"
98
+ or (_kind(r) == "model_call" and not (why == "orchestrator" and r.decision.get("role") == "reviewer"))]
99
+ if later:
100
+ v.append(Violation("nothing_after_a_stop", f"{len(later)} lab run(s) or model call(s) after the campaign ended ({why})"))
101
+
102
+ # 7. budgets hold
103
+ b = env.get("budget") or {}
104
+ calls = [r for r in recs if _kind(r) == "model_call"]
105
+ if b.get("max_total_runs") is not None and len(runs) > b["max_total_runs"]:
106
+ v.append(Violation("run_budget_holds", f"{len(runs)} lab runs, cap {b['max_total_runs']}"))
107
+ if b.get("max_model_calls") is not None and len(calls) > b["max_model_calls"]:
108
+ v.append(Violation("model_call_budget_holds", f"{len(calls)} model calls, cap {b['max_model_calls']}"))
109
+
110
+ # 8. every model call has its answer (or its failure) sealed, numbered without gaps
111
+ answered = {(r.decision or {}).get("n") for r in recs if _kind(r) in ("model_response", "model_error")}
112
+ missing = [(r.decision or {}).get("n") for r in calls if (r.decision or {}).get("n") not in answered]
113
+ if missing:
114
+ v.append(Violation("model_calls_are_sealed", f"call(s) {missing} have no sealed answer"))
115
+ ns = [(r.decision or {}).get("n") for r in calls]
116
+ if ns and ns != list(range(1, len(ns) + 1)):
117
+ v.append(Violation("model_calls_are_numbered", f"call numbers {ns}"))
118
+
119
+ # 9. accept and drop are suggestions: never executed. A follow-up exists only because a valid proposal asked for it.
120
+ props = {(r.decision or {}).get("hypothesis_id"): r.decision for r in recs if _kind(r) == "followup_proposal"}
121
+ for hid, d in props.items():
122
+ if d.get("action") in ("accept", "drop") and d.get("executes"):
123
+ v.append(Violation("person_decisions_are_not_executed", f"{d['action']} on {hid} marked as executable"))
124
+ for r in recs:
125
+ if _et(r) == "hypothesis_proposed" and (r.decision or {}).get("followup_of"):
126
+ src = props.get(r.decision["followup_of"])
127
+ if not src or not (src.get("validation") or {}).get("ok") or not src.get("executes") or src.get("action") != "follow_up":
128
+ v.append(Violation("follow_up_was_validated", f"follow-up of {r.decision['followup_of']} has no valid proposal behind it"))
129
+
130
+ # 10. a hypothesis the campaign's lab could not serve was never run
131
+ blocked = {(r.decision or {}).get("candidate") for r in recs if _kind(r) == "lab_cannot_serve"}
132
+ for _, r in runs:
133
+ title = str((r.decision or {}).get("title", ""))
134
+ if title.startswith("test-") and title[5:] in blocked:
135
+ v.append(Violation("unserved_hypotheses_do_not_run", f"{title[5:]} was refused by the lab check and ran anyway"))
136
+
137
+ # 11. the hash chain is intact
138
+ if store is not None and branch:
139
+ try:
140
+ bad = store.verify_chain(branch)
141
+ except Exception as exc: # noqa: BLE001
142
+ bad = [{"error": f"{type(exc).__name__}: {exc}"}]
143
+ if bad:
144
+ v.append(Violation("chain_verifies", f"{len(bad)} chain problem(s)"))
145
+ return v
146
+
147
+
148
+ def _same(a: Any, b: Any) -> bool:
149
+ try:
150
+ return abs(float(a) - float(b)) < 1e-9
151
+ except (TypeError, ValueError):
152
+ return a == b