gemsmap 0.3.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.
@@ -0,0 +1,118 @@
1
+ """Export simulation results (JSON with full provenance, CSV tables) and modified models."""
2
+ import csv
3
+ import io
4
+ import json
5
+ import tempfile
6
+ from pathlib import Path
7
+
8
+ import cobra
9
+
10
+ from ..errors import ScienceError
11
+ from ..schemas import ResultPayload, StateSpec
12
+ from . import annotation_service
13
+ from . import model_service as ms
14
+
15
+
16
+ def _provenance_lines(r: ResultPayload) -> list[str]:
17
+ md = r.metadata or {}
18
+ obj = (md.get("objective") or {})
19
+ terms = " + ".join(f"{c:g}*{k}" for k, c in (obj.get("coefficients") or {}).items())
20
+ model = md.get("model") or {}
21
+ return [
22
+ f"# result: {r.name}",
23
+ f"# model: {model.get('filename', '')} (sha256 {str(model.get('checksum', ''))[:16]})",
24
+ f"# state: {(md.get('state') or {}).get('name', '')}",
25
+ f"# method: {md.get('methodLabel', r.method)} solver: {md.get('solver', '')} status: {r.solver_status}",
26
+ f"# objective: {obj.get('direction', '')} {terms} value: {r.objective_value}",
27
+ f"# timestamp: {md.get('timestamp', '')} cobrapy: {md.get('cobraVersion', '')}",
28
+ ]
29
+
30
+
31
+ def result_file(r: ResultPayload, fmt: str, table: str) -> tuple[bytes, str, str]:
32
+ safe = "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in (r.name or "result"))[:60]
33
+ if fmt == "json":
34
+ body = {"format": "cobragui-result", "version": 1, **r.model_dump(by_alias=True)}
35
+ return json.dumps(body, indent=1, allow_nan=False).encode(), f"{safe}.json", "application/json"
36
+ buf = io.StringIO()
37
+ buf.write("\n".join(_provenance_lines(r)) + "\n")
38
+ w = csv.writer(buf, lineterminator="\n")
39
+ if table == "fluxes":
40
+ if r.reaction_fluxes is None:
41
+ raise ScienceError("No flux vector in this result", "FVA results export as 'fva' intervals.")
42
+ w.writerow(["reaction", "flux"])
43
+ for k, v in r.reaction_fluxes.items():
44
+ w.writerow([k, "" if v is None else repr(v)])
45
+ elif table == "fva":
46
+ if r.fva is None:
47
+ raise ScienceError("This result has no FVA intervals")
48
+ w.writerow(["reaction", "minimum", "maximum", "range"])
49
+ for k, iv in r.fva.items():
50
+ lo, hi = iv.get("minimum"), iv.get("maximum")
51
+ w.writerow([k, lo, hi, (hi - lo) if lo is not None and hi is not None else ""])
52
+ elif table in ("samples", "summary"):
53
+ smp = (r.model_extra or {}).get("samples")
54
+ if not smp:
55
+ raise ScienceError("This result has no flux samples")
56
+ if table == "summary":
57
+ w.writerow(["reaction", "mean", "sd", "median", "q2.5", "q25", "q75", "q97.5", "min", "max"])
58
+ for k, s in smp.get("summary", {}).items():
59
+ w.writerow([k, *(s.get(x) for x in ("mean", "sd", "median", "q025", "q25", "q75", "q975", "min", "max"))])
60
+ else:
61
+ # long format reaction,condition,value: what the Map Builder reads as a "samples" dataset
62
+ cond = r.name or "sampling"
63
+ n = (r.metadata or {}).get("sampling", {}).get("n") or max((len(v) for v in smp.get("reactions", {}).values()), default=1)
64
+ w.writerow(["reaction", "condition", "flux"])
65
+ for k, vals in smp.get("reactions", {}).items():
66
+ for v in vals:
67
+ w.writerow([k, cond, repr(v)])
68
+ for k, v in smp.get("constant", {}).items():
69
+ for _ in range(n):
70
+ w.writerow([k, cond, "" if v is None else repr(v)])
71
+ elif table == "turnover":
72
+ if r.metabolite_turnover is None:
73
+ raise ScienceError("No metabolite turnover in this result", "Turnover is derived from a single flux vector.")
74
+ w.writerow(["metabolite", "turnover"])
75
+ for k, v in r.metabolite_turnover.items():
76
+ w.writerow([k, "" if v is None else repr(v)])
77
+ elif table == "exchanges":
78
+ ex = r.exchanges or {}
79
+ if r.fva is not None:
80
+ w.writerow(["reaction", "metabolite", "kind", "flux_min", "flux_max", "uptake_max", "secretion_max"])
81
+ for k, x in ex.items():
82
+ w.writerow([k, x.get("metabolite"), x.get("kind"), x.get("fluxMin"), x.get("fluxMax"), x.get("uptakeMax"), x.get("secretionMax")])
83
+ else:
84
+ w.writerow(["reaction", "metabolite", "kind", "flux", "uptake", "secretion"])
85
+ for k, x in ex.items():
86
+ w.writerow([k, x.get("metabolite"), x.get("kind"), x.get("flux"), x.get("uptake"), x.get("secretion")])
87
+ return buf.getvalue().encode("utf-8"), f"{safe}_{table}.csv", "text/csv"
88
+
89
+
90
+ def model_file(entry, state: StateSpec, fmt: str) -> tuple[bytes, str, str]:
91
+ """A new model file with the state applied permanently. The imported file is never touched."""
92
+ with entry.lock:
93
+ model = entry.model.copy()
94
+ ms.apply_state(model, state)
95
+ cur = annotation_service.curation(entry.id)
96
+ if cur["metabolites"]:
97
+ n = len(cur["metabolites"])
98
+ model.notes = {**(model.notes or {}), "GEMsMAP curation": (
99
+ f"{n} metabolites annotated from MetaNetX/MNXref in GEMsMAP "
100
+ f"({sum(1 for c in cur['metabolites'].values() if c.get('formula'))} formulas filled); "
101
+ f"original file {entry.filename} sha256 {entry.checksum[:16]}")}
102
+ from . import edit_service
103
+ log = edit_service.log_of(entry)
104
+ if log["applied"]:
105
+ labels = [t["label"] for t in log["applied"]]
106
+ model.notes = {**(model.notes or {}), "GEMsMAP structural edits": (
107
+ f"{len(labels)} edit(s) in GEMsMAP (COBRAGUI backend) on {entry.filename} (sha256 {entry.checksum[:16]}, edits {edit_service.log_hash(log)}): "
108
+ + "; ".join(labels[:40]) + (" …" if len(labels) > 40 else ""))}
109
+ base = Path(entry.filename).stem + ("_" + "".join(ch if ch.isalnum() else "_" for ch in state.name) if state.name else "_modified")
110
+ if fmt == "json":
111
+ return cobra.io.to_json(model).encode("utf-8"), f"{base}.json", "application/json"
112
+ with tempfile.TemporaryDirectory() as tmp:
113
+ path = Path(tmp) / ("model.xml" if fmt == "sbml" else "model.mat")
114
+ if fmt == "sbml":
115
+ cobra.io.write_sbml_model(model, str(path))
116
+ return path.read_bytes(), f"{base}.xml", "application/xml"
117
+ cobra.io.save_matlab_model(model, str(path))
118
+ return path.read_bytes(), f"{base}.mat", "application/octet-stream"
@@ -0,0 +1,429 @@
1
+ """Template identity search (Template Builder): candidates for "what is this node / this reaction?",
2
+ without any GEM.
3
+
4
+ Compounds: the query goes to KEGG (REST `find/compound`) and ChEBI (EBI OLS4 search); the hits are
5
+ resolved through MetaNetX / MNXref, which gives the cross-references (MetaNetX, KEGG, ChEBI, BiGG,
6
+ ModelSEED, MetaCyc, HMDB …), formula and charge. Hits that describe the same MNX chemical are merged.
7
+ Identifiers typed directly (C00031, CHEBI:17634, MNXM…, cpd00027, HMDB…) are looked up as such.
8
+
9
+ Reactions: the template's participants (with their identifiers) are resolved to MNX chemicals and the
10
+ MNXref reactions that convert a main substrate into a main product are returned, with evidence:
11
+ which participants appear in the equation, EC agreement, and the reaction cross-references
12
+ (KEGG, Rhea, BiGG, ModelSEED, MetaCyc).
13
+
14
+ Results are suggestions: the user confirms them in the Template Builder. Every web answer is cached
15
+ (identity_cache.sqlite, 90 days) so a repeated search makes no network request. Standard library only.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import re
22
+ import sqlite3
23
+ import threading
24
+ import time
25
+ import urllib.error
26
+ import urllib.parse
27
+ import urllib.request
28
+ from pathlib import Path
29
+ from typing import Callable, Optional
30
+
31
+ from . import bigg_service
32
+ from . import metanetx as mnx_mod
33
+ from .annotation_service import MAX_METACYC, compact, mnx_uri, norm_id, parse_mnx_xref
34
+
35
+ TTL_DAYS = 90
36
+ USER_AGENT = "GEMsMAP-TemplateBuilder/0.3 (pathway template identity search)"
37
+ KEGG = "https://rest.kegg.jp"
38
+ OLS = "https://www.ebi.ac.uk/ols4/api/search"
39
+ REAC = "https://rdf.metanetx.org/reac/"
40
+
41
+ # namespaces returned to the frontend (its identifier keys)
42
+ # VMH is left out: MNXref attaches unrelated VMH entries to some chemicals (dolichol sugars to glucose 1-phosphate)
43
+ _NS_OUT = {"metanetx.chemical": "metanetx.chemical", "kegg.compound": "kegg.compound", "chebi": "chebi", "bigg.metabolite": "bigg.metabolite",
44
+ "seed.compound": "seed.compound", "metacyc.compound": "metacyc.compound", "hmdb": "hmdb", "lipidmaps": "lipidmaps", "inchikey": "inchikey"}
45
+
46
+
47
+ class SourceUnavailable(Exception):
48
+ pass
49
+
50
+
51
+ # ----------------------------------------------------------------------------- web cache
52
+
53
+ class WebCache:
54
+ def __init__(self, path: Path):
55
+ self._db = sqlite3.connect(str(path), check_same_thread=False)
56
+ self._lock = threading.Lock()
57
+ with self._lock:
58
+ self._db.execute("CREATE TABLE IF NOT EXISTS web (key TEXT PRIMARY KEY, body TEXT NOT NULL, at REAL NOT NULL)")
59
+ self._db.commit()
60
+
61
+ def get(self, key: str) -> Optional[str]:
62
+ with self._lock:
63
+ row = self._db.execute("SELECT body FROM web WHERE key = ? AND at > ?", (key, time.time() - TTL_DAYS * 86400)).fetchone()
64
+ return row[0] if row else None
65
+
66
+ def put(self, key: str, body: str) -> None:
67
+ with self._lock:
68
+ self._db.execute("INSERT OR REPLACE INTO web VALUES (?, ?, ?)", (key, body, time.time()))
69
+ self._db.commit()
70
+
71
+
72
+ _cache: Optional[WebCache] = None
73
+ _cache_lock = threading.Lock()
74
+
75
+
76
+ def _web_cache() -> WebCache:
77
+ global _cache
78
+ with _cache_lock:
79
+ if _cache is None:
80
+ from ..registry import cache_dir
81
+ _cache = WebCache(cache_dir().parent / "identity_cache.sqlite")
82
+ return _cache
83
+
84
+
85
+ def _http_get(url: str) -> str:
86
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json, text/plain"})
87
+ last: Exception | None = None
88
+ for attempt in range(2):
89
+ try:
90
+ with urllib.request.urlopen(req, timeout=25) as res:
91
+ return res.read().decode("utf-8")
92
+ except urllib.error.HTTPError as e:
93
+ if e.code == 404:
94
+ return "" # KEGG answers 404 for "no hit"
95
+ last = e
96
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
97
+ last = e
98
+ time.sleep(1.0 * (attempt + 1))
99
+ raise SourceUnavailable(str(last))
100
+
101
+
102
+ _fetch: Callable[[str], str] = _http_get
103
+
104
+
105
+ def set_fetch(f: Optional[Callable[[str], str]]) -> None:
106
+ """Tests inject a fake transport (no network)."""
107
+ global _fetch
108
+ _fetch = f or _http_get
109
+
110
+
111
+ def fetch(url: str) -> str:
112
+ cache = _web_cache()
113
+ hit = cache.get(url)
114
+ if hit is not None:
115
+ return hit
116
+ body = _fetch(url)
117
+ cache.put(url, body)
118
+ return body
119
+
120
+
121
+ def _sparql(q: str) -> list[dict]:
122
+ """MetaNetX SPARQL with the same cache (reaction queries are not part of the MetaNetX client cache)."""
123
+ key = "sparql:" + hashlib.sha1(q.encode()).hexdigest()
124
+ cache = _web_cache()
125
+ hit = cache.get(key)
126
+ if hit is not None:
127
+ return json.loads(hit)
128
+ rows = mnx_mod.client().query(q)
129
+ cache.put(key, json.dumps(rows))
130
+ return rows
131
+
132
+
133
+ # ----------------------------------------------------------------------------- name matching
134
+
135
+ def name_score(q: str, names: list[str]) -> tuple[float, str]:
136
+ """Relevance of a hit for a query: 1 exact name, 0.9 exact synonym, 0.7 prefix, 0.5 substring."""
137
+ k = compact(q)
138
+ if not k or not names:
139
+ return 0.0, ""
140
+ if compact(names[0]) == k:
141
+ return 1.0, "exact name"
142
+ for n in names[1:]:
143
+ if compact(n) == k:
144
+ return 0.9, f"synonym “{n}”"
145
+ if any(compact(n).startswith(k) for n in names):
146
+ return 0.7, "name starts with the query"
147
+ if any(k in compact(n) for n in names):
148
+ return 0.5, "name contains the query"
149
+ return 0.3, "related term"
150
+
151
+
152
+ # ----------------------------------------------------------------------------- sources
153
+
154
+ def kegg_find(q: str, limit: int = 6) -> list[dict]:
155
+ body = fetch(f"{KEGG}/find/compound/{urllib.parse.quote(q)}")
156
+ hits = []
157
+ for line in body.splitlines():
158
+ if "\t" not in line:
159
+ continue
160
+ cid, names = line.split("\t", 1)
161
+ cid = cid.replace("cpd:", "").strip()
162
+ if not re.fullmatch(r"C\d{5}", cid):
163
+ continue
164
+ ns = [n.strip() for n in names.split(";") if n.strip()]
165
+ score, why = name_score(q, ns)
166
+ hits.append({"id": cid, "names": ns, "score": score, "match": why})
167
+ hits.sort(key=lambda h: (-h["score"], len(h["names"][0]) if h["names"] else 99))
168
+ return [h for h in hits if h["score"] >= 0.5][:limit]
169
+
170
+
171
+ def chebi_search(q: str, limit: int = 6) -> list[dict]:
172
+ url = f"{OLS}?{urllib.parse.urlencode({'q': q, 'ontology': 'chebi', 'rows': 15, 'fieldList': 'obo_id,label,synonym'})}"
173
+ body = fetch(url)
174
+ try:
175
+ docs = json.loads(body or "{}").get("response", {}).get("docs", [])
176
+ except ValueError:
177
+ return []
178
+ hits = []
179
+ for d in docs:
180
+ oid = str(d.get("obo_id") or "")
181
+ if not re.fullmatch(r"CHEBI:\d+", oid):
182
+ continue
183
+ ns = [str(d.get("label") or "")] + [str(s) for s in (d.get("synonym") or [])]
184
+ ns = [n for i, n in enumerate(ns) if n and n not in ns[:i]]
185
+ score, why = name_score(q, ns)
186
+ hits.append({"id": oid, "names": ns, "score": score, "match": why})
187
+ hits.sort(key=lambda h: -h["score"])
188
+ return [h for h in hits if h["score"] >= 0.5][:limit]
189
+
190
+
191
+ def _identifiers(info: dict, mnx: str) -> dict[str, list[str]]:
192
+ found: dict[str, set[str]] = {}
193
+ for uri in info.get("xrefs", []):
194
+ p = parse_mnx_xref(uri)
195
+ if p and p[0] in _NS_OUT:
196
+ found.setdefault(_NS_OUT[p[0]], set()).add(p[1])
197
+ if len(found.get("metacyc.compound", ())) > MAX_METACYC:
198
+ found.pop("metacyc.compound") # MNXref merges whole compound classes into some chemicals
199
+ found.setdefault("metanetx.chemical", set()).add(mnx)
200
+ if info.get("inchikey"):
201
+ found.setdefault("inchikey", set()).add(info["inchikey"])
202
+ return {k: sorted(v) for k, v in found.items()}
203
+
204
+
205
+ _ID_PATTERNS = [
206
+ (re.compile(r"^C\d{5}$", re.I), "kegg.compound"), (re.compile(r"^CHEBI:\s*\d+$", re.I), "chebi"), (re.compile(r"^MNXM\d+$", re.I), "metanetx.chemical"),
207
+ (re.compile(r"^cpd\d{5}$", re.I), "seed.compound"), (re.compile(r"^HMDB\d+$", re.I), "hmdb"),
208
+ ]
209
+
210
+
211
+ def search_compounds(q: str, limit: int = 8) -> dict:
212
+ q = q.strip()
213
+ status: dict[str, str] = {}
214
+ if not q:
215
+ return {"query": q, "candidates": [], "sources": status}
216
+ direct = next((ns for pat, ns in _ID_PATTERNS if pat.match(q)), None)
217
+ hits: list[tuple[str, str, dict]] = [] # (namespace, id, hit)
218
+ if direct:
219
+ hits.append((direct, norm_id(direct, q), {"names": [], "score": 1.0, "match": f"identifier {q}"}))
220
+ else:
221
+ for name, fn, ns in (("KEGG", kegg_find, "kegg.compound"), ("ChEBI", chebi_search, "chebi")):
222
+ try:
223
+ for h in fn(q):
224
+ hits.append((ns, h["id"], {**h, "source": name}))
225
+ status[name] = "ok"
226
+ except SourceUnavailable as e:
227
+ status[name] = f"unavailable ({e})"
228
+ # resolve through MNXref
229
+ by_mnx: dict[str, list[tuple[str, str, dict]]] = {}
230
+ lone: list[tuple[str, str, dict]] = []
231
+ try:
232
+ client = mnx_mod.client()
233
+ uris = {mnx_uri(ns, i): (ns, i, h) for ns, i, h in hits if ns != "metanetx.chemical" and mnx_uri(ns, i)}
234
+ resolved = client.resolve_xrefs(uris.keys()) if uris else {}
235
+ for ns, i, h in hits:
236
+ mids = [i] if ns == "metanetx.chemical" else resolved.get(mnx_uri(ns, i) or "", [])
237
+ if not mids:
238
+ lone.append((ns, i, h))
239
+ for m in mids:
240
+ by_mnx.setdefault(m, []).append((ns, i, h))
241
+ info = client.chem_info(by_mnx.keys()) if by_mnx else {}
242
+ status["MetaNetX"] = "ok"
243
+ except mnx_mod.MetaNetXUnavailable as e:
244
+ status["MetaNetX"] = f"unavailable ({e})"
245
+ info, lone = {}, hits
246
+ out = []
247
+ for m, group in by_mnx.items():
248
+ d = info.get(m) or {}
249
+ if not d.get("exists"):
250
+ lone.extend(group)
251
+ continue
252
+ names = [d.get("name") or ""] + [n for _, _, h in group for n in h.get("names", [])]
253
+ names = [n for i, n in enumerate(names) if n and n not in names[:i]]
254
+ best = max(group, key=lambda g: g[2]["score"])
255
+ score, why = (best[2]["score"], best[2]["match"]) if direct else name_score(q, names)
256
+ out.append({
257
+ "name": d.get("name") or names[0], "formula": d.get("formula"), "charge": d.get("charge"), "synonyms": names[1:16],
258
+ "identifiers": _identifiers(d, m), "mnx": m, "structured": bool(d.get("formula") or d.get("inchikey")),
259
+ "sources": sorted({g[2].get("source", "identifier") for g in group} | {"MetaNetX"}),
260
+ "score": round(max(score, best[2]["score"] * 0.95), 3), "match": why or best[2]["match"],
261
+ "note": "via " + ", ".join(sorted({f"{'KEGG' if g[0] == 'kegg.compound' else 'ChEBI' if g[0] == 'chebi' else g[0]} {g[1]}" for g in group})),
262
+ })
263
+ for ns, i, h in lone: # known to KEGG/ChEBI but not resolved by MNXref: still a candidate, with that one identifier
264
+ if any(i in (c["identifiers"].get(ns) or []) for c in out):
265
+ continue
266
+ names = h.get("names") or [i]
267
+ out.append({"name": names[0], "formula": None, "charge": None, "synonyms": names[1:16], "identifiers": {ns: [i]}, "mnx": None, "structured": False,
268
+ "sources": [h.get("source", "identifier")], "score": h["score"], "match": h["match"], "note": "not resolved by MetaNetX"})
269
+ # BiGG universal metabolites (local, after a sync): merged with the hits above when they share an identifier
270
+ ix = bigg_service.index()
271
+ if ix is None:
272
+ status["BiGG"] = "not downloaded"
273
+ else:
274
+ status["BiGG"] = "ok"
275
+ for b in ix.search_metabolites(q, limit):
276
+ keys = {(ns, v) for ns, vs in b["identifiers"].items() if ns != "bigg.metabolite" for v in vs}
277
+ hit = next((c for c in out if keys & {(ns, v) for ns, vs in c["identifiers"].items() for v in vs}), None)
278
+ if hit:
279
+ for ns, vs in b["identifiers"].items():
280
+ hit["identifiers"][ns] = sorted(set(hit["identifiers"].get(ns, [])) | set(vs))
281
+ hit["sources"] = sorted(set(hit["sources"]) | {"BiGG"})
282
+ hit["score"] = max(hit["score"], b["score"])
283
+ hit["note"] = f"{hit.get('note') or ''} · {b['note']}".strip(" ·")
284
+ else:
285
+ out.append(b)
286
+ out.sort(key=lambda c: (-c["score"], not c["structured"], len(c["name"])))
287
+ return {"query": q, "candidates": out[:limit], "sources": status}
288
+
289
+
290
+ # ----------------------------------------------------------------------------- reactions
291
+
292
+ def _participant_mnx(p: dict, client) -> set[str]:
293
+ ids: set[str] = set()
294
+ uris = []
295
+ for ns, vals in (p.get("identifiers") or {}).items():
296
+ ns = "vmhmetabolite" if ns == "vmh" else ns
297
+ for v in vals or []:
298
+ if ns == "metanetx.chemical":
299
+ ids.add(str(v).upper())
300
+ continue
301
+ i = norm_id(ns, v)
302
+ u = mnx_uri(ns, i) if i else None
303
+ if u:
304
+ uris.append(u)
305
+ if uris:
306
+ for v in client.resolve_xrefs(uris).values():
307
+ ids.update(v)
308
+ return ids
309
+
310
+
311
+ def _reaction_xrefs(uris: list[str]) -> dict[str, list[str]]:
312
+ out: dict[str, set[str]] = {}
313
+ for u in uris:
314
+ m = re.match(r"https?://identifiers\.org/([^:/]+)[:/](.+)$", u)
315
+ if m:
316
+ prefix, rest = m.group(1).lower(), m.group(2)
317
+ ns = {"kegg.reaction": "kegg.reaction", "seed.reaction": "seed.reaction", "metacyc.reaction": "metacyc.reaction", "rhea": "rhea", "bigg.reaction": "bigg.reaction"}.get(prefix)
318
+ if ns:
319
+ out.setdefault(ns, set()).add(rest)
320
+ continue
321
+ m = re.match(r"https?://rdf\.rhea-db\.org/(\d+)$", u)
322
+ if m:
323
+ out.setdefault("rhea", set()).add(m.group(1))
324
+ continue
325
+ m = re.match(r"https?://bigg\.ucsd\.edu/universal/reactions/(.+)$", u)
326
+ if m and not m.group(1).startswith("R_"): # R_PGI is an SBML-prefixed copy of PGI
327
+ out.setdefault("bigg.reaction", set()).add(m.group(1))
328
+ return {k: sorted(v) for k, v in out.items()}
329
+
330
+
331
+ def search_reactions(participants: list[dict], ec: list[str], limit: int = 8) -> dict:
332
+ """BiGG universal reactions (local, every participant and compartment scored) and MNXref reactions."""
333
+ ix = bigg_service.index()
334
+ bigg = ix.search_reactions(participants, ec, limit) if ix else {"candidates": [], "notes": ["BiGG data not downloaded (Template Library → BiGG)"]}
335
+ mnx = search_reactions_mnx(participants, ec, limit)
336
+ out = list(bigg["candidates"])
337
+ for c in mnx["candidates"]:
338
+ # the same MNXref reaction already behind a BiGG candidate: one row, both sources
339
+ hit = next((b for b in out if set(b["identifiers"].get("metanetx.reaction", [])) & set(c["identifiers"].get("metanetx.reaction", []))), None)
340
+ if hit:
341
+ for ns, vs in c["identifiers"].items():
342
+ hit["identifiers"][ns] = sorted(set(hit["identifiers"].get(ns, [])) | set(vs))
343
+ hit["sources"] = sorted(set(hit["sources"]) | {"MetaNetX"})
344
+ else:
345
+ out.append(c)
346
+ # MetaNetX is the reference: MNXref candidates first; BiGG candidates follow as complementary evidence
347
+ # (their score also weighs compartments, cofactors and coefficients — the two scales are not comparable)
348
+ out.sort(key=lambda c: ("MetaNetX" not in c["sources"], -c["score"]))
349
+ return {"candidates": out[:limit], "notes": bigg["notes"] + [n for n in mnx["notes"] if n not in bigg["notes"]]}
350
+
351
+
352
+ def search_reactions_mnx(participants: list[dict], ec: list[str], limit: int = 8) -> dict:
353
+ """participants: [{name, identifiers, coefficient, main}] — coefficient < 0 substrate, > 0 product."""
354
+ try:
355
+ client = mnx_mod.client()
356
+ resolved = [(p, _participant_mnx(p, client)) for p in participants]
357
+ except mnx_mod.MetaNetXUnavailable as e:
358
+ return {"candidates": [], "notes": [f"MetaNetX unavailable ({e})"]}
359
+ subs = [x for x in resolved if x[0].get("coefficient", 0) < 0 and x[0].get("main") and x[1]]
360
+ prods = [x for x in resolved if x[0].get("coefficient", 0) > 0 and x[0].get("main") and x[1]]
361
+ notes = [f"{p.get('name') or '?'}: no MetaNetX chemical for its identifiers" for p, m in resolved if not m]
362
+ if not subs or not prods:
363
+ return {"candidates": [], "notes": notes + ["Define the identity of at least one drawn substrate and one drawn product first"]}
364
+ a, b = subs[0][1], prods[0][1]
365
+ vals = lambda ids: " ".join(f"<{mnx_mod.CHEM}{i}>" for i in sorted(ids))
366
+ try:
367
+ rows = _sparql(
368
+ "SELECT DISTINCT ?reac ?eq WHERE { VALUES ?ca { " + vals(a) + " } VALUES ?cb { " + vals(b) + " } "
369
+ "{ ?reac mnx:left ?pa . ?reac mnx:right ?pb } UNION { ?reac mnx:right ?pa . ?reac mnx:left ?pb } "
370
+ "?pa mnx:chem ?ca . ?pb mnx:chem ?cb . ?reac rdfs:comment ?eq } LIMIT 40")
371
+ reacs = sorted({r["reac"].replace(REAC, "") for r in rows if re.fullmatch(r"MNXR\d+", r["reac"].replace(REAC, ""))})
372
+ if not reacs:
373
+ return {"candidates": [], "notes": notes + ["MNXref has no reaction converting these compounds"]}
374
+ rv = " ".join(f"<{REAC}{r}>" for r in reacs)
375
+ parts = _sparql("SELECT ?reac ?side ?chem ?coef WHERE { VALUES ?reac { " + rv + " } ?reac ?side ?p . FILTER(?side IN (mnx:left, mnx:right)) ?p mnx:chem ?chem . OPTIONAL { ?p mnx:coef ?coef } }")
376
+ meta = _sparql("SELECT ?reac ?p ?o WHERE { VALUES ?reac { " + rv + " } ?reac ?p ?o . FILTER(?p IN (rdfs:comment, mnx:classification, mnx:reacXref, mnx:reacRefer, mnx:isBalanced)) }")
377
+ except mnx_mod.MetaNetXUnavailable as e:
378
+ return {"candidates": [], "notes": notes + [f"MetaNetX unavailable ({e})"]}
379
+ eqs: dict[str, dict] = {r: {"left": set(), "right": set(), "ec": set(), "xrefs": [], "eq": "", "balanced": None} for r in reacs}
380
+ for p in parts:
381
+ r = p["reac"].replace(REAC, "")
382
+ side = "left" if p["side"].endswith("left") else "right"
383
+ eqs[r][side].add(p["chem"].replace(mnx_mod.CHEM, ""))
384
+ for m in meta:
385
+ r, pred, o = m["reac"].replace(REAC, ""), m["p"].rsplit("/", 1)[-1].split("#")[-1], m["o"]
386
+ if pred == "comment":
387
+ eqs[r]["eq"] = o
388
+ elif pred == "classification":
389
+ eqs[r]["ec"].add(o)
390
+ elif pred in ("reacXref", "reacRefer"):
391
+ eqs[r]["xrefs"].append(o)
392
+ elif pred == "isBalanced":
393
+ eqs[r]["balanced"] = o in ("1", "true")
394
+ names = {}
395
+ try:
396
+ info = client.chem_info({c for e in eqs.values() for c in e["left"] | e["right"]})
397
+ names = {k: v.get("name") for k, v in info.items()}
398
+ except mnx_mod.MetaNetXUnavailable:
399
+ pass
400
+ out = []
401
+ for r, e in eqs.items():
402
+ forward = bool(a & e["left"]) and bool(b & e["right"])
403
+ sub_side, prod_side = (e["left"], e["right"]) if forward else (e["right"], e["left"])
404
+ evidence = []
405
+ hit = 0
406
+ for p, mids in resolved:
407
+ side = sub_side if p.get("coefficient", 0) < 0 else prod_side
408
+ role = "substrate" if p.get("coefficient", 0) < 0 else "product"
409
+ if mids & side:
410
+ hit += 1
411
+ evidence.append({"ok": True, "text": f"{p.get('name') or '?'} ({role})"})
412
+ elif mids & (e["left"] | e["right"]):
413
+ evidence.append({"ok": False, "text": f"{p.get('name') or '?'} is on the other side"})
414
+ else:
415
+ evidence.append({"ok": False, "text": f"{p.get('name') or '?'} not in this equation"})
416
+ extra = len((e["left"] | e["right"]) - set().union(*(m for _, m in resolved)))
417
+ if extra:
418
+ evidence.append({"ok": None, "text": f"{extra} other compound(s) in the MNXref equation"})
419
+ ec_ok = bool(set(ec) & e["ec"])
420
+ if ec:
421
+ evidence.append({"ok": ec_ok, "text": f"EC {', '.join(sorted(e['ec'])) or 'none'}" + (" matches" if ec_ok else f" (template: {', '.join(ec)})")})
422
+ score = hit / max(1, len(resolved)) * 0.8 + (0.2 if ec_ok else 0) - 0.02 * extra
423
+ ids = _reaction_xrefs(e["xrefs"])
424
+ ids["metanetx.reaction"] = [r]
425
+ readable = re.sub(r"(\d+(?:\.\d+)?) (MNXM\d+)@MNX[DC]\d+", lambda m: (m.group(1) + " " if m.group(1) not in ("1", "1.0") else "") + (names.get(m.group(2)) or m.group(2)), e["eq"])
426
+ out.append({"name": r, "ec": sorted(e["ec"]), "identifiers": ids, "equation": readable, "balanced": e["balanced"],
427
+ "direction": "as drawn" if forward else "written in reverse in MNXref", "sources": ["MetaNetX"], "score": round(max(0.0, min(1.0, score)), 3), "evidence": evidence})
428
+ out.sort(key=lambda c: -c["score"])
429
+ return {"candidates": out[:limit], "notes": notes}
@@ -0,0 +1,117 @@
1
+ """Medium = uptake limits of exchange reactions, read and written through COBRApy's `Model.medium`.
2
+
3
+ Edits are returned as bound changes so the frontend stores them in the model state like any other
4
+ constraint; the sign convention (X <=> vs <=> X) is COBRApy's, never re-derived in the UI.
5
+ """
6
+ import math
7
+ import re
8
+
9
+ from cobra.medium import minimal_medium
10
+
11
+ from ..errors import ScienceError, num
12
+ from ..schemas import StateSpec
13
+ from . import model_service as ms
14
+
15
+
16
+ def _uptake_secretion(coef: float, lb: float, ub: float) -> tuple[float, float]:
17
+ """Max uptake / max secretion allowed by the bounds of a boundary reaction."""
18
+ if coef < 0: # X <=> : negative flux imports X
19
+ return max(0.0, -lb), max(0.0, ub)
20
+ return max(0.0, ub), max(0.0, -lb) # <=> X : positive flux imports X
21
+
22
+
23
+ def medium_table(entry, state: StateSpec) -> dict:
24
+ kinds = ms.boundary_kinds(entry.model)
25
+ with ms.applied(entry, state) as model:
26
+ try:
27
+ medium = dict(model.medium)
28
+ except Exception: # noqa: BLE001
29
+ medium = {}
30
+ rows = []
31
+ for r in model.boundary:
32
+ met_id, coef = ms.boundary_metabolite(r)
33
+ met = model.metabolites.get_by_id(met_id) if met_id else None
34
+ up, sec = _uptake_secretion(coef, r.lower_bound, r.upper_bound)
35
+ olb, oub = entry.original_bounds[r.id]
36
+ oup, osec = _uptake_secretion(coef, olb, oub)
37
+ rows.append({
38
+ "reaction": r.id, "reactionName": r.name or "", "kind": kinds.get(r.id, "exchange"),
39
+ "metabolite": met_id, "metaboliteName": met.name if met else "", "formula": met.formula if met else None,
40
+ "uptakeMax": num(up) if math.isfinite(up) else None, "secretionMax": num(sec) if math.isfinite(sec) else None,
41
+ "uptakeUnbounded": not math.isfinite(up),
42
+ "originalUptakeMax": num(oup), "originalSecretionMax": num(osec),
43
+ "inMedium": r.id in medium,
44
+ "lb": num(r.lower_bound), "ub": num(r.upper_bound),
45
+ })
46
+ rows.sort(key=lambda x: (not x["inMedium"], x["kind"] != "exchange", x["metaboliteName"].lower() or x["reaction"]))
47
+ return {"medium": {k: num(v) for k, v in medium.items()}, "rows": rows}
48
+
49
+
50
+ def _apply_medium(model, new_medium: dict[str, float]) -> dict[str, list]:
51
+ before = {r.id: r.bounds for r in model.boundary}
52
+ for rid in new_medium:
53
+ if rid not in model.reactions:
54
+ raise ScienceError("Unknown exchange reaction", rid, status=422)
55
+ model.medium = {k: float(v) for k, v in new_medium.items() if v and v > 0}
56
+ return {r.id: [num(r.lower_bound), num(r.upper_bound)] for r in model.boundary if r.bounds != before[r.id]}
57
+
58
+
59
+ def set_medium(entry, state: StateSpec, medium: dict[str, float]) -> dict:
60
+ neg = [k for k, v in medium.items() if v is not None and v < 0]
61
+ if neg:
62
+ raise ScienceError("Uptake limits must be ≥ 0", ", ".join(neg[:5]), status=422,
63
+ hints=["Enter the maximum uptake rate as a positive number (mmol gDW⁻¹ h⁻¹)."])
64
+ with ms.applied(entry, state) as model:
65
+ changes = _apply_medium(model, medium)
66
+ result = {k: num(v) for k, v in model.medium.items()}
67
+ return {"bounds": changes, "medium": result}
68
+
69
+
70
+ def _oxygen_exchanges(model) -> list[str]:
71
+ out = []
72
+ for r in model.exchanges:
73
+ met_id, _ = ms.boundary_metabolite(r)
74
+ if not met_id:
75
+ continue
76
+ met = model.metabolites.get_by_id(met_id)
77
+ base = re.sub(r"(\[[a-z0-9]+\]|_[a-z][a-z0-9]?)$", "", met.id.replace("M_", "")).lower()
78
+ if base in ("o2", "oxygen") or (met.formula or "") == "O2" or re.fullmatch(r"(di)?oxygen|o2", (met.name or "").strip(), re.I):
79
+ out.append(r.id)
80
+ return out
81
+
82
+
83
+ def apply_preset(entry, state: StateSpec, preset: str, rich_uptake: float, growth_fraction: float) -> dict:
84
+ notes: list[str] = []
85
+ with ms.applied(entry, state) as model:
86
+ current = dict(model.medium)
87
+ if preset == "original":
88
+ new = dict(entry.original_medium)
89
+ notes.append("Uptake limits restored from the model file.")
90
+ elif preset == "rich":
91
+ new = {r.id: max(rich_uptake, current.get(r.id, 0.0)) for r in model.exchanges}
92
+ notes.append(f"Every exchange reaction allows uptake of at least {rich_uptake:g} mmol gDW⁻¹ h⁻¹.")
93
+ elif preset == "anaerobic":
94
+ o2 = _oxygen_exchanges(model)
95
+ if not o2:
96
+ raise ScienceError("No oxygen exchange found", "Could not identify an O2 exchange reaction in this model.",
97
+ hints=["Set the oxygen uptake to 0 manually in the medium table."])
98
+ new = {k: v for k, v in current.items() if k not in o2}
99
+ notes.append(f"Oxygen uptake closed ({', '.join(o2)}).")
100
+ elif preset == "minimal":
101
+ opt = model.slim_optimize(error_value=None)
102
+ if opt is None or not math.isfinite(opt) or opt <= 0:
103
+ raise ScienceError("Cannot compute a minimal medium",
104
+ "The objective cannot carry flux with the current state and medium.",
105
+ hints=["Check the objective.", "Open more substrates first (e.g. the Rich preset)."])
106
+ target = opt * growth_fraction
107
+ mm = minimal_medium(model, target, minimize_components=False)
108
+ if mm is None:
109
+ raise ScienceError("Minimal medium problem is infeasible")
110
+ new = {k: float(v) for k, v in mm.items() if v > 1e-9}
111
+ notes.append(f"Minimal total uptake supporting {growth_fraction:.0%} of the current optimum "
112
+ f"({target:.4g}). Uptake limits are set to exactly those fluxes.")
113
+ else:
114
+ raise ScienceError("Unknown medium preset", preset, status=422)
115
+ changes = _apply_medium(model, new)
116
+ result = {k: num(v) for k, v in model.medium.items()}
117
+ return {"bounds": changes, "medium": result, "notes": notes}