-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathamici.cpp
More file actions
278 lines (247 loc) · 9.26 KB
/
amici.cpp
File metadata and controls
278 lines (247 loc) · 9.26 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
/**
* @file amici.cpp
* @brief core routines for integration
*/
#include "amici/amici.h"
#include "amici/backwardproblem.h"
#include "amici/forwardproblem.h"
#include "amici/logging.h"
#include "amici/steadystateproblem.h"
#include <sundials/sundials_types.h> //sunrealtype
#include <map>
#include <memory>
#include <type_traits>
static_assert(
amici::AMICI_SINGULAR_JACOBIAN == SUN_ERR_EXT_FAIL,
"AMICI_SINGULAR_JACOBIAN != SUN_ERR_EXT_FAIL"
);
static_assert(
std::is_same_v<amici::realtype, sunrealtype>,
"Definition of realtype does not match"
);
namespace amici {
std::map<int, std::string> simulation_status_to_str_map = {
{AMICI_RECOVERABLE_ERROR, "AMICI_RECOVERABLE_ERROR"},
{AMICI_UNRECOVERABLE_ERROR, "AMICI_UNRECOVERABLE_ERROR"},
{AMICI_TOO_MUCH_WORK, "AMICI_TOO_MUCH_WORK"},
{AMICI_TOO_MUCH_ACC, "AMICI_TOO_MUCH_ACC"},
{AMICI_ERR_FAILURE, "AMICI_ERR_FAILURE"},
{AMICI_CONV_FAILURE, "AMICI_CONV_FAILURE"},
{AMICI_FIRST_RHSFUNC_ERR, "AMICI_FIRST_RHSFUNC_ERR"},
{AMICI_CONSTR_FAIL, "AMICI_CONSTR_FAIL"},
{AMICI_CVODES_CONSTR_FAIL, "AMICI_CVODES_CONSTR_FAIL"},
{AMICI_IDAS_CONSTR_FAIL, "AMICI_IDAS_CONSTR_FAIL"},
{AMICI_RHSFUNC_FAIL, "AMICI_RHSFUNC_FAIL"},
{AMICI_ILL_INPUT, "AMICI_ILL_INPUT"},
{AMICI_ERROR, "AMICI_ERROR"},
{AMICI_NO_STEADY_STATE, "AMICI_NO_STEADY_STATE"},
{AMICI_DAMPING_FACTOR_ERROR, "AMICI_DAMPING_FACTOR_ERROR"},
{AMICI_SINGULAR_JACOBIAN, "AMICI_SINGULAR_JACOBIAN"},
{AMICI_NOT_IMPLEMENTED, "AMICI_NOT_IMPLEMENTED"},
{AMICI_MAX_TIME_EXCEEDED, "AMICI_MAX_TIME_EXCEEDED"},
{AMICI_SUCCESS, "AMICI_SUCCESS"},
{AMICI_NOT_RUN, "AMICI_NOT_RUN"},
{AMICI_LSETUP_FAIL, "AMICI_LSETUP_FAIL"},
{AMICI_FIRST_QRHSFUNC_ERR, "AMICI_FIRST_QRHSFUNC_ERR"},
{AMICI_WARNING, "AMICI_WARNING"},
{AMICI_BAD_T, "AMICI_BAD_T"},
{AMICI_BAD_DKY, "AMICI_BAD_DKY"},
{AMICI_FIRST_SRHSFUNC_ERR, "AMICI_FIRST_SRHSFUNC_ERR"},
{AMICI_SRHSFUNC_FAIL, "AMICI_SRHSFUNC_FAIL"},
{AMICI_REPTD_SRHSFUNC_ERR, "AMICI_REPTD_SRHSFUNC_ERR"},
{AMICI_UNREC_SRHSFUNC_ERR, "AMICI_UNREC_SRHSFUNC_ERR"},
{AMICI_RTFUNC_FAIL, "AMICI_RTFUNC_FAIL"},
{AMICI_LINESEARCH_FAIL, "AMICI_LINESEARCH_FAIL"},
{AMICI_T_OVERFLOW, "AMICI_T_OVERFLOW"},
};
std::unique_ptr<ReturnData> run_simulation(
Solver& solver, ExpData const* edata, Model& model, bool const rethrow
) {
// create a temporary logger instance for Solver and Model to capture
// messages from only this simulation
Logger logger;
solver.set_logger(&logger);
model.set_logger(&logger);
// prevent dangling pointer
auto _ = gsl::finally([&solver, &model] {
solver.set_logger(nullptr);
model.set_logger(nullptr);
});
CpuTimer cpu_timer;
solver.start_timer();
// Applies condition-specific model settings and restores them when going
// out of scope. (This also sets `plist`, which is required for initializing
// ReturnData below.)
ConditionContext cc1(&model, edata, FixedParameterContext::simulation);
auto rdata = std::make_unique<ReturnData>(solver, model);
if (edata) {
rdata->id = edata->id;
}
std::unique_ptr<ForwardProblem> fwd{};
std::unique_ptr<BackwardProblem> bwd{};
// tracks whether backwards integration finished without exceptions
bool bwd_success = true;
try {
fwd = std::make_unique<ForwardProblem>(edata, &model, &solver);
fwd->run();
if (edata && solver.computing_asa()) {
bwd_success = false; // NOLINT
bwd = std::make_unique<BackwardProblem>(*fwd);
bwd->workBackwardProblem();
bwd_success = true;
}
rdata->status = AMICI_SUCCESS;
} catch (IntegrationFailure const& ex) {
if (ex.error_code == AMICI_RHSFUNC_FAIL && solver.time_exceeded()) {
rdata->status = AMICI_MAX_TIME_EXCEEDED;
if (rethrow)
throw;
logger.log(
LogSeverity::error, "MAXTIME_EXCEEDED",
"AMICI forward simulation failed at t = %g: "
"Maximum time exceeded in forward solve.",
ex.time
);
} else {
rdata->status = ex.error_code;
if (rethrow)
throw;
logger.log(
LogSeverity::error, "FORWARD_FAILURE",
"AMICI forward simulation failed at t = %g: %s", ex.time,
ex.what()
);
}
} catch (IntegrationFailureB const& ex) {
if (ex.error_code == AMICI_RHSFUNC_FAIL && solver.time_exceeded()) {
rdata->status = AMICI_MAX_TIME_EXCEEDED;
if (rethrow)
throw;
logger.log(
LogSeverity::error, "MAXTIME_EXCEEDED",
"AMICI backward simulation failed when trying to solve until "
"t = %g: Maximum time exceeded in backward solve.",
ex.time
);
} else {
rdata->status = ex.error_code;
if (rethrow)
throw;
logger.log(
LogSeverity::error, "BACKWARD_FAILURE",
"AMICI backward simulation failed when trying to solve until t "
"= %g"
" (check debug logs for details): %s",
ex.time, ex.what()
);
}
} catch (AmiException const& ex) {
rdata->status = AMICI_ERROR;
if (rethrow)
throw;
logger.log(
LogSeverity::error, "OTHER", "AMICI simulation failed: %s",
ex.what()
);
#ifndef NDEBUG
logger.log(
LogSeverity::debug, "BACKTRACE",
"The previous error occurred at:\n%s", ex.getBacktrace()
);
#endif
} catch (std::exception const& ex) {
rdata->status = AMICI_ERROR;
if (rethrow)
throw;
logger.log(
LogSeverity::error, "OTHER", "AMICI simulation failed: %s",
ex.what()
);
}
try {
rdata->process_simulation_objects(
fwd.get(), bwd_success ? bwd.get() : nullptr, model, solver, edata
);
} catch (std::exception const& ex) {
rdata->status = AMICI_ERROR;
if (rethrow)
throw;
logger.log(
LogSeverity::error, "OTHER", "AMICI simulation failed: %s",
ex.what()
);
}
rdata->t_last = solver.get_t();
rdata->cpu_time_total = cpu_timer.elapsed_milliseconds();
// verify that reported CPU times are plausible
gsl_EnsuresDebug(rdata->cpu_time <= rdata->cpu_time_total);
gsl_EnsuresDebug(rdata->cpu_time_b <= rdata->cpu_time_total);
gsl_EnsuresDebug(rdata->preeq_cpu_time <= rdata->cpu_time_total);
gsl_EnsuresDebug(rdata->preeq_cpu_time_b <= rdata->cpu_time_total);
gsl_EnsuresDebug(rdata->posteq_cpu_time <= rdata->cpu_time_total);
gsl_EnsuresDebug(rdata->posteq_cpu_time_b <= rdata->cpu_time_total);
if (fwd && !fwd->get_posteq_problem())
gsl_EnsuresDebug(
std::ranges::is_sorted(rdata->numsteps)
|| rdata->status != AMICI_SUCCESS
);
if (fwd && !fwd->get_preeq_problem())
gsl_EnsuresDebug(
std::ranges::is_sorted(rdata->numsteps_b)
|| rdata->status != AMICI_SUCCESS
);
rdata->messages = logger.items;
return rdata;
}
std::vector<std::unique_ptr<ReturnData>> run_simulations(
Solver const& solver, std::vector<ExpData*> const& edatas,
Model const& model, bool const failfast,
#if defined(_OPENMP)
int num_threads
#else
int /* num_threads */
#endif
) {
std::vector<std::unique_ptr<ReturnData>> results(edatas.size());
// is set to true if one simulation fails and we should skip the rest.
// shared across threads.
bool skipThrough = false;
#if defined(_OPENMP)
#pragma omp parallel for num_threads(num_threads)
#endif
for (int i = 0; i < (int)edatas.size(); ++i) {
// must catch exceptions in parallel section to avoid termination
try {
auto mySolver = std::unique_ptr<Solver>(solver.clone());
auto myModel = std::unique_ptr<Model>(model.clone());
// If we fail, we need to write empty ReturnDatas for the Python
// interface
if (skipThrough) {
ConditionContext conditionContext(myModel.get(), edatas[i]);
results[i] = std::make_unique<ReturnData>(solver, model);
} else {
results[i] = run_simulation(*mySolver, edatas[i], *myModel);
}
} catch (std::exception const& ex) {
results[i] = std::make_unique<ReturnData>(solver, model);
results[i]->status = AMICI_ERROR;
results[i]->messages.emplace_back(
LogSeverity::error, "OTHER", ex.what()
);
}
skipThrough |= failfast && results[i]->status < 0;
}
return results;
}
std::string simulation_status_to_str(int const status) {
try {
return simulation_status_to_str_map.at(status);
} catch (std::out_of_range const&) {
// Missing mapping - terminate if this is a debug build,
// but show the number if non-debug.
fprintf(stderr, "Unknown simulation status: %d\n", status);
gsl_ExpectsDebug(false);
return std::to_string(status);
}
}
} // namespace amici