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
@@ -0,0 +1,121 @@
1
+ """Evidence-based potency gates — suggest TPP thresholds from ChEMBL.
2
+
3
+ Instead of folklore constants, ask the published data: for a target's
4
+ reported binding activities (IC50, assay type B), the suggested HIT gate is
5
+ the top-quartile potency among known actives (pIC50 ≥ 6), and the LEAD gate
6
+ is 10× tighter. Falls back to conventional values (1 µM / 50 nM) when the
7
+ network or the data isn't there — the fallback is always labeled.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import math
13
+ import urllib.parse
14
+ import urllib.request
15
+ from dataclasses import asdict, dataclass
16
+
17
+ from proef.adapters.data.chembl import fetch_target_activities
18
+
19
+ SEARCH = "https://www.ebi.ac.uk/chembl/api/data/target/search.json"
20
+ CONVENTIONAL_HIT_NM = 1000.0
21
+ CONVENTIONAL_LEAD_NM = 50.0
22
+ MIN_ACTIVES = 50
23
+
24
+
25
+ @dataclass
26
+ class TargetProfile:
27
+ target: str
28
+ chembl_id: str | None
29
+ n_activities: int
30
+ median_pic50: float | None
31
+ hit_ic50_nm: float
32
+ lead_ic50_nm: float
33
+ basis: str
34
+ source: str # chembl | fallback
35
+
36
+ def as_dict(self) -> dict:
37
+ return asdict(self)
38
+
39
+
40
+ def _percentile(sorted_vals: list[float], q: float) -> float:
41
+ if not sorted_vals:
42
+ raise ValueError("empty")
43
+ idx = max(0, min(len(sorted_vals) - 1, int(q * (len(sorted_vals) - 1))))
44
+ return sorted_vals[idx]
45
+
46
+
47
+ def derive_gates(pic50s: list[float]) -> tuple[float, float, float] | None:
48
+ """(hit_nm, lead_nm, median) from published pIC50s, or None if too thin."""
49
+ actives = sorted(p for p in pic50s if p >= 6.0)
50
+ if len(actives) < MIN_ACTIVES:
51
+ return None
52
+ top_quartile = _percentile(actives, 0.75)
53
+ hit_nm = 10 ** (9.0 - top_quartile)
54
+ lead_nm = max(1.0, hit_nm / 10.0)
55
+ median = sum(actives) / len(actives)
56
+ return round(hit_nm, 1), round(lead_nm, 1), median
57
+
58
+
59
+ def lookup_targets(name: str) -> list[str]:
60
+ """Search ChEMBL by name; prefer SINGLE PROTEIN targets, exact pref_name
61
+ first (gene symbols like EGFR otherwise hit interaction complexes and
62
+ stale duplicate entries)."""
63
+ url = f"{SEARCH}?q={urllib.parse.quote(name)}&limit=20"
64
+ req = urllib.request.Request(url, headers={"Accept": "application/json"})
65
+ with urllib.request.urlopen(req, timeout=60) as r: # noqa: S310
66
+ data = json.loads(r.read())
67
+ targets = [t for t in data.get("targets", []) if t.get("target_chembl_id")]
68
+ singles = [t for t in targets if t.get("target_type") == "SINGLE PROTEIN"]
69
+ exact = [t for t in singles
70
+ if (t.get("pref_name") or "").lower() == name.lower()]
71
+ ordered = exact + [t for t in singles if t not in exact] + \
72
+ [t for t in targets if t not in singles]
73
+ return [t["target_chembl_id"] for t in ordered]
74
+
75
+
76
+ def lookup_target(name: str) -> str | None:
77
+ ids = lookup_targets(name)
78
+ return ids[0] if ids else None
79
+
80
+
81
+ def suggest(target_name: str, chembl_id: str | None = None) -> TargetProfile:
82
+ """Best-effort evidence-based gates; never raises — degrades to labeled
83
+ conventional defaults."""
84
+ try:
85
+ candidates = [chembl_id] if chembl_id else lookup_targets(target_name)
86
+ if not candidates:
87
+ raise ValueError(f"no ChEMBL target matches '{target_name}'")
88
+ cid, gates, pic50s = None, None, []
89
+ last_note = ""
90
+ for c in candidates[:5]: # stale duplicates can be thin
91
+ try:
92
+ path = fetch_target_activities(c, max_records=5000)
93
+ import csv
94
+ with open(path) as f:
95
+ pic50s = [float(r["pic50"]) for r in csv.DictReader(f)
96
+ if r.get("pic50")]
97
+ except Exception:
98
+ continue
99
+ gates = derive_gates(pic50s)
100
+ if gates:
101
+ cid = c
102
+ break
103
+ last_note = (f"{c}: only "
104
+ f"{sum(1 for p in pic50s if p >= 6.0)} actives")
105
+ if gates is None:
106
+ raise ValueError(f"no candidate had >= {MIN_ACTIVES} actives "
107
+ f"({last_note or 'no data'})")
108
+ hit, lead, med = gates
109
+ return TargetProfile(
110
+ target=target_name, chembl_id=cid, n_activities=len(pic50s),
111
+ median_pic50=round(med, 2), hit_ic50_nm=hit, lead_ic50_nm=lead,
112
+ basis=(f"{len(pic50s)} published activities for {cid} · "
113
+ f"hit gate = top-quartile potency of known actives "
114
+ f"(median pIC50 {med:.1f}) · lead = 10× tighter"),
115
+ source="chembl")
116
+ except Exception as exc:
117
+ return TargetProfile(
118
+ target=target_name, chembl_id=None, n_activities=0,
119
+ median_pic50=None, hit_ic50_nm=CONVENTIONAL_HIT_NM,
120
+ lead_ic50_nm=CONVENTIONAL_LEAD_NM,
121
+ basis=f"conventional defaults ({exc})", source="fallback")
@@ -0,0 +1,35 @@
1
+ """ChEMBL lookup for a model's knowledge tool: small, read-only questions about a target or a compound (not the bulk dataset download in
2
+ `adapters/data/chembl.py`). The fetch is injectable so tests and replays never touch the network."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.parse
7
+ import urllib.request
8
+ from typing import Any, Callable
9
+
10
+ BASE = "https://www.ebi.ac.uk/chembl/api/data"
11
+
12
+
13
+ def _http(url: str) -> dict:
14
+ req = urllib.request.Request(url, headers={"Accept": "application/json"})
15
+ with urllib.request.urlopen(req, timeout=30) as resp: # noqa: S310
16
+ return json.loads(resp.read())
17
+
18
+
19
+ class ChemblLookup:
20
+ def __init__(self, fetch: Callable[[str], dict] | None = None):
21
+ self._fetch = fetch or _http
22
+
23
+ def target_search(self, query: str, limit: int = 5) -> list[dict[str, Any]]:
24
+ d = self._fetch(f"{BASE}/target/search.json?q={urllib.parse.quote(query)}&limit={int(limit)}")
25
+ return [{"target_chembl_id": t.get("target_chembl_id"), "name": t.get("pref_name"), "type": t.get("target_type"),
26
+ "organism": t.get("organism")} for t in d.get("targets", [])[:limit]]
27
+
28
+ def activities(self, target_chembl_id: str, limit: int = 10) -> list[dict[str, Any]]:
29
+ q = urllib.parse.urlencode({"target_chembl_id": target_chembl_id, "assay_type": "B", "pchembl_value__isnull": "false",
30
+ "limit": int(limit)})
31
+ d = self._fetch(f"{BASE}/activity.json?{q}")
32
+ return [{"molecule_chembl_id": a.get("molecule_chembl_id"), "molecule_name": a.get("molecule_pref_name"),
33
+ "smiles": (a.get("canonical_smiles") or "")[:200] or None, "type": a.get("standard_type"), "value": a.get("standard_value"),
34
+ "units": a.get("standard_units"), "pchembl": a.get("pchembl_value"), "document": a.get("document_chembl_id")}
35
+ for a in d.get("activities", [])[:limit]]
@@ -0,0 +1,102 @@
1
+ """Open Targets adapter — target identification and validation queries.
2
+
3
+ Queries the Open Targets GraphQL API for target-disease associations,
4
+ tractability, and genetic evidence. Used by the Target Research Agent.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import urllib.request
10
+ from typing import Any
11
+
12
+ GRAPHQL_URL = "https://api.platform.opentargets.org/api/v4/graphql"
13
+
14
+ QUERY = """
15
+ query targetDetails($ensemblId: String!) {
16
+ target(ensemblId: $ensemblId) {
17
+ id
18
+ approvedSymbol
19
+ approvedName
20
+ biotype
21
+ tractability { label modality value }
22
+ geneticConstraint { constraintType score oe }
23
+ drugAndClinicalCandidates { count }
24
+ associatedDiseases(page: {index: 0, size: 10}) { rows { score disease { id name } } }
25
+ }
26
+ }
27
+ """
28
+
29
+ SEARCH = """
30
+ query findTarget($q: String!) {
31
+ search(queryString: $q, entityNames: ["target"], page: {index: 0, size: 5}) { hits { id name entity } }
32
+ }
33
+ """
34
+
35
+
36
+ class OpenTargetsAdapter:
37
+ """Adapter for Open Targets Platform GraphQL API (stdlib only)."""
38
+
39
+ name = "open-targets"
40
+
41
+ def __init__(self, base_url: str = GRAPHQL_URL):
42
+ self.base_url = base_url
43
+
44
+ def _graphql(self, query: str, variables: dict) -> dict:
45
+ body = json.dumps({"query": query, "variables": variables}).encode()
46
+ req = urllib.request.Request(
47
+ self.base_url, data=body,
48
+ headers={"Content-Type": "application/json"}, method="POST")
49
+ with urllib.request.urlopen(req, timeout=60) as resp: # noqa: S310
50
+ data = json.loads(resp.read())
51
+ if "errors" in data:
52
+ raise RuntimeError(f"OpenTargets GraphQL error: {data['errors']}")
53
+ return data.get("data", {})
54
+
55
+ def target_by_ensembl(self, ensembl_id: str) -> dict[str, Any]:
56
+ """Fetch target details, tractability, and disease associations."""
57
+ data = self._graphql(QUERY, {"ensemblId": ensembl_id})
58
+ return data.get("target", {})
59
+
60
+ def find_target(self, symbol: str) -> str | None:
61
+ """The Ensembl id of the target whose name is exactly this symbol (case-insensitive), else None."""
62
+ hits = self._graphql(SEARCH, {"q": symbol}).get("search", {}).get("hits", [])
63
+ return next((h["id"] for h in hits if str(h.get("name", "")).lower() == symbol.strip().lower()), None)
64
+
65
+ def summary(self, ensembl_id: str | None = None, symbol: str | None = None) -> dict[str, Any]:
66
+ """Compact summary for agent consumption. Give an Ensembl gene id, or a gene symbol to look up first."""
67
+ if not ensembl_id and symbol:
68
+ ensembl_id = self.find_target(symbol)
69
+ if not ensembl_id:
70
+ return {"error": f"no Open Targets target named {symbol!r}"}
71
+ if not ensembl_id:
72
+ return {"error": "give an ensembl_id or a symbol"}
73
+ t = self.target_by_ensembl(ensembl_id)
74
+ if not t:
75
+ return {"error": "target not found"}
76
+ diseases = [{"name": d["disease"]["name"], "score": round(d["score"], 3)}
77
+ for d in (t.get("associatedDiseases") or {}).get("rows", [])[:10]]
78
+ tractable = sorted({f"{x['modality']}: {x['label']}" for x in t.get("tractability") or [] if x.get("value")})
79
+ return {
80
+ "ensembl_id": t.get("id"),
81
+ "symbol": t.get("approvedSymbol"),
82
+ "name": t.get("approvedName"),
83
+ "biotype": t.get("biotype"),
84
+ "known_drugs": (t.get("drugAndClinicalCandidates") or {}).get("count"),
85
+ "genetic_constraint": t.get("geneticConstraint"),
86
+ "tractability_modalities": tractable,
87
+ "top_diseases": diseases,
88
+ }
89
+
90
+
91
+ def validate_target(ensembl_id: str) -> dict[str, Any]:
92
+ """Standalone helper: is this target druggable and genetically validated?"""
93
+ adapter = OpenTargetsAdapter()
94
+ s = adapter.summary(ensembl_id)
95
+ if "error" in s:
96
+ return s
97
+ return {
98
+ "symbol": s.get("symbol"),
99
+ "known_drugs": s.get("known_drugs", 0),
100
+ "tractability": s.get("tractability_modalities", []),
101
+ "top_disease_score": (s.get("top_diseases") or [{}])[0].get("score", 0),
102
+ }
@@ -0,0 +1,94 @@
1
+ """PubMed adapter — literature search via NCBI E-utilities.
2
+
3
+ Lightweight adapter for PubMed article search and abstract retrieval,
4
+ using the NCBI E-utilities API (stdlib only, no Biopython dependency).
5
+ Set NCBI_API_KEY env for higher rate limits (10 req/s vs 3 req/s).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import time
12
+ import urllib.parse
13
+ import urllib.request
14
+ from typing import Any
15
+
16
+ EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
17
+
18
+
19
+ class PubMedAdapter:
20
+ """Adapter for NCBI PubMed search and abstract retrieval."""
21
+
22
+ name = "pubmed"
23
+
24
+ def __init__(self, api_key: str | None = None, tool: str = "proef",
25
+ email: str = "", delay_secs: float = 0.5):
26
+ self.api_key = api_key or os.environ.get("NCBI_API_KEY", "")
27
+ self.tool = tool
28
+ self.email = email
29
+ self._delay = delay_secs if not self.api_key else max(delay_secs, 0.12)
30
+ self._last_call = 0.0
31
+
32
+ def _get(self, endpoint: str, params: dict[str, str]) -> Any:
33
+ elapsed = time.time() - self._last_call
34
+ if elapsed < self._delay:
35
+ time.sleep(self._delay - elapsed)
36
+ params.update({"tool": self.tool, "db": "pubmed"})
37
+ if self.email:
38
+ params["email"] = self.email
39
+ if self.api_key:
40
+ params["api_key"] = self.api_key
41
+ url = f"{EUTILS}/{endpoint}?{urllib.parse.urlencode(params)}"
42
+ req = urllib.request.Request(url)
43
+ self._last_call = time.time()
44
+ with urllib.request.urlopen(req, timeout=60) as resp: # noqa: S310
45
+ return resp.read()
46
+
47
+ def search(self, query: str, max_results: int = 10,
48
+ sort: str = "relevance", maxdate: str | None = None) -> list[str]:
49
+ """Search PubMed and return a list of PMID strings. `maxdate` (YYYY/MM/DD) keeps only records published on or before it."""
50
+ params = {
51
+ "term": query, "retmax": str(max_results),
52
+ "retmode": "json", "sort": sort,
53
+ }
54
+ if maxdate:
55
+ params.update({"datetype": "pdat", "mindate": "1900/01/01", "maxdate": maxdate})
56
+ raw = self._get("esearch.fcgi", params)
57
+ data = json.loads(raw)
58
+ return data.get("esearchresult", {}).get("idlist", [])
59
+
60
+ def fetch_abstracts(self, pmids: list[str]) -> list[dict[str, str]]:
61
+ """Fetch titles and abstracts for a list of PMIDs. efetch returns XML (it has no JSON mode)."""
62
+ if not pmids:
63
+ return []
64
+ raw = self._get("efetch.fcgi", {"id": ",".join(pmids), "rettype": "abstract", "retmode": "xml"})
65
+ return parse_efetch(raw)
66
+
67
+ def search_and_fetch(self, query: str, max_results: int = 10, maxdate: str | None = None) -> list[dict[str, str]]:
68
+ """Search + fetch in one call."""
69
+ pmids = self.search(query, max_results, maxdate=maxdate)
70
+ if not pmids:
71
+ return []
72
+ return self.fetch_abstracts(pmids)
73
+
74
+
75
+ def parse_efetch(raw: bytes | str) -> list[dict[str, str]]:
76
+ """Parse efetch XML into article dicts. Text from outside: entity declarations are refused, not expanded."""
77
+ import xml.etree.ElementTree as ET
78
+ data = raw if isinstance(raw, bytes) else raw.encode()
79
+ if b"<!ENTITY" in data:
80
+ raise ValueError("refusing XML with entity declarations")
81
+ root = ET.fromstring(data)
82
+ txt = lambda el: "".join(el.itertext()).strip() if el is not None else "" # noqa: E731
83
+ out = []
84
+ for art in root.iter("PubmedArticle"):
85
+ names = [f"{txt(a.find('LastName'))} {txt(a.find('Initials'))}".strip() for a in art.iter("Author")][:5]
86
+ out.append({
87
+ "pmid": txt(art.find(".//MedlineCitation/PMID")),
88
+ "title": txt(art.find(".//ArticleTitle")),
89
+ "abstract": " ".join(txt(x) for x in art.iterfind(".//Abstract/AbstractText"))[:2000],
90
+ "journal": txt(art.find(".//Journal/Title")),
91
+ "pub_date": txt(art.find(".//JournalIssue/PubDate/Year")) or txt(art.find(".//JournalIssue/PubDate/MedlineDate")),
92
+ "authors": ", ".join(n for n in names if n),
93
+ })
94
+ return out
File without changes
@@ -0,0 +1,251 @@
1
+ """Atlas Scientific EZO pH probe — wire-level LabAdapter proof (S-T4 POC).
2
+
3
+ THE PATTERN under test here: fine-grained instrument verbs (Cal, r, sleep...)
4
+ live at the WIRE; the agent surface speaks ProtocolSubmission; the gateway
5
+ decides in between. A raw command is NEVER offered as a tool — a datasheet-
6
+ faithful wire simulator lets the same adapter run against a real UART bridge
7
+ by changing the transport only.
8
+
9
+ Provenance, stated honestly:
10
+ * Command/reply grammar (*OK / *ER / ?i,pH,2.16, wake-on-first-char *WA,
11
+ calibration ladder) per the public Atlas Scientific EZO-pH(J) datasheets.
12
+ * The simulator is a hermetic stand-in for K-Dense LabMCP's
13
+ labmcp_atlas_ezo.EZOSimulator (Apache-2.0,
14
+ github.com/K-Dense-AI/lab-instrument-mcps) — notably its calibration-
15
+ reduces-error fidelity. PRODUCTION PATH: import that simulator (or a
16
+ real serial bridge) behind the same `_tx` seam; this in-repo copy exists
17
+ so CI stays hermetic (P8) and NOT to own an instrument manual.
18
+ * Status: SIMULATED. Never hardware-confirmed. hardware_validated=False
19
+ is surfaced in capabilities and must survive into any UI rendering.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import random
24
+ import re
25
+ import time
26
+ from typing import Any, Callable
27
+
28
+ from proef.core.contracts import (AssayResult, Envelope, InstrumentInfo,
29
+ Measurement, ProtocolSubmission,
30
+ RunStatus)
31
+
32
+
33
+ class EzoPHLine:
34
+ """Wire-level EZO-pH UART simulator: bytes in, bytes out.
35
+
36
+ `handle(command)` returns the device's raw reply. The uncertainty a
37
+ real probe advertises is a FUNCTION of calibration state — that
38
+ fidelity (borrowed from LabMCP's simulator) is the whole point: it
39
+ lets CI prove our verdict physics degrades honestly with uncalibrated
40
+ hardware, instead of pretending every reading is equally trustworthy.
41
+ """
42
+
43
+ _FIRMWARE = "2.16"
44
+ # (uncertainty when NO calibration, with mid only, full 2/3-pt)
45
+ _ERR = {"none": 0.120, "mid": 0.030, "buffered": 0.005}
46
+
47
+ def __init__(self, sample_ph: float = 7.20, seed: int = 7,
48
+ clock: Callable[[], float] = time.monotonic):
49
+ self.sample_ph = sample_ph
50
+ self.rng = random.Random(seed)
51
+ self.clock = clock
52
+ self.t0 = clock()
53
+ self.cal_points: set[str] = set()
54
+ self.continuous = 0 # datasheet ships 1; adapter sends C,0
55
+ self.asleep = False
56
+ self.log: list[tuple[str, str]] = []
57
+
58
+ @property
59
+ def uncertainty(self) -> float:
60
+ if not self.cal_points:
61
+ return self._ERR["none"]
62
+ if self.cal_points & {"low", "high"}:
63
+ return self._ERR["buffered"]
64
+ return self._ERR["mid"]
65
+
66
+ def _reading(self) -> str:
67
+ drift = 0.004 * ((self.clock() - self.t0) / 60.0) # slow wander
68
+ noise = self.rng.gauss(0.0, 0.002)
69
+ return f"{self.sample_ph + drift + noise:.3f}"
70
+
71
+ def handle(self, command: str) -> str:
72
+ cmd = command.strip()
73
+ if cmd == "":
74
+ return ""
75
+ if self.asleep:
76
+ self.asleep = False # first character wakes; command lost
77
+ return self._logq(cmd, "*WA")
78
+ reply = self._dispatch(cmd)
79
+ return self._logq(cmd, reply)
80
+
81
+ def _logq(self, cmd: str, reply: str) -> str:
82
+ self.log.append((cmd, reply))
83
+ return reply
84
+
85
+ def _dispatch(self, cmd: str) -> str:
86
+ parts = [p.strip() for p in cmd.split(",")]
87
+ head = parts[0].lower()
88
+ if head == "i" and len(parts) == 1:
89
+ return f"?i,pH,{self._FIRMWARE}*OK"
90
+ if head == "r" and len(parts) == 1:
91
+ return f"{self._reading()}*OK"
92
+ if head == "c" and len(parts) == 2:
93
+ n = parts[1]
94
+ if not n.isdigit() or not 0 <= int(n) <= 99:
95
+ return "*ER"
96
+ self.continuous = int(n)
97
+ return "*OK"
98
+ if head == "cal":
99
+ return self._cal(parts[1:])
100
+ if head == "status":
101
+ return "?Status,P,5.038*OK"
102
+ if head == "sleep":
103
+ self.asleep = True
104
+ return "*SL"
105
+ if head == "factory":
106
+ self.cal_points.clear()
107
+ return "*OK*RS*RE"
108
+ return "*ER" # unknown command, per datasheet
109
+
110
+ def _cal(self, args: list[str]) -> str:
111
+ if not args:
112
+ return "*ER"
113
+ if args[0] == "?":
114
+ return f"?Cal,{len(self.cal_points)}*OK"
115
+ if args[0] == "clear":
116
+ self.cal_points.clear()
117
+ return "*OK"
118
+ if len(args) != 2 or args[0] not in {"low", "mid", "high"}:
119
+ return "*ER"
120
+ try:
121
+ float(args[1])
122
+ except ValueError:
123
+ return "*ER"
124
+ if args[0] == "mid":
125
+ self.cal_points = {"mid"} # datasheet: mid clears the others
126
+ else:
127
+ self.cal_points.add(args[0])
128
+ return "*OK"
129
+
130
+
131
+ class EzoPHProbe:
132
+ """Proef LabAdapter: a sensor, not an assay robot.
133
+
134
+ Protocol semantics: each submission declares probe points as samples;
135
+ optional calibration via reagent metadata. submit_protocol compiles
136
+ that to wire commands (r, Cal,...) — the compilation step is exactly
137
+ what keeps `Cal` OUT of any agent's tool list.
138
+ """
139
+
140
+ name = "ezo_ph"
141
+
142
+ def __init__(self, line: EzoPHLine | None = None,
143
+ address: str = "serial:///dev/ttyUSB0?baud=115200"):
144
+ self.line = line or EzoPHLine()
145
+ self.address = address
146
+ self._runs: dict[str, dict[str, Any]] = {}
147
+ self._seq = 0
148
+
149
+ # -- transport seam: production swaps this for a real serial bridge ---
150
+
151
+ def _tx(self, command: str, retries: int = 2) -> str:
152
+ reply = self.line.handle(command)
153
+ # datasheet wake quirk: retry ONCE after *WA — this discipline is
154
+ # WHY the wire sim exists; mocks that skip quirks teach lies
155
+ for _ in range(retries):
156
+ if reply == "*WA":
157
+ reply = self.line.handle(command)
158
+ else:
159
+ break
160
+ if reply.endswith("*ER") or reply == "*ER":
161
+ raise RuntimeError(f"probe rejected command {command!r}: {reply}")
162
+ return reply
163
+
164
+ # -- LabAdapter protocol ------------------------------------------------
165
+
166
+ def list_capabilities(self) -> dict[str, Any]:
167
+ """For planner/readiness: WHAT the instrument can report, never
168
+ HOW to command it."""
169
+ return {
170
+ "kind": "sensor",
171
+ "readout": "pH",
172
+ "range_ph": [0.0, 14.0],
173
+ "resolution": 0.001,
174
+ "interface": self.address,
175
+ "calibration": {
176
+ "states": ["uncalibrated", "mid", "buffered"],
177
+ "uncertainty_ph": {"uncalibrated": EzoPHLine._ERR["none"],
178
+ "mid": EzoPHLine._ERR["mid"],
179
+ "buffered": EzoPHLine._ERR["buffered"]},
180
+ },
181
+ "simulated": True,
182
+ "hardware_validated": False,
183
+ "provenance": "wire grammar per EZO-pH(J) datasheets; simulator "
184
+ "stands in for labmcp_atlas_ezo (K-Dense, "
185
+ "Apache-2.0); production = real bridge or import",
186
+ }
187
+
188
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
189
+ for point in protocol.samples:
190
+ cal = (point.metadata or {}).get("calibrate")
191
+ if cal: # operator-declared calibration
192
+ if cal == "clear":
193
+ self._tx("Cal,clear")
194
+ else: # e.g. "mid,7.00"
195
+ self._tx(f"Cal,{cal}")
196
+ self._tx("c,0") # stop continuous mode (deterministic)
197
+ n = max(1, int((protocol.steps[0].params or {}).get("reads", 3))
198
+ if protocol.steps else 3)
199
+ readings = [self._read() for _ in range(n)]
200
+ self._seq += 1
201
+ run_id = f"ezo-{self._seq:03d}"
202
+ self._runs[run_id] = {
203
+ "protocol": protocol, "readings": readings,
204
+ "uncertainty": self.line.uncertainty,
205
+ "cal_state": sorted(self.line.cal_points) or ["uncalibrated"],
206
+ "log_len": len(self.line.log),
207
+ }
208
+ return run_id
209
+
210
+ def _read(self) -> float:
211
+ reply = self._tx("r")
212
+ m = re.fullmatch(r"([-+]?\d+\.\d+)\*OK", reply)
213
+ if not m:
214
+ raise RuntimeError(f"unparsable probe reply: {reply!r}")
215
+ return float(m.group(1))
216
+
217
+ def get_status(self, run_id: str) -> str:
218
+ return "done" if run_id in self._runs else "unknown"
219
+
220
+ def fetch_results(self, run_id: str) -> AssayResult:
221
+ run = self._runs[run_id]
222
+ readings: list[float] = run["readings"]
223
+ mean = sum(readings) / len(readings)
224
+ sd = (sum((r - mean) ** 2 for r in readings)
225
+ / max(1, len(readings) - 1)) ** 0.5
226
+ protocol: ProtocolSubmission = run["protocol"]
227
+ return AssayResult(
228
+ envelope=Envelope(experiment_branch_id="ezo_ph"),
229
+ run_id=run_id,
230
+ protocol_id=protocol.protocol_id,
231
+ instrument=InstrumentInfo(
232
+ adapter="ezo_ph(sim)", instrument_id="ezo-ph-sim-01",
233
+ raw_output_uri=f"wire-log://{run_id}?entries={run['log_len']}"),
234
+ status=RunStatus.completed,
235
+ measurements=[Measurement(
236
+ sample_id=s.sample_id, assay_type="ph",
237
+ value=round(mean, 3), unit="pH",
238
+ uncertainty=round(run["uncertainty"], 3),
239
+ derived_metrics={"n_reads": len(readings),
240
+ "sd_reads": round(sd, 4)},
241
+ metadata={"cal_state": run["cal_state"]})
242
+ for s in protocol.samples
243
+ if s.kind.value != "buffer"] or [Measurement(
244
+ sample_id="probe", assay_type="ph", value=round(mean, 3),
245
+ unit="pH", uncertainty=round(run["uncertainty"], 3),
246
+ metadata={"cal_state": run["cal_state"]})],
247
+ qc={"controls_passed": True,
248
+ "calibration": run["cal_state"],
249
+ "note": "SIMULATED instrument (S-T4 POC); uncertainty is the "
250
+ "probe's calibration-state error, not fitted noise"},
251
+ )