gemsmap 0.3.0b1__tar.gz

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 (34) hide show
  1. gemsmap-0.3.0b1/.gitignore +46 -0
  2. gemsmap-0.3.0b1/LICENSE +21 -0
  3. gemsmap-0.3.0b1/PKG-INFO +75 -0
  4. gemsmap-0.3.0b1/PYPI_README.md +48 -0
  5. gemsmap-0.3.0b1/backend/cobragui/__init__.py +4 -0
  6. gemsmap-0.3.0b1/backend/cobragui/errors.py +37 -0
  7. gemsmap-0.3.0b1/backend/cobragui/main.py +331 -0
  8. gemsmap-0.3.0b1/backend/cobragui/registry.py +68 -0
  9. gemsmap-0.3.0b1/backend/cobragui/schemas.py +171 -0
  10. gemsmap-0.3.0b1/backend/cobragui/services/__init__.py +0 -0
  11. gemsmap-0.3.0b1/backend/cobragui/services/annotation_service.py +737 -0
  12. gemsmap-0.3.0b1/backend/cobragui/services/bigg_service.py +498 -0
  13. gemsmap-0.3.0b1/backend/cobragui/services/comparison_service.py +164 -0
  14. gemsmap-0.3.0b1/backend/cobragui/services/edit_service.py +942 -0
  15. gemsmap-0.3.0b1/backend/cobragui/services/export_service.py +99 -0
  16. gemsmap-0.3.0b1/backend/cobragui/services/identity_service.py +429 -0
  17. gemsmap-0.3.0b1/backend/cobragui/services/medium_service.py +117 -0
  18. gemsmap-0.3.0b1/backend/cobragui/services/metanetx.py +209 -0
  19. gemsmap-0.3.0b1/backend/cobragui/services/model_service.py +480 -0
  20. gemsmap-0.3.0b1/backend/cobragui/services/search_service.py +97 -0
  21. gemsmap-0.3.0b1/backend/cobragui/services/simulation_service.py +350 -0
  22. gemsmap-0.3.0b1/backend/gemsmap/__init__.py +6 -0
  23. gemsmap-0.3.0b1/backend/gemsmap/__main__.py +6 -0
  24. gemsmap-0.3.0b1/backend/gemsmap/cli.py +172 -0
  25. gemsmap-0.3.0b1/backend/gemsmap/server.py +32 -0
  26. gemsmap-0.3.0b1/backend/gemsmap/web/assets/index-BaJDLO-W.css +1 -0
  27. gemsmap-0.3.0b1/backend/gemsmap/web/assets/index-CupjXseC.js +79 -0
  28. gemsmap-0.3.0b1/backend/gemsmap/web/brand/cobragui-logo.png +0 -0
  29. gemsmap-0.3.0b1/backend/gemsmap/web/examples/fva_2conditions.csv +33 -0
  30. gemsmap-0.3.0b1/backend/gemsmap/web/examples/pfba_4conditions.csv +33 -0
  31. gemsmap-0.3.0b1/backend/gemsmap/web/examples/timecourse.csv +10 -0
  32. gemsmap-0.3.0b1/backend/gemsmap/web/favicon.svg +33 -0
  33. gemsmap-0.3.0b1/backend/gemsmap/web/index.html +17 -0
  34. gemsmap-0.3.0b1/pyproject.toml +55 -0
