gemsmap 0.3.0b1__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.
- cobragui/__init__.py +4 -0
- cobragui/errors.py +37 -0
- cobragui/main.py +331 -0
- cobragui/registry.py +68 -0
- cobragui/schemas.py +171 -0
- cobragui/services/__init__.py +0 -0
- cobragui/services/annotation_service.py +737 -0
- cobragui/services/bigg_service.py +498 -0
- cobragui/services/comparison_service.py +164 -0
- cobragui/services/edit_service.py +942 -0
- cobragui/services/export_service.py +99 -0
- cobragui/services/identity_service.py +429 -0
- cobragui/services/medium_service.py +117 -0
- cobragui/services/metanetx.py +209 -0
- cobragui/services/model_service.py +480 -0
- cobragui/services/search_service.py +97 -0
- cobragui/services/simulation_service.py +350 -0
- gemsmap/__init__.py +6 -0
- gemsmap/__main__.py +6 -0
- gemsmap/cli.py +172 -0
- gemsmap/server.py +32 -0
- gemsmap/web/assets/index-BaJDLO-W.css +1 -0
- gemsmap/web/assets/index-CupjXseC.js +79 -0
- gemsmap/web/brand/cobragui-logo.png +0 -0
- gemsmap/web/examples/fva_2conditions.csv +33 -0
- gemsmap/web/examples/pfba_4conditions.csv +33 -0
- gemsmap/web/examples/timecourse.csv +10 -0
- gemsmap/web/favicon.svg +33 -0
- gemsmap/web/index.html +17 -0
- gemsmap-0.3.0b1.dist-info/METADATA +75 -0
- gemsmap-0.3.0b1.dist-info/RECORD +34 -0
- gemsmap-0.3.0b1.dist-info/WHEEL +4 -0
- gemsmap-0.3.0b1.dist-info/entry_points.txt +2 -0
- gemsmap-0.3.0b1.dist-info/licenses/LICENSE +21 -0
cobragui/__init__.py
ADDED
cobragui/errors.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Errors the UI can explain to a scientist (title + message + what to check), plus JSON-safe numbers."""
|
|
2
|
+
import math
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ScienceError(Exception):
|
|
7
|
+
"""An error with a meaningful explanation. Rendered as {"error": {...}} with the given HTTP status."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, title: str, message: str = "", *, status: int = 400,
|
|
10
|
+
hints: Optional[list[str]] = None, detail: Any = None):
|
|
11
|
+
super().__init__(f"{title}: {message}" if message else title)
|
|
12
|
+
self.title = title
|
|
13
|
+
self.message = message
|
|
14
|
+
self.status = status
|
|
15
|
+
self.hints = hints or []
|
|
16
|
+
self.detail = detail
|
|
17
|
+
|
|
18
|
+
def payload(self) -> dict:
|
|
19
|
+
return {"error": {"title": self.title, "message": self.message, "hints": self.hints, "detail": self.detail}}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def num(x: Any) -> Optional[float]:
|
|
23
|
+
"""Float or None (JSON has no NaN/Infinity; None means 'no value' or 'unbounded')."""
|
|
24
|
+
if x is None:
|
|
25
|
+
return None
|
|
26
|
+
try:
|
|
27
|
+
f = float(x)
|
|
28
|
+
except (TypeError, ValueError):
|
|
29
|
+
return None
|
|
30
|
+
return f if math.isfinite(f) else None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def bound_in(x: Optional[float], side: str) -> float:
|
|
34
|
+
"""None from the client means unbounded on that side."""
|
|
35
|
+
if x is None:
|
|
36
|
+
return -math.inf if side == "lower" else math.inf
|
|
37
|
+
return float(x)
|
cobragui/main.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""COBRAGUI backend: a thin FastAPI layer over COBRApy. Run from backend/:
|
|
2
|
+
|
|
3
|
+
.venv/Scripts/python -m uvicorn cobragui.main:app --port 8765
|
|
4
|
+
"""
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import platform
|
|
8
|
+
import traceback
|
|
9
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
10
|
+
from functools import partial
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
import cobra
|
|
14
|
+
import optlang
|
|
15
|
+
from fastapi import APIRouter, FastAPI, File, Request, UploadFile
|
|
16
|
+
from fastapi.exceptions import RequestValidationError
|
|
17
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
18
|
+
from fastapi.middleware.gzip import GZipMiddleware
|
|
19
|
+
from fastapi.responses import JSONResponse, Response
|
|
20
|
+
|
|
21
|
+
from . import __version__
|
|
22
|
+
from .errors import ScienceError
|
|
23
|
+
from .schemas import (AnnotationAnalyzeRequest, AnnotationApplyRequest, AnnotationIdsRequest, CancelRequest, CompareRequest, EditRequest, DeriveRequest, ExplainRequest, ExportModelRequest, ExportResultRequest, MediumPresetRequest,
|
|
24
|
+
MediumUpdate, ReactionIdentityRequest, BiggIdsRequest, SimulationRequest, StateRequest)
|
|
25
|
+
from .services import annotation_service, bigg_service, comparison_service, edit_service, export_service, identity_service, medium_service, model_service, simulation_service
|
|
26
|
+
|
|
27
|
+
logging.getLogger("cobra").setLevel(logging.ERROR)
|
|
28
|
+
log = logging.getLogger("cobragui")
|
|
29
|
+
|
|
30
|
+
app = FastAPI(title="COBRAGUI backend", version=__version__)
|
|
31
|
+
# model catalogs and annotation analyses of genome-scale models are several MB of JSON
|
|
32
|
+
app.add_middleware(GZipMiddleware, minimum_size=4096)
|
|
33
|
+
app.add_middleware(CORSMiddleware, allow_origin_regex=r"https?://(localhost|127\.0\.0\.1)(:\d+)?",
|
|
34
|
+
allow_methods=["*"], allow_headers=["*"], expose_headers=["Content-Disposition"])
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@app.exception_handler(ScienceError)
|
|
38
|
+
async def _science(_: Request, e: ScienceError):
|
|
39
|
+
return JSONResponse(e.payload(), status_code=e.status)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@app.exception_handler(RequestValidationError)
|
|
43
|
+
async def _invalid(_: Request, e: RequestValidationError):
|
|
44
|
+
errs = e.errors()
|
|
45
|
+
msg = "; ".join(f"{'.'.join(str(x) for x in er.get('loc', [])[1:])}: {er.get('msg')}" for er in errs[:5])
|
|
46
|
+
return JSONResponse({"error": {"title": "Invalid request", "message": msg, "hints": [], "detail": errs[:20]}}, status_code=422)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@app.exception_handler(Exception)
|
|
50
|
+
async def _unexpected(_: Request, e: Exception):
|
|
51
|
+
log.exception("unexpected error")
|
|
52
|
+
return JSONResponse({"error": {"title": "Unexpected backend error", "message": f"{type(e).__name__}: {e}",
|
|
53
|
+
"hints": [], "detail": traceback.format_exc()[-4000:]}}, status_code=500)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# GLPK keeps per-thread state: a problem built in one thread aborts the process when solved in another.
|
|
57
|
+
# All COBRApy work (import, catalog, solves) therefore runs on this single worker thread.
|
|
58
|
+
_cobra_thread = ThreadPoolExecutor(max_workers=1, thread_name_prefix="cobra")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def on_cobra(fn, *args, **kwargs):
|
|
62
|
+
return await asyncio.get_running_loop().run_in_executor(_cobra_thread, partial(fn, *args, **kwargs))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
api = APIRouter(prefix="/api")
|
|
66
|
+
# Only models bundled with COBRApy (load_model would otherwise try to download from BiGG).
|
|
67
|
+
EXAMPLES = {"textbook": "E. coli core (textbook, 95 reactions)",
|
|
68
|
+
"iJO1366": "E. coli iJO1366 (2,583 reactions, with subsystems)"}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _catalog(entry) -> dict:
|
|
72
|
+
"""The model catalog plus the structural edit history (the UI shows both)."""
|
|
73
|
+
return {**entry.catalog, "edits": edit_service.history(entry)}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _download(data: bytes, filename: str, media: str) -> Response:
|
|
77
|
+
return Response(data, media_type=media, headers={"Content-Disposition": f'attachment; filename="{filename}"'})
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@api.get("/health")
|
|
81
|
+
def health():
|
|
82
|
+
solvers = sorted(k for k, v in optlang.available_solvers.items() if v)
|
|
83
|
+
return {"status": "ok", "version": __version__, "cobraVersion": cobra.__version__, "solvers": solvers,
|
|
84
|
+
"defaultSolver": str(cobra.Configuration().solver.__name__).split(".")[-1].replace("_interface", "").upper(),
|
|
85
|
+
"python": platform.python_version(), "platform": platform.platform(terse=True)}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@api.get("/examples")
|
|
89
|
+
def examples():
|
|
90
|
+
return [{"name": k, "label": v} for k, v in EXAMPLES.items()]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@api.post("/models/import")
|
|
94
|
+
async def import_model(file: UploadFile = File(...)):
|
|
95
|
+
data = await file.read()
|
|
96
|
+
entry = await on_cobra(model_service.import_model, file.filename or "model", data)
|
|
97
|
+
return _catalog(entry)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@api.post("/models/examples/{name}")
|
|
101
|
+
async def import_example(name: str):
|
|
102
|
+
if name not in EXAMPLES:
|
|
103
|
+
raise ScienceError("Unknown example", name, status=404)
|
|
104
|
+
return _catalog(await on_cobra(model_service.import_example, name))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@api.get("/models/{model_id}")
|
|
108
|
+
async def get_model(model_id: str):
|
|
109
|
+
return _catalog(await on_cobra(model_service.get_entry, model_id))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@api.get("/models/{model_id}/summary")
|
|
113
|
+
async def get_summary(model_id: str):
|
|
114
|
+
c = (await on_cobra(model_service.get_entry, model_id)).catalog
|
|
115
|
+
return {"id": c["id"], "name": c["name"], "filename": c["filename"], "summary": c["summary"], "warnings": c["warnings"]}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@api.get("/models/{model_id}/metabolites")
|
|
119
|
+
async def get_metabolites(model_id: str):
|
|
120
|
+
return (await on_cobra(model_service.get_entry, model_id)).catalog["metabolites"]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@api.get("/models/{model_id}/reactions")
|
|
124
|
+
async def get_reactions(model_id: str):
|
|
125
|
+
return (await on_cobra(model_service.get_entry, model_id)).catalog["reactions"]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@api.get("/models/{model_id}/genes")
|
|
129
|
+
async def get_genes(model_id: str):
|
|
130
|
+
return (await on_cobra(model_service.get_entry, model_id)).catalog["genes"]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@api.get("/models/{model_id}/search")
|
|
134
|
+
async def search(model_id: str, q: str, kinds: Optional[str] = None, limit: int = 50):
|
|
135
|
+
entry = (await on_cobra(model_service.get_entry, model_id))
|
|
136
|
+
index = await on_cobra(model_service.search_index, entry)
|
|
137
|
+
return index.search(q, kinds.split(",") if kinds else None, max(1, min(limit, 500)))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@api.post("/models/{model_id}/medium/query")
|
|
141
|
+
async def medium_query(model_id: str, body: StateRequest):
|
|
142
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
143
|
+
return await on_cobra(medium_service.medium_table, entry, body.state)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@api.put("/models/{model_id}/medium")
|
|
147
|
+
async def medium_set(model_id: str, body: MediumUpdate):
|
|
148
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
149
|
+
return await on_cobra(medium_service.set_medium, entry, body.state, body.medium)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@api.post("/models/{model_id}/medium/preset")
|
|
153
|
+
async def medium_preset(model_id: str, body: MediumPresetRequest):
|
|
154
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
155
|
+
return await on_cobra(medium_service.apply_preset, entry, body.state, body.preset, body.rich_uptake, body.growth_fraction)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@api.post("/models/{model_id}/simulate/{method}")
|
|
159
|
+
async def simulate(model_id: str, method: str, body: SimulationRequest):
|
|
160
|
+
# registered before queueing on the cobra thread, so a run waiting behind another can be cancelled
|
|
161
|
+
simulation_service.job_register(body.job_id)
|
|
162
|
+
try:
|
|
163
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
164
|
+
return await on_cobra(simulation_service.simulate, entry, method, body)
|
|
165
|
+
finally:
|
|
166
|
+
simulation_service.job_finish(body.job_id)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@api.get("/jobs/{job_id}")
|
|
170
|
+
def job_status(job_id: str): # answered off the cobra thread, while the solve runs
|
|
171
|
+
st = simulation_service.job_status(job_id)
|
|
172
|
+
if st is None:
|
|
173
|
+
raise ScienceError("No such job", "It finished or never started.", status=404)
|
|
174
|
+
return st
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@api.post("/jobs/{job_id}/cancel")
|
|
178
|
+
def job_cancel(job_id: str, body: CancelRequest):
|
|
179
|
+
return {"cancelled": simulation_service.job_cancel(job_id, body.keep)}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@api.post("/models/{model_id}/derive")
|
|
183
|
+
async def derive(model_id: str, body: DeriveRequest):
|
|
184
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
185
|
+
return await on_cobra(simulation_service.derive_from_fluxes, entry, body.fluxes)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@api.post("/models/{model_id}/explain-turnover")
|
|
189
|
+
async def explain(model_id: str, body: ExplainRequest):
|
|
190
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
191
|
+
return await on_cobra(comparison_service.explain_turnover, entry, body.metabolite, body.fluxes_a, body.fluxes_b,
|
|
192
|
+
body.zero_tolerance)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@api.post("/models/{model_id}/export")
|
|
196
|
+
async def export_model(model_id: str, body: ExportModelRequest):
|
|
197
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
198
|
+
out = await on_cobra(export_service.model_file, entry, body.state, body.format)
|
|
199
|
+
edit_service.mark_exported(entry) # the structural edits are now saved in a file
|
|
200
|
+
return _download(*out)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# ----------------------------------------------------------------------------- structural edits
|
|
204
|
+
# Edits change the working cobra.Model itself (the one every simulation uses), as a logged, reversible
|
|
205
|
+
# layer re-applied on load. Validation never modifies the model; an invalid edit changes nothing.
|
|
206
|
+
|
|
207
|
+
@api.post("/models/{model_id}/edits/check")
|
|
208
|
+
async def edits_check(model_id: str, body: EditRequest):
|
|
209
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
210
|
+
return await on_cobra(edit_service.check, entry, body.ops)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@api.post("/models/{model_id}/edits")
|
|
214
|
+
async def edits_commit(model_id: str, body: EditRequest):
|
|
215
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
216
|
+
return await on_cobra(edit_service.commit, entry, body.ops, body.label)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@api.get("/models/{model_id}/edits")
|
|
220
|
+
async def edits_history(model_id: str):
|
|
221
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
222
|
+
return edit_service.history(entry)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@api.post("/models/{model_id}/edits/undo")
|
|
226
|
+
async def edits_undo(model_id: str):
|
|
227
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
228
|
+
return await on_cobra(edit_service.undo, entry)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@api.post("/models/{model_id}/edits/redo")
|
|
232
|
+
async def edits_redo(model_id: str):
|
|
233
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
234
|
+
return await on_cobra(edit_service.redo, entry)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@api.post("/models/{model_id}/edits/discard")
|
|
238
|
+
async def edits_discard(model_id: str):
|
|
239
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
240
|
+
return await on_cobra(edit_service.discard, entry)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@api.get("/models/{model_id}/edits/patch")
|
|
244
|
+
async def edits_patch(model_id: str):
|
|
245
|
+
import json as _json
|
|
246
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
247
|
+
p = edit_service.patch(entry)
|
|
248
|
+
name = "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in entry.filename.rsplit(".", 1)[0])
|
|
249
|
+
return _download(_json.dumps(p, indent=1).encode("utf-8"), f"{name}_model_patch.json", "application/json")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
@api.get("/models/{model_id}/validate")
|
|
253
|
+
async def validate_model(model_id: str):
|
|
254
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
255
|
+
return await on_cobra(edit_service.validate, entry)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# ----------------------------------------------------------------------------- metabolite annotation (MetaNetX)
|
|
259
|
+
# The analysis talks to MetaNetX on its own thread (network-bound); applying a curation only touches
|
|
260
|
+
# annotations and formulas, so it does not wait behind running solves either.
|
|
261
|
+
|
|
262
|
+
@api.post("/models/{model_id}/annotation/analyze")
|
|
263
|
+
async def annotation_analyze(model_id: str, body: AnnotationAnalyzeRequest):
|
|
264
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
265
|
+
return annotation_service.start(entry, body.use_names, body.auto_apply, body.fill_formulas)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
@api.get("/models/{model_id}/annotation")
|
|
269
|
+
async def annotation_status(model_id: str, full: bool = True):
|
|
270
|
+
"""full=false: job progress and curation summary only (cheap to poll while the analysis runs)."""
|
|
271
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
272
|
+
return annotation_service.status(entry, full)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@api.post("/models/{model_id}/annotation/apply")
|
|
276
|
+
async def annotation_apply(model_id: str, body: AnnotationApplyRequest):
|
|
277
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
278
|
+
return await asyncio.to_thread(annotation_service.apply, entry, [c.model_dump(by_alias=True) for c in body.items], "user")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
@api.post("/models/{model_id}/annotation/reject")
|
|
282
|
+
async def annotation_reject(model_id: str, body: AnnotationIdsRequest):
|
|
283
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
284
|
+
return await asyncio.to_thread(annotation_service.reject, entry, body.ids or [])
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@api.post("/models/{model_id}/annotation/revert")
|
|
288
|
+
async def annotation_revert(model_id: str, body: AnnotationIdsRequest):
|
|
289
|
+
entry = await on_cobra(model_service.get_entry, model_id)
|
|
290
|
+
return await asyncio.to_thread(annotation_service.revert, entry, body.ids)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# ----------------------------------------------------------------------------- template identity (Template Builder)
|
|
294
|
+
# Model-independent: KEGG / ChEBI searches resolved through MetaNetX. Network-bound, off the cobra thread.
|
|
295
|
+
|
|
296
|
+
@api.get("/identity/compounds")
|
|
297
|
+
async def identity_compounds(q: str, limit: int = 8):
|
|
298
|
+
return await asyncio.to_thread(identity_service.search_compounds, q, max(1, min(limit, 20)))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@api.post("/identity/reactions")
|
|
302
|
+
async def identity_reactions(body: ReactionIdentityRequest):
|
|
303
|
+
return await asyncio.to_thread(identity_service.search_reactions, [p.model_dump() for p in body.participants], body.ec)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
# ----------------------------------------------------------------------------- BiGG data layer
|
|
307
|
+
# The BiGG universal tables, installed locally (gemsmap bigg-data; npm run bigg:data in a checkout). GEMs MAP does not call the BiGG API.
|
|
308
|
+
|
|
309
|
+
@api.get("/bigg/status")
|
|
310
|
+
def bigg_status():
|
|
311
|
+
return bigg_service.status()
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
@api.post("/identity/bigg-ids")
|
|
315
|
+
async def identity_bigg_ids(body: BiggIdsRequest):
|
|
316
|
+
"""BiGG universal IDs for the entities and reactions of a template (only when unambiguous)."""
|
|
317
|
+
return await asyncio.to_thread(bigg_service.template_bigg_ids, [e.model_dump() for e in body.entities],
|
|
318
|
+
[{"id": r.id, "participants": [p.model_dump() for p in r.participants], "ec": r.ec, "identifiers": r.identifiers} for r in body.reactions])
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@api.post("/results/compare")
|
|
322
|
+
def compare(body: CompareRequest): # pure Python: does not wait behind running solves
|
|
323
|
+
return comparison_service.compare( body.a, body.b, body.zero_tolerance, body.pseudocount)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@api.post("/results/export")
|
|
327
|
+
def export_result(body: ExportResultRequest):
|
|
328
|
+
return _download(*export_service.result_file(body.result, body.format, body.table))
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
app.include_router(api)
|
cobragui/registry.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""In-memory registry of imported COBRA models, backed by an on-disk cache of the original files.
|
|
2
|
+
|
|
3
|
+
Model states never modify the imported cobra.Model: every computation applies a state inside
|
|
4
|
+
`with model:` (see model_service.applied), which COBRApy reverts on exit. Structural edits
|
|
5
|
+
(edit_service) do modify it, as a logged, reversible layer that is re-applied on load. Access to one
|
|
6
|
+
model is serialized with a per-model lock because cobra contexts are not thread-safe.
|
|
7
|
+
"""
|
|
8
|
+
import os
|
|
9
|
+
import threading
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Optional
|
|
13
|
+
|
|
14
|
+
import cobra
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def cache_dir() -> Path:
|
|
18
|
+
base = os.environ.get("COBRAGUI_CACHE")
|
|
19
|
+
if base:
|
|
20
|
+
p = Path(base)
|
|
21
|
+
else:
|
|
22
|
+
root = os.environ.get("LOCALAPPDATA") or os.path.join(Path.home(), ".cache")
|
|
23
|
+
p = Path(root) / "cobragui" / "models"
|
|
24
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
return p
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class ModelEntry:
|
|
30
|
+
id: str
|
|
31
|
+
checksum: str
|
|
32
|
+
filename: str
|
|
33
|
+
fmt: str
|
|
34
|
+
model: cobra.Model
|
|
35
|
+
original_bounds: dict[str, tuple[float, float]]
|
|
36
|
+
original_objective: dict[str, float]
|
|
37
|
+
original_direction: str
|
|
38
|
+
original_medium: dict[str, float]
|
|
39
|
+
validation: dict[str, Any] = field(default_factory=dict)
|
|
40
|
+
catalog: Optional[dict] = None
|
|
41
|
+
search: Any = None
|
|
42
|
+
lock: threading.RLock = field(default_factory=threading.RLock)
|
|
43
|
+
# structural edits (edit_service): the saved log, genes of the file, and edits that failed to re-apply
|
|
44
|
+
edits: Optional[dict] = None
|
|
45
|
+
base_genes: set = field(default_factory=set)
|
|
46
|
+
edit_errors: list = field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
_entries: dict[str, ModelEntry] = {}
|
|
50
|
+
_registry_lock = threading.Lock()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def put(entry: ModelEntry) -> None:
|
|
54
|
+
with _registry_lock:
|
|
55
|
+
_entries[entry.id] = entry
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def get(model_id: str) -> Optional[ModelEntry]:
|
|
59
|
+
with _registry_lock:
|
|
60
|
+
return _entries.get(model_id)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def cached_file(model_id: str) -> Optional[Path]:
|
|
64
|
+
"""Original file saved at import time: <cache>/<id>__<filename>."""
|
|
65
|
+
for p in cache_dir().glob(f"{model_id}__*"):
|
|
66
|
+
if p.is_file():
|
|
67
|
+
return p
|
|
68
|
+
return None
|
cobragui/schemas.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Request bodies. Responses are plain dicts built by the services (camelCase keys, JSON-safe floats)."""
|
|
2
|
+
from typing import Any, Literal, Optional
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
5
|
+
from pydantic.alias_generators import to_camel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Camel(BaseModel):
|
|
9
|
+
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra="ignore")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ObjectiveSpec(Camel):
|
|
13
|
+
"""Linear objective: reaction id -> coefficient."""
|
|
14
|
+
coefficients: dict[str, float]
|
|
15
|
+
direction: Literal["max", "min"] = "max"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class StateSpec(Camel):
|
|
19
|
+
"""A model state is a set of overrides on top of the imported model.
|
|
20
|
+
|
|
21
|
+
Bounds use null for an unbounded side (JSON has no infinity).
|
|
22
|
+
objective = None keeps the objective stored in the model file.
|
|
23
|
+
"""
|
|
24
|
+
id: Optional[str] = None
|
|
25
|
+
name: Optional[str] = None
|
|
26
|
+
bounds: dict[str, tuple[Optional[float], Optional[float]]] = Field(default_factory=dict)
|
|
27
|
+
objective: Optional[ObjectiveSpec] = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SimulationParams(Camel):
|
|
31
|
+
fraction_of_optimum: float = Field(1.0, ge=0.0, le=1.0)
|
|
32
|
+
loopless: bool = False
|
|
33
|
+
reactions: Optional[list[str]] = None
|
|
34
|
+
pfba_factor: Optional[float] = Field(None, ge=1.0)
|
|
35
|
+
processes: int = Field(1, ge=1, le=32)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SimulationRequest(Camel):
|
|
39
|
+
state: StateSpec = Field(default_factory=StateSpec)
|
|
40
|
+
params: SimulationParams = Field(default_factory=SimulationParams)
|
|
41
|
+
name: Optional[str] = None
|
|
42
|
+
# client-generated id: lets the UI follow progress and cancel the run (GET/POST /api/jobs/{id})
|
|
43
|
+
job_id: Optional[str] = None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CancelRequest(Camel):
|
|
47
|
+
"""keep = True stops an FVA early but returns the intervals already computed."""
|
|
48
|
+
keep: bool = False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class StateRequest(Camel):
|
|
52
|
+
state: StateSpec = Field(default_factory=StateSpec)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class MediumUpdate(Camel):
|
|
56
|
+
state: StateSpec = Field(default_factory=StateSpec)
|
|
57
|
+
medium: dict[str, float]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class MediumPresetRequest(Camel):
|
|
61
|
+
state: StateSpec = Field(default_factory=StateSpec)
|
|
62
|
+
preset: Literal["original", "minimal", "rich", "anaerobic"]
|
|
63
|
+
rich_uptake: float = Field(10.0, gt=0)
|
|
64
|
+
growth_fraction: float = Field(1.0, gt=0, le=1.0)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ResultPayload(Camel):
|
|
68
|
+
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra="allow")
|
|
69
|
+
id: Optional[str] = None
|
|
70
|
+
name: str = ""
|
|
71
|
+
method: str = "fba"
|
|
72
|
+
solver_status: Optional[str] = None
|
|
73
|
+
objective_value: Optional[float] = None
|
|
74
|
+
reaction_fluxes: Optional[dict[str, Optional[float]]] = None
|
|
75
|
+
fva: Optional[dict[str, dict[str, Optional[float]]]] = None
|
|
76
|
+
metabolite_turnover: Optional[dict[str, Optional[float]]] = None
|
|
77
|
+
exchanges: Optional[dict[str, dict[str, Any]]] = None
|
|
78
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class CompareRequest(Camel):
|
|
82
|
+
a: ResultPayload
|
|
83
|
+
b: ResultPayload
|
|
84
|
+
zero_tolerance: float = Field(1e-9, ge=0)
|
|
85
|
+
pseudocount: Optional[float] = Field(None, gt=0)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class DeriveRequest(Camel):
|
|
89
|
+
"""A flux vector read from a file; turnover and exchanges are recomputed with the loaded model."""
|
|
90
|
+
fluxes: dict[str, Optional[float]]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ExplainRequest(Camel):
|
|
94
|
+
metabolite: str
|
|
95
|
+
fluxes_a: dict[str, Optional[float]]
|
|
96
|
+
fluxes_b: dict[str, Optional[float]]
|
|
97
|
+
zero_tolerance: float = Field(1e-9, ge=0)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ExportResultRequest(Camel):
|
|
101
|
+
result: ResultPayload
|
|
102
|
+
format: Literal["json", "csv"] = "json"
|
|
103
|
+
table: Literal["fluxes", "fva", "turnover", "exchanges"] = "fluxes"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class EditRequest(Camel):
|
|
107
|
+
"""Structural edit: operations applied as one transaction (see edit_service).
|
|
108
|
+
|
|
109
|
+
put_reaction {id?, reaction}, put_metabolite {id?, metabolite}, add_compartment {id, name},
|
|
110
|
+
delete_reaction {id}, delete_metabolite {id, cascade?}. id = the entity being edited (absent = create).
|
|
111
|
+
"""
|
|
112
|
+
ops: list[dict[str, Any]]
|
|
113
|
+
label: Optional[str] = None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class ExportModelRequest(Camel):
|
|
117
|
+
state: StateSpec = Field(default_factory=StateSpec)
|
|
118
|
+
format: Literal["sbml", "json", "mat"] = "sbml"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class AnnotationAnalyzeRequest(Camel):
|
|
122
|
+
use_names: bool = True
|
|
123
|
+
auto_apply: bool = True
|
|
124
|
+
fill_formulas: bool = True
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class AnnotationChoice(Camel):
|
|
128
|
+
id: str
|
|
129
|
+
mnx: Optional[str] = None
|
|
130
|
+
fill_formula: bool = True
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class AnnotationApplyRequest(Camel):
|
|
134
|
+
items: list[AnnotationChoice]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class AnnotationIdsRequest(Camel):
|
|
138
|
+
"""ids = None reverts every accepted match."""
|
|
139
|
+
ids: Optional[list[str]] = None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class IdentityParticipant(Camel):
|
|
143
|
+
"""A template reaction participant: identifiers by namespace (kegg.compound, chebi, metanetx.chemical …)."""
|
|
144
|
+
name: Optional[str] = None
|
|
145
|
+
identifiers: dict[str, list[str]] = Field(default_factory=dict)
|
|
146
|
+
coefficient: float = -1
|
|
147
|
+
main: bool = True
|
|
148
|
+
# conceptual template compartment (cytosol, mitochondria …), compared with BiGG compartments
|
|
149
|
+
compartment: Optional[str] = None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class ReactionIdentityRequest(Camel):
|
|
153
|
+
participants: list[IdentityParticipant]
|
|
154
|
+
ec: list[str] = Field(default_factory=list)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class TemplateEntityIds(Camel):
|
|
158
|
+
id: str
|
|
159
|
+
identifiers: dict[str, list[str]] = Field(default_factory=dict)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class TemplateReactionIds(Camel):
|
|
163
|
+
id: str
|
|
164
|
+
participants: list[IdentityParticipant] = Field(default_factory=list)
|
|
165
|
+
ec: list[str] = Field(default_factory=list)
|
|
166
|
+
identifiers: dict[str, list[str]] = Field(default_factory=dict)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class BiggIdsRequest(Camel):
|
|
170
|
+
entities: list[TemplateEntityIds] = Field(default_factory=list)
|
|
171
|
+
reactions: list[TemplateReactionIds] = Field(default_factory=list)
|
|
File without changes
|