-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathode_export.py
3724 lines (3132 loc) · 127 KB
/
ode_export.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
"""
C++ Export
----------
This module provides all necessary functionality specify an ODE model and
generate executable C++ simulation code. The user generally won't have to
directly call any function from this module as this will be done by
:py:func:`amici.pysb_import.pysb2amici`,
:py:func:`amici.sbml_import.SbmlImporter.sbml2amici` and
:py:func:`amici.petab_import.import_model`.
"""
import sympy as sp
import numpy as np
import re
import shutil
import subprocess
import sys
import os
import copy
import numbers
import logging
import itertools
import contextlib
try:
import pysb
except ImportError:
pysb = None
from typing import (
Callable, Optional, Union, List, Dict, Tuple, SupportsFloat, Sequence,
Set, Any
)
from dataclasses import dataclass
from string import Template
from sympy.matrices.immutable import ImmutableDenseMatrix
from sympy.matrices.dense import MutableDenseMatrix
from sympy.logic.boolalg import BooleanAtom
from itertools import chain
from .cxxcodeprinter import AmiciCxxCodePrinter, get_switch_statement
from . import (
amiciSwigPath, amiciSrcPath, amiciModulePath, __version__, __commit__,
sbml_import
)
from .logging import get_logger, log_execution_time, set_log_level
from .constants import SymbolId
from .import_utils import smart_subs_dict, toposort_symbols, \
ObservableTransformation
# Template for model simulation main.cpp file
CXX_MAIN_TEMPLATE_FILE = os.path.join(amiciSrcPath, 'main.template.cpp')
# Template for model/swig/CMakeLists.txt
SWIG_CMAKE_TEMPLATE_FILE = os.path.join(amiciSwigPath,
'CMakeLists_model.cmake')
# Template for model/CMakeLists.txt
MODEL_CMAKE_TEMPLATE_FILE = os.path.join(amiciSrcPath,
'CMakeLists.template.cmake')
@dataclass
class _FunctionInfo:
"""Information on a model-specific generated C++ function
:ivar arguments: argument list of the function. input variables should be
``const``.
:ivar return_type: the return type of the function
:ivar assume_pow_positivity:
identifies the functions on which ``assume_pow_positivity`` will have
an effect when specified during model generation. generally these are
functions that are used for solving the ODE, where negative values may
negatively affect convergence of the integration algorithm
:ivar sparse:
specifies whether the result of this function will be stored in sparse
format. sparse format means that the function will only return an
array of nonzero values and not a full matrix.
:ivar generate_body:
indicates whether a model-specific implementation is to be generated
:ivar body:
the actual function body. will be filled later
"""
arguments: str = ''
return_type: str = 'void'
assume_pow_positivity: bool = False
sparse: bool = False
generate_body: bool = True
body: str = ''
# Information on a model-specific generated C++ function
# prototype for generated C++ functions, keys are the names of functions
functions = {
'Jy':
_FunctionInfo(
'realtype *Jy, const int iy, const realtype *p, '
'const realtype *k, const realtype *y, const realtype *sigmay, '
'const realtype *my'
),
'dJydsigma':
_FunctionInfo(
'realtype *dJydsigma, const int iy, const realtype *p, '
'const realtype *k, const realtype *y, const realtype *sigmay, '
'const realtype *my'
),
'dJydy':
_FunctionInfo(
'realtype *dJydy, const int iy, const realtype *p, '
'const realtype *k, const realtype *y, '
'const realtype *sigmay, const realtype *my',
sparse=True
),
'root':
_FunctionInfo(
'realtype *root, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h'
),
'dwdp':
_FunctionInfo(
'realtype *dwdp, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *w, const realtype *tcl, const realtype *dtcldp',
assume_pow_positivity=True, sparse=True
),
'dwdx':
_FunctionInfo(
'realtype *dwdx, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *w, const realtype *tcl',
assume_pow_positivity=True, sparse=True
),
'dwdw':
_FunctionInfo(
'realtype *dwdw, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *w, const realtype *tcl',
assume_pow_positivity=True, sparse=True
),
'dxdotdw':
_FunctionInfo(
'realtype *dxdotdw, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *w',
assume_pow_positivity=True, sparse=True
),
'dxdotdx_explicit':
_FunctionInfo(
'realtype *dxdotdx_explicit, const realtype t, '
'const realtype *x, const realtype *p, const realtype *k, '
'const realtype *h, const realtype *w',
assume_pow_positivity=True, sparse=True
),
'dxdotdp_explicit':
_FunctionInfo(
'realtype *dxdotdp_explicit, const realtype t, '
'const realtype *x, const realtype *p, const realtype *k, '
'const realtype *h, const realtype *w',
assume_pow_positivity=True, sparse=True
),
'dydx':
_FunctionInfo(
'realtype *dydx, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *w, const realtype *dwdx',
),
'dydp':
_FunctionInfo(
'realtype *dydp, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const int ip, const realtype *w, const realtype *dtcldp',
),
'dsigmaydp':
_FunctionInfo(
'realtype *dsigmaydp, const realtype t, const realtype *p, '
'const realtype *k, const int ip',
),
'sigmay':
_FunctionInfo(
'realtype *sigmay, const realtype t, const realtype *p, '
'const realtype *k',
),
'sroot':
_FunctionInfo(
'realtype *stau, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *sx, const int ip, const int ie',
generate_body=False
),
'drootdt':
_FunctionInfo(generate_body=False),
'drootdt_total':
_FunctionInfo(generate_body=False),
'drootdp':
_FunctionInfo(generate_body=False),
'drootdx':
_FunctionInfo(generate_body=False),
'stau':
_FunctionInfo(
'realtype *stau, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *sx, const int ip, const int ie'
),
'deltax':
_FunctionInfo(
'double *deltax, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const int ie, const realtype *xdot, const realtype *xdot_old'
),
'ddeltaxdx':
_FunctionInfo(generate_body=False),
'ddeltaxdt':
_FunctionInfo(generate_body=False),
'ddeltaxdp':
_FunctionInfo(generate_body=False),
'deltasx':
_FunctionInfo(
'realtype *deltasx, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *w, const int ip, const int ie, '
'const realtype *xdot, const realtype *xdot_old, '
'const realtype *sx, const realtype *stau'
),
'w':
_FunctionInfo(
'realtype *w, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, '
'const realtype *h, const realtype *tcl',
assume_pow_positivity=True
),
'x0':
_FunctionInfo(
'realtype *x0, const realtype t, const realtype *p, '
'const realtype *k'
),
'x0_fixedParameters':
_FunctionInfo(
'realtype *x0_fixedParameters, const realtype t, '
'const realtype *p, const realtype *k, '
'gsl::span<const int> reinitialization_state_idxs',
),
'sx0':
_FunctionInfo(
'realtype *sx0, const realtype t,const realtype *x, '
'const realtype *p, const realtype *k, const int ip',
),
'sx0_fixedParameters':
_FunctionInfo(
'realtype *sx0_fixedParameters, const realtype t, '
'const realtype *x0, const realtype *p, const realtype *k, '
'const int ip, gsl::span<const int> reinitialization_state_idxs',
),
'xdot':
_FunctionInfo(
'realtype *xdot, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, const realtype *h, '
'const realtype *w',
assume_pow_positivity=True
),
'xdot_old':
_FunctionInfo(generate_body=False),
'y':
_FunctionInfo(
'realtype *y, const realtype t, const realtype *x, '
'const realtype *p, const realtype *k, '
'const realtype *h, const realtype *w',
),
'x_rdata':
_FunctionInfo(
'realtype *x_rdata, const realtype *x, const realtype *tcl'
),
'total_cl':
_FunctionInfo('realtype *total_cl, const realtype *x_rdata'),
'x_solver':
_FunctionInfo('realtype *x_solver, const realtype *x_rdata')
}
# list of sparse functions
sparse_functions = [
func_name for func_name, func_info in functions.items()
if func_info.sparse
]
# list of nobody functions
nobody_functions = [
func_name for func_name, func_info in functions.items()
if not func_info.generate_body
]
# list of sensitivity functions
sensi_functions = [
func_name for func_name, func_info in functions.items()
if 'const int ip' in func_info.arguments
]
# list of sensitivity functions
sparse_sensi_functions = [
func_name for func_name, func_info in functions.items()
if 'const int ip' not in func_info.arguments
and func_name.endswith('dp') or func_name.endswith('dp_explicit')
]
# list of event functions
event_functions = [
func_name for func_name, func_info in functions.items()
if 'const int ie' in func_info.arguments and
'const int ip' not in func_info.arguments
]
event_sensi_functions = [
func_name for func_name, func_info in functions.items()
if 'const int ie' in func_info.arguments and
'const int ip' in func_info.arguments
]
# list of multiobs functions
multiobs_functions = [
func_name for func_name, func_info in functions.items()
if 'const int iy' in func_info.arguments
]
# list of equations that have ids which may not be unique
non_unique_id_symbols = [
'x_rdata', 'y'
]
# custom c++ function replacements
CUSTOM_FUNCTIONS = [
{'sympy': 'polygamma',
'c++': 'boost::math::polygamma',
'include': '#include <boost/math/special_functions/polygamma.hpp>',
'build_hint': 'Using polygamma requires libboost-math header files.'
},
{'sympy': 'Heaviside',
'c++': 'amici::heaviside'},
{'sympy': 'DiracDelta',
'c++': 'amici::dirac'}
]
# python log manager
logger = get_logger(__name__, logging.ERROR)
def var_in_function_signature(name: str, varname: str) -> bool:
"""
Checks if the values for a symbolic variable is passed in the signature
of a function
:param name:
name of the function
:param varname:
name of the symbolic variable
:return:
boolean indicating whether the variable occurs in the function
signature
"""
return name in functions \
and re.search(
rf'const (realtype|double) \*{varname}[0]*(,|$)+',
functions[name].arguments
)
class ModelQuantity:
"""
Base class for model components
"""
def __init__(self,
identifier: sp.Symbol,
name: str,
value: Union[SupportsFloat, numbers.Number, sp.Expr]):
"""
Create a new ModelQuantity instance.
:param identifier:
unique identifier of the quantity
:param name:
individual name of the quantity (does not need to be unique)
:param value:
either formula, numeric value or initial value
"""
if not isinstance(identifier, sp.Symbol):
raise TypeError(f'identifier must be sympy.Symbol, was '
f'{type(identifier)}')
self._identifier: sp.Symbol = identifier
if not isinstance(name, str):
raise TypeError(f'name must be str, was {type(name)}')
self._name: str = name
self._value: sp.Expr = cast_to_sym(value, 'value')
def __repr__(self) -> str:
"""
Representation of the ModelQuantity object
:return:
string representation of the ModelQuantity
"""
return str(self._identifier)
def get_id(self) -> sp.Symbol:
"""
ModelQuantity identifier
:return:
identifier of the ModelQuantity
"""
return self._identifier
def get_name(self) -> str:
"""
ModelQuantity name
:return:
name of the ModelQuantity
"""
return self._name
def get_val(self) -> sp.Expr:
"""
ModelQuantity value
:return:
value of the ModelQuantity
"""
return self._value
def set_val(self, val: sp.Expr):
"""
Set ModelQuantity value
:return:
value of the ModelQuantity
"""
self._value = cast_to_sym(val, 'value')
class State(ModelQuantity):
"""
A State variable defines an entity that evolves with time according to
the provided time derivative, abbreviated by ``x``.
:ivar _conservation_law:
algebraic formula that allows computation of this
state according to a conservation law
:ivar _dt:
algebraic formula that defines the temporal derivative of this state
"""
_dt: Union[sp.Expr, None] = None
_conservation_law: Union[sp.Expr, None] = None
def __init__(self,
identifier: sp.Symbol,
name: str,
init: sp.Expr,
dt: sp.Expr):
"""
Create a new State instance. Extends :meth:`ModelQuantity.__init__`
by ``dt``
:param identifier:
unique identifier of the state
:param name:
individual name of the state (does not need to be unique)
:param init:
initial value
:param dt:
time derivative
"""
super(State, self).__init__(identifier, name, init)
self._dt = cast_to_sym(dt, 'dt')
self._conservation_law = None
def set_conservation_law(self,
law: sp.Expr) -> None:
"""
Sets the conservation law of a state.
If a conservation law is set, the respective state will be replaced by
an algebraic formula according to the respective conservation law.
:param law:
linear sum of states that if added to this state remain
constant over time
"""
if not isinstance(law, sp.Expr):
raise TypeError(f'conservation law must have type sympy.Expr, '
f'was {type(law)}')
self._conservation_law = law
def set_dt(self,
dt: sp.Expr) -> None:
"""
Sets the time derivative
:param dt:
time derivative
"""
self._dt = cast_to_sym(dt, 'dt')
def get_dt(self) -> sp.Expr:
"""
Gets the time derivative
:return:
time derivative
"""
return self._dt
def get_free_symbols(self) -> Set[sp.Symbol]:
"""
Gets the set of free symbols in time derivative and initial conditions
:return:
free symbols
"""
return self._dt.free_symbols.union(self._value.free_symbols)
class ConservationLaw(ModelQuantity):
"""
A conservation law defines the absolute the total amount of a
(weighted) sum of states
"""
def __init__(self,
identifier: sp.Symbol,
name: str,
value: sp.Expr):
"""
Create a new ConservationLaw instance.
:param identifier:
unique identifier of the ConservationLaw
:param name:
individual name of the ConservationLaw (does not need to be
unique)
:param value: formula (sum of states)
"""
super(ConservationLaw, self).__init__(identifier, name, value)
class Observable(ModelQuantity):
"""
An Observable links model simulations to experimental measurements,
abbreviated by ``y``.
:ivar _measurement_symbol:
sympy symbol used in the objective function to represent
measurements to this observable
:ivar trafo:
observable transformation, only applies when evaluating objective
function or residuals
"""
_measurement_symbol: Union[sp.Symbol, None] = None
def __init__(self,
identifier: sp.Symbol,
name: str,
value: sp.Expr,
measurement_symbol: Optional[sp.Symbol] = None,
transformation: Optional[ObservableTransformation] = 'lin'):
"""
Create a new Observable instance.
:param identifier:
unique identifier of the Observable
:param name:
individual name of the Observable (does not need to be unique)
:param value:
formula
:param transformation:
observable transformation, only applies when evaluating objective
function or residuals
"""
super(Observable, self).__init__(identifier, name, value)
self._measurement_symbol = measurement_symbol
self.trafo = transformation
def get_measurement_symbol(self) -> sp.Symbol:
if self._measurement_symbol is None:
self._measurement_symbol = generate_measurement_symbol(
self.get_id()
)
return self._measurement_symbol
class SigmaY(ModelQuantity):
"""
A Standard Deviation SigmaY rescales the distance between simulations
and measurements when computing residuals or objective functions,
abbreviated by ``sigmay``.
"""
def __init__(self,
identifier: sp.Symbol,
name: str,
value: sp.Expr):
"""
Create a new Standard Deviation instance.
:param identifier:
unique identifier of the Standard Deviation
:param name:
individual name of the Standard Deviation (does not need to
be unique)
:param value:
formula
"""
super(SigmaY, self).__init__(identifier, name, value)
class Expression(ModelQuantity):
"""
An Expression is a recurring elements in symbolic formulas. Specifying
this may yield more compact expression which may lead to substantially
shorter model compilation times, but may also reduce model simulation time.
Abbreviated by ``w``.
"""
def __init__(self,
identifier: sp.Symbol,
name: str,
value: sp.Expr):
"""
Create a new Expression instance.
:param identifier:
unique identifier of the Expression
:param name:
individual name of the Expression (does not need to be unique)
:param value:
formula
"""
super(Expression, self).__init__(identifier, name, value)
class Parameter(ModelQuantity):
"""
A Parameter is a free variable in the model with respect to which
sensitivities may be computed, abbreviated by ``p``.
"""
def __init__(self,
identifier: sp.Symbol,
name: str,
value: numbers.Number):
"""
Create a new Expression instance.
:param identifier:
unique identifier of the Parameter
:param name:
individual name of the Parameter (does not need to be
unique)
:param value:
numeric value
"""
super(Parameter, self).__init__(identifier, name, value)
class Constant(ModelQuantity):
"""
A Constant is a fixed variable in the model with respect to which
sensitivities cannot be computed, abbreviated by ``k``.
"""
def __init__(self,
identifier: sp.Symbol,
name: str,
value: numbers.Number):
"""
Create a new Expression instance.
:param identifier:
unique identifier of the Constant
:param name:
individual name of the Constant (does not need to be unique)
:param value:
numeric value
"""
super(Constant, self).__init__(identifier, name, value)
class LogLikelihood(ModelQuantity):
"""
A LogLikelihood defines the distance between measurements and
experiments for a particular observable. The final LogLikelihood value
in the simulation will be the sum of all specified LogLikelihood
instances evaluated at all timepoints, abbreviated by ``Jy``.
"""
def __init__(self,
identifier: sp.Symbol,
name: str,
value: sp.Expr):
"""
Create a new Expression instance.
:param identifier:
unique identifier of the LogLikelihood
:param name:
individual name of the LogLikelihood (does not need to be
unique)
:param value:
formula
"""
super(LogLikelihood, self).__init__(identifier, name, value)
class Event(ModelQuantity):
"""
An Event defines either a SBML event or a root of the argument of a
Heaviside function. The Heaviside functions will be tracked via the
vector ``h`` during simulation and are needed to inform the ODE solver
about a discontinuity in either the right-hand side or the states
themselves, causing a reinitialization of the solver.
"""
def __init__(self,
identifier: sp.Symbol,
name: str,
value: sp.Expr,
state_update: Union[sp.Expr, None],
event_observable: Union[sp.Expr, None]):
"""
Create a new Event instance.
:param identifier:
unique identifier of the Event
:param name:
individual name of the Event (does not need to be unique)
:param value:
formula for the root / trigger function
:param state_update:
formula for the bolus function (None for Heaviside functions,
zero vector for events without bolus)
:param event_observable:
formula a potential observable linked to the event
(None for Heaviside functions, empty events without observable)
"""
super(Event, self).__init__(identifier, name, value)
# add the Event specific components
self._state_update = state_update
self._observable = event_observable
def __eq__(self, other):
"""
Check equality of events at the level of trigger/root functions, as we
need to collect unique root functions for ``roots.cpp``
"""
return self.get_val() == other.get_val()
# defines the type of some attributes in ODEModel
symbol_to_type = {
SymbolId.SPECIES: State,
SymbolId.PARAMETER: Parameter,
SymbolId.FIXED_PARAMETER: Constant,
SymbolId.OBSERVABLE: Observable,
SymbolId.SIGMAY: SigmaY,
SymbolId.LLHY: LogLikelihood,
SymbolId.EXPRESSION: Expression,
SymbolId.EVENT: Event
}
@log_execution_time('running smart_jacobian', logger)
def smart_jacobian(eq: sp.MutableDenseMatrix,
sym_var: sp.MutableDenseMatrix) -> sp.MutableDenseMatrix:
"""
Wrapper around symbolic jacobian with some additional checks that reduce
computation time for large matrices
:param eq:
equation
:param sym_var:
differentiation variable
:return:
jacobian of eq wrt sym_var
"""
if min(eq.shape) and min(sym_var.shape) \
and not smart_is_zero_matrix(eq) \
and not smart_is_zero_matrix(sym_var) \
and not sym_var.free_symbols.isdisjoint(eq.free_symbols):
return eq.jacobian(sym_var)
return sp.zeros(eq.shape[0], sym_var.shape[0])
@log_execution_time('running smart_multiply', logger)
def smart_multiply(x: Union[sp.MutableDenseMatrix, sp.MutableSparseMatrix],
y: sp.MutableDenseMatrix
) -> Union[sp.MutableDenseMatrix, sp.MutableSparseMatrix]:
"""
Wrapper around symbolic multiplication with some additional checks that
reduce computation time for large matrices
:param x:
educt 1
:param y:
educt 2
:return:
product
"""
if not x.shape[0] or not y.shape[1] or smart_is_zero_matrix(x) or \
smart_is_zero_matrix(y):
return sp.zeros(x.shape[0], y.shape[1])
return x.multiply(y)
def smart_is_zero_matrix(x: Union[sp.MutableDenseMatrix,
sp.MutableSparseMatrix]) -> bool:
"""A faster implementation of sympy's is_zero_matrix
Avoids repeated indexer type checks and double iteration to distinguish
False/None. Found to be about 100x faster for large matrices.
:param x: Matrix to check
"""
if isinstance(x, sp.MutableDenseMatrix):
return all(xx.is_zero is True for xx in x.flat())
return x.nnz() == 0
class ODEModel:
"""
Defines an Ordinary Differential Equation as set of ModelQuantities.
This class provides general purpose interfaces to compute arbitrary
symbolic derivatives that are necessary for model simulation or
sensitivity computation.
:ivar _states:
list of state variables
:ivar _observables:
list of observables
:ivar _sigmays:
list of sigmays
:ivar _parameters:
list of parameters
:ivar _loglikelihoods:
list of loglikelihoods
:ivar _expressions:
list of expressions instances
:ivar _conservationlaws:
list of conservation laws
:ivar _symboldim_funs:
define functions that compute model dimensions, these
are functions as the underlying symbolic expressions have not been
populated at compile time
:ivar _eqs:
carries symbolic formulas of the symbolic variables of the model
:ivar _sparseeqs:
carries linear list of all symbolic formulas for sparsified
variables
:ivar _vals:
carries numeric values of symbolic identifiers of the symbolic
variables of the model
:ivar _names:
carries names of symbolic identifiers of the symbolic variables
of the model
:ivar _syms:
carries symbolic identifiers of the symbolic variables of the
model
:ivar _strippedsyms:
carries symbolic identifiers that were stripped of additional class
information
:ivar _sparsesyms:
carries linear list of all symbolic identifiers for sparsified
variables
:ivar _colptrs:
carries column pointers for sparsified variables. See
SUNMatrixContent_Sparse definition in ``sunmatrix/sunmatrix_sparse.h``
:ivar _rowvals:
carries row values for sparsified variables. See
SUNMatrixContent_Sparse definition in ``sunmatrix/sunmatrix_sparse.h``
:ivar _equation_prototype:
defines the attribute from which an equation should be generated via
list comprehension (see :meth:`ODEModel._generate_equation`)
:ivar _variable_prototype:
defines the attribute from which a variable should be generated via
list comprehension (see :meth:`ODEModel._generate_symbol`)
:ivar _value_prototype:
defines the attribute from which a value should be generated via
list comprehension (see :meth:`ODEModel._generate_value`)
:ivar _total_derivative_prototypes:
defines how a total derivative equation is computed for an equation,
key defines the name and values should be arguments for
ODEModel.totalDerivative()
:ivar _lock_total_derivative:
add chainvariables to this set when computing total derivative from
a partial derivative call to enforce a partial derivative in the
next recursion. prevents infinite recursion
:ivar _simplify:
If not None, this function will be used to simplify symbolic
derivative expressions. Receives sympy expressions as only argument.
To apply multiple simplifications, wrap them in a lambda expression.
:ivar _x0_fixedParameters_idx:
Index list of subset of states for which x0_fixedParameters was
computed
:ivar _w_recursion_depth:
recursion depth in w, quantified as nilpotency of dwdw
:ivar _has_quadratic_nllh:
whether all observables have a gaussian noise model, i.e. whether
res and FIM make sense.
:ivar _code_printer:
Code printer to generate C++ code
"""
def __init__(self, verbose: Optional[Union[bool, int]] = False,
simplify: Optional[Callable] = sp.powsimp):
"""
Create a new ODEModel instance.
:param verbose:
verbosity level for logging, True/False default to
``logging.DEBUG``/``logging.ERROR``
:param simplify:
see :meth:`ODEModel._simplify`
"""
self._states: List[State] = []
self._observables: List[Observable] = []
self._sigmays: List[SigmaY] = []
self._parameters: List[Parameter] = []
self._constants: List[Constant] = []
self._loglikelihoods: List[LogLikelihood] = []
self._expressions: List[Expression] = []
self._conservationlaws: List[ConservationLaw] = []
self._events: List[Event] = []
self._symboldim_funs: Dict[str, Callable[[], int]] = {
'sx': self.num_states_solver,
'v': self.num_states_solver,
'vB': self.num_states_solver,
'xB': self.num_states_solver,
'sigmay': self.num_obs,
}
self._eqs: Dict[str, Union[sp.Matrix, List[sp.Matrix]]] = dict()
self._sparseeqs: Dict[str, Union[sp.Matrix, List[sp.Matrix]]] = dict()
self._vals: Dict[str, List[float]] = dict()
self._names: Dict[str, List[str]] = dict()
self._syms: Dict[str, Union[sp.Matrix, List[sp.Matrix]]] = dict()
self._strippedsyms: Dict[str, sp.Matrix] = dict()
self._sparsesyms: Dict[str, Union[List[str], List[List[str]]]] = dict()
self._colptrs: Dict[str, Union[List[int], List[List[int]]]] = dict()
self._rowvals: Dict[str, Union[List[int], List[List[int]]]] = dict()
self._equation_prototype: Dict[str, str] = {
'total_cl': '_conservationlaws',