@@ -0,0 +1,46 @@
1
+ # Dependencies & builds
2
+ node_modules/
3
+ dist/
4
+ *.tsbuildinfo
5
+
6
+ # Documentation build (mkdocs build) and its environment
7
+ site/
8
+ .venv-docs/
9
+
10
+ # Python backend
11
+ backend/.venv/
12
+ __pycache__/
13
+ *.py[cod]
14
+ .pytest_cache/
15
+
16
+ # Local tooling / editors / OS
17
+ .claude/
18
+ .vscode/
19
+ .idea/
20
+ .DS_Store
21
+ Thumbs.db
22
+ desktop.ini
23
+ *.log
24
+ .env
25
+ .env.*
26
+
27
+ # Private data: kept on disk, never versioned. Unpublished models, maps and results go in my_projects/
28
+ # (open them with File > Open project). Personal patterns belong in .git/info/exclude, which is never committed.
29
+ my_projects/
30
+ public/projects/
31
+ tests/*.gemsmap
32
+ tests/*.metmap
33
+ tests/analysis_test/
34
+
35
+ # Local test inputs and scratch files (BiGG exports, templates saved while testing)
36
+ tests/*.biggr.*
37
+ tests/*-template.json
38
+
39
+ # Generated test fixtures (tools/templates/make_fixtures.py)
40
+ tests/fixtures/
41
+
42
+ # Python package build (tools/release/build.py): compiled interface, archives, build folders
43
+ backend/gemsmap/web/
44
+ /release/
45
+ /build/
46
+ *.egg-info/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bruno Batista
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.5
2
+ Name: gemsmap
3
+ Version: 0.3.0b1
4
+ Summary: GEMs MAP: an interactive workbench for genome-scale metabolic models (COBRApy analyses, editable metabolic maps, identity-aware pathway templates)
5
+ Project-URL: Homepage, https://github.com/BatistaB/gemsmap
6
+ Project-URL: Source, https://github.com/BatistaB/gemsmap
7
+ Project-URL: Issues, https://github.com/BatistaB/gemsmap/issues
8
+ Project-URL: Changelog, https://github.com/BatistaB/gemsmap/blob/main/CHANGELOG.md
9
+ Author: Bruno Batista
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: COBRApy,GEM,flux balance analysis,genome-scale metabolic model,metabolic map,systems biology
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
19
+ Classifier: Topic :: Scientific/Engineering :: Visualization
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: cobra>=0.29
22
+ Requires-Dist: fastapi>=0.110
23
+ Requires-Dist: python-multipart>=0.0.9
24
+ Requires-Dist: scipy>=1.11
25
+ Requires-Dist: uvicorn[standard]>=0.29
26
+ Description-Content-Type: text/markdown
27
+
28
+ # GEMs MAP
29
+
30
+ **An Interactive Workbench for Genome-Scale Metabolic Models.**
31
+
32
+ > **Beta.** GEMs MAP 0.3 is in beta testing. It works, but features, file formats and the interface can still
33
+ > change before the first stable release. Save your work as `.gemsmap` project files and report problems.
34
+
35
+ GEMs MAP connects constraint-based computation, model exploration and editable metabolic maps in one application:
36
+
37
+ - **COBRAGUI**: a graphical front end to [COBRApy](https://opencobra.github.io/cobrapy/). Import SBML, COBRA JSON
38
+ or MATLAB models; set the medium, bounds and objective; run FBA, pFBA, loopless FBA or FVA; inspect, compare and
39
+ export the results.
40
+ - **Map Builder**: a canvas for publication-quality pathway figures. Draw or insert pathways, bind them to the
41
+ model, map fluxes to arrow width and colour, compare conditions, export SVG, PNG, PDF or GIF.
42
+ - **Templates**: reusable pathway layouts that describe biological identity, not model IDs, matched to any GEM
43
+ with a review of uncertain cases.
44
+
45
+ ## Install and start
46
+
47
+ Python 3.10 or newer, on Windows, macOS or Linux:
48
+
49
+ ```
50
+ pip install gemsmap
51
+ gemsmap
52
+ ```
53
+
54
+ `gemsmap` starts the application and opens it in your browser at <http://127.0.0.1:8765>. Keep the window open
55
+ while you work; press Ctrl+C to stop. Everything runs on your computer: your models are not uploaded anywhere.
56
+
57
+ Without Python, install [uv](https://docs.astral.sh/uv/) and run `uvx gemsmap`.
58
+
59
+ Other commands: `gemsmap diagnose` (versions and folders, for bug reports), `gemsmap bigg-data` (optional BiGG
60
+ tables for the Template Builder), `gemsmap --help`.
61
+
62
+ No Python at all? Each [release on GitHub](https://github.com/BatistaB/gemsmap/releases) also has a
63
+ `GEMsMAP-<version>.zip`: extract it and double-click *Start GEMs MAP*; the first start prepares everything inside
64
+ that folder.
65
+
66
+ ## Feedback
67
+
68
+ Source code, releases and the issue tracker: <https://github.com/BatistaB/gemsmap>. To report a problem, click
69
+ **GEMs MAP <version>** in the COBRAGUI status bar, then *Copy diagnostics*, and paste it into a
70
+ [new issue](https://github.com/BatistaB/gemsmap/issues).
71
+
72
+ ## License
73
+
74
+ MIT. GEMs MAP is an independent project and is not maintained or endorsed by the COBRApy, BiGG, MetaNetX or KEGG
75
+ teams.
@@ -0,0 +1,48 @@
1
+ # GEMs MAP
2
+
3
+ **An Interactive Workbench for Genome-Scale Metabolic Models.**
4
+
5
+ > **Beta.** GEMs MAP 0.3 is in beta testing. It works, but features, file formats and the interface can still
6
+ > change before the first stable release. Save your work as `.gemsmap` project files and report problems.
7
+
8
+ GEMs MAP connects constraint-based computation, model exploration and editable metabolic maps in one application:
9
+
10
+ - **COBRAGUI**: a graphical front end to [COBRApy](https://opencobra.github.io/cobrapy/). Import SBML, COBRA JSON
11
+ or MATLAB models; set the medium, bounds and objective; run FBA, pFBA, loopless FBA or FVA; inspect, compare and
12
+ export the results.
13
+ - **Map Builder**: a canvas for publication-quality pathway figures. Draw or insert pathways, bind them to the
14
+ model, map fluxes to arrow width and colour, compare conditions, export SVG, PNG, PDF or GIF.
15
+ - **Templates**: reusable pathway layouts that describe biological identity, not model IDs, matched to any GEM
16
+ with a review of uncertain cases.
17
+
18
+ ## Install and start
19
+
20
+ Python 3.10 or newer, on Windows, macOS or Linux:
21
+
22
+ ```
23
+ pip install gemsmap
24
+ gemsmap
25
+ ```
26
+
27
+ `gemsmap` starts the application and opens it in your browser at <http://127.0.0.1:8765>. Keep the window open
28
+ while you work; press Ctrl+C to stop. Everything runs on your computer: your models are not uploaded anywhere.
29
+
30
+ Without Python, install [uv](https://docs.astral.sh/uv/) and run `uvx gemsmap`.
31
+
32
+ Other commands: `gemsmap diagnose` (versions and folders, for bug reports), `gemsmap bigg-data` (optional BiGG
33
+ tables for the Template Builder), `gemsmap --help`.
34
+
35
+ No Python at all? Each [release on GitHub](https://github.com/BatistaB/gemsmap/releases) also has a
36
+ `GEMsMAP-<version>.zip`: extract it and double-click *Start GEMs MAP*; the first start prepares everything inside
37
+ that folder.
38
+
39
+ ## Feedback
40
+
41
+ Source code, releases and the issue tracker: <https://github.com/BatistaB/gemsmap>. To report a problem, click
42
+ **GEMs MAP <version>** in the COBRAGUI status bar, then *Copy diagnostics*, and paste it into a
43
+ [new issue](https://github.com/BatistaB/gemsmap/issues).
44
+
45
+ ## License
46
+
47
+ MIT. GEMs MAP is an independent project and is not maintained or endorsed by the COBRApy, BiGG, MetaNetX or KEGG
48
+ teams.
@@ -0,0 +1,4 @@
1
+ """COBRAGUI backend: COBRApy behind a small REST API, for COBRAGUI in GEMs MAP."""
2
+ from gemsmap import __version__ # one version for the whole application (backend/gemsmap/__init__.py)
3
+
4
+ __all__ = ["__version__"]
@@ -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)
@@ -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)
@@ -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