emasp 1.0.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.
- emasp/__init__.py +47 -0
- emasp/__main__.py +2 -0
- emasp/clingo.py +122 -0
- emasp/efm.py +458 -0
- emasp/enumerate_efm.clp +38 -0
- emasp/mmparser.py +436 -0
- emasp-1.0.0.dist-info/METADATA +115 -0
- emasp-1.0.0.dist-info/RECORD +12 -0
- emasp-1.0.0.dist-info/WHEEL +5 -0
- emasp-1.0.0.dist-info/entry_points.txt +2 -0
- emasp-1.0.0.dist-info/licenses/LICENSE.txt +661 -0
- emasp-1.0.0.dist-info/top_level.txt +1 -0
emasp/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
emasp: Global CLI entry point.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
__version__ = "1.0.0"
|
|
6
|
+
|
|
7
|
+
# Copyright (C) 2026 INRIA / Francois Gindraud
|
|
8
|
+
#
|
|
9
|
+
# This program is free software: you can redistribute it and/or modify
|
|
10
|
+
# it under the terms of the GNU Affero General Public License as
|
|
11
|
+
# published by the Free Software Foundation, either version 3 of the
|
|
12
|
+
# License, or (at your option) any later version.
|
|
13
|
+
#
|
|
14
|
+
# This program is distributed in the hope that it will be useful,
|
|
15
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
16
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
17
|
+
# GNU Affero General Public License for more details.
|
|
18
|
+
#
|
|
19
|
+
# You should have received a copy of the GNU Affero General Public License
|
|
20
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
21
|
+
|
|
22
|
+
from typing import Annotated
|
|
23
|
+
import typer
|
|
24
|
+
|
|
25
|
+
import emasp.efm
|
|
26
|
+
|
|
27
|
+
app = typer.Typer(no_args_is_help = True)
|
|
28
|
+
|
|
29
|
+
def _version_callback(version: bool):
|
|
30
|
+
if version:
|
|
31
|
+
print(__version__)
|
|
32
|
+
raise typer.Exit()
|
|
33
|
+
|
|
34
|
+
@app.callback()
|
|
35
|
+
def _app(
|
|
36
|
+
version: Annotated[bool | None, typer.Option("--version", help = "Print version and exits", callback = _version_callback, is_eager = True)] = None
|
|
37
|
+
):
|
|
38
|
+
"""
|
|
39
|
+
Elementary modes of metabolic network using Clingo/ASP.
|
|
40
|
+
|
|
41
|
+
Select the type of elementary mode with the sub-command below (for now only EFM).
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
app.add_typer(emasp.efm.app, name = "efm")
|
|
45
|
+
|
|
46
|
+
if __name__ == "__main__":
|
|
47
|
+
app()
|
emasp/__main__.py
ADDED
emasp/clingo.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Clingo solver tools:
|
|
3
|
+
- launching the solver
|
|
4
|
+
- formatting outputs
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import clingo.application
|
|
8
|
+
import clingo.ast
|
|
9
|
+
import clingo.control
|
|
10
|
+
import clingo.solving
|
|
11
|
+
import clingolpx
|
|
12
|
+
import io
|
|
13
|
+
import math
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Callable, Sequence
|
|
16
|
+
|
|
17
|
+
# We parse the clingo model object to generate a nice formatted EFM in JSON.
|
|
18
|
+
# Doing this in python slows the solver down significantly, see the benchmark data below.
|
|
19
|
+
# Thus we use a C++ formatter function instead, accessed using cffi, and reliant on the clingo cffi library and objects.
|
|
20
|
+
#
|
|
21
|
+
# Benchmarks carlson 2004, 1658 efms, 1 core, output to file :
|
|
22
|
+
# - conda clingolpx bin + aspefm args : 1.1s ; pure C++ app, with a C++ solution printer matching to the python one
|
|
23
|
+
# - conda python -m clingolpx + aspefm args : 2.1s ; python formatter bottleneck
|
|
24
|
+
# - uv run python -m clingolpx + aspefm args : 2.2s ; python formatter bottleneck
|
|
25
|
+
# - non-async emasp python formatter: 2.5s
|
|
26
|
+
# - Async emasp python formatter: 2s : not worth the complexity
|
|
27
|
+
# - Non async CPP formatter: 1.1s
|
|
28
|
+
try:
|
|
29
|
+
# Must be imported after clingo, so that the cffi clingo lib is already loaded and symbols are defined
|
|
30
|
+
from emasp._cpp import ffi
|
|
31
|
+
from emasp._cpp.lib import write_formatted_efm
|
|
32
|
+
|
|
33
|
+
def print_efm(model: clingo.solving.Model, output: io.TextIOWrapper):
|
|
34
|
+
write_formatted_efm(ffi.cast("clingo_model_t*", model._rep), output)
|
|
35
|
+
|
|
36
|
+
except ImportError as e:
|
|
37
|
+
# Provide a Python slow fallback in case the C++ module is unusable
|
|
38
|
+
print("Failed to import c++ efm formatter, using a slow Python fallback:", e, file = sys.stderr)
|
|
39
|
+
|
|
40
|
+
import json
|
|
41
|
+
|
|
42
|
+
def print_efm(model: clingo.solving.Model, output: io.TextIOWrapper):
|
|
43
|
+
non_zero_fluxes = {}
|
|
44
|
+
for symbol in sorted(model.symbols(theory = True)):
|
|
45
|
+
if symbol.match("__lpx", 2):
|
|
46
|
+
[flux, value] = symbol.arguments
|
|
47
|
+
value = value.string
|
|
48
|
+
if flux.match("flux", 1) and value != "0":
|
|
49
|
+
if value == "e":
|
|
50
|
+
value = 1.0
|
|
51
|
+
else:
|
|
52
|
+
parts = value.removesuffix("*e").split("/")
|
|
53
|
+
value = float(parts[0])
|
|
54
|
+
if len(parts) == 2:
|
|
55
|
+
value /= float(parts[1])
|
|
56
|
+
non_zero_fluxes[flux.arguments[0].string] = value
|
|
57
|
+
json.dump({ "index": model.number, "fluxes": non_zero_fluxes }, fp = output)
|
|
58
|
+
print(file = output) # add newline
|
|
59
|
+
|
|
60
|
+
def run_clingolpx(on_solution: Callable[[clingo.solving.Model], None], arguments: Sequence[str], verbose: bool = False) -> int:
|
|
61
|
+
"""
|
|
62
|
+
Launch the clingo solver with the given command line `arguments`.
|
|
63
|
+
|
|
64
|
+
Calls `on_solution` for each solution it finds.
|
|
65
|
+
emasp will give a formatting function to print the solution to an output file in the desired format.
|
|
66
|
+
|
|
67
|
+
If `verbose` is False (default), the output messages from clingo are silenced.
|
|
68
|
+
This is the default to let our formatting functions entirely control the output, especially if the output target is stdout.
|
|
69
|
+
This corresponds to the clingo option `--outf=3`.
|
|
70
|
+
|
|
71
|
+
Return the integer status value from clingo.
|
|
72
|
+
"""
|
|
73
|
+
class ClingoApp(clingo.application.Application):
|
|
74
|
+
"""
|
|
75
|
+
Clingo app object, copied from clingolpx __main__.py and modified for our uses.
|
|
76
|
+
"""
|
|
77
|
+
def __init__(self):
|
|
78
|
+
self.__theory = clingolpx.ClingoLPXTheory()
|
|
79
|
+
self.program_name = "clingo-lpx"
|
|
80
|
+
self.version = ".".join(map(str, self.__theory.version()))
|
|
81
|
+
|
|
82
|
+
def register_options(self, options: clingo.application.ApplicationOptions):
|
|
83
|
+
self.__theory.register_options(options)
|
|
84
|
+
|
|
85
|
+
def validate_options(self) -> bool:
|
|
86
|
+
self.__theory.validate_options()
|
|
87
|
+
return True
|
|
88
|
+
|
|
89
|
+
def main(self, control: clingo.control.Control, files: Sequence[str]):
|
|
90
|
+
self.__theory.register(control)
|
|
91
|
+
|
|
92
|
+
with clingo.ast.ProgramBuilder(control) as bld:
|
|
93
|
+
clingo.ast.parse_files(files, lambda stm: self.__theory.rewrite_ast(stm, bld.add))
|
|
94
|
+
|
|
95
|
+
control.ground([("base", [])])
|
|
96
|
+
self.__theory.prepare(control)
|
|
97
|
+
|
|
98
|
+
with control.solve(on_model = self.__theory.on_model, on_statistics = self.__theory.on_statistics, yield_ = True) as handle:
|
|
99
|
+
for model in handle:
|
|
100
|
+
on_solution(model)
|
|
101
|
+
|
|
102
|
+
if verbose:
|
|
103
|
+
# Print the clingo-lpx command line. Can be useful for debugging.
|
|
104
|
+
print(f"clingo-lpx {" ".join(arguments)}")
|
|
105
|
+
else:
|
|
106
|
+
# Disable all outputs from clingo, https://potassco.org/clingo/python-api/5.5/clingo/control.html#clingo.control.Control.solve
|
|
107
|
+
# Add first to let user arguments override it if necessary
|
|
108
|
+
arguments = ["--outf=3"] + list(arguments)
|
|
109
|
+
|
|
110
|
+
return clingo.application.clingo_main(ClingoApp(), arguments)
|
|
111
|
+
|
|
112
|
+
def lpx_float(v: float) -> str:
|
|
113
|
+
"""
|
|
114
|
+
Format a floating point number into a string suitable for clingo-lpx.
|
|
115
|
+
Clingo-lpx does not support scientific notation, so force fixed point with adaptative precision.
|
|
116
|
+
"""
|
|
117
|
+
if v == 0.0:
|
|
118
|
+
return "0"
|
|
119
|
+
precision = 10 - int(math.log10(v if v > 0 else -v))
|
|
120
|
+
if precision < 0:
|
|
121
|
+
precision = 0 # Clamp, we have enough digits visible
|
|
122
|
+
return '"{{:.{}f}}"'.format(precision).format(v)
|
emasp/efm.py
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
"""
|
|
2
|
+
EFM enumeration subcommands.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import csv
|
|
7
|
+
import importlib.resources
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import pathlib
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
import typer
|
|
14
|
+
from typing import Annotated
|
|
15
|
+
|
|
16
|
+
import emasp
|
|
17
|
+
from emasp import mmparser
|
|
18
|
+
|
|
19
|
+
app = typer.Typer(no_args_is_help = True)
|
|
20
|
+
|
|
21
|
+
@app.callback()
|
|
22
|
+
def _app():
|
|
23
|
+
"""
|
|
24
|
+
Enumeration of EFMs (Elementary Flux Modes).
|
|
25
|
+
|
|
26
|
+
Users should use the enumerate command.
|
|
27
|
+
The advanced commands are mostly useful for ASP users that want to inspect / modify the intermediate ASP.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
# All options of enumerate are copied and tweaked from the advanced option CLI commands, which are used as references.
|
|
31
|
+
@app.command(no_args_is_help = True)
|
|
32
|
+
def enumerate(
|
|
33
|
+
sbml: Annotated[pathlib.Path, typer.Argument(help = "SBML metabolic network")],
|
|
34
|
+
output: Annotated[pathlib.Path | None, typer.Option("-o", "--output", show_default = "stdout", help = "JSON sequence output file")] = None,
|
|
35
|
+
|
|
36
|
+
# Enumeration options
|
|
37
|
+
count: Annotated[int | None, typer.Option("--count", "-n", min = 0, help = "EFM count limit")] = None,
|
|
38
|
+
timeout: Annotated[int | None, typer.Option(min = 0, help = "Stop enumerating after <n> seconds")] = None,
|
|
39
|
+
nb_threads: Annotated[int, typer.Option("--nb-threads", "-j", min = 1, help = "Use multiple threads ; above 4 is usually not efficient")] = 1,
|
|
40
|
+
|
|
41
|
+
# SBML model options
|
|
42
|
+
ignore_null_reactions: Annotated[bool, typer.Option(
|
|
43
|
+
"--ignore-null-reactions", rich_help_panel = "SBML",
|
|
44
|
+
help = "Ignore reactions with the void or without internal metabolite")] = False,
|
|
45
|
+
biomass_reaction: Annotated[list[str], typer.Option(rich_help_panel = "SBML", help = "SBML id(s) of the biomass reaction", show_default = "auto-detect")] = [],
|
|
46
|
+
biomass_metabolite: Annotated[list[str], typer.Option(rich_help_panel = "SBML", help = "SBML id(s) of the biomass metabolite", show_default = "auto-detect")] = [],
|
|
47
|
+
external_boundary: Annotated[bool, typer.Option(
|
|
48
|
+
"--external-boundary", rich_help_panel = "SBML",
|
|
49
|
+
help = "Identify external metabolites with the SBML Boundary flag (default)")] = False,
|
|
50
|
+
external_compartment: Annotated[mmparser.ExternalMetaboliteFilter | None, typer.Option(
|
|
51
|
+
rich_help_panel = "SBML", metavar = "NAME", parser = mmparser.external_is_compartment,
|
|
52
|
+
help = "Identify external metabolites with a compartment of the given name")] = None,
|
|
53
|
+
external_suffix: Annotated[mmparser.ExternalMetaboliteFilter | None, typer.Option(
|
|
54
|
+
rich_help_panel = "SBML", metavar = "SUFFIX", parser = mmparser.external_is_suffix,
|
|
55
|
+
help = "Identify external metabolites with the given id suffix (<metabolite>_<suffix>)")] = None,
|
|
56
|
+
|
|
57
|
+
# Common extension options
|
|
58
|
+
omit_missing: Annotated[bool, typer.Option("--omit-missing", help = "Extension constraints: allow missing reaction/metabolite values by omitting the constraint. Makes the constraints inexact.")] = False,
|
|
59
|
+
csv_delimiter: Annotated[str, typer.Option(help = "Set CSV delimiter")] = ",",
|
|
60
|
+
|
|
61
|
+
# Enzymatic cost options
|
|
62
|
+
enzymatic_cost: Annotated[float | None, typer.Option(rich_help_panel = "Enzymatic cost constraint", metavar = "BETA", help = "Enable enzymatic constraints using the given beta. Requires kcat & mass value for each reaction.")] = None,
|
|
63
|
+
kcat_csv: Annotated[pathlib.Path | None, typer.Option(rich_help_panel = "Enzymatic cost constraint", help = "Provide Kcat with a CSV file containing 'reaction,kcat' entries")] = None,
|
|
64
|
+
kcat_value: Annotated[float | None, typer.Option(rich_help_panel = "Enzymatic cost constraint", min = 0, help = "Fallback Kcat value")] = None,
|
|
65
|
+
mass_csv: Annotated[pathlib.Path | None, typer.Option(rich_help_panel = "Enzymatic cost constraint", help = "Provide enzyme mass with a CSV file containing 'reaction,enzyme_mass' entries")] = None,
|
|
66
|
+
mass_value: Annotated[float | None, typer.Option(rich_help_panel = "Enzymatic cost constraint", min = 0, help = "Fallback enzyme mass value")] = None,
|
|
67
|
+
|
|
68
|
+
# Thermodynamic constraint
|
|
69
|
+
thermodynamic: Annotated[bool, typer.Option("--thermodynamic", rich_help_panel = "Thermodynamic constraint", help = "Enable thermodynamic constraint. Requires concentration [min,max] & DeltaG0 value for each metabolite.")] = False,
|
|
70
|
+
concentration_csv: Annotated[pathlib.Path | None, typer.Option(rich_help_panel = "Thermodynamic constraint", help = "CSV file containing 'metabolite,min,max' entries (mol/L)")] = None,
|
|
71
|
+
concentration_range: Annotated[tuple[float, float] | None, typer.Option(rich_help_panel = "Thermodynamic constraint", help = "Fallback concentration range value (mol/L)")] = None,
|
|
72
|
+
deltag0_csv: Annotated[pathlib.Path | None, typer.Option(rich_help_panel = "Thermodynamic constraint", help = "CSV file containing 'metabolite,deltag0' entries (J/mol)")] = None,
|
|
73
|
+
deltag0_value: Annotated[float | None, typer.Option(rich_help_panel = "Thermodynamic constraint", min = 0, help = "Fallback deltag0 value (J/mol)")] = None,
|
|
74
|
+
):
|
|
75
|
+
"""
|
|
76
|
+
Enumerate EFMs in the given metabolic network, with optional enzyme cost / thermodynamics constraints.
|
|
77
|
+
|
|
78
|
+
Inputs:
|
|
79
|
+
- required : SBML metabolic network model (+ some pre-processing options)
|
|
80
|
+
- optional enzyme cost constraint : a beta value, and kcat / enzyme mass values for each reaction
|
|
81
|
+
- optional thermodynamic constraint : deltaG0 / concentration ranges for each metabolite
|
|
82
|
+
Output:
|
|
83
|
+
- EFM as JSON objects, one per line : { "index": n, "fluxes": { "reaction_id": flux_value, ... } }
|
|
84
|
+
"""
|
|
85
|
+
with tempfile.TemporaryDirectory(prefix = "emasp-efm-enumerate") as workdir:
|
|
86
|
+
asp_model_path = os.path.join(workdir, "model.clp")
|
|
87
|
+
model_to_asp(
|
|
88
|
+
sbml, output = asp_model_path,
|
|
89
|
+
ignore_null_reactions = ignore_null_reactions,
|
|
90
|
+
biomass_reaction = biomass_reaction, biomass_metabolite = biomass_metabolite,
|
|
91
|
+
external_boundary = external_boundary, external_compartment = external_compartment, external_suffix = external_suffix,
|
|
92
|
+
)
|
|
93
|
+
asp_files = [asp_model_path]
|
|
94
|
+
|
|
95
|
+
if enzymatic_cost is not None:
|
|
96
|
+
asp_enzymatic_cost_path = os.path.join(workdir, "enzymatic_cost.clp")
|
|
97
|
+
enzymatic_cost_to_asp(
|
|
98
|
+
asp_model_path, output = asp_enzymatic_cost_path,
|
|
99
|
+
beta = enzymatic_cost,
|
|
100
|
+
kcat_csv = kcat_csv, kcat_value = kcat_value, mass_csv = mass_csv, mass_value = mass_value,
|
|
101
|
+
csv_delimiter = csv_delimiter, omit_missing = omit_missing,
|
|
102
|
+
)
|
|
103
|
+
asp_files.append(asp_enzymatic_cost_path)
|
|
104
|
+
|
|
105
|
+
if thermodynamic:
|
|
106
|
+
asp_thermodynamic_path = os.path.join(workdir, "thermodynamic.clp")
|
|
107
|
+
thermodynamics_to_asp(
|
|
108
|
+
asp_model_path, output = asp_thermodynamic_path,
|
|
109
|
+
concentration_csv = concentration_csv, concentration_range = concentration_range,
|
|
110
|
+
deltag0_csv = deltag0_csv, deltag0_value = deltag0_value,
|
|
111
|
+
csv_delimiter = csv_delimiter, omit_missing = omit_missing,
|
|
112
|
+
)
|
|
113
|
+
asp_files.append(asp_thermodynamic_path)
|
|
114
|
+
|
|
115
|
+
clingolpx(asp_files, output = output, count = count, timeout = timeout, nb_threads = nb_threads)
|
|
116
|
+
|
|
117
|
+
@app.command(no_args_is_help = True, rich_help_panel = "Advanced")
|
|
118
|
+
def clingolpx(
|
|
119
|
+
args: Annotated[list[str], typer.Argument(help = "ASP files or clingo options")],
|
|
120
|
+
output: Annotated[pathlib.Path | None, typer.Option("-o", "--output", show_default = "stdout", help = "JSON sequence output file")] = None,
|
|
121
|
+
|
|
122
|
+
count: Annotated[int | None, typer.Option("--count", "-n", min = 0, help = "EFM count limit")] = None,
|
|
123
|
+
timeout: Annotated[int | None, typer.Option(min = 0, help = "Stop enumerating after <n> seconds")] = None,
|
|
124
|
+
nb_threads: Annotated[int, typer.Option("--nb-threads", "-j", min = 1, help = "Use multiple threads ; above 4 is usually not efficient")] = 1,
|
|
125
|
+
verbose: Annotated[bool, typer.Option(help = "Enable raw clingo output on stdout")] = False,
|
|
126
|
+
):
|
|
127
|
+
"""
|
|
128
|
+
Enumerates EFM using the clingo-lpx solver with prepared ASP files.
|
|
129
|
+
|
|
130
|
+
Launch clingo-lpx with the appropriate mode for EFM enumeration (with --strict --heuristic Domain --enum-mode domRec, and the ASP EFM enumeration rules).
|
|
131
|
+
Enumerated EFMs are written to output as JSON objects, one per line : { "index": n, "fluxes": { "reaction_id": flux_value, ... } }
|
|
132
|
+
|
|
133
|
+
Input ASP files must be prepared and given to this command:
|
|
134
|
+
- a model encoding, made using `emasp efm model-to-asp` (required)
|
|
135
|
+
- enzyme cost constraints if used, made using `emasp efm enzymatic-cost-to-asp`
|
|
136
|
+
- additional ASP directives (for very advanced users)
|
|
137
|
+
"""
|
|
138
|
+
from emasp.clingo import print_efm, run_clingolpx
|
|
139
|
+
|
|
140
|
+
# Build argument list
|
|
141
|
+
arguments = [
|
|
142
|
+
# ASPEFM specific solving mode
|
|
143
|
+
"--strict",
|
|
144
|
+
"--heuristic", "Domain",
|
|
145
|
+
"--enum-mode", "domRec",
|
|
146
|
+
# Translate common options
|
|
147
|
+
"--models", f"{count if count is not None else 0}",
|
|
148
|
+
f"--time-limit={timeout if timeout is not None else 0}",
|
|
149
|
+
]
|
|
150
|
+
if nb_threads > 1:
|
|
151
|
+
arguments.extend(["--parallel-mode", f"{nb_threads},split"]) # Emma always used split mode
|
|
152
|
+
|
|
153
|
+
# Add files. Internal file may only be alive within the with clause.
|
|
154
|
+
with importlib.resources.as_file(importlib.resources.files(emasp).joinpath("enumerate_efm.clp")) as enumerate_efm_asp:
|
|
155
|
+
# Clingo wants raw str value
|
|
156
|
+
arguments.append(str(enumerate_efm_asp))
|
|
157
|
+
arguments.extend(map(str, args))
|
|
158
|
+
|
|
159
|
+
with open(output, mode = "w") if output else contextlib.nullcontext(sys.stdout) as f:
|
|
160
|
+
r = run_clingolpx(on_solution = lambda m: print_efm(m, f), arguments = arguments, verbose = verbose)
|
|
161
|
+
raise typer.Exit(r)
|
|
162
|
+
|
|
163
|
+
@app.command(no_args_is_help = True, rich_help_panel = "Advanced")
|
|
164
|
+
def model_to_asp(
|
|
165
|
+
sbml: Annotated[pathlib.Path, typer.Argument(help = "SBML model file to convert")],
|
|
166
|
+
output: Annotated[pathlib.Path | None, typer.Option("-o", "--output", show_default = "stdout", help = "Output ASP file")] = None,
|
|
167
|
+
ignore_null_reactions: Annotated[bool, typer.Option("--ignore-null-reactions", help = "Ignore reactions with the void or without internal metabolite")] = False,
|
|
168
|
+
biomass_reaction: Annotated[list[str], typer.Option(help = "SBML id(s) of the biomass reaction", show_default = "auto-detect")] = [],
|
|
169
|
+
biomass_metabolite: Annotated[list[str], typer.Option(help = "SBML id(s) of the biomass metabolite", show_default = "auto-detect")] = [],
|
|
170
|
+
|
|
171
|
+
external_boundary: Annotated[bool, typer.Option(
|
|
172
|
+
"--external-boundary", rich_help_panel = "External metabolite definition",
|
|
173
|
+
help = "metabolite has the SBML Boundary flag (default)")] = False,
|
|
174
|
+
external_compartment: Annotated[mmparser.ExternalMetaboliteFilter | None, typer.Option(
|
|
175
|
+
rich_help_panel = "External metabolite definition", metavar = "NAME", parser = mmparser.external_is_compartment,
|
|
176
|
+
help = "metabolite is in a compartment of the given name")] = None,
|
|
177
|
+
external_suffix: Annotated[mmparser.ExternalMetaboliteFilter | None, typer.Option(
|
|
178
|
+
rich_help_panel = "External metabolite definition", metavar = "SUFFIX", parser = mmparser.external_is_suffix,
|
|
179
|
+
help = "metabolite id has the given suffix")] = None,
|
|
180
|
+
):
|
|
181
|
+
"""
|
|
182
|
+
Create a set of ASP definitions and constraints from an SBML model, suitable for EFM enumeration.
|
|
183
|
+
|
|
184
|
+
The resulting file is then used by `emasp efm clingolpx` to un the enumeration:
|
|
185
|
+
|
|
186
|
+
emasp efm model-to-asp sbml_file -o asp_file [CONVERSION_OPTIONS]
|
|
187
|
+
emasp efm clingolpx asp_file [ENUMERATE_OPTIONS]
|
|
188
|
+
|
|
189
|
+
EFM enumeration needs to distinguish external metabolites from internal ones.
|
|
190
|
+
The various --external-* options below define how they are distinguished.
|
|
191
|
+
If no filters are specified, SBML boundary flag is used.
|
|
192
|
+
If multiple filter are used, only metabolites that pass all of them are defined as external.
|
|
193
|
+
|
|
194
|
+
Extensions also need to identify the biomass reaction(s). They can be specified either:
|
|
195
|
+
- manually with --biomass-reaction <name>
|
|
196
|
+
- or auto-detected from the model: reactions with "biomass" in the name, or producing a biomass metabolite
|
|
197
|
+
Thermodynamic constraints also need to identify the biomass metabolite, which is specified:
|
|
198
|
+
- manually with --biomass-metabolite <name>
|
|
199
|
+
- or auto-detected from the model: metabolite with "biomass" in the name
|
|
200
|
+
"""
|
|
201
|
+
# Select filters
|
|
202
|
+
filters = list(filter(None, [
|
|
203
|
+
mmparser.external_is_boundary() if external_boundary else None,
|
|
204
|
+
external_compartment,
|
|
205
|
+
external_suffix,
|
|
206
|
+
]))
|
|
207
|
+
if not filters:
|
|
208
|
+
filters = [mmparser.external_is_boundary()]
|
|
209
|
+
def all_filters(species) -> bool:
|
|
210
|
+
return all(f(species) for f in filters)
|
|
211
|
+
|
|
212
|
+
network = mmparser.MetabolicNetwork.from_sbml(
|
|
213
|
+
sbml, is_external_metabolite = all_filters, ignore_null_reactions = ignore_null_reactions,
|
|
214
|
+
biomass_metabolite_ids = set(biomass_metabolite) if len(biomass_metabolite) > 0 else None,
|
|
215
|
+
biomass_reaction_ids = set(biomass_reaction) if len(biomass_reaction) > 0 else None,
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
with open(output, mode = "w") if output else contextlib.nullcontext(sys.stdout) as f:
|
|
219
|
+
f.write(network.to_asp())
|
|
220
|
+
|
|
221
|
+
@app.command(no_args_is_help = True, rich_help_panel = "Advanced")
|
|
222
|
+
def thermodynamics_to_asp(
|
|
223
|
+
asp_model: Annotated[pathlib.Path, typer.Argument(help = "ASP metabolic network (output of model-to-asp command)")],
|
|
224
|
+
|
|
225
|
+
concentration_csv: Annotated[pathlib.Path | None, typer.Option(rich_help_panel = "Concentration range", help = "CSV file containing 'metabolite,min,max' entries (mol/L)")] = None,
|
|
226
|
+
concentration_range: Annotated[tuple[float, float] | None, typer.Option(rich_help_panel = "Concentration range", help = "Fallback concentration range value (mol/L)")] = None,
|
|
227
|
+
|
|
228
|
+
deltag0_csv: Annotated[pathlib.Path | None, typer.Option(rich_help_panel = "DeltaG0", help = "CSV file containing 'metabolite,deltag0' entries (J/mol)")] = None,
|
|
229
|
+
deltag0_value: Annotated[float | None, typer.Option(rich_help_panel = "DeltaG0", min = 0, help = "Fallback deltag0 value (J/mol)")] = None,
|
|
230
|
+
|
|
231
|
+
output: Annotated[pathlib.Path | None, typer.Option("-o", "--output", show_default = "stdout", help = "Output ASP file")] = None,
|
|
232
|
+
omit_missing: Annotated[bool, typer.Option("--omit-missing", help = "Omit metabolites with missing concentration/deltaG0 from thermodynamic constraints (inexact)")] = False,
|
|
233
|
+
csv_delimiter: Annotated[str, typer.Option(help = "Set CSV delimiter")] = ",",
|
|
234
|
+
temperature: Annotated[float, typer.Option(min = 0, help = "Temperature (K)")] = 298.15,
|
|
235
|
+
):
|
|
236
|
+
"""
|
|
237
|
+
Create a set of additional ASP definitions that encode thermodynamic constraints for EFM enumeration.
|
|
238
|
+
|
|
239
|
+
The constraint requires for each metabolite:
|
|
240
|
+
- a DeltaG0 value : the standard chemical potential of the metabolite (J/mol)
|
|
241
|
+
- a range of concentration [min,max] (mol/L)
|
|
242
|
+
These values can be provided with:
|
|
243
|
+
- a csv file containing "metabolite_id,deltag0" / "metabolite_id,cmin,cmax" entries (--deltag0-csv / --concentration-csv)
|
|
244
|
+
- a fallback value/range if the csv does not provide one (--deltag0-value / --concentration-range)
|
|
245
|
+
By default, metabolites with missing values are an error.
|
|
246
|
+
You can omit the constraints for metabolites with missing values using --omit-missing, but the EFM enumeration will be inexact.
|
|
247
|
+
|
|
248
|
+
Metabolite concentrations in found EFM are not displayed, as they are not meaningful.
|
|
249
|
+
They are random values that fulfill the constraints, among an infinity of such values.
|
|
250
|
+
"""
|
|
251
|
+
network = mmparser.MetabolicNetwork.from_asp(asp_model)
|
|
252
|
+
if len(network.biomass_reaction_ids) == 0:
|
|
253
|
+
raise ValueError("The model must define a biomass reaction (--biomass-reaction)")
|
|
254
|
+
constraint_metabolites = network.all_metabolite_ids - network.biomass_metabolite_ids
|
|
255
|
+
|
|
256
|
+
def gather_deltag0(csv_path: pathlib.Path | None, default: float | None) -> dict[str, tuple[float, str]]:
|
|
257
|
+
""" Returns dict(id: str -> (value: float > 0, source: str)) from csv file and/or default value """
|
|
258
|
+
values = dict()
|
|
259
|
+
# Read from csv
|
|
260
|
+
if csv_path is not None:
|
|
261
|
+
with open(csv_path, newline = "") as file:
|
|
262
|
+
reader = csv.reader(file, delimiter = csv_delimiter)
|
|
263
|
+
for row in reader:
|
|
264
|
+
if len(row) < 2: raise ValueError(f"{csv_path}: line {reader.line_num}: missing fields reaction_id{csv_delimiter}deltag0")
|
|
265
|
+
try: values[row[0]] = (float(row[1]), "csv")
|
|
266
|
+
except ValueError as e: raise ValueError(f"{csv_path}: line {reader.line_num}: deltag0: {e}")
|
|
267
|
+
# Fill with defaults
|
|
268
|
+
if default is not None:
|
|
269
|
+
for id in constraint_metabolites:
|
|
270
|
+
if id not in values:
|
|
271
|
+
values[id] = (default, "fallback")
|
|
272
|
+
return values
|
|
273
|
+
|
|
274
|
+
def gather_concentrations(csv_path: pathlib.Path | None, default: tuple[float, float] | None) -> dict[str, tuple[float, float, str]]:
|
|
275
|
+
""" Returns dict(id: str -> (min: float > 0, max: float >= min, source: str)) from csv file and/or default value """
|
|
276
|
+
values = dict()
|
|
277
|
+
# Read from csv
|
|
278
|
+
if csv_path is not None:
|
|
279
|
+
with open(csv_path, newline = "") as file:
|
|
280
|
+
reader = csv.reader(file, delimiter = csv_delimiter)
|
|
281
|
+
for row in reader:
|
|
282
|
+
if len(row) < 3: raise ValueError(f"{csv_path}: line {reader.line_num}: missing fields metabolite_id{csv_delimiter}min{csv_delimiter}max")
|
|
283
|
+
try:
|
|
284
|
+
min = float(row[1])
|
|
285
|
+
max = float(row[2])
|
|
286
|
+
if not min > 0: raise ValueError("min must be positive")
|
|
287
|
+
if not max >= min: raise ValueError("range min > max")
|
|
288
|
+
values[row[0]] = (min, max, "csv")
|
|
289
|
+
except ValueError as e:
|
|
290
|
+
raise ValueError(f"{csv_path}: line {reader.line_num}: range[min,max]: {e}")
|
|
291
|
+
# Fill with defaults
|
|
292
|
+
if default is not None:
|
|
293
|
+
for id in constraint_metabolites:
|
|
294
|
+
if id not in values:
|
|
295
|
+
values[id] = (*default, "fallback")
|
|
296
|
+
return values
|
|
297
|
+
|
|
298
|
+
asp = generate_thermodynamic_constraint_asp(
|
|
299
|
+
metabolite_ids = constraint_metabolites, temperature = temperature, omit_missing = omit_missing,
|
|
300
|
+
deltag0_values = gather_deltag0(deltag0_csv, deltag0_value),
|
|
301
|
+
concentration_ranges = gather_concentrations(concentration_csv, concentration_range),
|
|
302
|
+
)
|
|
303
|
+
with open(output, mode = "w") if output else contextlib.nullcontext(sys.stdout) as f:
|
|
304
|
+
f.write(asp)
|
|
305
|
+
|
|
306
|
+
def generate_thermodynamic_constraint_asp(
|
|
307
|
+
metabolite_ids: set[str],
|
|
308
|
+
deltag0_values: dict[str, tuple[float, str]], concentration_ranges: dict[str, tuple[float, float, str]],
|
|
309
|
+
temperature: float, omit_missing: bool,
|
|
310
|
+
) -> str:
|
|
311
|
+
"""
|
|
312
|
+
Generate the thermodynamics ASP constraint (str) from input data :
|
|
313
|
+
- metabolite_ids: set of all metabolites under constraints
|
|
314
|
+
- deltag0: dict[metabolite: str -> (deltag0: float, source: str)]
|
|
315
|
+
- concentrations: dict[metabolite: str -> (min: float, max: float, source: str)]
|
|
316
|
+
- temperature: float, Kelvin
|
|
317
|
+
- if omit_missing is True, allow missing values, instead they are an error
|
|
318
|
+
"""
|
|
319
|
+
from emasp.clingo import lpx_float
|
|
320
|
+
|
|
321
|
+
missing_values: set[str] = metabolite_ids - set.intersection(set(deltag0_values), set(concentration_ranges))
|
|
322
|
+
if not omit_missing and len(missing_values) > 0:
|
|
323
|
+
raise ValueError(f"Metabolites with missing DeltaG0 or concentration range: {missing_values}. Use --omit-missing to allow missing values or provide them.")
|
|
324
|
+
|
|
325
|
+
R = 8.3145 # J mol^-1 K^-1 ; molar gas constant
|
|
326
|
+
def deltafgprime_asp(metabolite_id: str) -> str:
|
|
327
|
+
if metabolite_id in missing_values:
|
|
328
|
+
# Missing values : report value source or missing. Only is omit_missing is enabled.
|
|
329
|
+
deltag0_source = deltag0_values[metabolite_id][1] if metabolite_id in deltag0_values else "missing"
|
|
330
|
+
concentration_source = concentration_ranges[metabolite_id][2] if metabolite_id in concentration_ranges else "missing"
|
|
331
|
+
return f"% omitted {metabolite_id} : DeltaG0 {deltag0_source} + RT ln(concentration range {concentration_source})\n"
|
|
332
|
+
else:
|
|
333
|
+
# DeltaFG' bounds : declaration + report sources in comment.
|
|
334
|
+
deltag0, deltag0_source = deltag0_values[metabolite_id]
|
|
335
|
+
c_min, c_max, c_source = concentration_ranges[metabolite_id]
|
|
336
|
+
dfgp_min = deltag0 + R * temperature * math.log(c_min)
|
|
337
|
+
dfgp_max = deltag0 + R * temperature * math.log(c_max)
|
|
338
|
+
return f'&dom{{ {lpx_float(dfgp_min)} .. {lpx_float(dfgp_max)} }} = deltafgprime("{metabolite_id}"). % {deltag0} (DeltaG0 {deltag0_source}) + RT ln({c_min} .. {c_max} (concentration {c_source}))\n'
|
|
339
|
+
|
|
340
|
+
asp = "% EMASP thermodynamics constraints\n"
|
|
341
|
+
asp += "% Represent concentration variables with DeltaFG' = DeltaG0 + RT * ln(C) values:\n"
|
|
342
|
+
asp += "{deltafgprime(M)} :- metabolite(M).\n"
|
|
343
|
+
asp += "{deltafgprime(M)} :- external(M).\n"
|
|
344
|
+
asp += f"% DeltaFG' ranges : {len(metabolite_ids) - len(missing_values)}\n"
|
|
345
|
+
asp += "".join(map(deltafgprime_asp, sorted(metabolite_ids)))
|
|
346
|
+
asp += "% Thermodynamic constraint and restriction to specific reactions\n"
|
|
347
|
+
asp += "thermodynamic_reaction(R) :- reaction(R), not transport_reaction(R), not biomass_reaction(R), support(R).\n"
|
|
348
|
+
asp += "&sum{C*deltafgprime(M) : stoichiometry(M, R, C), metabolite(M)} <= 0 :- thermodynamic_reaction(R).\n"
|
|
349
|
+
return asp
|
|
350
|
+
|
|
351
|
+
@app.command(no_args_is_help = True, rich_help_panel = "Advanced")
|
|
352
|
+
def enzymatic_cost_to_asp(
|
|
353
|
+
asp_model: Annotated[pathlib.Path, typer.Argument(help = "ASP metabolic network (output of model-to-asp command)")],
|
|
354
|
+
beta: Annotated[float, typer.Option(min = 0, help = "Beta threshold")],
|
|
355
|
+
|
|
356
|
+
kcat_csv: Annotated[pathlib.Path | None, typer.Option(rich_help_panel = "Apparent Kcat", help = "CSV file containing 'reaction,kcat' entries (s^-1)")] = None,
|
|
357
|
+
kcat_value: Annotated[float | None, typer.Option(rich_help_panel = "Apparent Kcat", min = 0, help = "Fallback Kcat value (s^-1)")] = None,
|
|
358
|
+
|
|
359
|
+
mass_csv: Annotated[pathlib.Path | None, typer.Option(rich_help_panel = "Enzyme mass", help = "CSV file containing 'reaction,enzyme_mass' entries (kDa)")] = None,
|
|
360
|
+
mass_value: Annotated[float | None, typer.Option(rich_help_panel = "Enzyme mass", min = 0, help = "Fallback mass value (kDa)")] = None,
|
|
361
|
+
|
|
362
|
+
output: Annotated[pathlib.Path | None, typer.Option("-o", "--output", show_default = "stdout", help = "Output ASP file")] = None,
|
|
363
|
+
omit_missing: Annotated[bool, typer.Option("--omit-missing", help = "Omit reactions with missing kcat/mass from enzyme cost constraints (inexact)")] = False,
|
|
364
|
+
csv_delimiter: Annotated[str, typer.Option(help = "Set CSV delimiter")] = ",",
|
|
365
|
+
):
|
|
366
|
+
"""
|
|
367
|
+
Create a set of additional ASP definitions that encode enzyme cost constraints for EFM enumeration.
|
|
368
|
+
|
|
369
|
+
Beta is dependent on the data set, so no default is provided.
|
|
370
|
+
A typical strategy is to use dichotomic search with increasing values until at least 1 EFM is found.
|
|
371
|
+
|
|
372
|
+
The enzyme cost constraint mode requires for each reaction:
|
|
373
|
+
- a Kcat value : the apparent Michaelis-Menten constant for the reaction (s^-1)
|
|
374
|
+
- a mass value : the molecular weight of the enzyme for the reaction (kDa ; kilo Dalton)
|
|
375
|
+
These values can be provided with:
|
|
376
|
+
- a csv file containing "reaction_id,value" entries (--kcat-csv / --mass-csv)
|
|
377
|
+
- a fallback value if the csv does not provide one (--kcat-value / --mass-value)
|
|
378
|
+
By default, reaction with missing values are an error.
|
|
379
|
+
You can omit the constraints for reactions with missing values using --omit-missing, but the EFM enumeration will be inexact.
|
|
380
|
+
"""
|
|
381
|
+
network = mmparser.MetabolicNetwork.from_asp(asp_model)
|
|
382
|
+
if len(network.biomass_reaction_ids) == 0:
|
|
383
|
+
raise ValueError("The model must define a biomass reaction (--biomass-reaction)")
|
|
384
|
+
|
|
385
|
+
def gather_values_by_reaction(value_name: str, csv_path: pathlib.Path | None, default: float | None) -> dict[str, tuple[float, str]]:
|
|
386
|
+
""" Returns dict(id: str -> (value: float > 0, source: str)) from csv file and/or default value """
|
|
387
|
+
values = dict()
|
|
388
|
+
# Read from csv
|
|
389
|
+
if csv_path is not None:
|
|
390
|
+
with open(csv_path, newline = "") as file:
|
|
391
|
+
reader = csv.reader(file, delimiter = csv_delimiter)
|
|
392
|
+
for row in reader:
|
|
393
|
+
if len(row) < 2: raise ValueError(f"{csv_path}: line {reader.line_num}: missing fields reaction_id{csv_delimiter}{value_name}")
|
|
394
|
+
try:
|
|
395
|
+
value = float(row[1])
|
|
396
|
+
if not value > 0: raise ValueError("must be positive")
|
|
397
|
+
values[row[0]] = (value, "csv")
|
|
398
|
+
except ValueError as e:
|
|
399
|
+
raise ValueError(f"{csv_path}: line {reader.line_num}: {value_name}: {e}")
|
|
400
|
+
# Fill with defaults
|
|
401
|
+
if default is not None:
|
|
402
|
+
for id in network.reaction_ids:
|
|
403
|
+
if id not in values:
|
|
404
|
+
values[id] = (default, "fallback")
|
|
405
|
+
return values
|
|
406
|
+
|
|
407
|
+
asp = generate_enzymatic_cost_constraint_asp(
|
|
408
|
+
reaction_ids = network.reaction_ids,
|
|
409
|
+
beta = beta,
|
|
410
|
+
kcat_values = gather_values_by_reaction("kcat", kcat_csv, kcat_value),
|
|
411
|
+
mass_values = gather_values_by_reaction("enzyme mass", mass_csv, mass_value),
|
|
412
|
+
omit_missing = omit_missing,
|
|
413
|
+
)
|
|
414
|
+
with open(output, mode = "w") if output else contextlib.nullcontext(sys.stdout) as f:
|
|
415
|
+
f.write(asp)
|
|
416
|
+
|
|
417
|
+
def generate_enzymatic_cost_constraint_asp(
|
|
418
|
+
reaction_ids: set[str], beta: float,
|
|
419
|
+
kcat_values: dict[str, tuple[float, str]], mass_values: dict[str, tuple[float, str]],
|
|
420
|
+
omit_missing: bool,
|
|
421
|
+
) -> str:
|
|
422
|
+
"""
|
|
423
|
+
Generate the enzymatic cost ASP constraint (str) from input data :
|
|
424
|
+
- reaction_ids: set of all reactions under constraints
|
|
425
|
+
- beta: float
|
|
426
|
+
- kcat_values: dict[reaction: str -> (kcat: float, source: str)]
|
|
427
|
+
- mass_values: dict[reaction: str -> (mass: float, source: str)]
|
|
428
|
+
- if omit_missing is True, allow missing values, instead they are an error
|
|
429
|
+
"""
|
|
430
|
+
from emasp.clingo import lpx_float
|
|
431
|
+
|
|
432
|
+
missing_values: set[str] = reaction_ids - set.intersection(set(kcat_values), set(mass_values))
|
|
433
|
+
if not omit_missing and len(missing_values) > 0:
|
|
434
|
+
raise ValueError(f"Reactions with missing kcat or enzyme mass: {missing_values}. Use --omit-missing to allow missing values or provide them.")
|
|
435
|
+
|
|
436
|
+
gamma = 1e-3 / 3600.0
|
|
437
|
+
def specific_cost_asp(reaction_id: str) -> str:
|
|
438
|
+
if reaction_id in missing_values:
|
|
439
|
+
# Missing values : report value source or missing. Only is omit_missing is enabled.
|
|
440
|
+
kcat_source = kcat_values[reaction_id][1] if reaction_id in kcat_values else "missing"
|
|
441
|
+
mass_source = mass_values[reaction_id][1] if reaction_id in mass_values else "missing"
|
|
442
|
+
return f"% omitted {reaction_id} : mass {mass_source} / kcat {kcat_source}\n"
|
|
443
|
+
else:
|
|
444
|
+
# Alpha value : declaration + report sources in comment.
|
|
445
|
+
kcat, kcat_source = kcat_values[reaction_id]
|
|
446
|
+
mass, mass_source = mass_values[reaction_id]
|
|
447
|
+
specific_cost = gamma * mass / kcat
|
|
448
|
+
return f'specific_cost("{reaction_id}", {lpx_float(specific_cost)}). % gamma * {mass} (mass {mass_source}) / {kcat} (kcat {kcat_source})\n'
|
|
449
|
+
|
|
450
|
+
asp = "% EMASP enzymatic cost constraints\n"
|
|
451
|
+
asp += f"#const beta = {lpx_float(beta)}.\n"
|
|
452
|
+
asp += "% Conditions of application of the constraint\n"
|
|
453
|
+
asp += "&sum{flux(RB)} > 0 :- biomass_reaction(RB).\n"
|
|
454
|
+
asp += "% Constraint : sum(gamma * alpha * v(except biomass))- beta * v(biomass) <= 0\n"
|
|
455
|
+
asp += '&sum{C*flux(R): specific_cost(R, C), not biomass_reaction(R), reaction(R); - beta*flux(RB)} <= 0 :- biomass_reaction(RB).\n'
|
|
456
|
+
asp += f"% Specific cost values : {len(reaction_ids) - len(missing_values)}\n"
|
|
457
|
+
asp += "".join(map(specific_cost_asp, sorted(reaction_ids)))
|
|
458
|
+
return asp
|