-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathsbml_import.py
More file actions
2374 lines (2023 loc) · 92.4 KB
/
sbml_import.py
File metadata and controls
2374 lines (2023 loc) · 92.4 KB
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
-----------
This module provides all necessary functionality to import a model specified
in the `Systems Biology Markup Language (SBML) <http://sbml.org/Main_Page>`_.
"""
import copy
import itertools as itt
import logging
import math
import os
import re
import warnings
from pathlib import Path
from typing import (Any, Callable, Dict, Iterable, List, Optional, Tuple,
Union)
import libsbml as sbml
import sympy as sp
from . import has_clibs
from .constants import SymbolId
from .import_utils import (RESERVED_SYMBOLS,
_check_unsupported_functions,
_get_str_symbol_identifiers,
_parse_special_functions,
generate_measurement_symbol,
generate_regularization_symbol,
noise_distribution_to_cost_function,
noise_distribution_to_observable_transformation,
smart_subs, smart_subs_dict, toposort_symbols)
from .logging import get_logger, log_execution_time, set_log_level
from .ode_export import (
ODEExporter, ODEModel, symbol_with_assumptions, _default_simplify
)
class SBMLException(Exception):
pass
SymbolicFormula = Dict[sp.Symbol, sp.Expr]
default_symbols = {
symbol: {} for symbol in SymbolId
}
ConservationLaw = Dict[str, Union[str, sp.Expr]]
NoiseDistDict = Dict[str, Union[str, list]]
logger = get_logger(__name__, logging.ERROR)
class SbmlImporter:
"""
Class to generate AMICI C++ files for a model provided in the Systems
Biology Markup Language (SBML).
:ivar show_sbml_warnings:
indicates whether libSBML warnings should be
displayed
:ivar symbols:
dict carrying symbolic definitions
:ivar sbml_reader:
The libSBML sbml reader
.. warning::
Not storing this may result in a segfault.
:ivar sbml_doc:
document carrying the sbml definition
.. warning::
Not storing this may result in a segfault.
:ivar sbml:
SBML model to import
:ivar compartments:
dict of compartment ids and compartment volumes
:ivar stoichiometric_matrix:
stoichiometric matrix of the model
:ivar flux_vector:
reaction kinetic laws
:ivar flux_ids:
identifiers for elements of flux_vector
:ivar _local_symbols:
model symbols for sympy to consider during sympification
see `locals`argument in `sympy.sympify`
:ivar species_assignment_rules:
Assignment rules for species.
Key is symbolic identifier and value is assignment value
:ivar compartment_assignment_rules:
Assignment rules for compartments.
Key is symbolic identifier and value is assignment value
:ivar parameter_assignment_rules:
assignment rules for parameters, these parameters are not permissible
for sensitivity analysis
:ivar initial_assignments:
initial assignments for parameters, these parameters are not
permissible for sensitivity analysis
:ivar sbml_parser_settings:
sets behaviour of SBML Formula parsing
"""
def __init__(self,
sbml_source: Union[str, Path, sbml.Model],
show_sbml_warnings: bool = False,
from_file: bool = True) -> None:
"""
Create a new Model instance.
:param sbml_source:
Either a path to SBML file where the model is specified,
or a model string as created by sbml.sbmlWriter(
).writeSBMLToString() or an instance of `libsbml.Model`.
:param show_sbml_warnings:
Indicates whether libSBML warnings should be displayed.
:param from_file:
Whether `sbml_source` is a file name (True, default), or an SBML
string
"""
if isinstance(sbml_source, sbml.Model):
self.sbml_doc: sbml.Document = sbml_source.getSBMLDocument()
else:
self.sbml_reader: sbml.SBMLReader = sbml.SBMLReader()
if from_file:
sbml_doc = self.sbml_reader.readSBMLFromFile(str(sbml_source))
else:
sbml_doc = self.sbml_reader.readSBMLFromString(sbml_source)
self.sbml_doc = sbml_doc
self.show_sbml_warnings: bool = show_sbml_warnings
# process document
self._process_document()
self.sbml: sbml.Model = self.sbml_doc.getModel()
# Long and short names for model components
self.symbols: Dict[SymbolId, Dict[sp.Symbol, Dict[str, Any]]] = {}
self._local_symbols: Dict[str, Union[sp.Expr, sp.Function]] = {}
self.compartments: SymbolicFormula = {}
self.compartment_assignment_rules: SymbolicFormula = {}
self.species_assignment_rules: SymbolicFormula = {}
self.parameter_assignment_rules: SymbolicFormula = {}
self.initial_assignments: SymbolicFormula = {}
self._reset_symbols()
# http://sbml.org/Software/libSBML/5.18.0/docs/python-api/classlibsbml_1_1_l3_parser_settings.html#abcfedd34efd3cae2081ba8f42ea43f52
# all defaults except disable unit parsing
self.sbml_parser_settings = sbml.L3ParserSettings(
self.sbml, sbml.L3P_PARSE_LOG_AS_LOG10,
sbml.L3P_EXPAND_UNARY_MINUS, sbml.L3P_NO_UNITS,
sbml.L3P_AVOGADRO_IS_CSYMBOL,
sbml.L3P_COMPARE_BUILTINS_CASE_INSENSITIVE, None,
sbml.L3P_MODULO_IS_PIECEWISE
)
def _process_document(self) -> None:
"""
Validate and simplify document.
"""
# Ensure we got a valid SBML model, otherwise further processing
# might lead to undefined results
self.sbml_doc.validateSBML()
_check_lib_sbml_errors(self.sbml_doc, self.show_sbml_warnings)
# apply several model simplifications that make our life substantially
# easier
if self.sbml_doc.getModel().getNumFunctionDefinitions():
convert_config = sbml.SBMLFunctionDefinitionConverter()\
.getDefaultProperties()
self.sbml_doc.convert(convert_config)
convert_config = sbml.SBMLLocalParameterConverter().\
getDefaultProperties()
self.sbml_doc.convert(convert_config)
# If any of the above calls produces an error, this will be added to
# the SBMLError log in the sbml document. Thus, it is sufficient to
# check the error log just once after all conversion/validation calls.
_check_lib_sbml_errors(self.sbml_doc, self.show_sbml_warnings)
def _reset_symbols(self) -> None:
"""
Reset the symbols attribute to default values
"""
self.symbols = copy.deepcopy(default_symbols)
self._local_symbols = {}
def sbml2amici(
self,
model_name: str,
output_dir: Union[str, Path] = None,
observables: Dict[str, Dict[str, str]] = None,
event_observables: Dict[str, Dict[str, str]] = None,
constant_parameters: Iterable[str] = None,
sigmas: Dict[str, Union[str, float]] = None,
event_sigmas: Dict[str, Union[str, float]] = None,
noise_distributions: Optional[
Dict[str, Union[NoiseDistDict, Callable]]] = None,
event_noise_distributions: Dict[str, Union[str, Callable]] = None,
verbose: Union[int, bool] = logging.ERROR,
assume_pow_positivity: bool = False,
compiler: str = None,
allow_reinit_fixpar_initcond: bool = True,
compile: bool = True,
compute_conservation_laws: bool = True,
simplify: Optional[Callable] = _default_simplify,
cache_simplify: bool = False,
log_as_log10: bool = True,
generate_sensitivity_code: bool = True,
) -> None:
"""
Generate and compile AMICI C++ files for the model provided to the
constructor.
The resulting model can be imported as a regular Python module (if
`compile=True`), or used from Matlab or C++ as described in the
documentation of the respective AMICI interface.
Note that this generates model ODEs for changes in concentrations, not
amounts unless the `hasOnlySubstanceUnits` attribute has been
defined for a particular species.
Sensitivity analysis for local parameters is enabled by creating
global parameters _{reactionId}_{localParameterName}.
:param model_name:
name of the model/model directory
:param output_dir:
see :meth:`amici.ode_export.ODEExporter.set_paths`
:param observables:
dictionary( observableId:{'name':observableName
(optional), 'formula':formulaString)}) to be added to the model
:param event_observables:
dictionary( eventObservableId:{'name':eventObservableName
(optional), 'event':eventId, 'formula':formulaString)}) to be
added to the model
:param constant_parameters:
list of SBML Ids identifying constant parameters
:param sigmas:
dictionary(observableId: sigma value or (existing) parameter name)
:param event_sigmas:
dictionary(eventObservableId: sigma value or (existing) parameter
name)
:param noise_distributions:
dictionary(observableId: noise type).
If nothing is passed for some observable id, a normal model is
assumed as default. Either pass a noise type identifier, or a
callable generating a custom noise string.
:param event_noise_distributions:
dictionary(eventObservableId: noise type).
If nothing is passed for some observable id, a normal model is
assumed as default. Either pass a noise type identifier, or a
callable generating a custom noise string.
:param verbose:
verbosity level for logging, ``True``/``False`` default to
``logging.Error``/``logging.DEBUG``
:param assume_pow_positivity:
if set to ``True``, a special pow function is
used to avoid problems with state variables that may become
negative due to numerical errors
:param compiler:
distutils/setuptools compiler selection to build the
python extension
:param allow_reinit_fixpar_initcond:
see :class:`amici.ode_export.ODEExporter`
:param compile:
If ``True``, compile the generated Python package,
if ``False``, just generate code.
:param compute_conservation_laws:
if set to ``True``, conservation laws are automatically computed
and applied such that the state-jacobian of the ODE
right-hand-side has full rank. This option should be set to
``True`` when using the Newton algorithm to compute steadystate
sensitivities.
Conservation laws for constant species are enabled by default.
Support for conservation laws for non-constant species is
experimental and may be enabled by setting an environment variable
``AMICI_EXPERIMENTAL_SBML_NONCONST_CLS`` to either ``demartino``
to use the algorithm proposed by De Martino et al. (2014)
https://doi.org/10.1371/journal.pone.0100750, or to any other value
to use the deterministic algorithm implemented in
``conserved_moieties2.py``. In some cases, the ``demartino`` may
run for a very long time. This has been observed for example in the
case of stoichiometric coefficients with many significant digits.
:param simplify:
see :attr:`amici.ODEModel._simplify`
:param cache_simplify:
see :meth:`amici.ODEModel.__init__`
:param log_as_log10:
If ``True``, log in the SBML model will be parsed as ``log10``
(default), if ``False``, log will be parsed as natural logarithm
``ln``
:param generate_sensitivity_code:
If ``False``, the code required for sensitivity computation will
not be generated
"""
set_log_level(logger, verbose)
ode_model = self._build_ode_model(
observables=observables,
event_observables=event_observables,
constant_parameters=constant_parameters,
sigmas=sigmas,
event_sigmas=event_sigmas,
noise_distributions=noise_distributions,
event_noise_distributions=event_noise_distributions,
verbose=verbose,
compute_conservation_laws=compute_conservation_laws,
simplify=simplify,
cache_simplify=cache_simplify,
log_as_log10=log_as_log10,
)
exporter = ODEExporter(
ode_model,
model_name=model_name,
outdir=output_dir,
verbose=verbose,
assume_pow_positivity=assume_pow_positivity,
compiler=compiler,
allow_reinit_fixpar_initcond=allow_reinit_fixpar_initcond,
generate_sensitivity_code=generate_sensitivity_code
)
exporter.generate_model_code()
if compile:
if not has_clibs:
warnings.warn('AMICI C++ extensions have not been built. '
'Generated model code, but unable to compile.')
exporter.compile_model()
def _build_ode_model(
self,
observables: Dict[str, Dict[str, str]] = None,
event_observables: Dict[str, Dict[str, str]] = None,
constant_parameters: Iterable[str] = None,
sigmas: Dict[str, Union[str, float]] = None,
event_sigmas: Dict[str, Union[str, float]] = None,
noise_distributions: Optional[
Dict[str, Union[NoiseDistDict, Callable]]] = None,
event_noise_distributions: Dict[str, Union[str, Callable]] = None,
verbose: Union[int, bool] = logging.ERROR,
compute_conservation_laws: bool = True,
simplify: Optional[Callable] = _default_simplify,
cache_simplify: bool = False,
log_as_log10: bool = True,
) -> ODEModel:
"""Generate an ODEModel from this SBML model.
See :py:func:`sbml2amici` for parameters.
"""
constant_parameters = list(constant_parameters) \
if constant_parameters else []
if sigmas is None:
sigmas = {}
if event_sigmas is None:
event_sigmas = {}
if noise_distributions is None:
noise_distributions = {}
if event_noise_distributions is None:
event_noise_distributions = {}
self._reset_symbols()
self.sbml_parser_settings.setParseLog(
sbml.L3P_PARSE_LOG_AS_LOG10 if log_as_log10 else
sbml.L3P_PARSE_LOG_AS_LN
)
self._process_sbml(constant_parameters)
if self.symbols.get(SymbolId.EVENT, False):
if compute_conservation_laws:
logger.warning(
'Conservation laws are currently not supported for models '
'with events, and will be turned off.'
)
compute_conservation_laws = False
self._process_observables(
observables,
sigmas,
noise_distributions
)
self._process_event_observables(
event_observables,
event_sigmas,
event_noise_distributions
)
self._replace_compartments_with_volumes()
self._clean_reserved_symbols()
self._process_time()
ode_model = ODEModel(
verbose=verbose,
simplify=simplify,
cache_simplify=cache_simplify,
)
ode_model.import_from_sbml_importer(
self, compute_cls=compute_conservation_laws)
return ode_model
@log_execution_time('importing SBML', logger)
def _process_sbml(self, constant_parameters: List[str] = None) -> None:
"""
Read parameters, species, reactions, and so on from SBML model
:param constant_parameters:
SBML Ids identifying constant parameters
"""
self.check_support()
self._gather_locals()
self._process_parameters(constant_parameters)
self._process_compartments()
self._process_species()
self._process_reactions()
self._process_rules()
self._process_initial_assignments()
self._process_species_references()
self._process_events()
def check_support(self) -> None:
"""
Check whether all required SBML features are supported.
Also ensures that the SBML contains at least one reaction, or rate
rule, or assignment rule, to produce change in the system over time.
"""
# Check for required but unsupported SBML extensions
if self.sbml_doc.getLevel() != 3 \
and hasattr(self.sbml, 'all_elements_from_plugins') \
and self.sbml.all_elements_from_plugins.getSize():
raise SBMLException('SBML extensions are currently not supported!')
if self.sbml_doc.getLevel() == 3:
# the "required" attribute is only available in SBML Level 3
for i_plugin in range(self.sbml.getNumPlugins()):
plugin = self.sbml.getPlugin(i_plugin)
if plugin.getPackageName() in ('layout',):
# 'layout' plugin does not have the 'required' attribute
continue
if hasattr(plugin, 'getRequired') and not plugin.getRequired():
# if not "required", this has no impact on model
# simulation, and we can safely ignore it
continue
# Check if there are extension elements. If not, we can safely
# ignore the enabled package
if plugin.getListOfAllElements():
raise SBMLException(
f'Required SBML extension {plugin.getPackageName()} '
f'is currently not supported!')
if any(not rule.isAssignment() and not isinstance(
self.sbml.getElementBySId(rule.getVariable()),
(sbml.Compartment, sbml.Species, sbml.Parameter)
) for rule in self.sbml.getListOfRules()):
raise SBMLException('Algebraic rules are currently not supported, '
'and rate rules are only supported for '
'species, compartments, and parameters.')
if any(not (rule.isAssignment() or rule.isRate())
and isinstance(
self.sbml.getElementBySId(rule.getVariable()),
(sbml.Compartment, sbml.Species, sbml.Parameter)
) for rule in self.sbml.getListOfRules()):
raise SBMLException('Only assignment and rate rules are '
'currently supported for compartments, '
'species, and parameters!')
if any(r.getFast() for r in self.sbml.getListOfReactions()):
raise SBMLException('Fast reactions are currently not supported!')
# Check events for unsupported functionality
self.check_event_support()
def check_event_support(self) -> None:
"""
Check possible events in the model, as AMICI does currently not support
* delays in events
* priorities of events
* events fired at initial time
Furthermore, event triggers are optional (e.g., if an event is fired at
initial time, no trigger function is necessary).
In this case, warn that this event will have no effect.
"""
for event in self.sbml.getListOfEvents():
event_id = event.getId()
# Check for delays in events
delay = event.getDelay()
if delay is not None:
try:
delay_time = float(self._sympy_from_sbml_math(delay))
if delay_time != 0:
raise ValueError
# `TypeError` would be raised in the above `float(...)`
# if the delay is not a fixed time
except (TypeError, ValueError):
raise SBMLException('Events with execution delays are '
'currently not supported in AMICI.')
# Check for priorities
if event.getPriority() is not None:
raise SBMLException(f'Event {event_id} has a priority '
'specified. This is currently not '
'supported in AMICI.')
# check trigger
trigger_sbml = event.getTrigger()
if trigger_sbml is None:
logger.warning(f'Event {event_id} trigger has no trigger, '
'so will be skipped.')
continue
if trigger_sbml.getMath() is None:
logger.warning(f'Event {event_id} trigger has no trigger '
'expression, so a dummy trigger will be set.')
if not trigger_sbml.getPersistent():
raise SBMLException(
f'Event {event_id} has a non-persistent trigger.'
'This is currently not supported in AMICI.'
)
@log_execution_time('gathering local SBML symbols', logger)
def _gather_locals(self) -> None:
"""
Populate self.local_symbols with all model entities.
This is later used during sympifications to avoid sympy builtins
shadowing model entities as well as to avoid possibly costly
symbolic substitutions
"""
self._gather_base_locals()
self._gather_dependent_locals()
def _gather_base_locals(self):
"""
Populate self.local_symbols with pure symbol definitions that do not
depend on any other symbol.
"""
special_symbols_and_funs = {
# oo is sympy infinity
'INF': sp.oo,
'NaN': sp.nan,
'rem': sp.Mod,
'time': symbol_with_assumptions('time'),
# SBML L3 explicitly defines this value, which is not equal
# to the most recent SI definition.
'avogadro': sp.Float(6.02214179e23),
'exponentiale': sp.E,
}
for s, v in special_symbols_and_funs.items():
self.add_local_symbol(s, v)
for c in itt.chain(self.sbml.getListOfSpecies(),
self.sbml.getListOfParameters(),
self.sbml.getListOfCompartments()):
if not c.isSetId():
continue
self.add_local_symbol(c.getId(), _get_identifier_symbol(c))
for x_ref in _get_list_of_species_references(self.sbml):
if not x_ref.isSetId():
continue
if x_ref.isSetStoichiometry() and not \
self.is_assignment_rule_target(x_ref):
value = sp.Float(x_ref.getStoichiometry())
else:
value = _get_identifier_symbol(x_ref)
ia_sym = self._get_element_initial_assignment(x_ref.getId())
if ia_sym is not None:
value = ia_sym
self.add_local_symbol(x_ref.getId(), value)
for r in self.sbml.getListOfReactions():
for e in itt.chain(r.getListOfReactants(), r.getListOfProducts()):
if isinstance(e, sbml.SpeciesReference):
continue
if not (e.isSetId() and e.isSetStoichiometry()) or \
self.is_assignment_rule_target(e):
continue
self.add_local_symbol(e.getId(),
sp.Float(e.getStoichiometry()))
def _gather_dependent_locals(self):
"""
Populate self.local_symbols with symbol definitions that may depend on
other symbol definitions.
"""
for r in self.sbml.getListOfReactions():
if not r.isSetId():
continue
self.add_local_symbol(
r.getId(),
self._sympy_from_sbml_math(r.getKineticLaw())
)
def add_local_symbol(self, key: str, value: sp.Expr):
"""
Add local symbols with some sanity checking for duplication which
would indicate redefinition of internals, which SBML permits,
but we don't.
:param key:
local symbol key
:param value:
local symbol value
"""
if key in self._local_symbols.keys():
raise SBMLException(
f'AMICI tried to add a local symbol {key} with value {value}, '
f'but {key} was already instantiated with '
f'{self._local_symbols[key]}. This means that there '
f'are multiple SBML elements with SId {key}, which is '
f'invalid SBML. This can be fixed by renaming '
f'the elements with SId {key}.'
)
if key in {'True', 'False', 'true', 'false', 'pi'}:
raise SBMLException(
f'AMICI tried to add a local symbol {key} with value {value}, '
f'but {key} is a reserved symbol in AMICI. This can be fixed '
f'by renaming the element with SId {key}.'
)
self._local_symbols[key] = value
@log_execution_time('processing SBML compartments', logger)
def _process_compartments(self) -> None:
"""
Get compartment information, stoichiometric matrix and fluxes from
SBML model.
"""
compartments = self.sbml.getListOfCompartments()
self.compartments = {}
for comp in compartments:
init = sp.Float(1.0)
if comp.isSetVolume():
init = self._sympy_from_sbml_math(comp.getVolume())
ia_sym = self._get_element_initial_assignment(comp.getId())
if ia_sym is not None:
init = ia_sym
self.compartments[_get_identifier_symbol(comp)] = init
@log_execution_time('processing SBML species', logger)
def _process_species(self) -> None:
"""
Get species information from SBML model.
"""
if self.sbml.isSetConversionFactor():
conversion_factor = symbol_with_assumptions(
self.sbml.getConversionFactor()
)
else:
conversion_factor = 1
for s in self.sbml.getListOfSpecies():
if self.is_assignment_rule_target(s):
continue
self.symbols[SymbolId.SPECIES][_get_identifier_symbol(s)] = {
'name': s.getName() if s.isSetName() else s.getId(),
'compartment': _get_species_compartment_symbol(s),
'constant': s.getConstant() or s.getBoundaryCondition(),
'amount': s.getHasOnlySubstanceUnits(),
'conversion_factor': symbol_with_assumptions(
s.getConversionFactor()
)
if s.isSetConversionFactor()
else conversion_factor,
'index': len(self.symbols[SymbolId.SPECIES]),
}
self._convert_event_assignment_parameter_targets_to_species()
self._process_species_initial()
self._process_rate_rules()
@log_execution_time('processing SBML species initials', logger)
def _process_species_initial(self):
"""
Extract initial values and initial assignments from species
"""
for species_variable in self.sbml.getListOfSpecies():
initial = get_species_initial(species_variable)
species_id = _get_identifier_symbol(species_variable)
# If species_id is a target of an AssignmentRule, species will be
# None, but we don't have to account for the initial definition
# of the species itself and SBML doesn't permit AssignmentRule
# targets to have InitialAssignments.
species = self.symbols[SymbolId.SPECIES].get(species_id, None)
ia_initial = self._get_element_initial_assignment(
species_variable.getId()
)
if ia_initial is not None:
if species and species['amount'] \
and 'compartment' in species:
ia_initial *= self.compartments.get(
species['compartment'], species['compartment']
)
initial = ia_initial
if species:
species['init'] = initial
# don't assign this since they need to stay in order
sorted_species = toposort_symbols(self.symbols[SymbolId.SPECIES],
'init')
for species in self.symbols[SymbolId.SPECIES].values():
species['init'] = smart_subs_dict(species['init'],
sorted_species,
'init')
@log_execution_time('processing SBML rate rules', logger)
def _process_rate_rules(self):
"""
Process rate rules for species, compartments and parameters.
Compartments and parameters with rate rules are implemented as species.
Note that, in the case of species, rate rules may describe the change
in amount, not concentration, of a species.
"""
rules = self.sbml.getListOfRules()
# compartments with rules are replaced with constants in the relevant
# equations during the _replace_in_all_expressions call inside
# _process_rules
for rule in rules:
if rule.getTypeCode() != sbml.SBML_RATE_RULE:
continue
variable = symbol_with_assumptions(rule.getVariable())
formula = self._sympy_from_sbml_math(rule)
if formula is None:
continue
# Species rules are processed first, to avoid processing
# compartments twice (as compartments with rate rules are
# implemented as species).
ia_init = self._get_element_initial_assignment(rule.getVariable())
if variable in self.symbols[SymbolId.SPECIES]:
init = self.symbols[SymbolId.SPECIES][variable]['init']
name = None
if variable in self.compartments:
init = self.compartments[variable]
name = str(variable)
del self.compartments[variable]
elif variable in self.symbols[SymbolId.PARAMETER]:
init = self._sympy_from_sbml_math(
self.symbols[SymbolId.PARAMETER][variable]['value'],
)
name = self.symbols[SymbolId.PARAMETER][variable]['name']
del self.symbols[SymbolId.PARAMETER][variable]
# parameter with initial assignment, cannot use
# self.initial_assignments as it is not filled at this
# point
elif ia_init is not None:
init = ia_init
par = self.sbml.getElementBySId(rule.getVariable())
name = par.getName() if par.isSetName() else par.getId()
self.add_d_dt(formula, variable, init, name)
def add_d_dt(
self,
d_dt: sp.Expr,
variable: sp.Symbol,
variable0: Union[float, sp.Expr],
name: str,
) -> None:
"""
Creates or modifies species, to implement rate rules for
compartments and species, respectively.
:param d_dt:
The rate rule (or, right-hand side of an ODE).
:param variable:
The subject of the rate rule.
:param variable0:
The initial value of the variable.
:param name:
Species name, only applicable if this function generates a new
species
"""
if variable in self.symbols[SymbolId.SPECIES]:
# only update dt if species was already generated
self.symbols[SymbolId.SPECIES][variable]['dt'] = d_dt
else:
# update initial values
for species_id, species in self.symbols[SymbolId.SPECIES].items():
variable0 = smart_subs(variable0, species_id, species['init'])
for species in self.symbols[SymbolId.SPECIES].values():
species['init'] = smart_subs(species['init'],
variable, variable0)
# add compartment/parameter species
self.symbols[SymbolId.SPECIES][variable] = {
'name': name,
'init': variable0,
'amount': False,
'conversion_factor': 1.0,
'constant': False,
'index': len(self.symbols[SymbolId.SPECIES]),
'dt': d_dt,
}
@log_execution_time('processing SBML parameters', logger)
def _process_parameters(self,
constant_parameters: List[str] = None) -> None:
"""
Get parameter information from SBML model.
:param constant_parameters:
SBML Ids identifying constant parameters
"""
if constant_parameters is None:
constant_parameters = []
# Ensure specified constant parameters exist in the model
for parameter in constant_parameters:
if not self.sbml.getParameter(parameter):
raise KeyError('Cannot make %s a constant parameter: '
'Parameter does not exist.' % parameter)
fixed_parameters = [
parameter
for parameter in self.sbml.getListOfParameters()
if parameter.getId() in constant_parameters
]
for parameter in fixed_parameters:
if self._get_element_initial_assignment(parameter.getId()) is not \
None or self.is_assignment_rule_target(parameter) or \
self.is_rate_rule_target(parameter):
raise SBMLException(
f'Cannot turn parameter {parameter.getId()} into a '
'constant/fixed parameter since it either has an '
'initial assignment or is the target of an assignment or '
'rate rule.'
)
parameters = [
parameter for parameter
in self.sbml.getListOfParameters()
if parameter.getId() not in constant_parameters
and self._get_element_initial_assignment(parameter.getId()) is None
and not self.is_assignment_rule_target(parameter)
]
loop_settings = {
SymbolId.PARAMETER: {'var': parameters, 'name': 'parameter'},
SymbolId.FIXED_PARAMETER: {'var': fixed_parameters,
'name': 'fixed_parameter'}
}
for partype, settings in loop_settings.items():
for par in settings['var']:
self.symbols[partype][_get_identifier_symbol(par)] = {
'name': par.getName() if par.isSetName() else par.getId(),
'value': par.getValue()
}
@log_execution_time('processing SBML reactions', logger)
def _process_reactions(self):
"""
Get reactions from SBML model.
"""
reactions = self.sbml.getListOfReactions()
# nr (number of reactions) should have a minimum length of 1. This is
# to ensure that, if there are no reactions, the stoichiometric matrix
# and flux vector multiply to a zero vector with dimensions (nx, 1).
nr = max(1, len(reactions))
nx = len(self.symbols[SymbolId.SPECIES])
# stoichiometric matrix
self.stoichiometric_matrix = sp.SparseMatrix(sp.zeros(nx, nr))
self.flux_vector = sp.zeros(nr, 1)
# Use reaction IDs as IDs for flux expressions (note that prior to SBML
# level 3 version 2 the ID attribute was not mandatory and may be
# unset)
self.flux_ids = [
f"flux_{reaction.getId()}" if reaction.isSetId()
else f"flux_r{reaction_idx}"
for reaction_idx, reaction in enumerate(reactions)
] or ['flux_r0']
reaction_ids = [
reaction.getId() for reaction in reactions
if reaction.isSetId()
]
for reaction_index, reaction in enumerate(reactions):
for element_list, sign in [(reaction.getListOfReactants(), -1),
(reaction.getListOfProducts(), 1)]:
for element in element_list:
stoichiometry = self._get_element_stoichiometry(
element
)
sbml_species = self.sbml.getSpecies(element.getSpecies())
if self.is_assignment_rule_target(sbml_species):
continue
species_id = _get_identifier_symbol(sbml_species)
species = self.symbols[SymbolId.SPECIES][species_id]
if species['constant']:
continue
# Division by species compartment size (to find the
# rate of change in species concentration) now occurs
# in the `dx_dt` method in "ode_export.py", which also
# accounts for possibly variable compartments.
self.stoichiometric_matrix[species['index'],
reaction_index] += \
sign * stoichiometry * species['conversion_factor']
if reaction.isSetId():
sym_math = self._local_symbols[reaction.getId()]
else:
sym_math = self._sympy_from_sbml_math(reaction.getKineticLaw())
self.flux_vector[reaction_index] = sym_math
if any(
str(symbol) in reaction_ids
for symbol in self.flux_vector[reaction_index].free_symbols
):
raise SBMLException(
'Kinetic laws involving reaction ids are currently'
' not supported!'
)
@log_execution_time('processing SBML rules', logger)
def _process_rules(self) -> None:
"""
Process Rules defined in the SBML model.
"""
for rule in self.sbml.getListOfRules():
# rate rules are processed in _process_species
if rule.getTypeCode() == sbml.SBML_RATE_RULE:
continue
sbml_var = self.sbml.getElementBySId(rule.getVariable())
sym_id = symbol_with_assumptions(rule.getVariable())
formula = self._sympy_from_sbml_math(rule)
if formula is None:
continue
if isinstance(sbml_var, sbml.Species):
self.species_assignment_rules[sym_id] = formula