-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathde_export.py
More file actions
1358 lines (1198 loc) · 47.4 KB
/
de_export.py
File metadata and controls
1358 lines (1198 loc) · 47.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
"""
C++ Export
----------
This module provides all necessary functionality to specify a differential
equation 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`.
"""
from __future__ import annotations
import copy
import logging
import os
import re
import shutil
from pathlib import Path
from typing import (
TYPE_CHECKING,
Literal,
)
import sympy as sp
from . import (
__commit__,
__version__,
amiciModulePath,
amiciSrcPath,
amiciSwigPath,
splines,
)
from ._codegen.cxx_functions import (
_FunctionInfo,
functions,
sparse_functions,
nobody_functions,
sensi_functions,
sparse_sensi_functions,
event_functions,
event_sensi_functions,
multiobs_functions,
)
from ._codegen.model_class import (
get_function_extern_declaration,
get_sunindex_extern_declaration,
get_model_override_implementation,
get_sunindex_override_implementation,
get_state_independent_event_intializer,
)
from ._codegen.template import apply_template
from .cxxcodeprinter import (
AmiciCxxCodePrinter,
get_switch_statement,
)
from .de_model import DEModel
from .de_model_components import *
from .import_utils import (
strip_pysb,
)
from .logging import get_logger, log_execution_time, set_log_level
from .compile import build_model_extension
from .sympy_utils import (
_custom_pow_eval_derivative,
_monkeypatched,
smart_is_zero_matrix,
)
if TYPE_CHECKING:
pass
# 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"
)
IDENTIFIER_PATTERN = re.compile(r"^[a-zA-Z_]\w*$")
#: 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)
class DEExporter:
"""
The DEExporter class generates AMICI C++ files for a model as
defined in symbolic expressions.
:ivar model:
DE definition
:ivar verbose:
more verbose output if True
:ivar 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
:ivar compiler:
Absolute path to the compiler executable to be used to build the Python
extension, e.g. ``/usr/bin/clang``.
:ivar functions:
carries C++ function signatures and other specifications
:ivar model_name:
name of the model that will be used for compilation
:ivar model_path:
path to the generated model specific files
:ivar model_swig_path:
path to the generated swig files
:ivar allow_reinit_fixpar_initcond:
indicates whether reinitialization of
initial states depending on fixedParameters is allowed for this model
:ivar _build_hints:
If the given model uses special functions, this set contains hints for
model building.
:ivar _code_printer:
Code printer to generate C++ code
:ivar generate_sensitivity_code:
Specifies whether code for sensitivity computation is to be generated
.. note::
When importing large models (several hundreds of species or
parameters), import time can potentially be reduced by using multiple
CPU cores. This is controlled by setting the ``AMICI_IMPORT_NPROCS``
environment variable to the number of parallel processes that are to be
used (default: 1). Note that for small models this may (slightly)
increase import times.
"""
def __init__(
self,
de_model: DEModel,
outdir: Path | str | None = None,
verbose: bool | int | None = False,
assume_pow_positivity: bool | None = False,
compiler: str | None = None,
allow_reinit_fixpar_initcond: bool | None = True,
generate_sensitivity_code: bool | None = True,
model_name: str | None = "model",
):
"""
Generate AMICI C++ files for the DE provided to the constructor.
:param de_model:
DE model definition
:param outdir:
see :meth:`amici.de_export.DEExporter.set_paths`
:param verbose:
verbosity level for logging, ``True``/``False`` default to
:data:`logging.Error`/:data:`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 generate_sensitivity_code:
specifies whether code required for sensitivity computation will be
generated
:param model_name:
name of the model to be used during code generation
"""
set_log_level(logger, verbose)
self.verbose: bool = logger.getEffectiveLevel() <= logging.DEBUG
self.assume_pow_positivity: bool = assume_pow_positivity
self.compiler: str = compiler
self.model_path: str = ""
self.model_swig_path: str = ""
self.set_name(model_name)
self.set_paths(outdir)
self._code_printer = AmiciCxxCodePrinter()
for fun in CUSTOM_FUNCTIONS:
self._code_printer.known_functions[fun["sympy"]] = fun["c++"]
# Signatures and properties of generated model functions (see
# include/amici/model.h for details)
self.model: DEModel = de_model
self._code_printer.known_functions.update(
splines.spline_user_functions(
self.model._splines, self._get_index("p")
)
)
# To only generate a subset of functions, apply subselection here
self.functions: dict[str, _FunctionInfo] = copy.deepcopy(functions)
self.allow_reinit_fixpar_initcond: bool = allow_reinit_fixpar_initcond
self._build_hints = set()
self.generate_sensitivity_code: bool = generate_sensitivity_code
@log_execution_time("generating cpp code", logger)
def generate_model_code(self) -> None:
"""
Generates the native C++ code for the loaded model and a Matlab
script that can be run to compile a mex file from the C++ code
"""
with _monkeypatched(
sp.Pow, "_eval_derivative", _custom_pow_eval_derivative
):
self._prepare_model_folder()
self._generate_c_code()
self._generate_m_code()
@log_execution_time("compiling cpp code", logger)
def compile_model(self) -> None:
"""
Compiles the generated code it into a simulatable module
"""
build_model_extension(
package_dir=self.model_path,
compiler=self.compiler,
verbose=self.verbose,
extra_msg="\n".join(self._build_hints),
)
def _prepare_model_folder(self) -> None:
"""
Create model directory or remove all files if the output directory
already exists.
"""
os.makedirs(self.model_path, exist_ok=True)
for file in os.listdir(self.model_path):
file_path = os.path.join(self.model_path, file)
if os.path.isfile(file_path):
os.remove(file_path)
def _generate_c_code(self) -> None:
"""
Create C++ code files for the model based on
:attribute:`DEExporter.model`.
"""
for func_name, func_info in self.functions.items():
if (
func_name in sensi_functions + sparse_sensi_functions
and not self.generate_sensitivity_code
):
continue
if func_info.generate_body:
dec = log_execution_time(f"writing {func_name}.cpp", logger)
dec(self._write_function_file)(func_name)
for name in self.model.sym_names():
# only generate for those that have nontrivial implementation,
# check for both basic variables (not in functions) and function
# computed values
if (
(
name in self.functions
and not self.functions[name].body
and name not in nobody_functions
)
or name not in self.functions
) and len(self.model.sym(name)) == 0:
continue
self._write_index_files(name)
self._write_wrapfunctions_cpp()
self._write_wrapfunctions_header()
self._write_model_header_cpp()
self._write_c_make_file()
self._write_swig_files()
self._write_module_setup()
_write_gitignore(Path(self.model_path))
shutil.copy(
CXX_MAIN_TEMPLATE_FILE, os.path.join(self.model_path, "main.cpp")
)
def _generate_m_code(self) -> None:
"""
Create a Matlab script for compiling code files to a mex file
"""
# Second order code is not yet implemented. Once this is done,
# those variables will have to be replaced by
# "self.model.<var>true()", or the corresponding "model.self.o2flag"
nxtrue_rdata = self.model.num_states_rdata()
nytrue = self.model.num_obs()
nztrue = self.model.num_eventobs()
o2flag = 0
lines = [
"% This compile script was automatically created from"
" Python SBML import.",
"% If mex compiler is set up within MATLAB, it can be run"
" from MATLAB ",
"% in order to compile a mex-file from the Python"
" generated C++ files.",
"",
f"modelName = '{self.model_name}';",
"amimodel.compileAndLinkModel(modelName, '', [], [], [], []);",
f"amimodel.generateMatlabWrapper({nxtrue_rdata}, "
f"{nytrue}, {self.model.num_par()}, "
f"{self.model.num_const()}, {nztrue}, {o2flag}, ...",
" [], ['simulate_' modelName '.m'], modelName, ...",
" 'lin', 1, 1);",
]
# write compile script (for mex)
compile_script = os.path.join(self.model_path, "compileMexFile.m")
with open(compile_script, "w") as fileout:
fileout.write("\n".join(lines))
def _get_index(self, name: str) -> dict[sp.Symbol, int]:
"""
Compute indices for a symbolic array.
:param name:
key in self.model._syms for which to obtain the index.
:return:
a dictionary of symbol/index pairs.
"""
if name in self.model.sym_names():
if name in sparse_functions:
symbols = self.model.sparsesym(name)
else:
symbols = self.model.sym(name).T
else:
raise ValueError(f"Unknown symbolic array: {name}")
return {
strip_pysb(symbol).name: index
for index, symbol in enumerate(symbols)
}
def _write_index_files(self, name: str) -> None:
"""
Write index file for a symbolic array.
:param name:
key in ``self.model._syms`` for which the respective file should
be written
"""
if name not in self.model.sym_names():
raise ValueError(f"Unknown symbolic array: {name}")
symbols = (
self.model.sparsesym(name)
if name in sparse_functions
else self.model.sym(name).T
)
if not len(symbols):
return
# flatten multiobs
if isinstance(next(iter(symbols), None), list):
symbols = [symbol for obs in symbols for symbol in obs]
lines = []
for index, symbol in enumerate(symbols):
symbol_name = strip_pysb(symbol)
if str(symbol) == "0":
continue
if str(symbol_name) == "":
raise ValueError(f'{name} contains a symbol called ""')
lines.append(f"#define {symbol_name} {name}[{index}]")
if name == "stau":
# we only need a single macro, as all entries have the same symbol
break
filename = os.path.join(self.model_path, f"{name}.h")
with open(filename, "w") as fileout:
fileout.write("\n".join(lines))
fileout.write("\n")
def _write_function_file(self, function: str) -> None:
"""
Generate equations and write the C++ code for the function
``function``.
:param function:
name of the function to be written (see ``self.functions``)
"""
# first generate the equations to make sure we have everything we
# need in subsequent steps
if function in sparse_functions:
equations = self.model.sparseeq(function)
elif (
not self.allow_reinit_fixpar_initcond
and function == "sx0_fixedParameters"
):
# Not required. Will create empty function body.
equations = sp.Matrix()
elif function == "create_splines":
# nothing to do
pass
else:
equations = self.model.eq(function)
# function body
if function == "create_splines":
body = self._get_create_splines_body()
else:
body = self._get_function_body(function, equations)
if not body:
return
# colptrs / rowvals for sparse matrices
if function in sparse_functions:
lines = self._generate_function_index(function, "colptrs")
lines.extend(self._generate_function_index(function, "rowvals"))
lines.append("\n\n")
else:
lines = []
# function header
lines.extend(
[
'#include "amici/symbolic_functions.h"',
'#include "amici/defines.h"',
'#include "sundials/sundials_types.h"',
"",
"#include <gsl/gsl-lite.hpp>",
"#include <algorithm>",
"",
]
)
if function == "create_splines":
lines += [
'#include "amici/splinefunctions.h"',
"#include <vector>",
]
func_info = self.functions[function]
# extract symbols that need definitions from signature
# don't add includes for files that won't be generated.
# Unfortunately we cannot check for `self.functions[sym].body`
# here since it may not have been generated yet.
for sym in re.findall(
r"const (?:realtype|double) \*([\w]+)[0]*(?:,|$)",
func_info.arguments(self.model.is_ode()),
):
if sym not in self.model.sym_names():
continue
if sym in sparse_functions:
iszero = smart_is_zero_matrix(self.model.sparseeq(sym))
elif sym in self.functions:
iszero = smart_is_zero_matrix(self.model.eq(sym))
else:
iszero = len(self.model.sym(sym)) == 0
if iszero and not (
(sym == "y" and "Jy" in function)
or (
sym == "w"
and "xdot" in function
and len(self.model.sym(sym))
)
):
continue
lines.append(f'#include "{sym}.h"')
# include return symbols
if (
function in self.model.sym_names()
and function not in non_unique_id_symbols
):
lines.append(f'#include "{function}.h"')
lines.extend(
[
"",
"namespace amici {",
f"namespace model_{self.model_name} {{",
"",
f"{func_info.return_type} {function}_{self.model_name}"
f"({func_info.arguments(self.model.is_ode())}){{",
]
)
if self.assume_pow_positivity and func_info.assume_pow_positivity:
pow_rx = re.compile(r"(^|\W)std::pow\(")
body = [
# execute this twice to catch cases where the ending '(' would
# be the starting (^|\W) for the following match
pow_rx.sub(
r"\1amici::pos_pow(",
pow_rx.sub(r"\1amici::pos_pow(", line),
)
for line in body
]
self.functions[function].body = body
lines += body
lines.extend(
[
"}",
"",
f"}} // namespace model_{self.model_name}",
"} // namespace amici\n",
]
)
# check custom functions
for fun in CUSTOM_FUNCTIONS:
if "include" in fun and any(fun["c++"] in line for line in lines):
if "build_hint" in fun:
self._build_hints.add(fun["build_hint"])
lines.insert(0, fun["include"])
# if not body is None:
filename = os.path.join(self.model_path, f"{function}.cpp")
with open(filename, "w") as fileout:
fileout.write("\n".join(lines))
def _generate_function_index(
self, function: str, indextype: Literal["colptrs", "rowvals"]
) -> list[str]:
"""
Generate equations and C++ code for the function ``function``.
:param function:
name of the function to be written (see ``self.functions``)
:param indextype:
type of index {'colptrs', 'rowvals'}
:returns:
The code lines for the respective function index file
"""
if indextype == "colptrs":
values = self.model.colptrs(function)
setter = "indexptrs"
elif indextype == "rowvals":
values = self.model.rowvals(function)
setter = "indexvals"
else:
raise ValueError(
"Invalid value for indextype, must be colptrs or "
f"rowvals: {indextype}"
)
# function signature
if function in multiobs_functions:
signature = f"(SUNMatrixWrapper &{function}, int index)"
else:
signature = f"(SUNMatrixWrapper &{function})"
lines = [
'#include "amici/sundials_matrix_wrapper.h"',
'#include "sundials/sundials_types.h"',
"",
"#include <array>",
"#include <algorithm>",
"",
"namespace amici {",
f"namespace model_{self.model_name} {{",
"",
]
# Generate static array with indices
if len(values):
static_array_name = f"{function}_{indextype}_{self.model_name}_"
if function in multiobs_functions:
# list of index vectors
lines.append(
"static constexpr std::array<std::array<sunindextype, "
f"{len(values[0])}>, {len(values)}> "
f"{static_array_name} = {{{{"
)
lines.extend(
[
" {" + ", ".join(map(str, index_vector)) + "}, "
for index_vector in values
]
)
lines.append("}};")
else:
# single index vector
lines.extend(
[
"static constexpr std::array<sunindextype, "
f"{len(values)}> {static_array_name} = {{",
" " + ", ".join(map(str, values)),
"};",
]
)
lines.extend(
[
"",
f"void {function}_{indextype}_{self.model_name}{signature}{{",
]
)
if len(values):
if function in multiobs_functions:
lines.append(
f" {function}.set_{setter}"
f"(gsl::make_span({static_array_name}[index]));"
)
else:
lines.append(
f" {function}.set_{setter}"
f"(gsl::make_span({static_array_name}));"
)
lines.extend(
[
"}" "",
f"}} // namespace model_{self.model_name}",
"} // namespace amici\n",
]
)
return lines
def _get_function_body(
self, function: str, equations: sp.Matrix
) -> list[str]:
"""
Generate C++ code for body of function ``function``.
:param function:
name of the function to be written (see ``self.functions``)
:param equations:
symbolic definition of the function body
:return:
generated C++ code
"""
lines = []
if len(equations) == 0 or (
isinstance(equations, sp.Matrix | sp.ImmutableDenseMatrix)
and min(equations.shape) == 0
):
# dJydy is a list
return lines
if not self.allow_reinit_fixpar_initcond and function in {
"sx0_fixedParameters",
"x0_fixedParameters",
}:
return lines
if function == "sx0_fixedParameters":
# here we only want to overwrite values where x0_fixedParameters
# was applied
lines.extend(
[
# Keep list of indices of fixed parameters occurring in x0
" static const std::array<int, "
+ str(len(self.model._x0_fixedParameters_idx))
+ "> _x0_fixedParameters_idxs = {",
" "
+ ", ".join(
str(x) for x in self.model._x0_fixedParameters_idx
),
" };",
"",
# Set all parameters that are to be reset to 0, so that the
# switch statement below only needs to handle non-zero entries
# (which usually reduces file size and speeds up
# compilation significantly).
" for(auto idx: reinitialization_state_idxs) {",
" if(std::find(_x0_fixedParameters_idxs.cbegin(), "
"_x0_fixedParameters_idxs.cend(), idx) != "
"_x0_fixedParameters_idxs.cend())\n"
" sx0_fixedParameters[idx] = 0.0;",
" }",
]
)
cases = {}
for ipar in range(self.model.num_par()):
expressions = []
for index, formula in zip(
self.model._x0_fixedParameters_idx,
equations[:, ipar],
strict=True,
):
if not formula.is_zero:
expressions.extend(
[
f"if(std::find("
"reinitialization_state_idxs.cbegin(), "
f"reinitialization_state_idxs.cend(), {index}) != "
"reinitialization_state_idxs.cend())",
f" {function}[{index}] = "
f"{self._code_printer.doprint(formula)};",
]
)
cases[ipar] = expressions
lines.extend(get_switch_statement("ip", cases, 1))
elif function == "x0_fixedParameters":
for index, formula in zip(
self.model._x0_fixedParameters_idx, equations, strict=True
):
lines.append(
f" if(std::find(reinitialization_state_idxs.cbegin(), "
f"reinitialization_state_idxs.cend(), {index}) != "
"reinitialization_state_idxs.cend())\n "
f"{function}[{index}] = "
f"{self._code_printer.doprint(formula)};"
)
elif function in event_functions:
cases = {
ie: self._code_printer._get_sym_lines_array(
equations[ie], function, 0
)
for ie in range(self.model.num_events())
if not smart_is_zero_matrix(equations[ie])
}
lines.extend(get_switch_statement("ie", cases, 1))
elif function in event_sensi_functions:
outer_cases = {}
for ie, inner_equations in enumerate(equations):
inner_lines = []
inner_cases = {
ipar: self._code_printer._get_sym_lines_array(
inner_equations[:, ipar], function, 0
)
for ipar in range(self.model.num_par())
if not smart_is_zero_matrix(inner_equations[:, ipar])
}
inner_lines.extend(get_switch_statement("ip", inner_cases, 0))
outer_cases[ie] = copy.copy(inner_lines)
lines.extend(get_switch_statement("ie", outer_cases, 1))
elif (
function in sensi_functions
and equations.shape[1] == self.model.num_par()
):
cases = {
ipar: self._code_printer._get_sym_lines_array(
equations[:, ipar], function, 0
)
for ipar in range(self.model.num_par())
if not smart_is_zero_matrix(equations[:, ipar])
}
lines.extend(get_switch_statement("ip", cases, 1))
elif function in multiobs_functions:
if function == "dJydy":
cases = {
iobs: self._code_printer._get_sym_lines_array(
equations[iobs], function, 0
)
for iobs in range(self.model.num_obs())
if not smart_is_zero_matrix(equations[iobs])
}
else:
cases = {
iobs: self._code_printer._get_sym_lines_array(
equations[:, iobs], function, 0
)
for iobs in range(equations.shape[1])
if not smart_is_zero_matrix(equations[:, iobs])
}
if function.startswith(("Jz", "dJz", "Jrz", "dJrz")):
iterator = "iz"
else:
iterator = "iy"
lines.extend(get_switch_statement(iterator, cases, 1))
elif (
function in self.model.sym_names()
and function not in non_unique_id_symbols
):
if function in sparse_functions:
symbols = list(map(sp.Symbol, self.model.sparsesym(function)))
else:
symbols = self.model.sym(function)
if function in ("w", "dwdw", "dwdx", "dwdp"):
# Split into a block of static and dynamic expressions.
if len(static_idxs := self.model.static_indices(function)) > 0:
tmp_symbols = sp.Matrix(
[[symbols[i]] for i in static_idxs]
)
tmp_equations = sp.Matrix(
[equations[i] for i in static_idxs]
)
tmp_lines = self._code_printer._get_sym_lines_symbols(
tmp_symbols,
tmp_equations,
function,
8,
static_idxs,
)
if tmp_lines:
lines.extend(
[
" // static expressions",
" if (include_static) {",
*tmp_lines,
" }",
]
)
# dynamic expressions
if len(dynamic_idxs := self.model.dynamic_indices(function)):
tmp_symbols = sp.Matrix(
[[symbols[i]] for i in dynamic_idxs]
)
tmp_equations = sp.Matrix(
[equations[i] for i in dynamic_idxs]
)
tmp_lines = self._code_printer._get_sym_lines_symbols(
tmp_symbols,
tmp_equations,
function,
4,
dynamic_idxs,
)
if tmp_lines:
lines.append("\n // dynamic expressions")
lines.extend(tmp_lines)
else:
lines += self._code_printer._get_sym_lines_symbols(
symbols, equations, function, 4
)
else:
lines += self._code_printer._get_sym_lines_array(
equations, function, 4
)
return [line for line in lines if line]
def _get_create_splines_body(self):
if not self.model._splines:
return [" return {};"]
ind4 = " " * 4
ind8 = " " * 8
body = ["return {"]
for ispl, spline in enumerate(self.model._splines):
if isinstance(spline.nodes, splines.UniformGrid):
nodes = (
f"{ind8}{{{spline.nodes.start}, {spline.nodes.stop}}}, "
)
else:
nodes = f"{ind8}{{{', '.join(map(str, spline.nodes))}}}, "
# vector with the node values
values = (
f"{ind8}{{{', '.join(map(str, spline.values_at_nodes))}}}, "
)
# vector with the slopes
if spline.derivatives_by_fd:
slopes = f"{ind8}{{}},"
else:
slopes = f"{ind8}{{{', '.join(map(str, spline.derivatives_at_nodes))}}},"
body.extend(
[
f"{ind4}HermiteSpline(",
nodes,
values,
slopes,
]
)
bc_to_cpp = {
None: "SplineBoundaryCondition::given, ",
"zeroderivative": "SplineBoundaryCondition::zeroDerivative, ",
"natural": "SplineBoundaryCondition::natural, ",
"zeroderivative+natural": "SplineBoundaryCondition::naturalZeroDerivative, ",
"periodic": "SplineBoundaryCondition::periodic, ",
}
for bc in spline.bc:
try:
body.append(ind8 + bc_to_cpp[bc])
except KeyError:
raise ValueError(
f"Unknown boundary condition '{bc}' "
"found in spline object"
)
extrapolate_to_cpp = {
None: "SplineExtrapolation::noExtrapolation, ",
"polynomial": "SplineExtrapolation::polynomial, ",
"constant": "SplineExtrapolation::constant, ",
"linear": "SplineExtrapolation::linear, ",
"periodic": "SplineExtrapolation::periodic, ",
}
for extr in spline.extrapolate:
try:
body.append(ind8 + extrapolate_to_cpp[extr])
except KeyError:
raise ValueError(
f"Unknown extrapolation '{extr}' "
"found in spline object"
)
line = ind8
line += "true, " if spline.derivatives_by_fd else "false, "
line += (
"true, "
if isinstance(spline.nodes, splines.UniformGrid)
else "false, "
)
line += "true" if spline.logarithmic_parametrization else "false"
body.append(line)
body.append(f"{ind4}),")
body.append("};")
return [" " + line for line in body]
def _write_wrapfunctions_cpp(self) -> None:
"""
Write model-specific 'wrapper' file (``wrapfunctions.cpp``).
"""
template_data = {"MODELNAME": self.model_name}
apply_template(
os.path.join(amiciSrcPath, "wrapfunctions.template.cpp"),
os.path.join(self.model_path, "wrapfunctions.cpp"),
template_data,
)
def _write_wrapfunctions_header(self) -> None:
"""
Write model-specific header file (``wrapfunctions.h``).
"""
template_data = {"MODELNAME": str(self.model_name)}
apply_template(
os.path.join(amiciSrcPath, "wrapfunctions.template.h"),
os.path.join(self.model_path, "wrapfunctions.h"),
template_data,
)
def _write_model_header_cpp(self) -> None:
"""
Write model-specific header and cpp file (MODELNAME.{h,cpp}).
"""
model_type = "ODE" if self.model.is_ode() else "DAE"
tpl_data = {
"MODEL_TYPE_LOWER": model_type.lower(),
"MODEL_TYPE_UPPER": model_type,
"MODELNAME": self.model_name,
"NX_RDATA": self.model.num_states_rdata(),
"NXTRUE_RDATA": self.model.num_states_rdata(),
"NX_SOLVER": self.model.num_states_solver(),
"NXTRUE_SOLVER": self.model.num_states_solver(),
"NX_SOLVER_REINIT": self.model.num_state_reinits(),
"NY": self.model.num_obs(),
"NYTRUE": self.model.num_obs(),
"NZ": self.model.num_eventobs(),
"NZTRUE": self.model.num_eventobs(),
"NEVENT": self.model.num_events(),
"NEVENT_SOLVER": self.model.num_events_solver(),
"NOBJECTIVE": "1",