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/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """proef — framework for agentic drug discovery.
2
+
3
+ Core is dependency-light (pydantic only). All integrations are adapters.
4
+ """
5
+ __version__ = "0.2.0"
6
+
7
+ # Legacy names: this project was called BioNexus. Environment variables set under the old
8
+ # prefixes (BIONEXUS_*, BN_*) keep working; the new name wins when both are set.
9
+ import os as _os
10
+
11
+ for _old, _new in (("BIONEXUS_", "PROEF_"), ("BN_PROGRAM", "PROEF_PROGRAM"),
12
+ ("BN_CAMPAIGN_ID", "PROEF_CAMPAIGN_ID"), ("BN_SKIP_DOCKER", "PROEF_SKIP_DOCKER"),
13
+ ("BN_REQUIRE_DOCKER", "PROEF_REQUIRE_DOCKER"), ("BN_SANDBOX_IMAGE", "PROEF_SANDBOX_IMAGE")):
14
+ for _k in [k for k in _os.environ if k.startswith(_old)]:
15
+ _os.environ.setdefault(_new + _k[len(_old):] if _old.endswith("_") else _new, _os.environ[_k])
16
+
17
+ from proef.core.contracts import Envelope # noqa: F401
18
+ from proef.core.registry import Registry # noqa: F401
19
+ from proef.core.safety import ( # noqa: F401
20
+ ForbiddenComboRule,
21
+ LabGateway,
22
+ MaxBslRule,
23
+ MaxStepsRule,
24
+ SafetyEngine,
25
+ )
proef/acquisition.py ADDED
@@ -0,0 +1,244 @@
1
+ """acquisition — deterministic, AD-gated batch selection ("which experiments
2
+ run").
3
+
4
+ The campaign loop always had a socket for this (round-2+ policy slot);
5
+ this is the first real plug. The framing is honest about what it is: a
6
+ closed-form expected-improvement acquisition over DECLARED posteriors —
7
+ the posterior (mean ± sd) is supplied by whoever ran the surrogate, the
8
+ AD module decides whether a candidate may be chosen at all, and the
9
+ harness layer (safety, budget, diversity, approval) still vetoes every
10
+ pick. Nothing here fits a model; nothing here clears a refusal.
11
+
12
+ Why EI and not a GP library: at DMTA batch scale (tens of candidates,
13
+ k of 4–8) EI-over-CI behaves like the Bayesian-dosing module behaves on
14
+ wells — graded, deterministic, explainable — while a GP over fingerprints
15
+ would smuggle in exactly the unvalidated ranking the CS07/CS08 negatives
16
+ warned about.
17
+
18
+ Determinism: identical posteriors + params + seed => identical `Selection`.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import hashlib
23
+ import math
24
+ from typing import Literal
25
+
26
+ from pydantic import BaseModel, Field, ConfigDict
27
+
28
+ POLICY_NAME = "bo-ei"
29
+ POLICY_VERSION = 1
30
+
31
+
32
+ class Posterior(BaseModel):
33
+ """One candidate's DECLARED predictive posterior on the metric scale.
34
+
35
+ For "min" metrics whose good values span orders of magnitude (IC50 µM),
36
+ mean/sd are interpreted on the log10 scale by the acquisition — sd is
37
+ OPTIONAL: no fabricated uncertainty, a missing sd is an explicit
38
+ point-posterior and is labeled as such in the pick reason.
39
+ """
40
+ model_config = ConfigDict(extra="forbid")
41
+
42
+ candidate: str
43
+ mean: float
44
+ sd: float | None = None
45
+ family: str | None = None
46
+ in_domain: bool = True
47
+ ad_note: str = "" # why an AD stamp fired, when it did
48
+ source: str = "declared" # surrogate | flywheel | declared
49
+
50
+
51
+ class Pick(BaseModel):
52
+ candidate: str
53
+ acquisition: float
54
+ mean: float
55
+ sd: float | None = None
56
+ reason: str
57
+
58
+
59
+ class Refusal(BaseModel):
60
+ candidate: str
61
+ reason: str
62
+
63
+
64
+ class Selection(BaseModel):
65
+ policy: str = POLICY_NAME
66
+ policy_version: int = POLICY_VERSION
67
+ seed: int = 0
68
+ round: int = 1
69
+ k: int = 0
70
+ target: float | None = None # threshold or best-observed, on scale
71
+ direction: Literal["min", "max"] = "min"
72
+ picks: list[Pick] = Field(default_factory=list)
73
+ refusals: list[Refusal] = Field(default_factory=list)
74
+ note: str = ""
75
+
76
+ def decision_payload(self) -> dict:
77
+ """JSON-ready for the provenance chain — every pick and every
78
+ refusal, with the arithmetic worded out."""
79
+ return {
80
+ "kind": "acquisition_selection", "policy": self.policy,
81
+ "policy_version": self.policy_version, "seed": self.seed,
82
+ "round": self.round, "k": self.k, "target": self.target,
83
+ "direction": self.direction,
84
+ "picks": [p.model_dump() for p in self.picks],
85
+ "refusals": [r.model_dump() for r in self.refusals],
86
+ "note": self.note,
87
+ }
88
+
89
+
90
+ def _normal_pdf(x: float) -> float:
91
+ return math.exp(-0.5 * x * x) / math.sqrt(2 * math.pi)
92
+
93
+
94
+ def _cdf(z: float) -> float:
95
+ return 0.5 * (1.0 + math.erf(z / math.sqrt(2.0)))
96
+
97
+
98
+ def expected_improvement(mean: float, sd: float | None, target: float,
99
+ direction: str = "min") -> float:
100
+ """Closed-form EI: for "min" metrics improvement = (target - mean);
101
+ for "max" it's (mean - target). sd None => point posterior: the
102
+ improvement itself, never a silent Gaussian invention."""
103
+ imp = (target - mean) if direction == "min" else (mean - target)
104
+ if not sd or sd <= 0:
105
+ return max(0.0, imp)
106
+ z = imp / sd
107
+ return max(0.0, imp * _cdf(z) + sd * _normal_pdf(z))
108
+
109
+
110
+ def select_batch(posteriors: list[Posterior], k: int,
111
+ target: float | None = None,
112
+ best_observed: float | None = None,
113
+ direction: Literal["min", "max"] = "min",
114
+ metric_log: bool = True, seed: int = 0, round_no: int = 1,
115
+ max_per_family: int | None = 1,
116
+ explore_weight: float = 0.0) -> Selection:
117
+ """Rank by EI(+kappa·sd when explore_weight>0), apply the diversity
118
+ cap, return k picks. The AD gate runs BEFORE ranking: a candidate
119
+ outside the surrogate's domain is refused, not "explored" — the
120
+ infinite-exploration failure mode the applicability-domain module
121
+ exists to stop.
122
+
123
+ target: the decision gate a scientist registered. If absent, the
124
+ acquisition improves on best_observed (the classic BO reference).
125
+ A non-positive mean on a log-scale metric is a REFUSED invalid
126
+ posterior, never a floor-substituted super-hit.
127
+ Ties break by sha256(seed:candidate) — the seed is a real
128
+ reproducibility nonce, so candidate-name ordering can't bias the
129
+ batch; identical inputs still give identical Selections.
130
+ """
131
+ log = direction == "min" and metric_log
132
+ ref: float | None = None
133
+ if target is not None:
134
+ ref = target
135
+ elif best_observed is not None:
136
+ ref = best_observed
137
+ sel = Selection(seed=seed, round=round_no, k=k, target=ref,
138
+ direction=direction)
139
+ if ref is None:
140
+ sel.note = ("no target (gate) and no observation yet — EI has "
141
+ "nothing to improve on; falling back to raw posterior "
142
+ "ranking")
143
+
144
+ def _to_axis(value: float) -> float:
145
+ """project a raw metric value onto the good-is-LARGER axis: log10
146
+ for span metrics (so IC50 sd reads as multiplicative fold), sign
147
+ flipped so a LOWER IC50 (direction=min) is a LARGER axis value."""
148
+ v = math.log10(value) if log else value
149
+ return v if direction == "max" else -v
150
+
151
+ def _tie_key(candidate: str) -> str:
152
+ return hashlib.sha256(f"{seed}:{candidate}".encode()).hexdigest()
153
+
154
+ scored: list[tuple[float, Posterior, float, float | None]] = []
155
+ for p in posteriors:
156
+ if not p.in_domain:
157
+ sel.refusals.append(Refusal(
158
+ candidate=p.candidate,
159
+ reason=(f"extrapolation-veto (AD): selection outside the "
160
+ f"surrogate's domain is refused exploration"
161
+ + (f" — {p.ad_note}" if p.ad_note else ""))))
162
+ continue
163
+ if log and p.mean <= 0:
164
+ sel.refusals.append(Refusal(
165
+ candidate=p.candidate,
166
+ reason=(f"invalid posterior on a log-scale metric: "
167
+ f"mean={p.mean} is not a positive value — refused "
168
+ f"rather than floored into a fake super-hit")))
169
+ continue
170
+ m = _to_axis(p.mean)
171
+ s = p.sd if (p.sd is not None and p.sd > 0) else None
172
+ if ref is None:
173
+ val = m + explore_weight * (s or 0.0)
174
+ else:
175
+ # on the good-is-larger axis, improvement over target is "max"
176
+ ei = expected_improvement(m, s, _to_axis(ref), direction="max")
177
+ val = ei + explore_weight * (s or 0.0)
178
+ scored.append((val, p, m, s))
179
+ # stable, deterministic ordering: value desc, then the seed hash
180
+ scored.sort(key=lambda t: (-round(t[0], 9), _tie_key(t[1].candidate)))
181
+
182
+ fam_counts: dict[str, int] = {}
183
+ for val, p, m, s in scored:
184
+ if len(sel.picks) >= k:
185
+ sel.refusals.append(Refusal(candidate=p.candidate,
186
+ reason="outside batch (budget)"))
187
+ continue
188
+ if (max_per_family is not None and p.family
189
+ and fam_counts.get(p.family, 0) >= max_per_family):
190
+ sel.refusals.append(Refusal(
191
+ candidate=p.candidate,
192
+ reason=f"family '{p.family}' already has {max_per_family} "
193
+ f"selected (diversity cap)"))
194
+ continue
195
+ reason = (f"acquisition={round(val, 4)}; "
196
+ + ("point-posterior, no sd declared (exploit-only)"
197
+ if s is None
198
+ else f"mean={round(p.mean, 4)}, sd={round(p.sd, 4)}"))
199
+ sel.picks.append(Pick(candidate=p.candidate,
200
+ acquisition=round(val, 6),
201
+ mean=round(p.mean, 6),
202
+ sd=round(p.sd, 6) if s is not None else None,
203
+ reason=reason))
204
+ if p.family:
205
+ fam_counts[p.family] = fam_counts.get(p.family, 0) + 1
206
+ if not sel.picks and not sel.note:
207
+ sel.note = "nothing selectable — every candidate refused (see refusals)"
208
+ return sel
209
+
210
+
211
+ def randomize_batch(posteriors: list[Posterior], k: int, seed: int = 0,
212
+ round_no: int = 1,
213
+ max_per_family: int | None = 1,
214
+ skip_out_of_domain: bool = False) -> Selection:
215
+ """The interim champion, spelled out so the comparison is apples to
216
+ apples: gates + randomize, never rank. AD gate is still applied when
217
+ skip_out_of_domain (the campaign's real behaviour keeps it)."""
218
+ sel = Selection(policy="gates-random", policy_version=1, seed=seed,
219
+ round=round_no, k=k)
220
+ # deterministic shuffle, not python's RNG ordering luck
221
+ shuffled = sorted(posteriors, key=lambda p: hashlib.sha256(
222
+ f"{seed}:{p.candidate}".encode()).hexdigest())
223
+ fam_counts: dict[str, int] = {}
224
+ for p in shuffled:
225
+ if not p.in_domain and skip_out_of_domain:
226
+ sel.refusals.append(Refusal(
227
+ candidate=p.candidate, reason="extrapolation-veto (AD)"))
228
+ continue
229
+ if len(sel.picks) >= k:
230
+ sel.refusals.append(Refusal(candidate=p.candidate,
231
+ reason="outside batch (budget)"))
232
+ continue
233
+ if (max_per_family is not None and p.family
234
+ and fam_counts.get(p.family, 0) >= max_per_family):
235
+ sel.refusals.append(Refusal(
236
+ candidate=p.candidate,
237
+ reason=f"family '{p.family}' capped"))
238
+ continue
239
+ sel.picks.append(Pick(candidate=p.candidate, acquisition=0.0,
240
+ mean=round(p.mean, 6), sd=p.sd,
241
+ reason="uniform batch pick (gates+randomize)"))
242
+ if p.family:
243
+ fam_counts[p.family] = fam_counts.get(p.family, 0) + 1
244
+ return sel
proef/ad.py ADDED
@@ -0,0 +1,159 @@
1
+ """Applicability domain — the "every model is a local model" guard.
2
+
3
+ Bender & Cortés-Ciriano (Nat Rev Drug Discov, Aug 2026) audit of agentic
4
+ drug discovery lands on one sentence this module exists for: a trained
5
+ predictor is a LOCAL model of the chemistry it was fitted on, and silence
6
+ about the boundary is how overclaiming happens. So: at predict time, the
7
+ nearest-neighbour Tanimoto similarity to the training set is computed;
8
+ below a declared floor the prediction is stamped ``extrapolation`` —
9
+ widening abstention rules (SuccessCriteria.classify(extrapolation=True)
10
+ never returns a claim-grade verdict) and surfacing a card chip.
11
+
12
+ This is the model-facing twin of the ingestion regime gate (CS06): data
13
+ frames and model domains are both answered the same way — claim inside
14
+ what has been validated, refuse outside it, and SAY which case happened.
15
+
16
+ Featurization basis degrades honestly: Morgan bits (2048, r=2) when rdkit
17
+ is installed, else char 3-gram sets — the basis is reported in every
18
+ stamp so the similarity number is never read without its units.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from typing import Any, Iterable
23
+
24
+ #: nn-Tanimoto below this -> extrapolation. Declared, not tuned per model;
25
+ #: 0.5 on Morgan/char binary sets is the conservative literature default
26
+ #: (near-neighbor identity ~ same scaffold neighborhood).
27
+ AD_FLOOR = 0.5
28
+
29
+
30
+ def _morgan_set(smiles: str, n_bits: int = 2048, radius: int = 2) -> set[int]:
31
+ from rdkit import Chem
32
+ from rdkit.Chem import rdFingerprintGenerator
33
+
34
+ mol = Chem.MolFromSmiles(smiles)
35
+ if mol is None:
36
+ return set()
37
+ gen = rdFingerprintGenerator.GetMorganGenerator(radius=radius,
38
+ fpSize=n_bits)
39
+ fp = gen.GetFingerprintAsNumPy(mol).astype(bool)
40
+ return {i for i, b in enumerate(fp) if b}
41
+
42
+
43
+ def _char_set(smiles: str, n: int = 3) -> set[int]:
44
+ s = smiles or ""
45
+ return {hash(s[i:i + n]) & 0xFFFFFFFF for i in range(max(0, len(s) - n + 1))}
46
+
47
+
48
+ def _basis_available() -> str:
49
+ try:
50
+ import rdkit # noqa: F401
51
+ return "morgan"
52
+ except ImportError:
53
+ return "char3"
54
+
55
+
56
+ def tanimoto(a: set[int], b: set[int]) -> float:
57
+ if not a and not b:
58
+ return 1.0
59
+ if not a or not b:
60
+ return 0.0
61
+ return len(a & b) / len(a | b)
62
+
63
+
64
+ class ApplicabilityDomain:
65
+ """Nearest-neighbour Tanimoto domain over the training structures.
66
+
67
+ Floors are per-domain decisions:
68
+ * fixed (legacy default, AD_FLOOR) — one constant across modalities;
69
+ * auto — DATA-DERIVED: leave-one-out NN-Tanimoto of the domain
70
+ against itself, at a declared quantile (default p05). 'in-domain'
71
+ then MEANS 'at least as close to the domain as a typical domain
72
+ member is to its nearest sibling' — the control false-alarm rate
73
+ on in-domain data is the quantile itself, by construction, which
74
+ no constant floor can promise (CS07 proved 0.5 mis-flags proteins).
75
+ Disclosure fields (floor_mode/floor_basis/floor_p05/floor_p50) ride
76
+ in every stamp so a number is never read without its calibration.
77
+ """
78
+
79
+ def __init__(self, feats: list[set[int]], basis: str,
80
+ floor: float = AD_FLOOR):
81
+ self._feats = [f for f in feats]
82
+ self.basis = basis
83
+ self.floor = floor
84
+ self.floor_mode = "fixed"
85
+ self.floor_basis = f"constant {floor}"
86
+ self._loo: list[float] = []
87
+
88
+ def _auto_floor(self, quantile: float) -> float:
89
+ fs = self._feats
90
+ if len(fs) < 4:
91
+ return self.floor # too few references to calibrate
92
+ loo = []
93
+ for i, a in enumerate(fs):
94
+ best = max((tanimoto(a, b) for j, b in enumerate(fs)
95
+ if j != i), default=0.0)
96
+ loo.append(best)
97
+ loo.sort()
98
+ self._loo = loo
99
+ k = min(len(loo) - 1, max(0, int(quantile * len(loo))))
100
+ return max(0.0, round(loo[k], 4))
101
+
102
+ @classmethod
103
+ def from_smiles(cls, smiles: Iterable[str], basis: str = "auto",
104
+ floor: float | str = AD_FLOOR,
105
+ loo_quantile: float = 0.05
106
+ ) -> "ApplicabilityDomain":
107
+ seen: set[str] = set()
108
+ smiles = [x for x in smiles if x and not (x in seen or seen.add(x))]
109
+ if basis == "auto":
110
+ basis = _basis_available()
111
+ feat = _morgan_set if basis == "morgan" else _char_set
112
+ try:
113
+ feats = [feat(s) for s in smiles]
114
+ except ImportError: # rdkit vanished mid-flight
115
+ basis = "char3"
116
+ feat = _char_set
117
+ feats = [feat(s) for s in smiles]
118
+ inst = cls(feats, basis,
119
+ AD_FLOOR if floor == "auto" else float(floor))
120
+ if floor == "auto":
121
+ auto = inst._auto_floor(loo_quantile)
122
+ inst.floor = auto
123
+ inst.floor_mode = "auto"
124
+ inst.floor_basis = (f"LOO-NN Tanimoto p{int(loo_quantile * 100)}"
125
+ f" of n={len(inst._feats)}")
126
+ inst._loo_q = loo_quantile
127
+ return inst
128
+
129
+ def __len__(self) -> int:
130
+ return len(self._feats)
131
+
132
+ def check(self, smiles: str) -> dict[str, Any]:
133
+ """Stamp payload: the claim-grade fields are `extrapolation` and
134
+ `nn_tanimoto`; `basis` and `n_reference` keep the number honest."""
135
+ feat = _morgan_set if self.basis == "morgan" else _char_set
136
+ try:
137
+ q = feat(smiles)
138
+ except ImportError:
139
+ q = _char_set(smiles)
140
+ nn = max((tanimoto(q, f) for f in self._feats), default=0.0)
141
+ in_dom = nn >= self.floor and bool(q) and len(self._feats) > 0
142
+ return {"extrapolation": not in_dom,
143
+ "nn_tanimoto": round(nn, 3),
144
+ "ad_floor": self.floor,
145
+ "floor_mode": self.floor_mode,
146
+ "floor_basis": self.floor_basis,
147
+ "ad_basis": self.basis,
148
+ "n_reference": len(self._feats)}
149
+
150
+ def stamp(self, payload: dict[str, Any], smiles: str) -> dict[str, Any]:
151
+ """Merge the AD fields into a prediction/card payload. An
152
+ UNPARSEABLE or empty structure never reads as in-domain."""
153
+ c = self.check(smiles)
154
+ payload["extrapolation"] = c["extrapolation"]
155
+ payload["nn_tanimoto"] = c["nn_tanimoto"]
156
+ payload["ad_floor"] = c["ad_floor"]
157
+ payload["ad_basis"] = c["ad_basis"]
158
+ payload["ad_n_reference"] = c["n_reference"]
159
+ return payload
File without changes
@@ -0,0 +1,196 @@
1
+ """ADMET prediction panel — rule-based + extensible.
2
+
3
+ Two tiers:
4
+ 1. Rule-based filters that work without any external dependency
5
+ (Lipinski RO5, Veber, PAINS alert list as SMARTS-free heuristics)
6
+ 2. RDKit-computed descriptors when rdkit is installed (optional dep)
7
+
8
+ The panel returns structured ADMET predictions that feed into the readiness
9
+ review and the TPP evaluation. Model-based predictors (QSAR, ML) implement the
10
+ same `ADMETPredictor` protocol and are registered alongside.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from dataclasses import dataclass, field
16
+ from typing import Any, Protocol
17
+
18
+
19
+ @dataclass
20
+ class ADMETResult:
21
+ smiles: str
22
+ mw_da: float | None = None
23
+ logp: float | None = None
24
+ tpsa: float | None = None
25
+ hbd: int | None = None
26
+ hba: int | None = None
27
+ rotatable_bonds: int | None = None
28
+ lipinski_violations: int = 0
29
+ veber_violations: int = 0
30
+ pains_alerts: list[str] = field(default_factory=list)
31
+ flags: list[str] = field(default_factory=list)
32
+
33
+ @property
34
+ def passes_lipinski(self) -> bool:
35
+ return self.lipinski_violations <= 1
36
+
37
+ @property
38
+ def passes_veber(self) -> bool:
39
+ return (self.rotatable_bonds is not None and self.rotatable_bonds <= 10 and
40
+ self.tpsa is not None and self.tpsa <= 140)
41
+
42
+ @property
43
+ def has_pains(self) -> bool:
44
+ return bool(self.pains_alerts)
45
+
46
+ def summary(self) -> dict[str, Any]:
47
+ return {
48
+ "smiles": self.smiles,
49
+ "mw_da": self.mw_da,
50
+ "logp": self.logp,
51
+ "tpsa": self.tpsa,
52
+ "hbd": self.hbd, "hba": self.hba,
53
+ "rotatable_bonds": self.rotatable_bonds,
54
+ "lipinski_violations": self.lipinski_violations,
55
+ "lipinski_pass": self.passes_lipinski,
56
+ "veber_pass": self.passes_veber,
57
+ "pains_alerts": self.pains_alerts,
58
+ "flags": self.flags,
59
+ }
60
+
61
+
62
+ class ADMETPredictor(Protocol):
63
+ """Protocol for any ADMET prediction backend."""
64
+
65
+ def predict(self, smiles: str) -> ADMETResult: ...
66
+
67
+
68
+ # ------------------------------------------------ rule-based (no RDKit)
69
+
70
+ # Known PAINS-like substructure patterns (SMARTS-free string heuristics).
71
+ _PAINS_PATTERNS: list[tuple[str, str]] = [
72
+ ("rhodanine", r"O=C1SCC(=S)S1"),
73
+ ("cyanoacrylate", r"C=C\(C#N\)C(=O)"),
74
+ ("hydroxyphenylhydrazide", r"Nc1ccc(O)cc1C(=O)"),
75
+ ("catechol_methyl_sulfate", r"OS\(=O\)\(=O\)OC"),
76
+ ]
77
+
78
+ _SIMPLE_MW_FACTORS = {"C": 12.01, "N": 14.01, "O": 16.00, "S": 32.06,
79
+ "F": 19.00, "Cl": 35.45, "Br": 79.90, "I": 126.90,
80
+ "P": 30.97, "H": 1.01}
81
+
82
+
83
+ def _estimate_mw(smiles: str) -> float:
84
+ """Crude MW estimate from atom counts in the SMILES string."""
85
+ total = 0.0
86
+ for el, mass in sorted(_SIMPLE_MW_FACTORS.items(), key=lambda x: -len(x[0])):
87
+ count = len(re.findall(r"(?<![A-Za-z])" + el + r"(?![a-z])", smiles))
88
+ total += count * mass
89
+ # implicit hydrogens: rough estimate
90
+ heavy = sum(len(re.findall(r"(?<![A-Za-z])" + el + r"(?![a-z])", smiles))
91
+ for el in _SIMPLE_MW_FACTORS if el != "H")
92
+ total += heavy * 1.5 # ~1.5 H per heavy atom average
93
+ return round(total, 1)
94
+
95
+
96
+ class RuleBasedADMET:
97
+ """Rule-based ADMET estimation without external dependencies.
98
+
99
+ Uses SMILES string analysis for approximate molecular weight and
100
+ pattern-matching for PAINS alerts. Accurate descriptor calculation
101
+ (LogP, TPSA, HBD/HBA) requires RDKit via `RDKitADMET`.
102
+ """
103
+
104
+ name = "rule-based"
105
+
106
+ def predict(self, smiles: str) -> ADMETResult:
107
+ result = ADMETResult(smiles=smiles)
108
+ result.mw_da = _estimate_mw(smiles)
109
+ if result.mw_da > 500:
110
+ result.lipinski_violations += 1
111
+ result.flags.append("MW > 500")
112
+
113
+ # PAINS pattern detection
114
+ for name, pattern in _PAINS_PATTERNS:
115
+ if re.search(pattern, smiles):
116
+ result.pains_alerts.append(name)
117
+ if result.pains_alerts:
118
+ result.flags.append(f"PAINS: {', '.join(result.pains_alerts)}")
119
+
120
+ return result
121
+
122
+
123
+ class RDKitADMET:
124
+ """Full descriptor calculation using RDKit (requires rdkit extra)."""
125
+
126
+ name = "rdkit"
127
+
128
+ def __init__(self, pains_check: bool = True):
129
+ self.pains_check = pains_check
130
+ from rdkit import Chem
131
+ from rdkit.Chem import Descriptors, Lipinski, rdMolDescriptors
132
+ self._Chem = Chem
133
+ self._Descriptors = Descriptors
134
+ self._rdMolDescriptors = rdMolDescriptors
135
+ self._Lipinski = Lipinski
136
+
137
+ def predict(self, smiles: str) -> ADMETResult:
138
+ mol = self._Chem.MolFromSmiles(smiles)
139
+ if mol is None:
140
+ result = ADMETResult(smiles=smiles)
141
+ result.flags.append("invalid SMILES")
142
+ return result
143
+ result = ADMETResult(smiles=smiles)
144
+ result.mw_da = round(self._Descriptors.MolWt(mol), 1)
145
+ result.logp = round(self._Descriptors.MolLogP(mol), 2)
146
+ result.tpsa = round(self._rdMolDescriptors.CalcTPSA(mol), 1)
147
+ result.hbd = self._Lipinski.NumHDonors(mol)
148
+ result.hba = self._Lipinski.NumHAcceptors(mol)
149
+ result.rotatable_bonds = self._Lipinski.NumRotatableBonds(mol)
150
+
151
+ # Lipinski RO5
152
+ violations = 0
153
+ if result.mw_da > 500:
154
+ violations += 1
155
+ if result.logp is not None and result.logp > 5:
156
+ violations += 1
157
+ if result.hbd is not None and result.hbd > 5:
158
+ violations += 1
159
+ if result.hba is not None and result.hba > 10:
160
+ violations += 1
161
+ result.lipinski_violations = violations
162
+ if violations > 1:
163
+ result.flags.append(f"Lipinski violations: {violations}")
164
+
165
+ # Veber
166
+ if result.rotatable_bonds is not None and result.rotatable_bonds > 10:
167
+ result.flags.append("rotatable bonds > 10")
168
+ if result.tpsa is not None and result.tpsa > 140:
169
+ result.flags.append("TPSA > 140")
170
+
171
+ # PAINS via SMARTS
172
+ if self.pains_check:
173
+ pains_smarts = [
174
+ ("rhodanine", "O=C1SCC(=S)S1"),
175
+ ("cyanoacrylate", "C=C(C#N)C(=O)"),
176
+ ("hydroxyphenylhydrazide", "Nc1ccc(O)cc1C(=O)"),
177
+ ("phenolic_sulfate", "OS(=O)(=O)Oc1ccccc1"),
178
+ ]
179
+ for name, smarts in pains_smarts:
180
+ patt = self._Chem.MolFromSmarts(smarts)
181
+ if patt and mol.HasSubstructMatch(patt):
182
+ result.pains_alerts.append(name)
183
+ if result.pains_alerts:
184
+ result.flags.append(f"PAINS: {', '.join(result.pains_alerts)}")
185
+
186
+ return result
187
+
188
+
189
+ def get_admet_predictor(prefer_rdkit: bool = True) -> ADMETPredictor:
190
+ """Factory: return the best available ADMET predictor."""
191
+ if prefer_rdkit:
192
+ try:
193
+ return RDKitADMET()
194
+ except ImportError:
195
+ pass
196
+ return RuleBasedADMET()
File without changes
@@ -0,0 +1,52 @@
1
+ """RDKit-backed bio tools (optional extra: pip install proef[bio-rdkit]).
2
+
3
+ Implemented lazily so the module imports cleanly without rdkit installed.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+ from proef.core.contracts import ToolInvocation, ToolName, ToolResult
10
+
11
+
12
+ class MoleculeDescriptors:
13
+ """Compute basic descriptors for SMILES payloads (capability: fm_predict_property
14
+ for local, deterministic chemistry — no model server needed)."""
15
+
16
+ name = "rdkit_descriptors"
17
+ capabilities = (ToolName.fm_predict_property,)
18
+
19
+ def invoke(self, invocation: ToolInvocation) -> ToolResult:
20
+ try:
21
+ from rdkit import Chem
22
+ from rdkit.Chem import Descriptors, Lipinski
23
+ except ImportError:
24
+ return ToolResult(
25
+ envelope=invocation.envelope.model_copy(),
26
+ invocation_id=invocation.invocation_id,
27
+ status="rejected",
28
+ rejection_reason="rdkit not installed (pip install proef[bio-rdkit])",
29
+ )
30
+ smiles_list = invocation.args.get("smiles", [])
31
+ out = []
32
+ for smi in smiles_list:
33
+ mol = Chem.MolFromSmiles(smi)
34
+ if mol is None:
35
+ out.append({"smiles": smi, "valid": False})
36
+ continue
37
+ out.append(
38
+ {
39
+ "smiles": smi,
40
+ "valid": True,
41
+ "mol_wt": round(Descriptors.MolWt(mol), 2),
42
+ "logp": round(Descriptors.MolLogP(mol), 2),
43
+ "hbd": Lipinski.NumHDonors(mol),
44
+ "hba": Lipinski.NumHAcceptors(mol),
45
+ }
46
+ )
47
+ return ToolResult(
48
+ envelope=invocation.envelope.model_copy(),
49
+ invocation_id=invocation.invocation_id,
50
+ status="succeeded",
51
+ output={"descriptors": out},
52
+ )