forked from AMICI-dev/AMICI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsbml_import.py
More file actions
3526 lines (3081 loc) · 133 KB
/
sbml_import.py
File metadata and controls
3526 lines (3081 loc) · 133 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) <https://sbml.org/>`_.
"""
import copy
import itertools as itt
import logging
import math
import os
import re
import warnings
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import (
Any,
)
from collections.abc import Callable
from collections.abc import Iterable, Sequence
import libsbml
from sbmlmath import SBMLMathMLParser, TimeSymbol, avogadro
import numpy as np
import sympy as sp
from sympy.logic.boolalg import BooleanFalse, BooleanTrue, BooleanFunction
from . import has_clibs
from .de_model import DEModel
from .constants import SymbolId
from .de_export import (
DEExporter,
)
from .de_model_components import symbol_to_type, Expression
from .sympy_utils import smart_is_zero_matrix, smart_multiply
from .import_utils import (
RESERVED_SYMBOLS,
_check_unsupported_functions,
_get_str_symbol_identifiers,
amici_time_symbol,
annotation_namespace,
generate_measurement_symbol,
generate_regularization_symbol,
noise_distribution_to_cost_function,
noise_distribution_to_observable_transformation,
sbml_time_symbol,
smart_subs,
smart_subs_dict,
symbol_with_assumptions,
toposort_symbols,
_default_simplify,
generate_flux_symbol,
_parse_piecewise_to_heaviside,
_xor_to_or,
)
from .logging import get_logger, log_execution_time, set_log_level
from .sbml_utils import SBMLException
from .splines import AbstractSpline
from sympy.matrices.dense import MutableDenseMatrix
SymbolicFormula = dict[sp.Symbol, sp.Expr]
default_symbols = {symbol: {} for symbol in SymbolId}
ConservationLaw = dict[str, str | sp.Expr]
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: str | Path | libsbml.Model,
show_sbml_warnings: bool = False,
from_file: bool = True,
discard_annotations: bool = False,
) -> 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
:param discard_annotations:
discard information contained in AMICI SBML annotations (debug).
"""
if isinstance(sbml_source, libsbml.Model):
self.sbml_doc: libsbml.Document = sbml_source.getSBMLDocument()
else:
self.sbml_reader: libsbml.SBMLReader = libsbml.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: libsbml.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, 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.splines: list[AbstractSpline] = []
self._reset_symbols()
# https://sbml.org/software/libsbml/5.18.0/docs/formatted/python-api/classlibsbml_1_1_l3_parser_settings.html#ab30d7ed52ca24cbb842d0a7fed7f4bfd
# all defaults except disable unit parsing
self.sbml_parser_settings = libsbml.L3ParserSettings()
self.sbml_parser_settings.setModel(self.sbml)
self.sbml_parser_settings.setParseUnits(libsbml.L3P_NO_UNITS)
self._discard_annotations: bool = discard_annotations
self._mathml_parser = SBMLMathMLParser(
sbml_level=self.sbml.getLevel(),
sbml_version=self.sbml.getVersion(),
symbol_kwargs={"real": True},
ignore_units=True,
evaluate=True,
)
@log_execution_time("loading SBML", logger)
def _process_document(self) -> None:
"""
Validate and simplify document.
"""
# Ensure we got a valid SBML model, otherwise further processing
# might lead to undefined results
log_execution_time("validating SBML", logger)(
self.sbml_doc.validateSBML
)()
_check_lib_sbml_errors(self.sbml_doc, self.show_sbml_warnings)
# Flatten "comp" model? Do that before any other converters are run
if any(
self.sbml_doc.getPlugin(i_plugin).getPackageName() == "comp"
for i_plugin in range(self.sbml_doc.getNumPlugins())
):
# see libsbml CompFlatteningConverter for options
conversion_properties = libsbml.ConversionProperties()
conversion_properties.addOption("flatten comp", True)
conversion_properties.addOption("leave_ports", False)
conversion_properties.addOption("performValidation", False)
conversion_properties.addOption("abortIfUnflattenable", "none")
if (
log_execution_time("flattening hierarchical SBML", logger)(
self.sbml_doc.convert
)(conversion_properties)
!= libsbml.LIBSBML_OPERATION_SUCCESS
):
raise SBMLException(
"Required SBML comp extension is currently not supported "
"and flattening the model failed."
)
# check the flattened model is still valid
log_execution_time("re-validating SBML", logger)(
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 = libsbml.SBMLFunctionDefinitionConverter().getDefaultProperties()
log_execution_time("converting SBML functions", logger)(
self.sbml_doc.convert
)(convert_config)
convert_config = (
libsbml.SBMLLocalParameterConverter().getDefaultProperties()
)
log_execution_time("converting SBML local parameters", logger)(
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)
# need to reload the converted model
self.sbml = self.sbml_doc.getModel()
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: str | Path = None,
observables: dict[str, dict[str, str | sp.Expr]] = None,
event_observables: dict[str, dict[str, str | sp.Expr]] = None,
constant_parameters: Iterable[str] = None,
sigmas: dict[str, str | float | sp.Expr] = None,
event_sigmas: dict[str, str | float | sp.Expr] = None,
noise_distributions: dict[str, str | Callable] = None,
event_noise_distributions: dict[str, str | Callable] = None,
verbose: 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: Callable | None = _default_simplify,
cache_simplify: bool = False,
log_as_log10: bool = None,
generate_sensitivity_code: bool = True,
hardcode_symbols: Sequence[str] = None,
) -> 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 in the SBML model for a particular species.
Sensitivity analysis for local parameters is enabled by creating
global parameters ``_{reactionId}_{localParameterName}``.
.. note::
When providing expressions for (event) observables and their sigmas
as strings (see below), those will be passed to
:func:`sympy.sympify`. The supported grammar is not well defined.
Note there can be issues with, for example, ``==`` or n-ary (n>2)
comparison operators.
Also note that operator precedence and function names may differ
from SBML L3 formulas or PEtab math expressions.
Passing a sympy expression directly will
be the safer option for more complex expressions.
.. note::
In any math expressions passed to this function, ``time`` will
be interpreted as the time symbol.
:param model_name:
Name of the generated model package.
Note that in a given Python session, only one model with a given
name can be loaded at a time.
The generated Python extensions cannot be unloaded. Therefore,
make sure to choose a unique name for each model.
:param output_dir:
Directory where the generated model package will be stored.
:param observables:
Observables to be added to the model:
.. code-block::
dict(
observableId: {
'name': observableName, # optional
'formula': formulaString or sympy expression,
}
)
If the observation function is passed as a string,
it will be passed to :func:`sympy.sympify` (see note above).
:param event_observables:
Event observables to be added to the model:
.. code-block::
dict(
eventObservableId: {
'name': eventObservableName, # optional
'event':eventId,
'formula': formulaString or sympy expression,
}
)
If the formula is passed as a string, it will be passed to
:func:`sympy.sympify` (see note above).
:param constant_parameters:
list of SBML Ids identifying constant parameters
:param sigmas:
Expression for the scale parameter of the noise distribution for
each observable. This can be a numeric value, a sympy expression,
or an expression string that will be passed to
:func:`sympy.sympify`.
``{observableId: sigma}``
:param event_sigmas:
Expression for the scale parameter of the noise distribution for
each observable. This can be a numeric value, a sympy expression,
or an expression string that will be passed to
:func:`sympy.sympify`.
``{eventObservableId: sigma}``
: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.
For noise identifiers, see
:func:`amici.import_utils.noise_distribution_to_cost_function`.
: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.
For noise identifiers, see
:func:`amici.import_utils.noise_distribution_to_cost_function`.
:param verbose:
Verbosity level for logging, ``True``/``False`` defaults 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:
Absolute path to the compiler executable to be used to build the Python
extension, e.g. ``/usr/bin/clang``.
:param allow_reinit_fixpar_initcond:
See :class:`amici.de_export.DEExporter`.
: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.DEModel._simplify`.
:param cache_simplify:
See :meth:`amici.DEModel.__init__`.
:param log_as_log10:
This option is deprecated and will be removed in a future version.
Also, this option never had any effect on model import.
:param generate_sensitivity_code:
If ``False``, the code required for sensitivity computation will
not be generated.
:param hardcode_symbols:
List of SBML entity IDs that are to be hardcoded in the generated model.
Their values cannot be changed anymore after model import.
Currently, only parameters that are not targets of rules or
initial assignments are supported.
"""
set_log_level(logger, verbose)
if log_as_log10 is not None:
# deprecated 04/2025
warnings.warn(
"The `log_as_log10` argument is deprecated and will be "
"removed in a future version. This argument can safely be "
"dropped without replacement.",
category=DeprecationWarning,
stacklevel=2,
)
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,
hardcode_symbols=hardcode_symbols,
)
exporter = DEExporter(
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.",
stacklevel=2,
)
exporter.compile_model()
def sbml2jax(
self,
model_name: str,
output_dir: str | Path = None,
observables: dict[str, dict[str, str]] = None,
sigmas: dict[str, str | float] = None,
noise_distributions: dict[str, str | Callable] = None,
verbose: int | bool = logging.ERROR,
compute_conservation_laws: bool = True,
simplify: Callable | None = _default_simplify,
cache_simplify: bool = False,
log_as_log10: bool = None,
) -> None:
"""
Generate and compile AMICI jax files for the model provided to the
constructor.
The resulting model can be imported as a regular Python module.
Note that this generates model ODEs for changes in concentrations, not
amounts unless the `hasOnlySubstanceUnits` attribute has been
defined for a particular species.
:param model_name:
Name of the generated model package.
Note that in a given Python session, only one model with a given
name can be loaded at a time.
The generated Python extensions cannot be unloaded. Therefore,
make sure to choose a unique name for each model.
:param output_dir:
Directory where the generated model package will be stored.
:param observables:
Observables to be added to the model:
``dictionary( observableId:{'name':observableName
(optional), 'formula':formulaString)})``.
:param sigmas:
dictionary(observableId: 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.
For noise identifiers, see
:func:`amici.import_utils.noise_distribution_to_cost_function`.
:param verbose:
verbosity level for logging, ``True``/``False`` default to
``logging.Error``/``logging.DEBUG``
: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.DEModel._simplify`
:param cache_simplify:
see :meth:`amici.DEModel.__init__`
:param log_as_log10:
This option is deprecated and will be removed in a future version.
Also, this option never had any effect on model import.
"""
set_log_level(logger, verbose)
if log_as_log10 is not None:
warnings.warn(
"The `log_as_log10` argument is deprecated and will be "
"removed in a future version. This argument can safely be "
"dropped without replacement.",
category=DeprecationWarning,
stacklevel=2,
)
ode_model = self._build_ode_model(
observables=observables,
sigmas=sigmas,
noise_distributions=noise_distributions,
verbose=verbose,
compute_conservation_laws=compute_conservation_laws,
simplify=simplify,
cache_simplify=cache_simplify,
)
from amici.jax.ode_export import ODEExporter
exporter = ODEExporter(
ode_model,
model_name=model_name,
outdir=output_dir,
verbose=verbose,
)
exporter.generate_model_code()
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, str | float] = None,
event_sigmas: dict[str, str | float] = None,
noise_distributions: dict[str, str | Callable] = None,
event_noise_distributions: dict[str, str | Callable] = None,
verbose: int | bool = logging.ERROR,
compute_conservation_laws: bool = True,
simplify: Callable | None = _default_simplify,
cache_simplify: bool = False,
hardcode_symbols: Sequence[str] = None,
) -> DEModel:
"""Generate a DEModel from this SBML model.
See :py:func:`sbml2amici` for parameters.
"""
constant_parameters = (
list(constant_parameters) if constant_parameters else []
)
hardcode_symbols = set(hardcode_symbols) if hardcode_symbols else {}
if invalid := (set(constant_parameters) & set(hardcode_symbols)):
raise ValueError(
"The following parameters were selected as both constant "
f"and hard-coded which is not allowed: {invalid}"
)
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._process_sbml(
constant_parameters=constant_parameters,
hardcode_symbols=hardcode_symbols,
)
if (
self.symbols.get(SymbolId.EVENT, False)
or any(
x["value"].has(sp.Heaviside, sp.Piecewise)
for x in self.symbols[SymbolId.EXPRESSION].values()
)
or self.flux_vector.has(sp.Heaviside, sp.Piecewise)
):
if compute_conservation_laws:
logger.warning(
"Conservation laws are currently not supported for models "
"with events, piecewise or Heaviside functions, "
"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 = DEModel(
verbose=verbose,
simplify=simplify,
cache_simplify=cache_simplify,
)
ode_model._has_quadratic_nllh = all(
llh["dist"]
in ["normal", "lin-normal", "log-normal", "log10-normal"]
for llh in self.symbols[SymbolId.LLHY].values()
)
# add splines as expressions to the model
# saved for later substituting into the fluxes
spline_subs = {}
for ispl, spl in enumerate(self.splines):
spline_expr = spl.ode_model_symbol(self)
spline_subs[spl.sbml_id] = spline_expr
ode_model.add_spline(spl, spline_expr)
# assemble fluxes and add them as expressions to the model
assert len(self.flux_ids) == len(self.flux_vector)
fluxes = [
generate_flux_symbol(ir, name=flux_id)
for ir, flux_id in enumerate(self.flux_ids)
]
# create dynamics without respecting conservation laws first
dxdt = smart_multiply(
self.stoichiometric_matrix, MutableDenseMatrix(fluxes)
)
# dxdt has algebraic states at the end
assert dxdt.shape[0] - len(self.symbols[SymbolId.SPECIES]) == len(
self.symbols.get(SymbolId.ALGEBRAIC_STATE, [])
), (
self.symbols.get(SymbolId.SPECIES),
dxdt,
self.symbols.get(SymbolId.ALGEBRAIC_STATE),
)
# correct time derivatives for compartment changes
for ix, ((species_id, species), formula) in enumerate(
zip(self.symbols[SymbolId.SPECIES].items(), dxdt, strict=False)
):
# rate rules and amount species don't need to be updated
if "dt" in species:
continue
if species["amount"]:
species["dt"] = formula
else:
species["dt"] = self._transform_dxdt_to_concentration(
species_id, formula
)
# create all basic components of the DE model and add them.
for symbol_name in self.symbols:
# transform dict of lists into a list of dicts
args = ["name", "identifier"]
if symbol_name == SymbolId.SPECIES:
args += ["dt", "init"]
elif symbol_name == SymbolId.ALGEBRAIC_STATE:
args += ["init"]
else:
args += ["value"]
if symbol_name == SymbolId.EVENT:
args += ["state_update", "initial_value"]
elif symbol_name == SymbolId.OBSERVABLE:
args += ["transformation"]
elif symbol_name == SymbolId.EVENT_OBSERVABLE:
args += ["event"]
comp_kwargs = [
{
"identifier": var_id,
**{k: v for k, v in var.items() if k in args},
}
for var_id, var in self.symbols[symbol_name].items()
]
for comp_kwarg in comp_kwargs:
ode_model.add_component(
symbol_to_type[symbol_name](**comp_kwarg)
)
# add fluxes as expressions, this needs to happen after base
# expressions from symbols have been parsed
for flux_id, flux in zip(fluxes, self.flux_vector, strict=True):
# replace splines inside fluxes
flux = flux.subs(spline_subs)
ode_model.add_component(
Expression(identifier=flux_id, name=str(flux_id), value=flux)
)
if compute_conservation_laws:
self._process_conservation_laws(ode_model)
# fill in 'self._sym' based on prototypes and components in ode_model
ode_model.generate_basic_variables()
# substitute SBML-rateOf constructs
ode_model._process_sbml_rate_of()
return ode_model
@log_execution_time("importing SBML", logger)
def _process_sbml(
self,
constant_parameters: list[str] = None,
hardcode_symbols: Sequence[str] = None,
) -> None:
"""
Read parameters, species, reactions, and so on from SBML model
:param constant_parameters:
SBML Ids identifying constant parameters
:param hardcode_symbols:
Parameter IDs to be replaced by their values in the generated model.
"""
if not self._discard_annotations:
self._process_annotations()
self.check_support()
self._gather_locals(hardcode_symbols=hardcode_symbols)
self._process_parameters(
constant_parameters=constant_parameters,
hardcode_symbols=hardcode_symbols,
)
self._process_compartments()
self._process_species()
self._process_reactions()
self._process_rules()
self._process_events()
self._process_initial_assignments()
self._process_species_references()
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 (
self.sbml_doc.getPkgRequired(plugin.getPackageName())
is False
):
# if not "required", this has no impact on model
# simulation, and we can safely ignore it
if (
plugin.getPackageName() == "fbc"
and plugin.getListOfAllElements()
):
# fbc is labeled not-required, but in fact it is.
# we don't care about the extra attributes of core
# elements, such as fbc:chemicalFormula, but we can't
# do anything meaningful with fbc:objective or
# fbc:fluxBounds
raise SBMLException(
"The following fbc extension elements are "
"currently not supported: "
+ ", ".join(
list(map(str, plugin.getListOfAllElements()))
)
)
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(
rule.isRate()
and not isinstance(
self.sbml.getElementBySId(rule.getVariable()),
libsbml.Compartment | libsbml.Species | libsbml.Parameter,
)
for rule in self.sbml.getListOfRules()
):
raise SBMLException(
"Rate rules are only supported for "
"species, compartments, 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._sympify(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, hardcode_symbols: Sequence[str] = None) -> 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(hardcode_symbols=hardcode_symbols)
self._gather_dependent_locals()
def _gather_base_locals(
self, hardcode_symbols: Sequence[str] = None
) -> None:
"""
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": sbml_time_symbol,
# SBML L3 explicitly defines this value, which is not equal
# to the most recent SI definition.
"avogadro": sp.Float(6.02214179e23),
"exponentiale": sp.E,
"log10": lambda x: sp.log(x, 10),
}
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