-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathmodel.cpp
3110 lines (2694 loc) · 99.6 KB
/
model.cpp
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
#include <amici/amici.h>
#include <amici/cblas.h>
#include <amici/exception.h>
#include <amici/misc.h>
#include <amici/model.h>
#include <amici/symbolic_functions.h>
#include <algorithm>
#include <assert.h>
#include <cmath>
#include <cstring>
#include <numeric>
#include <regex>
#include <typeinfo>
#include <utility>
namespace amici {
/**
* @brief Maps ModelQuantity items to their string value
*/
const std::map<ModelQuantity, std::string> model_quantity_to_str{
{ModelQuantity::J, "J"},
{ModelQuantity::JB, "JB"},
{ModelQuantity::Jv, "Jv"},
{ModelQuantity::JvB, "JvB"},
{ModelQuantity::JDiag, "JDiag"},
{ModelQuantity::sx, "sx"},
{ModelQuantity::sy, "sy"},
{ModelQuantity::sz, "sz"},
{ModelQuantity::srz, "srz"},
{ModelQuantity::ssigmay, "ssigmay"},
{ModelQuantity::ssigmaz, "ssigmaz"},
{ModelQuantity::xdot, "xdot"},
{ModelQuantity::sxdot, "sxdot"},
{ModelQuantity::xBdot, "xBdot"},
{ModelQuantity::x0, "x0"},
{ModelQuantity::x0_rdata, "x0_rdata"},
{ModelQuantity::x, "x"},
{ModelQuantity::x_rdata, "x_rdata"},
{ModelQuantity::dwdw, "dwdw"},
{ModelQuantity::dwdx, "dwdx"},
{ModelQuantity::dwdp, "dwdp"},
{ModelQuantity::y, "y"},
{ModelQuantity::dydp, "dydp"},
{ModelQuantity::dydx, "dydx"},
{ModelQuantity::w, "w"},
{ModelQuantity::root, "root"},
{ModelQuantity::qBdot, "qBdot"},
{ModelQuantity::qBdot_ss, "qBdot_ss"},
{ModelQuantity::xBdot_ss, "xBdot_ss"},
{ModelQuantity::JSparseB_ss, "JSparseB_ss"},
{ModelQuantity::deltax, "deltax"},
{ModelQuantity::deltasx, "deltasx"},
{ModelQuantity::deltaxB, "deltaxB"},
{ModelQuantity::k, "k"},
{ModelQuantity::p, "p"},
{ModelQuantity::ts, "ts"},
{ModelQuantity::dJydy, "dJydy"},
{ModelQuantity::dJydy_matlab, "dJydy"},
{ModelQuantity::deltaqB, "deltaqB"},
{ModelQuantity::dsigmaydp, "dsigmaydp"},
{ModelQuantity::dsigmaydy, "dsigmaydy"},
{ModelQuantity::dsigmazdp, "dsigmazdp"},
{ModelQuantity::dJydsigma, "dJydsigma"},
{ModelQuantity::dJydx, "dJydx"},
{ModelQuantity::dJrzdx, "dJrzdx"},
{ModelQuantity::dJzdx, "dJzdx"},
{ModelQuantity::dzdp, "dzdp"},
{ModelQuantity::dzdx, "dzdx"},
{ModelQuantity::dJrzdsigma, "dJrzdsigma"},
{ModelQuantity::dJrzdz, "dJrzdz"},
{ModelQuantity::dJzdsigma, "dJzdsigma"},
{ModelQuantity::dJzdz, "dJzdz"},
{ModelQuantity::drzdp, "drzdp"},
{ModelQuantity::drzdx, "drzdx"},
};
static void setNaNtoZero(std::vector<realtype>& vec) {
std::for_each(vec.begin(), vec.end(), [](double& val) {
if (std::isnan(val)) {
val = 0.0;
}
});
}
/**
* @brief local helper function to get parameters
* @param ids vector of name/ids of (fixed)Parameters
* @param values values of the (fixed)Parameters
* @param id name/id to look for in the vector
* @param variable_name string indicating what variable we are looking at
* @param id_name string indicating whether name or id was specified
* @return value of the selected parameter
*/
static realtype getValueById(
std::vector<std::string> const& ids, std::vector<realtype> const& values,
std::string const& id, char const* variable_name, char const* id_name
) {
auto it = std::find(ids.begin(), ids.end(), id);
if (it != ids.end())
return values.at(it - ids.begin());
throw AmiException(
"Could not find %s with specified %s", variable_name, id_name
);
}
/**
* @brief local helper function to set parameters
* @param ids vector of names/ids of (fixed)Parameters
* @param values values of the (fixed)Parameters
* @param value for the selected parameter
* @param id name/id to look for in the vector
* @param variable_name string indicating what variable we are looking at
* @param id_name string indicating whether name or id was specified
*/
static void setValueById(
std::vector<std::string> const& ids, std::vector<realtype>& values,
realtype value, std::string const& id, char const* variable_name,
char const* id_name
) {
auto it = std::find(ids.begin(), ids.end(), id);
if (it != ids.end())
values.at(it - ids.begin()) = value;
else
throw AmiException(
"Could not find %s with specified %s", variable_name, id_name
);
}
/**
* @brief local helper function to set parameters via regex
* @param ids vector of names/ids of (fixed)Parameters
* @param values values of the (fixed)Parameters
* @param value for the selected parameter
* @param regex string according to which names/ids are to be matched
* @param variable_name string indicating what variable we are looking at
* @param id_name string indicating whether name or id was specified
* @return number of matched names/ids
*/
static int setValueByIdRegex(
std::vector<std::string> const& ids, std::vector<realtype>& values,
realtype value, std::string const& regex, char const* variable_name,
char const* id_name
) {
try {
std::regex pattern(regex);
int n_found = 0;
for (auto const& id : ids) {
if (std::regex_match(id, pattern)) {
values.at(&id - &ids[0]) = value;
++n_found;
}
}
if (n_found == 0)
throw AmiException(
"Could not find %s with specified %s (%s)", variable_name,
id_name, regex.c_str()
);
return n_found;
} catch (std::regex_error const& e) {
auto err_string = regexErrorToString(e.code());
throw AmiException(
"Specified regex pattern %s could not be compiled:"
" %s (%s)",
regex.c_str(), e.what(), err_string.c_str()
);
}
}
Model::Model(
ModelDimensions const& model_dimensions,
SimulationParameters simulation_parameters, SecondOrderMode o2mode,
std::vector<realtype> idlist, std::vector<int> z2event,
bool const pythonGenerated, int const ndxdotdp_explicit,
int const ndxdotdx_explicit, int const w_recursion_depth
)
: ModelDimensions(model_dimensions)
, pythonGenerated(pythonGenerated)
, o2mode(o2mode)
, idlist(std::move(idlist))
, derived_state_(model_dimensions)
, z2event_(std::move(z2event))
, state_is_non_negative_(nx_solver, false)
, w_recursion_depth_(w_recursion_depth)
, simulation_parameters_(std::move(simulation_parameters)) {
Expects(
model_dimensions.np
== gsl::narrow<int>(simulation_parameters_.parameters.size())
);
Expects(
model_dimensions.nk
== gsl::narrow<int>(simulation_parameters_.fixedParameters.size())
);
simulation_parameters.pscale = std::vector<ParameterScaling>(
model_dimensions.np, ParameterScaling::none
);
state_.h.resize(ne, 0.0);
state_.total_cl.resize(nx_rdata - nx_solver, 0.0);
state_.stotal_cl.resize((nx_rdata - nx_solver) * np(), 0.0);
state_.unscaledParameters.resize(np());
unscaleParameters(
simulation_parameters_.parameters, simulation_parameters_.pscale,
state_.unscaledParameters
);
state_.fixedParameters = simulation_parameters_.fixedParameters;
state_.plist = simulation_parameters_.plist;
root_initial_values_.resize(ne, true);
/* If Matlab wrapped: dxdotdp is a full AmiVector,
if Python wrapped: dxdotdp_explicit and dxdotdp_implicit are CSC matrices
*/
if (pythonGenerated) {
dwdw_ = SUNMatrixWrapper(nw, nw, ndwdw, CSC_MAT);
// size dynamically adapted for dwdx_ and dwdp_
derived_state_.dwdx_ = SUNMatrixWrapper(nw, nx_solver, 0, CSC_MAT);
derived_state_.dwdp_ = SUNMatrixWrapper(nw, np(), 0, CSC_MAT);
for (int irec = 0; irec <= w_recursion_depth_; ++irec) {
/* for the first element we know the exact size, while for all
others we guess the size*/
dwdp_hierarchical_.emplace_back(
SUNMatrixWrapper(nw, np(), irec * ndwdw + ndwdp, CSC_MAT)
);
dwdx_hierarchical_.emplace_back(
SUNMatrixWrapper(nw, nx_solver, irec * ndwdw + ndwdx, CSC_MAT)
);
}
assert(
gsl::narrow<int>(dwdp_hierarchical_.size())
== w_recursion_depth_ + 1
);
assert(
gsl::narrow<int>(dwdx_hierarchical_.size())
== w_recursion_depth_ + 1
);
derived_state_.dxdotdp_explicit
= SUNMatrixWrapper(nx_solver, np(), ndxdotdp_explicit, CSC_MAT);
// guess size, will be dynamically reallocated
derived_state_.dxdotdp_implicit
= SUNMatrixWrapper(nx_solver, np(), ndwdp + ndxdotdw, CSC_MAT);
derived_state_.dxdotdx_explicit = SUNMatrixWrapper(
nx_solver, nx_solver, ndxdotdx_explicit, CSC_MAT
);
// guess size, will be dynamically reallocated
derived_state_.dxdotdx_implicit
= SUNMatrixWrapper(nx_solver, nx_solver, ndwdx + ndxdotdw, CSC_MAT);
// dynamically allocate on first call
derived_state_.dxdotdp_full
= SUNMatrixWrapper(nx_solver, np(), 0, CSC_MAT);
for (int iytrue = 0; iytrue < nytrue; ++iytrue)
derived_state_.dJydy_.emplace_back(
SUNMatrixWrapper(nJ, ny, ndJydy.at(iytrue), CSC_MAT)
);
} else {
derived_state_.dwdx_ = SUNMatrixWrapper(nw, nx_solver, ndwdx, CSC_MAT);
derived_state_.dwdp_ = SUNMatrixWrapper(nw, np(), ndwdp, CSC_MAT);
derived_state_.dJydy_matlab_
= std::vector<realtype>(nJ * nytrue * ny, 0.0);
}
requireSensitivitiesForAllParameters();
}
bool operator==(Model const& a, Model const& b) {
if (typeid(a) != typeid(b))
return false;
return (static_cast<ModelDimensions const&>(a)
== static_cast<ModelDimensions const&>(b))
&& (a.o2mode == b.o2mode) && (a.z2event_ == b.z2event_)
&& (a.idlist == b.idlist)
&& (a.simulation_parameters_ == b.simulation_parameters_)
&& (a.x0data_ == b.x0data_) && (a.sx0data_ == b.sx0data_)
&& (a.nmaxevent_ == b.nmaxevent_)
&& (a.state_is_non_negative_ == b.state_is_non_negative_)
&& (a.sigma_res_ == b.sigma_res_) && (a.min_sigma_ == b.min_sigma_)
&& a.state_ == b.state_;
}
bool operator==(ModelDimensions const& a, ModelDimensions const& b) {
if (typeid(a) != typeid(b))
return false;
return (a.nx_rdata == b.nx_rdata) && (a.nxtrue_rdata == b.nxtrue_rdata)
&& (a.nx_solver == b.nx_solver)
&& (a.nxtrue_solver == b.nxtrue_solver)
&& (a.nx_solver_reinit == b.nx_solver_reinit) && (a.np == b.np)
&& (a.nk == b.nk) && (a.ny == b.ny) && (a.nytrue == b.nytrue)
&& (a.nz == b.nz) && (a.nztrue == b.nztrue) && (a.ne == b.ne)
&& (a.nw == b.nw) && (a.ndwdx == b.ndwdx) && (a.ndwdp == b.ndwdp)
&& (a.ndwdw == b.ndwdw) && (a.ndxdotdw == b.ndxdotdw)
&& (a.ndJydy == b.ndJydy) && (a.nnz == b.nnz) && (a.nJ == b.nJ)
&& (a.ubw == b.ubw) && (a.lbw == b.lbw);
}
void Model::initialize(
AmiVector& x, AmiVector& dx, AmiVectorArray& sx, AmiVectorArray& /*sdx*/,
bool computeSensitivities, std::vector<int>& roots_found
) {
initializeStates(x);
initializeSplines();
if (computeSensitivities) {
initializeStateSensitivities(sx, x);
initializeSplineSensitivities();
}
fdx0(x, dx);
if (computeSensitivities)
fsdx0();
if (ne)
initEvents(x, dx, roots_found);
}
void Model::initializeB(
AmiVector& xB, AmiVector& dxB, AmiVector& xQB, bool posteq
) const {
xB.zero();
dxB.zero();
if (!posteq)
xQB.zero();
}
void Model::initializeStates(AmiVector& x) {
if (x0data_.empty()) {
fx0(x);
} else {
std::vector<realtype> x0_solver(nx_solver, 0.0);
ftotal_cl(
state_.total_cl.data(), x0data_.data(),
state_.unscaledParameters.data(), state_.fixedParameters.data()
);
fx_solver(x0_solver.data(), x0data_.data());
std::copy(x0_solver.cbegin(), x0_solver.cend(), x.data());
}
checkFinite(x.getVector(), ModelQuantity::x0);
}
void Model::initializeSplines() {
splines_ = fcreate_splines(
state_.unscaledParameters.data(), state_.fixedParameters.data()
);
state_.spl_.resize(splines_.size(), 0.0);
for (auto& spline : splines_) {
spline.compute_coefficients();
}
}
void Model::initializeSplineSensitivities() {
derived_state_.sspl_ = SUNMatrixWrapper(splines_.size(), np());
int allnodes = 0;
for (auto const& spline : splines_) {
allnodes += spline.n_nodes();
}
std::vector<realtype> dspline_valuesdp(allnodes * nplist(), 0.0);
std::vector<realtype> dspline_slopesdp(allnodes * nplist(), 0.0);
std::vector<realtype> tmp_dvalues(allnodes, 0.0);
std::vector<realtype> tmp_dslopes(allnodes, 0.0);
for (int ip = 0; ip < nplist(); ip++) {
std::fill(tmp_dvalues.begin(), tmp_dvalues.end(), 0.0);
std::fill(tmp_dslopes.begin(), tmp_dslopes.end(), 0.0);
fdspline_valuesdp(
tmp_dvalues.data(), state_.unscaledParameters.data(),
state_.fixedParameters.data(), plist(ip)
);
fdspline_slopesdp(
tmp_dslopes.data(), state_.unscaledParameters.data(),
state_.fixedParameters.data(), plist(ip)
);
/* NB dspline_valuesdp/dspline_slopesdp must be filled
* using the following order for the indices
* (from slower to faster): spline, node, parameter.
* That is what the current spline implementation expects.
*/
int k = 0;
int offset = ip;
for (auto const& spline : splines_) {
for (int n = 0; n < spline.n_nodes(); n++) {
dspline_valuesdp[offset] = tmp_dvalues[k];
dspline_slopesdp[offset] = tmp_dslopes[k];
offset += nplist();
k += 1;
}
}
assert(k == allnodes);
}
int spline_offset = 0;
for (auto& spline : splines_) {
spline.compute_coefficients_sensi(
nplist(), spline_offset, dspline_valuesdp, dspline_slopesdp
);
spline_offset += spline.n_nodes() * nplist();
}
}
void Model::initializeStateSensitivities(
AmiVectorArray& sx, AmiVector const& x
) {
if (sx0data_.empty()) {
fsx0(sx, x);
} else {
realtype* stcl = nullptr;
std::vector<realtype> sx0_solver_slice(nx_solver, 0.0);
for (int ip = 0; ip < nplist(); ip++) {
if (ncl() > 0)
stcl = &state_.stotal_cl.at(plist(ip) * ncl());
fstotal_cl(
stcl, &sx0data_.at(ip * nx_rdata), plist(ip),
derived_state_.x_rdata_.data(),
state_.unscaledParameters.data(), state_.fixedParameters.data(),
state_.total_cl.data()
);
fsx_solver(sx0_solver_slice.data(), &sx0data_.at(ip * nx_rdata));
for (int ix = 0; ix < nx_solver; ix++) {
sx.at(ix, ip) = sx0_solver_slice.at(ix);
}
}
}
}
void Model::initEvents(
AmiVector const& x, AmiVector const& dx, std::vector<int>& roots_found
) {
std::vector<realtype> rootvals(ne, 0.0);
froot(simulation_parameters_.tstart_, x, dx, rootvals);
std::fill(roots_found.begin(), roots_found.end(), 0);
for (int ie = 0; ie < ne; ie++) {
if (rootvals.at(ie) < 0) {
state_.h.at(ie) = 0.0;
} else {
state_.h.at(ie) = 1.0;
if (!root_initial_values_.at(ie)) // only false->true triggers event
roots_found.at(ie) = 1;
}
}
}
int Model::nplist() const { return gsl::narrow<int>(state_.plist.size()); }
int Model::np() const {
return gsl::narrow<int>(static_cast<ModelDimensions const&>(*this).np);
}
int Model::nk() const {
return gsl::narrow<int>(state_.fixedParameters.size());
}
int Model::ncl() const { return nx_rdata - nx_solver; }
int Model::nx_reinit() const { return nx_solver_reinit; }
double const* Model::k() const { return state_.fixedParameters.data(); }
int Model::nMaxEvent() const { return nmaxevent_; }
void Model::setNMaxEvent(int nmaxevent) { nmaxevent_ = nmaxevent; }
int Model::nt() const {
return gsl::narrow<int>(simulation_parameters_.ts_.size());
}
std::vector<ParameterScaling> const& Model::getParameterScale() const {
return simulation_parameters_.pscale;
}
void Model::setParameterScale(ParameterScaling pscale) {
simulation_parameters_.pscale.assign(
simulation_parameters_.pscale.size(), pscale
);
scaleParameters(
state_.unscaledParameters, simulation_parameters_.pscale,
simulation_parameters_.parameters
);
sx0data_.clear();
}
void Model::setParameterScale(std::vector<ParameterScaling> const& pscaleVec) {
if (pscaleVec.size() != simulation_parameters_.parameters.size())
throw AmiException("Dimension mismatch. Size of parameter scaling does "
"not match number of model parameters.");
simulation_parameters_.pscale = pscaleVec;
scaleParameters(
state_.unscaledParameters, simulation_parameters_.pscale,
simulation_parameters_.parameters
);
sx0data_.clear();
}
std::vector<realtype> const& Model::getUnscaledParameters() const {
return state_.unscaledParameters;
}
std::vector<realtype> const& Model::getParameters() const {
return simulation_parameters_.parameters;
}
realtype Model::getParameterById(std::string const& par_id) const {
if (!hasParameterIds())
throw AmiException(
"Could not access parameters by id as they are not set"
);
return getValueById(
getParameterIds(), simulation_parameters_.parameters, par_id,
"parameters", "id"
);
}
realtype Model::getParameterByName(std::string const& par_name) const {
if (!hasParameterNames())
throw AmiException(
"Could not access parameters by name as they are not set"
);
return getValueById(
getParameterNames(), simulation_parameters_.parameters, par_name,
"parameters", "name"
);
}
void Model::setParameters(std::vector<realtype> const& p) {
if (p.size() != (unsigned)np())
throw AmiException("Dimension mismatch. Size of parameters does not "
"match number of model parameters.");
simulation_parameters_.parameters = p;
state_.unscaledParameters.resize(simulation_parameters_.parameters.size());
unscaleParameters(
simulation_parameters_.parameters, simulation_parameters_.pscale,
state_.unscaledParameters
);
}
void Model::setParameterById(
std::map<std::string, realtype> const& p, bool ignoreErrors
) {
for (auto& kv : p) {
try {
setParameterById(kv.first, kv.second);
} catch (AmiException const&) {
if (!ignoreErrors)
throw;
}
}
}
void Model::setParameterById(std::string const& par_id, realtype value) {
if (!hasParameterIds())
throw AmiException(
"Could not access parameters by id as they are not set"
);
setValueById(
getParameterIds(), simulation_parameters_.parameters, value, par_id,
"parameter", "id"
);
unscaleParameters(
simulation_parameters_.parameters, simulation_parameters_.pscale,
state_.unscaledParameters
);
}
int Model::setParametersByIdRegex(
std::string const& par_id_regex, realtype value
) {
if (!hasParameterIds())
throw AmiException(
"Could not access parameters by id as they are not set"
);
int n_found = setValueByIdRegex(
getParameterIds(), simulation_parameters_.parameters, value,
par_id_regex, "parameter", "id"
);
unscaleParameters(
simulation_parameters_.parameters, simulation_parameters_.pscale,
state_.unscaledParameters
);
return n_found;
}
void Model::setParameterByName(std::string const& par_name, realtype value) {
if (!hasParameterNames())
throw AmiException(
"Could not access parameters by name as they are not set"
);
setValueById(
getParameterNames(), simulation_parameters_.parameters, value, par_name,
"parameter", "name"
);
unscaleParameters(
simulation_parameters_.parameters, simulation_parameters_.pscale,
state_.unscaledParameters
);
}
void Model::setParameterByName(
std::map<std::string, realtype> const& p, bool ignoreErrors
) {
for (auto& kv : p) {
try {
setParameterByName(kv.first, kv.second);
} catch (AmiException const&) {
if (!ignoreErrors)
throw;
}
}
}
int Model::setParametersByNameRegex(
std::string const& par_name_regex, realtype value
) {
if (!hasParameterNames())
throw AmiException(
"Could not access parameters by name as they are not set"
);
int n_found = setValueByIdRegex(
getParameterNames(), simulation_parameters_.parameters, value,
par_name_regex, "parameter", "name"
);
unscaleParameters(
simulation_parameters_.parameters, simulation_parameters_.pscale,
state_.unscaledParameters
);
return n_found;
}
std::vector<realtype> const& Model::getFixedParameters() const {
return state_.fixedParameters;
}
realtype Model::getFixedParameterById(std::string const& par_id) const {
if (!hasFixedParameterIds())
throw AmiException(
"Could not access fixed parameters by id as they are not set"
);
return getValueById(
getFixedParameterIds(), state_.fixedParameters, par_id,
"fixedParameters", "id"
);
}
realtype Model::getFixedParameterByName(std::string const& par_name) const {
if (!hasFixedParameterNames())
throw AmiException(
"Could not access fixed parameters by name as they are not set"
);
return getValueById(
getFixedParameterNames(), state_.fixedParameters, par_name,
"fixedParameters", "name"
);
}
void Model::setFixedParameters(std::vector<realtype> const& k) {
if (k.size() != (unsigned)nk())
throw AmiException("Dimension mismatch. Size of fixedParameters does "
"not match number of fixed model parameters.");
state_.fixedParameters = k;
}
void Model::setFixedParameterById(std::string const& par_id, realtype value) {
if (!hasFixedParameterIds())
throw AmiException(
"Could not access fixed parameters by id as they are not set"
);
setValueById(
getFixedParameterIds(), state_.fixedParameters, value, par_id,
"fixedParameters", "id"
);
}
int Model::setFixedParametersByIdRegex(
std::string const& par_id_regex, realtype value
) {
if (!hasFixedParameterIds())
throw AmiException(
"Could not access fixed parameters by id as they are not set"
);
return setValueByIdRegex(
getFixedParameterIds(), state_.fixedParameters, value, par_id_regex,
"fixedParameters", "id"
);
}
void Model::setFixedParameterByName(
std::string const& par_name, realtype value
) {
if (!hasFixedParameterNames())
throw AmiException(
"Could not access fixed parameters by name as they are not set"
);
setValueById(
getFixedParameterNames(), state_.fixedParameters, value, par_name,
"fixedParameters", "name"
);
}
int Model::setFixedParametersByNameRegex(
std::string const& par_name_regex, realtype value
) {
if (!hasFixedParameterNames())
throw AmiException(
"Could not access fixed parameters by name as they are not set"
);
return setValueByIdRegex(
getFixedParameterIds(), state_.fixedParameters, value, par_name_regex,
"fixedParameters", "name"
);
}
std::string Model::getName() const { return ""; }
bool Model::hasParameterNames() const {
return np() == 0 || !getParameterNames().empty();
}
std::vector<std::string> Model::getParameterNames() const {
return std::vector<std::string>();
}
bool Model::hasStateNames() const {
return nx_rdata == 0 || !getStateNames().empty();
}
std::vector<std::string> Model::getStateNames() const {
return std::vector<std::string>();
}
std::vector<std::string> Model::getStateNamesSolver() const {
return std::vector<std::string>();
}
bool Model::hasFixedParameterNames() const {
return nk() == 0 || !getFixedParameterNames().empty();
}
std::vector<std::string> Model::getFixedParameterNames() const {
return std::vector<std::string>();
}
bool Model::hasObservableNames() const {
return ny == 0 || !getObservableNames().empty();
}
std::vector<std::string> Model::getObservableNames() const {
return std::vector<std::string>();
}
bool Model::hasExpressionNames() const {
return ny == 0 || !getExpressionNames().empty();
}
std::vector<std::string> Model::getExpressionNames() const {
return std::vector<std::string>();
}
bool Model::hasParameterIds() const {
return np() == 0 || !getParameterIds().empty();
}
std::vector<std::string> Model::getParameterIds() const {
return std::vector<std::string>();
}
bool Model::hasStateIds() const {
return nx_rdata == 0 || !getStateIds().empty();
}
std::vector<std::string> Model::getStateIds() const {
return std::vector<std::string>();
}
std::vector<std::string> Model::getStateIdsSolver() const {
return std::vector<std::string>();
}
bool Model::hasFixedParameterIds() const {
return nk() == 0 || !getFixedParameterIds().empty();
}
std::vector<std::string> Model::getFixedParameterIds() const {
return std::vector<std::string>();
}
bool Model::hasObservableIds() const {
return ny == 0 || !getObservableIds().empty();
}
std::vector<std::string> Model::getObservableIds() const {
return std::vector<std::string>();
}
bool Model::hasExpressionIds() const {
return ny == 0 || !getExpressionIds().empty();
}
std::vector<std::string> Model::getExpressionIds() const {
return std::vector<std::string>();
}
bool Model::hasQuadraticLLH() const { return true; }
std::vector<realtype> const& Model::getTimepoints() const {
return simulation_parameters_.ts_;
}
double Model::getTimepoint(int const it) const {
return simulation_parameters_.ts_.at(it);
}
void Model::setTimepoints(std::vector<realtype> const& ts) {
if (!std::is_sorted(ts.begin(), ts.end()))
throw AmiException("Encountered non-monotonic timepoints, please order"
" timepoints such that they are monotonically"
" increasing!");
simulation_parameters_.ts_ = ts;
}
double Model::t0() const { return simulation_parameters_.tstart_; }
void Model::setT0(double t0) { simulation_parameters_.tstart_ = t0; }
std::vector<bool> const& Model::getStateIsNonNegative() const {
return state_is_non_negative_;
}
void Model::setStateIsNonNegative(std::vector<bool> const& nonNegative) {
auto any_state_non_negative
= std::any_of(nonNegative.begin(), nonNegative.end(), [](bool x) {
return x;
});
if (nx_solver != nx_rdata) {
if (any_state_non_negative)
throw AmiException("Non-negative states are not supported with"
" conservation laws enabled.");
// nothing to do, as `state_is_non_negative_` will always be all-false
// in case of conservation laws
return;
}
if (state_is_non_negative_.size() != gsl::narrow<unsigned long>(nx_rdata)) {
throw AmiException(
"Dimension of input stateIsNonNegative (%u) does "
"not agree with number of state variables (%d)",
state_is_non_negative_.size(), nx_rdata
);
}
state_is_non_negative_ = nonNegative;
any_state_non_negative_ = any_state_non_negative;
}
void Model::setAllStatesNonNegative() {
setStateIsNonNegative(std::vector<bool>(nx_solver, true));
}
std::vector<int> const& Model::getParameterList() const { return state_.plist; }
int Model::plist(int pos) const { return state_.plist.at(pos); }
void Model::setParameterList(std::vector<int> const& plist) {
int np = this->np(); // cannot capture 'this' in lambda expression
if (std::any_of(plist.begin(), plist.end(), [&np](int idx) {
return idx < 0 || idx >= np;
})) {
throw AmiException("Indices in plist must be in [0..np]");
}
state_.plist = plist;
initializeVectors();
}
std::vector<realtype> Model::getInitialStates() {
if (!x0data_.empty()) {
return x0data_;
}
/* Initial states have not been set explicitly on this instance, so we
* compute it, but don't save it, as this would have to be invalidated upon
* changing parameters etc.
*/
std::vector<realtype> x0(nx_rdata, 0.0);
fx0(x0.data(), simulation_parameters_.tstart_,
state_.unscaledParameters.data(), state_.fixedParameters.data());
return x0;
}
void Model::setInitialStates(std::vector<realtype> const& x0) {
if (x0.size() != (unsigned)nx_rdata && !x0.empty())
throw AmiException("Dimension mismatch. Size of x0 does not match "
"number of model states.");
if (x0.empty()) {
x0data_.clear();
return;
}
x0data_ = x0;
}
bool Model::hasCustomInitialStates() const { return !x0data_.empty(); }
std::vector<realtype> Model::getInitialStateSensitivities() {
if (!sx0data_.empty()) {
return sx0data_;
}
/* Initial state sensitivities have not been set explicitly on this
* instance, so we compute it, but don't save it, as this would have to be
* invalidated upon changing parameters etc.
*/
std::vector<realtype> sx0(nx_rdata * nplist(), 0.0);
auto x0 = getInitialStates();
for (int ip = 0; ip < nplist(); ip++) {
fsx0(
sx0.data(), simulation_parameters_.tstart_, x0.data(),
state_.unscaledParameters.data(), state_.fixedParameters.data(),
plist(ip)
);
}
return sx0;
}
void Model::setInitialStateSensitivities(std::vector<realtype> const& sx0) {
if (sx0.size() != (unsigned)nx_rdata * nplist() && !sx0.empty())
throw AmiException("Dimension mismatch. Size of sx0 does not match "
"number of model states * number of parameter "
"selected for sensitivities.");
if (sx0.empty()) {
sx0data_.clear();
return;
}
realtype chainrulefactor = 1.0;
std::vector<realtype> sx0_rdata(nx_rdata * nplist(), 0.0);
for (int ip = 0; ip < nplist(); ip++) {
// revert chainrule
switch (simulation_parameters_.pscale.at(plist(ip))) {
case ParameterScaling::log10:
chainrulefactor = state_.unscaledParameters.at(plist(ip)) * log(10);
break;
case ParameterScaling::ln:
chainrulefactor = state_.unscaledParameters.at(plist(ip));
break;
case ParameterScaling::none:
chainrulefactor = 1.0;
break;
}
for (int ix = 0; ix < nx_rdata; ++ix) {
sx0_rdata.at(ip * nx_rdata + ix)
= sx0.at(ip * nx_rdata + ix) / chainrulefactor;
}
}
setUnscaledInitialStateSensitivities(sx0_rdata);
}
bool Model::hasCustomInitialStateSensitivities() const {
return !sx0data_.empty();
}
void Model::setUnscaledInitialStateSensitivities(
std::vector<realtype> const& sx0
) {
if (sx0.size() != (unsigned)nx_rdata * nplist() && !sx0.empty())
throw AmiException("Dimension mismatch. Size of sx0 does not match "
"number of model states * number of parameter "
"selected for sensitivities.");
if (sx0.empty()) {
sx0data_.clear();
return;
}
sx0data_ = sx0;
}
void Model::setSteadyStateSensitivityMode(const SteadyStateSensitivityMode mode
) {
steadystate_sensitivity_mode_ = mode;
}