-
Notifications
You must be signed in to change notification settings - Fork 216
/
sbml.py
2080 lines (1791 loc) · 70.1 KB
/
sbml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
SBML import and export using python-libsbml.
- The SBML importer supports all versions of SBML and the fbc package.
- The SBML exporter writes SBML L3 models.
- Annotation information is stored on the cobrapy objects
- Information from the group package is read
Parsing of fbc models was implemented as efficient as possible, whereas
(discouraged) fallback solutions are not optimized for efficiency.
Notes are only supported in a minimal way relevant for constraint-based
models. I.e., structured information from notes in the form
<p>key: value</p>
is read into the Object.notes dictionary when reading SBML files.
On writing the Object.notes dictionary is serialized to the SBML
notes information.
Annotations are read in the Object.annotation fields.
Some SBML related issues are still open, please refer to the respective issue:
- update annotation format and support qualifiers (depends on decision
for new annotation format; https://github.com/opencobra/cobrapy/issues/684)
- write compartment annotations and notes (depends on updated first-class
compartments; see https://github.com/opencobra/cobrapy/issues/760)
- support compression on file handles (depends on solution for
https://github.com/opencobra/cobrapy/issues/812)
"""
import datetime
import logging
import re
from ast import And, BoolOp, Module, Name, Or
from collections import defaultdict, namedtuple
from copy import deepcopy
from io import StringIO
from pathlib import Path
from sys import platform
from typing import IO, Match, Optional, Pattern, Tuple, Type, Union
import libsbml
import cobra
from ..core import GPR, Gene, Group, Metabolite, Model, Reaction
from ..manipulation.validate import check_metabolite_compartment_formula
from ..util.solver import linear_reaction_coefficients, set_objective
class CobraSBMLError(Exception):
"""SBML error class."""
pass
LOGGER = logging.getLogger(__name__)
# -----------------------------------------------------------------------------
# Defaults and constants for writing SBML
# -----------------------------------------------------------------------------
config = cobra.Configuration() # for default bounds
LOWER_BOUND_ID = "cobra_default_lb"
UPPER_BOUND_ID = "cobra_default_ub"
ZERO_BOUND_ID = "cobra_0_bound"
BOUND_MINUS_INF = "minus_inf"
BOUND_PLUS_INF = "plus_inf"
SBO_FBA_FRAMEWORK = "SBO:0000624"
SBO_DEFAULT_FLUX_BOUND = "SBO:0000626"
SBO_FLUX_BOUND = "SBO:0000625"
SBO_EXCHANGE_REACTION = "SBO:0000627"
LONG_SHORT_DIRECTION = {"maximize": "max", "minimize": "min"}
SHORT_LONG_DIRECTION = {"min": "minimize", "max": "maximize"}
Unit = namedtuple("Unit", ["kind", "scale", "multiplier", "exponent"])
UNITS_FLUX = (
"mmol_per_gDW_per_hr",
[
Unit(kind=libsbml.UNIT_KIND_MOLE, scale=-3, multiplier=1, exponent=1),
Unit(kind=libsbml.UNIT_KIND_GRAM, scale=0, multiplier=1, exponent=-1),
Unit(kind=libsbml.UNIT_KIND_SECOND, scale=0, multiplier=3600, exponent=-1),
],
)
# -----------------------------------------------------------------------------
# Functions for id replacements (import/export)
# -----------------------------------------------------------------------------
SBML_DOT = "__SBML_DOT__"
# -----------------------------------------------------------------------------
# Precompiled note pattern
# -----------------------------------------------------------------------------
pattern_notes: Pattern = re.compile(
r"<(?P<prefix>(\w+:)?)p[^>]*>(?P<content>.*?)</(?P=prefix)p>",
re.IGNORECASE | re.DOTALL,
)
pattern_to_sbml: Pattern = re.compile(r"([^0-9_a-zA-Z])")
pattern_from_sbml: Pattern = re.compile(r"__(\d+)__")
def _escape_non_alphanum(nonASCII: Match) -> str:
"""Convert non alphanumeric to string representation of ascii number.
Converts a non alphanumeric character to a string representation of
its ascii number using ord.
Parameters
---------
nonASCII: Match
Match object, identified by pattern_from_sbml
Returns
-------
str:
The ascii code, surronded by __.
"""
return "__" + str(ord(nonASCII.group())) + "__"
def _number_to_chr(numberStr: Match) -> str:
"""Convert an ascii number to a character.
Parameters
---------
numberStr: Match
Match object, identified by pattern_from_sbml
Returns
-------
str:
The first match between the underscores, converted to character.
"""
return chr(int(numberStr.group(1)))
def _clip(sid: str, prefix: str) -> str:
"""Clip a prefix from the beginning of a string if it exists.
Parameters
----------
sid: str
String to clip.
prefix: str
Prefix to remove.
Returns
-------
str
The string with prefix clipped if it existed. Otherwise the original string.
"""
return sid[len(prefix) :] if sid.startswith(prefix) else sid
def _f_gene(sid: str, prefix: str = "G_") -> str:
"""Clip gene prefix from id.
Parameters
----------
sid: str
String to process
prefix: str, optional
Prefix for gene (default "G_").
Returns
-------
str
Returns modified str with prefix removed, SBML_DOT (see above) replaced
with ".", __(NUMBER)__ replaced with the character value of NUMBER.
See Also
--------
pattern_from_sbml
_number_to_chr
SBML_DOT
"""
sid = sid.replace(SBML_DOT, ".")
sid = pattern_from_sbml.sub(_number_to_chr, sid)
return _clip(sid, prefix)
def _f_gene_rev(sid: str, prefix: str = "G_") -> str:
"""Add gene prefix to id.
Parameters
----------
sid: str
String to process
prefix: str, optional
Prefix for gene (default "G_").
Returns
-------
str
Returns prefix prepended to modified str, with "." replaced with
SBML_DOT, non alphanumeric repalced with a string representation of the
unicode number.
See Also
--------
pattern_to_sbml
_escape_non_alphanum
SBML_DOT
"""
sid = pattern_to_sbml.sub(_escape_non_alphanum, sid)
return prefix + sid.replace(".", SBML_DOT)
def _f_specie(sid: str, prefix: str = "M_") -> str:
"""Clip specie/metabolite prefix from id.
Parameters
----------
sid: str
String to process
prefix: str, optional
Prefix for species/metabolite (default "M_").
Returns
-------
str
Returns modified str with prefix removed, SBML_DOT (see above) replaced
with ".", __(NUMBER)__ replaced with the character value of NUMBER.
See Also
--------
pattern_from_sbml
_number_to_chr
SBML_DOT
"""
sid = pattern_from_sbml.sub(_number_to_chr, sid)
return _clip(sid, prefix)
def _f_specie_rev(sid: str, prefix: str = "M_") -> str:
"""Add specie/metabolite prefix to id.
Parameters
----------
sid: str
String to process
prefix: str, optional
Prefix for metabolite (default "M_").
Returns
-------
str
Returns prefix prepended to modified str, with "." replaced with
SBML_DOT, non alphanumeric repalced with a string representation of the
unicode number.
See Also
--------
pattern_to_sbml
_escape_non_alphanum
SBML_DOT
"""
sid = pattern_to_sbml.sub(_escape_non_alphanum, sid)
return prefix + sid
def _f_reaction(sid: str, prefix: str = "R_") -> str:
"""Clip reaction prefix from id.
Parameters
----------
sid: str
String to process
prefix: str, optional
Prefix for reaction (default "R_").
Returns
-------
str
Returns modified str with prefix removed, SBML_DOT (see above) replaced
with ".", __(NUMBER)__ replaced with the character value of NUMBER.
See Also
--------
pattern_from_sbml
_number_to_chr
SBML_DOT
"""
sid = pattern_from_sbml.sub(_number_to_chr, sid)
return _clip(sid, prefix)
def _f_reaction_rev(sid: str, prefix: str = "R_") -> str:
"""Add reaction prefix to id.
Parameters
----------
sid: str
String to process
prefix: str, optional
Prefix for reaction (default "R_").
Returns
-------
str
Returns prefix prepended to modified str, with "." replaced with
SBML_DOT, non alphanumeric repalced with a string representation of the
unicode number.
See Also
--------
pattern_to_sbml
_escape_non_alphanum
SBML_DOT
"""
sid = pattern_to_sbml.sub(_escape_non_alphanum, sid)
return prefix + sid
def _f_group(sid: str, prefix: str = "G_") -> str:
"""Clip group prefix from id.
Parameters
----------
sid: str
String to process
prefix: str, optional
Prefix for group (default "G_").
Returns
-------
str
Returns modified str with prefix removed, SBML_DOT (see above) replaced
with ".", __(NUMBER)__ replaced with the character value of NUMBER.
See Also
--------
pattern_from_sbml
_number_to_chr
SBML_DOT
"""
sid = pattern_from_sbml.sub(_number_to_chr, sid)
return _clip(sid, prefix)
def _f_group_rev(sid: str, prefix: str = "G_") -> str:
"""Add group prefix to id.
Parameters
----------
sid: str
String to process
prefix: str, optional
Prefix for group (default "G_").
Returns
-------
str
Returns prefix prepended to modified str, with "." replaced with
SBML_DOT, non alphanumeric repalced with a string representation of the
unicode number.
See Also
--------
pattern_to_sbml
_escape_non_alphanum
SBML_DOT
"""
sid = pattern_to_sbml.sub(_escape_non_alphanum, sid)
return prefix + sid
F_GENE = "F_GENE"
F_GENE_REV = "F_GENE_REV"
F_SPECIE = "F_SPECIE"
F_SPECIE_REV = "F_SPECIE_REV"
F_REACTION = "F_REACTION"
F_REACTION_REV = "F_REACTION_REV"
F_GROUP = "F_GROUP"
F_GROUP_REV = "F_GROUP_REV"
F_REPLACE: dict = {
F_GENE: _f_gene,
F_GENE_REV: _f_gene_rev,
F_SPECIE: _f_specie,
F_SPECIE_REV: _f_specie_rev,
F_REACTION: _f_reaction,
F_REACTION_REV: _f_reaction_rev,
F_GROUP: _f_group,
F_GROUP_REV: _f_group_rev,
}
# -----------------------------------------------------------------------------
# Read SBML
# -----------------------------------------------------------------------------
# noinspection PyDefaultArgument
def read_sbml_model(
filename: Union[str, IO, Path],
number: Type = float,
f_replace: dict = F_REPLACE,
**kwargs,
) -> Model:
"""Read SBML model from given filename.
If the given filename ends with the suffix ''.gz'' (for example,
''myfile.xml.gz'),' the file is assumed to be compressed in gzip
format and will be automatically decompressed upon reading. Similarly,
if the given filename ends with ''.zip'' or ''.bz2',' the file is
assumed to be compressed in zip or bzip2 format (respectively). Files
whose names lack these suffixes will be read uncompressed. Note that
if the file is in zip format but the archive contains more than one
file, only the first file in the archive will be read and the rest
ignored.
To read a gzip/zip file, libSBML needs to be configured and linked
with the zlib library at compile time. It also needs to be linked
with the bzip2 library to read files in bzip2 format. (Both of these
are the default configurations for libSBML.)
This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models
are converted to FBC-v2 models before reading.
The parser tries to fall back to information in notes dictionaries
if information is not available in the FBC packages, e.g.,
CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.
Parameters
----------
filename : path to SBML file, or SBML string, or SBML file handle
SBML which is read into cobra model
number: data type of stoichiometry: {float, int}
In which data type should the stoichiometry be parsed.
f_replace : dict of replacement functions for id replacement
Dictionary of replacement functions for gene, specie, and reaction.
By default the following id changes are performed on import:
clip G_ from genes, clip M_ from species, clip R_ from reactions
If no replacements should be performed, set f_replace={}, None
**kwargs:
Further keyword arguments are passed on to the called function (_sbml_to_model)
Returns
-------
cobra.core.Model
Raises
------
IOError if file not read
All other errors are wrapped around in a message pointing to SBML validator.
Notes
-----
Provided file handles cannot be opened in binary mode, i.e., use
with open(path, "r" as f):
read_sbml_model(f)
File handles to compressed files are not supported yet.
"""
try:
doc = _get_doc_from_filename(filename)
return _sbml_to_model(doc, number=number, f_replace=f_replace, **kwargs)
except IOError as e:
raise e
except Exception as original_error:
cobra_error = CobraSBMLError(
"Something went wrong reading the SBML model. Most likely the SBML"
" model is not valid. Please check that your model is valid using "
"the `cobra.io.sbml.validate_sbml_model` function or via the "
"online validator at https://sbml.org/validator_servlet/ .\n"
"\t`(model, errors) = validate_sbml_model(filename)`"
"\nIf the model is valid and cannot be read please open an issue "
"at https://github.com/opencobra/cobrapy/issues ."
)
raise cobra_error from original_error
def _get_doc_from_filename(filename: Union[str, IO, Path]) -> "libsbml.SBMLDocument":
"""Get SBMLDocument from given filename.
Parameters
----------
filename : path to SBML, or SBML string, or filehandle
Returns
-------
libsbml.SBMLDocument
Raises
------
IOError if file not readable or does not contain SBML.
CobraSBMLError if input type is not valid.
"""
if isinstance(filename, Path) and {".bz2", ".gz"}.isdisjoint(filename.suffixes):
doc: libsbml.SBMLDocument = libsbml.readSBMLFromString(filename.read_text())
elif isinstance(filename, Path) and {".bz2", ".gz"}.intersection(filename.suffixes):
doc: libsbml.SBMLDocument = libsbml.readSBMLFromFile(str(filename))
elif isinstance(filename, str):
if "<sbml" in filename:
doc: libsbml.SBMLDocument = libsbml.readSBMLFromString(filename)
elif (
("win" in platform) and (len(filename) < 260) or "win" not in platform
) and Path(filename).exists():
doc: libsbml.SBMLDocument = libsbml.readSBMLFromFile(filename)
else:
# string representation
raise IOError(
f"The file with '{filename}' does not exist, "
f"or is not an SBML string. Provide the path to "
f"an existing SBML file or a valid SBML string representation:\n"
)
elif hasattr(filename, "read"):
# file handle
doc: libsbml.SBMLDocument = libsbml.readSBMLFromString(filename.read())
else:
raise CobraSBMLError(
f"Input type '{type(filename)}' for '{filename}' is not supported."
f" Provide a path, SBML str, or file handle."
)
return doc
# noinspection PyDefaultArgument
# noinspection PyUnusedLocal
def _sbml_to_model(
doc: "libsbml.SBMLDocument",
number: Type = float,
f_replace: dict = F_REPLACE,
set_missing_bounds: bool = False,
**kwargs,
) -> Model:
"""Create cobra model from SBMLDocument.
Parameters
----------
doc: libsbml.SBMLDocument
number: data type of stoichiometry: {float, int}
In which data type should the stoichiometry be parsed.
f_replace : dict
dict of replacement functions for id replacement
set_missing_bounds : bool
flag to set missing bounds. Looks like it will be ignored.
**kwargs:
Further keyword arguments are passed on.
Returns
-------
cobra.core.Model
Raises
------
CobraSBMLError if no SBML model detected in file.
Exception if fbc coversion from v1 to v2 needed and not successful.
CobraSBMLError if upper or lower bound are missing from a reaction.
CobraSBMLError if objective reaction declared and not found. Objective reaction not
declared will lead to an ERROR being logged.
"""
if f_replace is None:
f_replace = {}
# SBML model
model: "libsbml.Model" = doc.getModel()
if model is None:
raise CobraSBMLError("No SBML model detected in file.")
model_fbc: "libsbml.FbcModelPlugin" = model.getPlugin("fbc")
if not model_fbc:
LOGGER.warning("Model does not contain SBML fbc package information.")
else:
if not model_fbc.isSetStrict():
LOGGER.warning('Loading SBML model without fbc:strict="true"')
# fbc-v1 (legacy)
doc_fbc: "libsbml.FbcSBMLDocumentPlugin" = doc.getPlugin("fbc")
fbc_version = doc_fbc.getPackageVersion()
if fbc_version == 1:
LOGGER.warning(
"Loading SBML with fbc-v1 (models should be encoded using fbc-v2)"
)
conversion_properties = libsbml.ConversionProperties()
conversion_properties.addOption(
"convert fbc v1 to fbc v2", True, "Convert FBC-v1 model to FBC-v2"
)
result = doc.convert(conversion_properties)
if result != libsbml.LIBSBML_OPERATION_SUCCESS:
raise Exception("Conversion of SBML fbc v1 to fbc v2 failed")
# Model
model_id = model.getIdAttribute()
if not libsbml.SyntaxChecker.isValidSBMLSId(model_id):
LOGGER.error(f"'{model_id}' is not a valid SBML 'SId'.")
cobra_model = Model(model_id)
cobra_model.name = model.getName() or None
# meta information
meta = {
"model.id": model_id,
"level": model.getLevel(),
"version": model.getVersion(),
"packages": [],
}
# History
creators = []
created = None
if model.isSetModelHistory():
history: "libsbml.ModelHistory" = model.getModelHistory()
if history.isSetCreatedDate():
created = history.getCreatedDate().getDateAsString()
c: "libsbml.ModelCreator"
for c in history.getListCreators():
creators.append(
{
"familyName": c.getFamilyName() if c.isSetFamilyName() else None,
"givenName": c.getGivenName() if c.isSetGivenName() else None,
"organisation": (
c.getOrganisation() if c.isSetOrganisation() else None
),
"email": c.getEmail() if c.isSetEmail() else None,
}
)
meta["creators"] = creators
meta["created"] = created
meta["notes"] = _parse_notes_dict(doc)
meta["annotation"] = _parse_annotations(doc)
info = f"<{model_id}> SBML L{model.getLevel()}V{model.getVersion()}"
packages = {}
for k in range(doc.getNumPlugins()):
plugin: "libsbml.SBasePlugin" = doc.getPlugin(k)
key, value = plugin.getPackageName(), plugin.getPackageVersion()
packages[key] = value
info += f", {key}-v{value}"
if key not in ["fbc", "groups", "l3v2extendedmath"]:
LOGGER.warning(
f"SBML package '{key}' not supported by cobrapy, "
f"information is not parsed"
)
meta["info"] = info
meta["packages"] = packages
cobra_model._sbml = meta
# notes and annotations
cobra_model.notes = _parse_notes_dict(model)
cobra_model.annotation = _parse_annotations(model)
# Compartments
# FIXME: update with new compartments
compartments = {}
for (
compartment
) in model.getListOfCompartments(): # noqa: E501 type: libsbml.Compartment
cid = _check_required(compartment, compartment.getIdAttribute(), "id")
compartments[cid] = compartment.getName()
cobra_model.compartments = compartments
# Species
metabolites = []
boundary_metabolites = []
if model.getNumSpecies() == 0:
LOGGER.warning("No metabolites in model")
specie: "libsbml.Species"
for specie in model.getListOfSpecies():
sid = _check_required(specie, specie.getIdAttribute(), "id")
if f_replace and F_SPECIE in f_replace:
sid = f_replace[F_SPECIE](sid)
met = Metabolite(sid)
met.name = specie.getName()
met.notes = _parse_notes_dict(specie)
met.annotation = _parse_annotations(specie)
met.compartment = specie.getCompartment()
specie_fbc: "libsbml.FbcSpeciesPlugin" = specie.getPlugin("fbc")
if specie_fbc:
met.charge = specie_fbc.getCharge()
met.formula = specie_fbc.getChemicalFormula() or None
else:
if specie.isSetCharge():
LOGGER.warning(
f"Use of the species charge attribute is "
f"discouraged, use fbc:charge instead: {specie}"
)
met.charge = specie.getCharge()
else:
if "CHARGE" in met.notes:
LOGGER.warning(
f"Use of CHARGE in the notes element is "
f"discouraged, use fbc:charge instead: {specie}"
)
try:
met.charge = int(met.notes["CHARGE"])
except ValueError:
# handle nan, na, NA, ...
pass
if "FORMULA" in met.notes:
LOGGER.warning(
f"Use of FORMULA in the notes element is "
f"discouraged, use fbc:chemicalFormula instead: {specie}"
)
met.formula = met.notes["FORMULA"] or None
# Detect boundary metabolites
if specie.getBoundaryCondition() is True:
boundary_metabolites.append(met)
metabolites.append(met)
cobra_model.add_metabolites(metabolites)
# Add exchange reactions for boundary metabolites
ex_reactions = []
for met in boundary_metabolites:
ex_rid = f"EX_{met.id}"
ex_reaction = Reaction(ex_rid)
ex_reaction.name = ex_rid
ex_reaction.annotation = {"sbo": SBO_EXCHANGE_REACTION}
ex_reaction.lower_bound = config.lower_bound
ex_reaction.upper_bound = config.upper_bound
LOGGER.warning(
f"Adding exchange reaction {ex_reaction.id} with default bounds for "
f"boundary metabolite: {met.id}."
)
# species is reactant
ex_reaction.add_metabolites({met: -1})
ex_reactions.append(ex_reaction)
cobra_model.add_reactions(ex_reactions)
# Genes
if model_fbc:
for (
gp
) in model_fbc.getListOfGeneProducts(): # noqa: E501 type: libsbml.GeneProduct
gid = _check_required(gp, gp.getIdAttribute(), "id")
if f_replace and F_GENE in f_replace:
gid = f_replace[F_GENE](gid)
cobra_gene = Gene(gid)
cobra_gene.name = gp.getName()
if cobra_gene.name is None:
cobra_gene.name = gid
cobra_gene.annotation = _parse_annotations(gp)
cobra_gene.notes = _parse_notes_dict(gp)
cobra_model.genes.append(cobra_gene)
else:
for (
cobra_reaction
) in model.getListOfReactions(): # noqa: E501 type: libsbml.Reaction
# fallback to notes information
notes = _parse_notes_dict(cobra_reaction)
if "GENE ASSOCIATION" in notes:
gpr = notes["GENE ASSOCIATION"]
elif "GENE_ASSOCIATION" in notes:
gpr = notes["GENE_ASSOCIATION"]
else:
gpr = ""
if len(gpr) > 0:
gpr = gpr.replace("(", ";")
gpr = gpr.replace(")", ";")
gpr = gpr.replace("or", ";")
gpr = gpr.replace("and", ";")
# Interaction of the above replacements can lead to multiple
# ;, which results in empty gids
gids = [t.strip() for t in gpr.split(";")]
gids = set(gids).difference({""})
# create missing genes
for gid in gids:
if f_replace and F_GENE in f_replace:
gid = f_replace[F_GENE](gid)
if gid not in cobra_model.genes:
cobra_gene = Gene(gid)
cobra_gene.name = gid
cobra_model.genes.append(cobra_gene)
# GPR rules
def process_association(ass: "libsbml.FbcAssociation") -> Union[BoolOp, Name]:
"""Recursively convert gpr association to a GPR class.
Defined as inline functions to not pass the replacement dict around.
Parameters
----------
ass: libsbml.FbcAssociation
Returns
-------
BoolOp or Name
AST formatted of the FbcAssociation, which will be processed by GPR().
"""
if ass.isFbcOr():
return BoolOp(
Or(), [process_association(c) for c in ass.getListOfAssociations()]
)
elif ass.isFbcAnd():
return BoolOp(
And(), [process_association(c) for c in ass.getListOfAssociations()]
)
elif ass.isGeneProductRef():
g_id = ass.getGeneProduct()
if f_replace and F_GENE in f_replace:
return Name(id=f_replace[F_GENE](g_id))
else:
return Name(id=g_id)
# Reactions
missing_bounds = False
reactions = []
if model.getNumReactions() == 0:
LOGGER.warning("No reactions in model")
reaction: "libsbml.Reaction"
for reaction in model.getListOfReactions():
rid = _check_required(reaction, reaction.getIdAttribute(), "id")
if f_replace and F_REACTION in f_replace:
rid = f_replace[F_REACTION](rid)
cobra_reaction = Reaction(rid)
cobra_reaction.name = reaction.getName().strip()
cobra_reaction.annotation = _parse_annotations(reaction)
cobra_reaction.notes = _parse_notes_dict(reaction)
# set bounds
p_ub, p_lb = None, None
r_fbc: "libsbml.FbcReactionPlugin" = reaction.getPlugin("fbc")
if r_fbc:
# bounds in fbc
lb_id = r_fbc.getLowerFluxBound()
if lb_id:
p_lb: "libsbml.Parameter" = model.getParameter(lb_id)
if p_lb and p_lb.getConstant() and (p_lb.getValue() is not None):
cobra_reaction.lower_bound = p_lb.getValue()
else:
raise CobraSBMLError(
f"No constant bound '{p_lb}' for reaction: {reaction}"
)
ub_id = r_fbc.getUpperFluxBound()
if ub_id:
p_ub: "libsbml.Parameter" = model.getParameter(ub_id)
if p_ub and p_ub.getConstant() and (p_ub.getValue() is not None):
cobra_reaction.upper_bound = p_ub.getValue()
else:
raise CobraSBMLError(
f"No constant bound '{p_ub}' for reaction: {reaction}"
)
elif reaction.isSetKineticLaw():
# some legacy models encode bounds in kinetic laws
klaw: "libsbml.KineticLaw" = reaction.getKineticLaw()
p_lb = klaw.getParameter(
"LOWER_BOUND"
) # noqa: E501 type: libsbml.LocalParameter
if p_lb:
cobra_reaction.lower_bound = p_lb.getValue()
p_ub = klaw.getParameter(
"UPPER_BOUND"
) # noqa: E501 type: libsbml.LocalParameter
if p_ub:
cobra_reaction.upper_bound = p_ub.getValue()
if p_ub is not None or p_lb is not None:
LOGGER.warning(
f"Encoding LOWER_BOUND and UPPER_BOUND in "
f"KineticLaw is discouraged, "
f"use fbc:fluxBounds instead: {reaction}"
)
if p_lb is None:
missing_bounds = True
lower_bound = config.lower_bound
cobra_reaction.lower_bound = lower_bound
LOGGER.warning(
f"Missing lower flux bound set to '{lower_bound}' for "
f"reaction: '{reaction}'"
)
if p_ub is None:
missing_bounds = True
upper_bound = config.upper_bound
cobra_reaction.upper_bound = upper_bound
LOGGER.warning(
f"Missing upper flux bound set to '{upper_bound}' for "
f"reaction: '{reaction}'"
)
# add reaction
reactions.append(cobra_reaction)
# parse equation
stoichiometry = defaultdict(lambda: 0)
for (
sref
) in reaction.getListOfReactants(): # noqa: E501 type: libsbml.SpeciesReference
sid = _check_required(sref, sref.getSpecies(), "species")
if f_replace and F_SPECIE in f_replace:
sid = f_replace[F_SPECIE](sid)
stoichiometry[sid] -= number(
_check_required(sref, sref.getStoichiometry(), "stoichiometry")
)
for (
sref
) in reaction.getListOfProducts(): # noqa: E501 type: libsbml.SpeciesReference
sid = _check_required(sref, sref.getSpecies(), "species")
if f_replace and F_SPECIE in f_replace:
sid = f_replace[F_SPECIE](sid)
stoichiometry[sid] += number(
_check_required(sref, sref.getStoichiometry(), "stoichiometry")
)
# convert to metabolite objects
object_stoichiometry = {}
for met_id in stoichiometry:
metabolite = cobra_model.metabolites.get_by_id(met_id)
object_stoichiometry[metabolite] = stoichiometry[met_id]
cobra_reaction.add_metabolites(object_stoichiometry)
# GPR
if r_fbc:
gpr = None
gpa = (
r_fbc.getGeneProductAssociation()
) # noqa: E501 type: libsbml.GeneProductAssociation
if gpa is not None:
association = (
gpa.getAssociation()
) # noqa: E501 type: libsbml.FbcAssociation
gpr = Module(process_association(association))
cobra_reaction.gpr = GPR(gpr_from=gpr)
else:
# fallback to notes information
notes = cobra_reaction.notes
if "GENE ASSOCIATION" in notes:
gpr = notes["GENE ASSOCIATION"]
elif "GENE_ASSOCIATION" in notes:
gpr = notes["GENE_ASSOCIATION"]
else:
gpr = ""
if len(gpr) > 0:
LOGGER.warning(
f"Use of GENE ASSOCIATION or GENE_ASSOCIATION "
f"in the notes element is discouraged, use "
f"fbc:gpr instead: {reaction}"
)
if f_replace and F_GENE in f_replace:
gpr = " ".join(f_replace[F_GENE](t) for t in gpr.split(" "))
cobra_reaction.gpr = GPR.from_string(gpr)
cobra_model.add_reactions(reactions)
# Objective
obj_direction = "max"
coefficients = {}
if model_fbc:
obj_list = (
model_fbc.getListOfObjectives()
) # noqa: E501 type: libsbml.ListOfObjectives
if obj_list is None:
LOGGER.warning("listOfObjectives element not found")
elif obj_list.size() == 0:
LOGGER.warning("No objective in listOfObjectives")
elif not obj_list.getActiveObjective():
LOGGER.warning("No active objective in listOfObjectives")
else:
obj_id = obj_list.getActiveObjective()
obj: "libsbml.Objective" = model_fbc.getObjective(obj_id)
obj_direction = LONG_SHORT_DIRECTION[obj.getType()]
for (
flux_obj
) in (
obj.getListOfFluxObjectives()
): # noqa: E501 type: libsbml.FluxObjective
rid = flux_obj.getReaction()
if f_replace and F_REACTION in f_replace:
rid = f_replace[F_REACTION](rid)
try:
objective_reaction = cobra_model.reactions.get_by_id(rid)
except KeyError:
raise CobraSBMLError(f"Objective reaction '{rid}' not found")
try:
coefficients[objective_reaction] = number(flux_obj.getCoefficient())
except ValueError as e:
LOGGER.warning(str(e))
else:
# some legacy models encode objective coefficients in kinetic laws
reaction: "libsbml.Reaction"
for reaction in model.getListOfReactions():
if reaction.isSetKineticLaw():
klaw: "libsbml.KineticLaw" = reaction.getKineticLaw()
p_oc: "libsbml.LocalParameter" = klaw.getParameter(