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/program.py ADDED
@@ -0,0 +1,308 @@
1
+ """Program profile — the TPP one level above experiments.
2
+
3
+ Hierarchy: Program (TPP) ▸ Problem (objective + constraints) ▸ Hypothesis
4
+ (success criteria) ▸ Experiment (evidence). The program is node-local state
5
+ (.data/program.json); the wizard and the launch dialog read their default
6
+ potency bar from it so the TPP actually *governs* things instead of being a
7
+ poster on the wall.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from pathlib import Path
13
+
14
+ from proef.tpp import CriterionPhase, standard_small_molecule_tpp
15
+
16
+ PATH = Path(".data/program.json")
17
+
18
+ DEFAULT = {
19
+ "program": "My-Program",
20
+ "target": "MAP4K1",
21
+ "gate": "hit", # which phase this campaign is screening against
22
+ "hit_ic50_nm": 1000.0, # hit gate: any signal worth following
23
+ "lead_ic50_nm": 50.0, # lead gate: worth investing chemistry in
24
+ # custom-problem mode: ANY metric, not just small-molecule IC50.
25
+ # when custom is true the IC50 fields above are ignored and the gate
26
+ # is (metric, direction, gate_value, unit) with a free-text objective.
27
+ "custom": False,
28
+ "objective": "",
29
+ "modality": "", # e.g. small molecule, biologic, cell
30
+ # therapy, agrochemical, material —
31
+ # free text; the flow is modality-agnostic
32
+ "metric": "ic50",
33
+ "unit": "µM",
34
+ "direction": "min", # min = lower is better
35
+ "gate_value": 20.0,
36
+ }
37
+
38
+ GATE_LABELS = {p.value: p for p in CriterionPhase}
39
+
40
+
41
+ # ------------------------------------------------------ program registry
42
+ # Programs are first-class shared records in the provenance store: every
43
+ # user of a shared service sees the same program roots. program.json
44
+ # remains only the LOCAL pointer to the active program (wizard defaults).
45
+
46
+ def _slug(name: str) -> str:
47
+ import re as _re
48
+ s = _re.sub(r"[^a-zA-Z0-9]+", "-", (name or "program").lower()).strip("-")
49
+ return s[:48] or "program"
50
+
51
+
52
+ def save_program_record(doc: dict, slug: str | None = None) -> str:
53
+ """Register/refresh a program as a shared provenance root. Returns
54
+ the program branch id (programs/<slug>)."""
55
+ from proef.adapters.store.sqlite import get_store
56
+ from proef.core.contracts import Envelope, EventType
57
+ from proef.core.interfaces import record_for, system_actor
58
+ slug = slug or _slug(doc.get("program"))
59
+ branch = f"programs/{slug}"
60
+ # relational row: the query source for the workspace
61
+ from proef.wizard_store import WizardStore
62
+ WizardStore().upsert_program(slug, doc.get("program", slug), doc)
63
+ store = get_store("proef.db")
64
+ store.append(record_for(
65
+ Envelope(experiment_branch_id=branch),
66
+ EventType.problem_defined, system_actor("program"),
67
+ decision={"kind": "program_root", "program_id": slug,
68
+ "name": doc.get("program", slug),
69
+ "mode": doc.get("mode", "autonomous"),
70
+ "program": doc,
71
+ "gate_summary": gate_summary(doc)}))
72
+ return branch
73
+
74
+
75
+ def attach_experiment(program_name: str, eid: str, problem_id: str,
76
+ question: str, status: str = "executing") -> str | None:
77
+ """Attach an experiment to a program root: it becomes a leaf of the
78
+ program's tree in the shared registry instead of a free-standing
79
+ node. Append-only: the latest record carries the attachment list."""
80
+ slug = _slug(program_name)
81
+ existing = {x["slug"]: x for x in list_programs()}
82
+ if slug not in existing:
83
+ return None
84
+ from proef.wizard_store import WizardStore
85
+ WizardStore().link_experiment(slug, eid, role="leaf",
86
+ campaign_root=problem_id or None,
87
+ question=question, status=status)
88
+ from proef.adapters.store.sqlite import get_store
89
+ from proef.core.contracts import Envelope, EventType
90
+ from proef.core.interfaces import record_for, system_actor
91
+ prev = existing[slug]
92
+ attachments = [a for a in prev.get("attachments", [])
93
+ if a.get("eid") != eid]
94
+ attachments.append({"eid": eid, "problem_id": problem_id,
95
+ "question": question[:120], "status": status,
96
+ "ts": __import__("time").time()})
97
+ store = get_store("proef.db")
98
+ store.append(record_for(
99
+ Envelope(experiment_branch_id=f"programs/{slug}"),
100
+ EventType.problem_defined, system_actor("program"),
101
+ decision={"kind": "program_root", "program_id": slug,
102
+ "program": prev.get("program", {}),
103
+ "gate_summary": prev.get("gate_summary", ""),
104
+ "attachments": attachments}))
105
+ return branch_of(slug)
106
+
107
+
108
+ def record_launch(program_name: str, root_id: str, objective: str = "") -> None:
109
+ """Link a campaign's problem-tree root to a program (append-only).
110
+ This single record is what nests the tree under the program in the
111
+ workspace: Program -> Autonomous campaign -> problem tree."""
112
+ slug = _slug(program_name)
113
+ from proef.wizard_store import WizardStore
114
+ WizardStore().link_experiment(slug, root_id, role="campaign",
115
+ campaign_root=root_id,
116
+ question=objective)
117
+ from proef.adapters.store.sqlite import get_store
118
+ from proef.core.contracts import Envelope, EventType
119
+ from proef.core.interfaces import record_for, system_actor
120
+ get_store("proef.db").append(record_for(
121
+ Envelope(experiment_branch_id=f"programs/{slug}"),
122
+ EventType.problem_defined, system_actor("program"),
123
+ decision={"kind": "program_launch", "program_id": slug,
124
+ "name": program_name, "root": root_id,
125
+ "objective": (objective or "")[:120]}))
126
+
127
+
128
+ def link_leaf(program_name: str, eid: str, campaign_root: str,
129
+ question: str, status: str = "executing") -> None:
130
+ """Register a campaign leaf under a program (relational only — the
131
+ provenance audit trail is written by the campaign itself)."""
132
+ slug = _slug(program_name)
133
+ from proef.wizard_store import WizardStore
134
+ WizardStore().link_experiment(slug, eid, role="leaf",
135
+ campaign_root=campaign_root,
136
+ question=question, status=status)
137
+
138
+
139
+ def launches_by_program() -> dict:
140
+ """program name -> list of linked problem-tree root ids (relation)."""
141
+ from proef.paths import DATA_DIR
142
+ if not (DATA_DIR / "wizard.db").exists():
143
+ return {}
144
+ from proef.wizard_store import WizardStore
145
+ ws = WizardStore()
146
+ out: dict = {}
147
+ for p in ws.db_programs():
148
+ for l in ws.program_links(p["slug"]):
149
+ if l["role"] == "campaign" and l["campaign_root"]:
150
+ out.setdefault(p["name"], []).append(l["campaign_root"])
151
+ return out
152
+
153
+
154
+ def delete_program(program_name: str) -> bool:
155
+ """Delete a program: relations + program row go, experiments survive
156
+ unlinked, and a tombstone is appended to provenance."""
157
+ slug = _slug(program_name)
158
+ from proef.adapters.store.sqlite import get_store
159
+ from proef.core.contracts import Envelope, EventType
160
+ from proef.core.interfaces import record_for, system_actor
161
+ from proef.wizard_store import WizardStore
162
+ ws = WizardStore()
163
+ if ws.get_program(slug) is None:
164
+ return False
165
+ ws.delete_program(slug)
166
+ get_store("proef.db").append(record_for(
167
+ Envelope(experiment_branch_id=f"programs/{slug}"),
168
+ EventType.problem_defined, system_actor("program"),
169
+ decision={"kind": "program_deleted", "program_id": slug,
170
+ "name": program_name}))
171
+ return True
172
+
173
+
174
+ def links_for(program_name: str) -> list[dict]:
175
+ """All program_experiments relations for a program slug."""
176
+ from proef.wizard_store import WizardStore
177
+ return WizardStore().program_links(_slug(program_name))
178
+
179
+
180
+ def branch_of(slug: str) -> str:
181
+ return f"programs/{slug}"
182
+
183
+
184
+ def attachments_for(program_name: str) -> list[dict]:
185
+ slug = _slug(program_name)
186
+ for x in list_programs():
187
+ if x["slug"] == slug:
188
+ return x.get("attachments", [])
189
+ return []
190
+
191
+
192
+ def list_programs() -> list[dict]:
193
+ """Programs from the relational tables; first call migrates any
194
+ legacy provenance-only programs into them."""
195
+ from proef.wizard_store import WizardStore
196
+ ws = WizardStore()
197
+ if ws.db_program_count() == 0 and Path("proef.db").exists():
198
+ _migrate_from_provenance(ws)
199
+ out = []
200
+ for p in ws.db_programs():
201
+ doc = p["doc"]
202
+ slug = p["slug"]
203
+ attachments = [{"eid": l["eid"], "question": l["question"],
204
+ "status": l["status"]}
205
+ for l in ws.program_links(slug)
206
+ if l["role"] == "leaf"]
207
+ out.append({"branch": f"programs/{slug}", "slug": slug,
208
+ "name": p["name"], "program": doc,
209
+ "mode": doc.get("mode", "autonomous"),
210
+ "gate_summary": gate_summary(doc),
211
+ "attachments": attachments})
212
+ return out
213
+
214
+
215
+ def _migrate_from_provenance(ws) -> None:
216
+ """One-time: seed the relational programs table from legacy
217
+ provenance-only program records."""
218
+ from proef.adapters.store.sqlite import get_store
219
+ store = get_store("proef.db")
220
+ for br in store.branches():
221
+ if not br.startswith("programs/") or br.count("/") != 1:
222
+ continue
223
+ recs = store.branch_records(br)
224
+ latest = next((r.decision or {} for r in reversed(recs)
225
+ if (r.decision or {}).get("kind") == "program_root"),
226
+ None)
227
+ if not latest:
228
+ continue
229
+ slug = br.split("/", 1)[1]
230
+ # a deletion tombstone on the branch means the program was
231
+ # intentionally removed — never resurrect it
232
+ if any((r.decision or {}).get("kind") == "program_deleted"
233
+ for r in recs):
234
+ continue
235
+ doc = latest.get("program", {})
236
+ name = latest.get("name", latest.get("program_id", slug))
237
+ ws.upsert_program(slug, name, doc)
238
+ for a in latest.get("attachments", []):
239
+ if a.get("eid"):
240
+ ws.link_experiment(slug, a["eid"], role="leaf",
241
+ campaign_root=a.get("problem_id"),
242
+ question=a.get("question", ""),
243
+ status=a.get("status", "executing"))
244
+
245
+
246
+ def load() -> dict:
247
+ if PATH.exists():
248
+ try:
249
+ doc = {**DEFAULT, **json.loads(PATH.read_text())}
250
+ return doc
251
+ except Exception:
252
+ pass
253
+ return dict(DEFAULT)
254
+
255
+
256
+ def save(doc: dict) -> dict:
257
+ merged = {**DEFAULT, **doc}
258
+ PATH.parent.mkdir(parents=True, exist_ok=True)
259
+ PATH.write_text(json.dumps(merged, indent=1))
260
+ return merged
261
+
262
+
263
+ def is_custom(doc: dict | None = None) -> bool:
264
+ return bool((doc or load()).get("custom"))
265
+
266
+
267
+ def gate_threshold_um(doc: dict | None = None) -> float:
268
+ """The potency bar for the selected gate, in µM (the lab unit).
269
+ Custom problems: the gate value in its own unit (numeric only)."""
270
+ doc = doc or load()
271
+ if doc.get("custom") or "target" not in doc:
272
+ return float(doc.get("gate_value", 20.0))
273
+ nm = doc["hit_ic50_nm"] if doc["gate"] == "hit" else doc["lead_ic50_nm"]
274
+ return float(nm) / 1000.0
275
+
276
+
277
+ def gate_metric(doc: dict | None = None) -> str:
278
+ return str((doc or load()).get("metric") or "ic50")
279
+
280
+
281
+ def gate_unit(doc: dict | None = None) -> str:
282
+ return str((doc or load()).get("unit") or "µM")
283
+
284
+
285
+ def gate_direction(doc: dict | None = None) -> str:
286
+ return str((doc or load()).get("direction") or "min")
287
+
288
+
289
+ def gate_symbol(doc: dict | None = None) -> str:
290
+ return "≤" if gate_direction(doc) == "min" else "≥"
291
+
292
+
293
+ def gate_summary(doc: dict | None = None) -> str:
294
+ doc = doc or load()
295
+ if doc.get("custom") or "target" not in doc:
296
+ obj = doc.get("objective") or doc.get("target")
297
+ mod = f"[{doc['modality']}] " if doc.get("modality") else ""
298
+ return (f"{doc['program']} · {mod}{obj} · gate: {doc['metric']} "
299
+ f"{gate_symbol(doc)} {float(doc.get('gate_value', 20.0)):g} "
300
+ f"{doc.get('unit', '')}").rstrip()
301
+ return (f"{doc['program']} · {doc['target']} · gate: {doc['gate']} "
302
+ f"(IC50 ≤ {gate_threshold_um(doc):g} µM)")
303
+
304
+
305
+ def tpp(doc: dict | None = None):
306
+ doc = doc or load()
307
+ return standard_small_molecule_tpp(
308
+ doc["program"], doc["target"], ic50_nm=doc["lead_ic50_nm"])
@@ -0,0 +1,42 @@
1
+ """The dose ladder a model may design for one hypothesis — validated, bounded, never trusted as-is.
2
+
3
+ A model may propose WHICH concentrations to test (a ladder that brackets the gate resolves a potency
4
+ curve far better than a default one). It cannot propose anything the lab would not accept: the ladder is
5
+ cleaned here (finite, positive, de-duplicated, sorted, in range, between MIN and MAX doses) and anything
6
+ that fails is dropped, so the campaign falls back to the default ladder instead of running a bad one.
7
+ Replicates are a property of the lab (the instrument runs them), not a model choice, so they are not here.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from typing import Any
13
+
14
+ MIN_DOSES, MAX_DOSES = 3, 8
15
+ LOW_UM, HIGH_UM = 0.001, 1000.0
16
+
17
+
18
+ def sanitize_protocol(raw: Any) -> dict | None:
19
+ """{"concentrations": ["0.5uM", ...], "why": str} or None when the proposal is unusable."""
20
+ if not isinstance(raw, dict):
21
+ return None
22
+ vals: list[float] = []
23
+ for v in raw.get("concentrations_uM") or raw.get("concentrations") or []:
24
+ try:
25
+ x = float(str(v).lower().replace("um", "").replace("µm", "").strip())
26
+ except (TypeError, ValueError):
27
+ continue
28
+ if math.isfinite(x) and LOW_UM <= x <= HIGH_UM:
29
+ vals.append(x)
30
+ ladder = sorted(set(round(x, 6) for x in vals))
31
+ if len(ladder) < MIN_DOSES:
32
+ return None
33
+ ladder = ladder[:MAX_DOSES]
34
+ return {"concentrations": [f"{x:g}uM" for x in ladder], "why": str(raw.get("why") or raw.get("rationale") or "")[:200]}
35
+
36
+
37
+ def describe(protocol: dict | None) -> str:
38
+ """One line for the plan the person reviews."""
39
+ if not protocol:
40
+ return ""
41
+ c = protocol["concentrations"]
42
+ return f"{len(c)} doses, {c[0].replace('uM', '')} to {c[-1].replace('uM', '')} µM" + (f": {protocol['why']}" if protocol.get("why") else "")
proef/proxy.py ADDED
@@ -0,0 +1,78 @@
1
+ """The proxy ladder — a measure is always a proxy for the claim.
2
+
3
+ Bender et al.'s Goodhart warning, made mechanical: an IC50 is not target
4
+ engagement, target engagement is not cellular efficacy, cellular efficacy
5
+ is not the clinical question. Every criterion may therefore declare
6
+ `proxy_of`, and every verdict/rollup PRINTS the evidence distance — the
7
+ chain of rungs between what was measured and what is ultimately claimed.
8
+ Distance is never hidden by confident phrasing; a program gated on ic50
9
+ is four rungs from the patient, and the UI says so.
10
+
11
+ Default ladder (drug-discovery convention; extend per program by
12
+ declaring proxy_of on the criterion):
13
+
14
+ ic50_um / percent_inhibition / kda / ... (biophysical/biochemical)
15
+ -> target_engagement
16
+ -> cellular_efficacy
17
+ -> animal_efficacy
18
+ -> clinical_efficacy
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from typing import Any
23
+
24
+ CLINICAL = "clinical_efficacy"
25
+
26
+ #: metric -> the claim it is a proxy FOR (one rung up)
27
+ LADDER: dict[str, str] = {
28
+ "ic50_um": "target_engagement",
29
+ "ic50": "target_engagement",
30
+ "percent_inhibition": "target_engagement",
31
+ "potency_pct": "target_engagement",
32
+ "kd_nM": "target_engagement",
33
+ "tensile_mpa": "preclinical_performance",
34
+ "strength_mpa": "preclinical_performance",
35
+ "target_engagement": "cellular_efficacy",
36
+ "cellular_efficacy": "animal_efficacy",
37
+ "in_vivo_potency": "animal_efficacy",
38
+ "animal_efficacy": "clinical_efficacy",
39
+ "preclinical_performance": "clinical_efficacy",
40
+ }
41
+
42
+
43
+ def chain(metric: str, proxy_of: str | None = None) -> list[str]:
44
+ """The full evidence chain from `metric` up to the clinical claim.
45
+
46
+ `proxy_of` (when declared) overrides the default ladder step for the
47
+ starting metric; the walk then follows the canonical ladder. Cycles
48
+ stop the walk — an unresolvable claim distance is reported as such,
49
+ never as zero."""
50
+ chain_: list[str] = [metric]
51
+ cur = (proxy_of or LADDER.get(metric) or "").strip()
52
+ while cur and cur != CLINICAL and cur not in chain_:
53
+ chain_.append(cur)
54
+ cur = LADDER.get(cur, "")
55
+ if cur == CLINICAL:
56
+ chain_.append(CLINICAL)
57
+ return chain_
58
+
59
+
60
+ def distance(metric: str, proxy_of: str | None = None) -> dict[str, Any]:
61
+ """{"rungs": int | None, "chain": [...], "claim": clinical}.
62
+ rungs=None => the chain does not reach the clinical claim from this
63
+ metric (an unresolved proxy — say so, don't print 0)."""
64
+ c = chain(metric, proxy_of)
65
+ return {"rungs": len(c) - 1 if c and c[-1] == CLINICAL else None,
66
+ "chain": c,
67
+ "claim": CLINICAL,
68
+ "resolved": bool(c) and c[-1] == CLINICAL}
69
+
70
+
71
+ def evidence_line(metric: str, proxy_of: str | None = None) -> str:
72
+ d = distance(metric, proxy_of)
73
+ if not d["resolved"]:
74
+ return (f"proxy chain from '{metric}' does not reach the clinical "
75
+ f"claim ({'→'.join(d['chain'])}) — unresolved")
76
+ n = d["rungs"]
77
+ return (f"evidence distance: {n} rung{'s' if n != 1 else ''} from "
78
+ f"clinical ({'→'.join(d['chain'])})")