forked from AMICI-dev/AMICI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathde_model.py
More file actions
2347 lines (2014 loc) · 79.9 KB
/
de_model.py
File metadata and controls
2347 lines (2014 loc) · 79.9 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
"""Symbolic differential equation model."""
from __future__ import annotations
import contextlib
import copy
import itertools
import re
from itertools import chain
from typing import TYPE_CHECKING
from collections.abc import Callable
from collections.abc import Sequence
import numpy as np
import sympy as sp
from sympy import ImmutableDenseMatrix, MutableDenseMatrix
from ._codegen.cxx_functions import (
sparse_functions,
sensi_functions,
nobody_functions,
var_in_function_signature,
)
from .cxxcodeprinter import csc_matrix
from .de_model_components import (
DifferentialState,
AlgebraicState,
AlgebraicEquation,
Observable,
EventObservable,
SigmaY,
SigmaZ,
Parameter,
Constant,
LogLikelihoodY,
LogLikelihoodZ,
LogLikelihoodRZ,
NoiseParameter,
ObservableParameter,
Expression,
ConservationLaw,
Event,
State,
ModelQuantity,
)
from .import_utils import (
_default_simplify,
SBMLException,
toposort_symbols,
smart_subs_dict,
ObservableTransformation,
amici_time_symbol,
strip_pysb,
unique_preserve_order,
)
from .sympy_utils import (
smart_jacobian,
smart_is_zero_matrix,
smart_multiply,
_parallel_applyfunc,
)
from .logging import get_logger, log_execution_time, set_log_level
import logging
if TYPE_CHECKING:
from .splines import AbstractSpline
logger = get_logger(__name__, logging.ERROR)
DERIVATIVE_PATTERN = re.compile(r"^d(x_rdata|xdot|\w+?)d(\w+?)(?:_explicit)?$")
class DEModel:
"""
Defines a 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 _differential_states:
list of differential state variables
:ivar _algebraic_states:
list of algebraic state variables
:ivar _observables:
list of observables
:ivar _event_observables:
list of event observables
:ivar _sigma_ys:
list of sigmas for observables
:ivar _sigma_zs:
list of sigmas for event observables
:ivar _parameters:
list of parameters
:ivar _log_likelihood_ys:
list of loglikelihoods for observables
:ivar _log_likelihood_zs:
list of loglikelihoods for event observables
:ivar _log_likelihood_rzs:
list of loglikelihoods for event observable regularizations
:ivar _expressions:
list of expressions instances
:ivar _conservation_laws:
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 the names of symbolic identifiers of the symbolic variables
of the model
:ivar _syms:
carries symbolic identifiers of the symbolic variables of the
model
: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:`OEModel._generate_equation`)
:ivar _variable_prototype:
defines the attribute from which a variable should be generated via
list comprehension (see :meth:`DEModel._generate_symbol`)
:ivar _value_prototype:
defines the attribute from which a value should be generated via
list comprehension (see :meth:`DEModel._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
:meth:`DEModel.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 _static_indices:
dict of lists list of indices of static variables for different
model entities.
:ivar _z2event:
list of event indices for each event observable
"""
def __init__(
self,
verbose: bool | int | None = False,
simplify: Callable | None = _default_simplify,
cache_simplify: bool = False,
):
"""
Create a new DEModel instance.
:param verbose:
verbosity level for logging, True/False default to
``logging.DEBUG``/``logging.ERROR``
:param simplify:
see :meth:`DEModel._simplify`
:param cache_simplify:
Whether to cache calls to the simplify method. Can e.g. decrease
import times for models with events.
"""
self._differential_states: list[DifferentialState] = []
self._algebraic_states: list[AlgebraicState] = []
self._algebraic_equations: list[AlgebraicEquation] = []
self._observables: list[Observable] = []
self._event_observables: list[EventObservable] = []
self._sigma_ys: list[SigmaY] = []
self._sigma_zs: list[SigmaZ] = []
self._parameters: list[Parameter] = []
self._constants: list[Constant] = []
self._log_likelihood_ys: list[LogLikelihoodY] = []
self._log_likelihood_zs: list[LogLikelihoodZ] = []
self._log_likelihood_rzs: list[LogLikelihoodRZ] = []
self._noise_parameters: list[NoiseParameter] = []
self._observable_parameters: list[ObservableParameter] = []
self._expressions: list[Expression] = []
self._conservation_laws: list[ConservationLaw] = []
self._events: list[Event] = []
self._splines: list[AbstractSpline] = []
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,
"sigmaz": self.num_eventobs,
}
self._eqs: dict[
str,
(sp.Matrix | sp.SparseMatrix | list[sp.Matrix | sp.SparseMatrix]),
] = dict()
self._sparseeqs: dict[str, sp.Matrix | list[sp.Matrix]] = dict()
self._vals: dict[str, list[sp.Expr]] = dict()
self._names: dict[str, list[str]] = dict()
self._syms: dict[str, sp.Matrix | list[sp.Matrix]] = dict()
self._sparsesyms: dict[str, list[str] | list[list[str]]] = dict()
self._colptrs: dict[str, list[int] | list[list[int]]] = dict()
self._rowvals: dict[str, list[int] | list[list[int]]] = dict()
self._equation_prototype: dict[str, Callable] = {
"total_cl": self.conservation_laws,
"x0": self.states,
"y": self.observables,
"Jy": self.log_likelihood_ys,
"Jz": self.log_likelihood_zs,
"Jrz": self.log_likelihood_rzs,
"w": self.expressions,
"root": self.events,
"sigmay": self.sigma_ys,
"sigmaz": self.sigma_zs,
}
self._variable_prototype: dict[str, Callable] = {
"tcl": self.conservation_laws,
"x_rdata": self.states,
"y": self.observables,
"z": self.event_observables,
"p": self.parameters,
"k": self.constants,
"w": self.expressions,
"sigmay": self.sigma_ys,
"sigmaz": self.sigma_zs,
"h": self.events,
"np": self.noise_parameters,
"op": self.observable_parameters,
}
self._value_prototype: dict[str, Callable] = {
"p": self.parameters,
"k": self.constants,
}
self._total_derivative_prototypes: dict[
str, dict[str, str | list[str]]
] = {
"sroot": {
"eq": "root",
"chainvars": ["x"],
"var": "p",
"dxdz_name": "sx",
},
}
self._lock_total_derivative: list[str] = list()
self._simplify: Callable = simplify
if cache_simplify and simplify is not None:
def cached_simplify(
expr: sp.Expr,
_simplified: dict[str, sp.Expr] = {}, # noqa B006
_simplify: Callable = simplify,
) -> sp.Expr:
"""Speed up expression simplification with caching.
NB: This can decrease model import times for models that have
many repeated expressions during C++ file generation.
For example, this can be useful for models with events.
However, for other models, this may increase model import
times.
:param expr:
The SymPy expression.
:param _simplified:
The cache.
:param _simplify:
The simplification method.
:return:
The simplified expression.
"""
expr_str = repr(expr)
if expr_str not in _simplified:
_simplified[expr_str] = _simplify(expr)
return _simplified[expr_str]
self._simplify = cached_simplify
self._x0_fixedParameters_idx: None | Sequence[int]
self._w_recursion_depth: int = 0
self._has_quadratic_nllh: bool = True
set_log_level(logger, verbose)
self._static_indices: dict[str, list[int]] = {}
def differential_states(self) -> list[DifferentialState]:
"""Get all differential states."""
return self._differential_states
def algebraic_states(self) -> list[AlgebraicState]:
"""Get all algebraic states."""
return self._algebraic_states
def observables(self) -> list[Observable]:
"""Get all observables."""
return self._observables
def parameters(self) -> list[Parameter]:
"""Get all parameters."""
return self._parameters
def constants(self) -> list[Constant]:
"""Get all constants."""
return self._constants
def expressions(self) -> list[Expression]:
"""Get all expressions."""
return self._expressions
def events(self) -> list[Event]:
"""Get all events."""
return self._events
def event_observables(self) -> list[EventObservable]:
"""Get all event observables."""
return self._event_observables
def sigma_ys(self) -> list[SigmaY]:
"""Get all observable sigmas."""
return self._sigma_ys
def sigma_zs(self) -> list[SigmaZ]:
"""Get all event observable sigmas."""
return self._sigma_zs
def conservation_laws(self) -> list[ConservationLaw]:
"""Get all conservation laws."""
return self._conservation_laws
def log_likelihood_ys(self) -> list[LogLikelihoodY]:
"""Get all observable log likelihoodss."""
return self._log_likelihood_ys
def log_likelihood_zs(self) -> list[LogLikelihoodZ]:
"""Get all event observable log likelihoods."""
return self._log_likelihood_zs
def log_likelihood_rzs(self) -> list[LogLikelihoodRZ]:
"""Get all event observable regularization log likelihoods."""
return self._log_likelihood_rzs
def noise_parameters(self) -> list[NoiseParameter]:
"""Get all noise parameters."""
return self._noise_parameters
def observable_parameters(self) -> list[ObservableParameter]:
"""Get all observable parameters."""
return self._observable_parameters
def is_ode(self) -> bool:
"""Check if model is ODE model."""
return len(self._algebraic_equations) == 0
def states(self) -> list[State]:
"""Get all states."""
return self._differential_states + self._algebraic_states
def _process_sbml_rate_of(self) -> None:
"""Substitute any SBML-rateOf constructs in the model equations"""
from sbmlmath import rate_of as rate_of_func
species_sym_to_xdot = dict(
zip(self.sym("x"), self.sym("xdot"), strict=True)
)
species_sym_to_idx = {x: i for i, x in enumerate(self.sym("x"))}
def get_rate(symbol: sp.Symbol):
"""Get rate of change of the given symbol"""
if symbol.find(rate_of_func):
raise SBMLException("Nesting rateOf() is not allowed.")
# Replace all rateOf(some_species) by their respective xdot equation
with contextlib.suppress(KeyError):
return self._eqs["xdot"][species_sym_to_idx[symbol]]
# For anything other than a state, rateOf(.) is 0 or invalid
return 0
# replace rateOf-instances in xdot by xdot symbols
made_substitutions = False
for i_state in range(len(self.eq("xdot"))):
if rate_ofs := self._eqs["xdot"][i_state].find(rate_of_func):
self._eqs["xdot"][i_state] = self._eqs["xdot"][i_state].subs(
{
# either the rateOf argument is a state, or it's 0
rate_of: species_sym_to_xdot.get(rate_of.args[0], 0)
for rate_of in rate_ofs
}
)
made_substitutions = True
if made_substitutions:
# substitute in topological order
subs = toposort_symbols(
dict(zip(self.sym("xdot"), self.eq("xdot"), strict=True))
)
self._eqs["xdot"] = smart_subs_dict(self.eq("xdot"), subs)
# replace rateOf-instances in x0 by xdot equation
for i_state in range(len(self.eq("x0"))):
new, replacement = self._eqs["x0"][i_state].replace(
rate_of_func, get_rate, map=True
)
if replacement:
self._eqs["x0"][i_state] = new
# replace rateOf-instances in w by xdot equation
# here we may need toposort, as xdot may depend on w
made_substitutions = False
for i_expr in range(len(self.eq("w"))):
new, replacement = self._eqs["w"][i_expr].replace(
rate_of_func, get_rate, map=True
)
if replacement:
self._eqs["w"][i_expr] = new
made_substitutions = True
if made_substitutions:
# Sort expressions in self._expressions, w symbols, and w equations
# in topological order. Ideally, this would already happen before
# adding the expressions to the model, but at that point, we don't
# have access to xdot yet.
# NOTE: elsewhere, conservations law expressions are expected to
# occur before any other w expressions, so we must maintain their
# position
# toposort everything but conservation law expressions,
# then prepend conservation laws
w_sorted = toposort_symbols(
dict(
zip(
self.sym("w")[self.num_cons_law() :, :],
self.eq("w")[self.num_cons_law() :, :],
strict=True,
)
)
)
w_sorted = (
dict(
zip(
self.sym("w")[: self.num_cons_law(), :],
self.eq("w")[: self.num_cons_law(), :],
strict=True,
)
)
| w_sorted
)
old_syms = tuple(self._syms["w"])
topo_expr_syms = tuple(w_sorted.keys())
new_order = [old_syms.index(s) for s in topo_expr_syms]
self._expressions = [self._expressions[i] for i in new_order]
self._syms["w"] = sp.Matrix(topo_expr_syms)
self._eqs["w"] = sp.Matrix(list(w_sorted.values()))
for component in chain(
self.observables(),
self.events(),
self._algebraic_equations,
):
if rate_ofs := component.get_val().find(rate_of_func):
if isinstance(component, Event):
# TODO froot(...) can currently not depend on `w`, so this substitution fails for non-zero rates
# see, e.g., sbml test case 01293
raise SBMLException(
"AMICI does currently not support rateOf(.) inside event trigger functions."
)
if isinstance(component, AlgebraicEquation):
# TODO IDACalcIC fails with
# "The linesearch algorithm failed: step too small or too many backtracks."
# see, e.g., sbml test case 01482
raise SBMLException(
"AMICI does currently not support rateOf(.) inside AlgebraicRules."
)
component.set_val(
component.get_val().subs(
{
rate_of: get_rate(rate_of.args[0])
for rate_of in rate_ofs
}
)
)
for event in self.events():
if event._state_update is None:
continue
for i_state in range(len(event._state_update)):
if rate_ofs := event._state_update[i_state].find(rate_of_func):
raise SBMLException(
"AMICI does currently not support rateOf(.) inside event state updates."
)
# TODO here we need xdot sym, not eqs
# event._state_update[i_state] = event._state_update[i_state].subs(
# {rate_of: get_rate(rate_of.args[0]) for rate_of in rate_ofs}
# )
def add_component(
self, component: ModelQuantity, insert_first: bool | None = False
) -> None:
"""
Adds a new ModelQuantity to the model.
:param component:
model quantity to be added
:param insert_first:
whether to add quantity first or last, relevant when components
may refer to other components of the same type.
"""
if type(component) not in {
Observable,
Expression,
Parameter,
Constant,
DifferentialState,
AlgebraicState,
AlgebraicEquation,
LogLikelihoodY,
LogLikelihoodZ,
LogLikelihoodRZ,
SigmaY,
SigmaZ,
ConservationLaw,
Event,
EventObservable,
NoiseParameter,
ObservableParameter,
}:
raise ValueError(f"Invalid component type {type(component)}")
component_list = getattr(
self,
"_"
+ "_".join(
s.lower()
for s in re.split(r"([A-Z][^A-Z]+)", type(component).__name__)
if s
)
+ "s",
)
if insert_first:
component_list.insert(0, component)
else:
component_list.append(component)
def add_conservation_law(
self,
state: sp.Symbol,
total_abundance: sp.Symbol,
coefficients: dict[sp.Symbol, sp.Expr],
) -> None:
r"""
Adds a new conservation law to the model. A conservation law is defined
by the conserved quantity :math:`T = \sum_i(a_i * x_i)`, where
:math:`a_i` are coefficients and :math:`x_i` are different state
variables.
:param state:
symbolic identifier of the state that should be replaced by
the conservation law (:math:`x_j`)
:param total_abundance:
symbolic identifier of the total abundance (:math:`T/a_j`)
:param coefficients:
Dictionary of coefficients {x_i: a_i}
"""
try:
ix = next(
filter(
lambda is_s: is_s[1].get_id() == state,
enumerate(self._differential_states),
)
)[0]
except StopIteration:
raise ValueError(
f"Specified state {state} was not found in the "
f"model states."
)
state_id = self._differential_states[ix].get_id()
# \sum_{i≠j}(a_i * x_i)/a_j
target_expression = (
sp.Add(
*(
c_i * x_i
for x_i, c_i in coefficients.items()
if x_i != state
)
)
/ coefficients[state]
)
# x_j = T/a_j - \sum_{i≠j}(a_i * x_i)/a_j
state_expr = total_abundance - target_expression
# T/a_j = \sum_{i≠j}(a_i * x_i)/a_j + x_j
abundance_expr = target_expression + state_id
self.add_component(
Expression(state_id, str(state_id), state_expr), insert_first=True
)
cl = ConservationLaw(
total_abundance,
f"total_{state_id}",
abundance_expr,
coefficients,
state_id,
)
self.add_component(cl)
self._differential_states[ix].set_conservation_law(cl)
def add_spline(self, spline: AbstractSpline, spline_expr: sp.Expr) -> None:
"""Add a spline to the model.
:param spline:
Spline instance to be added
:param spline_expr:
Sympy function representation of `spline` from
``spline.ode_model_symbol()``.
"""
self._splines.append(spline)
self.add_component(
Expression(
identifier=spline.sbml_id,
name=str(spline.sbml_id),
value=spline_expr,
)
)
def get_observable_transformations(self) -> list[ObservableTransformation]:
"""
List of observable transformations
:return:
list of transformations
"""
return [obs.trafo for obs in self._observables]
def num_states_rdata(self) -> int:
"""
Number of states.
:return:
number of state variable symbols
"""
return len(self.sym("x_rdata"))
def num_states_solver(self) -> int:
"""
Number of states after applying conservation laws.
:return:
number of state variable symbols
"""
return len(self.sym("x"))
def num_cons_law(self) -> int:
"""
Number of conservation laws.
:return:
number of conservation laws
"""
return self.num_states_rdata() - self.num_states_solver()
def num_state_reinits(self) -> int:
"""
Number of solver states which would be reinitialized after
preequilibration
:return:
number of state variable symbols with reinitialization
"""
reinit_states = self.eq("x0_fixedParameters")
solver_states = self.eq("x_solver")
return sum(ix in solver_states for ix in reinit_states)
def num_obs(self) -> int:
"""
Number of Observables.
:return:
number of observable symbols
"""
return len(self.sym("y"))
def num_eventobs(self) -> int:
"""
Number of Event Observables.
:return:
number of event observable symbols
"""
return len(self.sym("z"))
def num_const(self) -> int:
"""
Number of Constants.
:return:
number of constant symbols
"""
return len(self.sym("k"))
def num_par(self) -> int:
"""
Number of Parameters.
:return:
number of parameter symbols
"""
return len(self.sym("p"))
def num_expr(self) -> int:
"""
Number of Expressions.
:return:
number of expression symbols
"""
return len(self.sym("w"))
def num_events(self) -> int:
"""
Total number of Events (those for which root-functions are added and those without).
:return:
number of events
"""
return len(self.sym("h"))
def num_events_solver(self) -> int:
"""
Number of Events.
:return:
number of event symbols (length of the root vector in AMICI)
"""
return sum(
not event.triggers_at_fixed_timepoint() for event in self.events()
)
def sym(self, name: str) -> sp.Matrix:
"""
Returns (and constructs if necessary) the identifiers for a symbolic
entity.
:param name:
name of the symbolic variable
:return:
matrix of symbolic identifiers
"""
if name not in self._syms:
self._generate_symbol(name)
return self._syms[name]
def sparsesym(self, name: str, force_generate: bool = True) -> list[str]:
"""
Returns (and constructs if necessary) the sparsified identifiers for
a sparsified symbolic variable.
:param name:
name of the symbolic variable
:param force_generate:
whether the symbols should be generated if not available
:return:
linearized Matrix containing the symbolic identifiers
"""
if name not in sparse_functions:
raise ValueError(f"{name} is not marked as sparse")
if name not in self._sparsesyms and force_generate:
self._generate_sparse_symbol(name)
return self._sparsesyms.get(name, [])
def eq(self, name: str) -> sp.Matrix:
"""
Returns (and constructs if necessary) the formulas for a symbolic
entity.
:param name:
name of the symbolic variable
:return:
matrix of symbolic formulas
"""
if name not in self._eqs:
dec = log_execution_time(f"computing {name}", logger)
dec(self._compute_equation)(name)
return self._eqs[name]
def sparseeq(self, name) -> sp.Matrix:
"""
Returns (and constructs if necessary) the sparsified formulas for a
sparsified symbolic variable.
:param name:
name of the symbolic variable
:return:
linearized matrix containing the symbolic formulas
"""
if name not in sparse_functions:
raise ValueError(f"{name} is not marked as sparse")
if name not in self._sparseeqs:
self._generate_sparse_symbol(name)
return self._sparseeqs[name]
def colptrs(self, name: str) -> list[sp.Number] | list[list[sp.Number]]:
"""
Returns (and constructs if necessary) the column pointers for
a sparsified symbolic variable.
:param name:
name of the symbolic variable
:return:
list containing the column pointers
"""
if name not in sparse_functions:
raise ValueError(f"{name} is not marked as sparse")
if name not in self._sparseeqs:
self._generate_sparse_symbol(name)
return self._colptrs[name]
def rowvals(self, name: str) -> list[sp.Number] | list[list[sp.Number]]:
"""
Returns (and constructs if necessary) the row values for a
sparsified symbolic variable.
:param name:
name of the symbolic variable
:return:
list containing the row values
"""
if name not in sparse_functions:
raise ValueError(f"{name} is not marked as sparse")
if name not in self._sparseeqs:
self._generate_sparse_symbol(name)
return self._rowvals[name]
def val(self, name: str) -> list[sp.Number]:
"""
Returns (and constructs if necessary) the numeric values of a
symbolic entity
:param name:
name of the symbolic variable
:return:
list containing the numeric values
"""
if name not in self._vals:
self._generate_value(name)
return self._vals[name]
def name(self, name: str) -> list[str]:
"""
Returns (and constructs if necessary) the names of a symbolic
variable
:param name:
name of the symbolic variable
:return:
list of names
"""
if name not in self._names:
self._generate_name(name)
return self._names[name]
def free_symbols(self) -> set[sp.Basic]:
"""
Returns list of free symbols that appear in RHS and initial
conditions.
"""
return set(
chain.from_iterable(
state.get_free_symbols() for state in self.states()
)
)
def static_indices(self, name: str) -> list[int]:
"""
Returns the indices of static expressions in the given model entity.
Static expressions are those that do not depend on time,
neither directly nor indirectly.
:param name: Name of the model entity.
:return: List of indices of static expressions.
"""
# already computed?
if (res := self._static_indices.get(name)) is not None:
return res
if name == "w":
dwdx = self.sym("dwdx")
dwdw = self.sym("dwdw")
w = self.eq("w")
# Check for direct (via `t`) or indirect (via `x`, `h`, or splines)
# time dependency.
# To avoid lengthy symbolic computations, we only check if we have
# any non-zeros in hierarchy. We currently neglect the case where
# different hierarchy levels may cancel out. Treating a static
# expression as dynamic in such rare cases shouldn't be a problem.
dynamic_dependency = np.asarray(
dwdx.applyfunc(lambda x: int(not x.is_zero))
).astype(np.int64)
# to check for other time-dependence, we add a column to the dwdx
# matrix
dynamic_syms = [
# FIXME: see spline comment below
# *self.sym("spl"),
*self.sym("h"),
amici_time_symbol,
]
dynamic_dependency = np.hstack(
(
dynamic_dependency,
np.array(
[
expr.has(*dynamic_syms)
# FIXME: the current spline implementation is a giant pita
# currently, the splines occur in the form of sympy functions, e.g.:
# AmiciSpline(y0, time, y0_3, y0_1)
# AmiciSplineSensitivity(y0, time, y0_1, y0_3, y0_1)
# until it uses the proper self.sym("spl") / self.sym("sspl")
# symbols, which will require quite some refactoring,
# we just do dumb string checks :|
or (
bool(self._splines)
and "AmiciSpline" in str(expr)
)
for expr in w
]
)[:, np.newaxis],