/
cvodessolver.cpp
443 lines (322 loc) · 16.2 KB
/
cvodessolver.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
/*******************************************************************************
Copyright (C) The University of Auckland
OpenCOR is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenCOR is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
//==============================================================================
// CVODES solver
//==============================================================================
#include "cvodessolver.h"
//==============================================================================
#include "cvodes/cvodes.h"
#include "cvodes/cvodes_bandpre.h"
#include "cvodes/cvodes_diag.h"
#include "cvodes/cvodes_direct.h"
#include "cvodes/cvodes_spils.h"
#include "sunlinsol/sunlinsol_band.h"
#include "sunlinsol/sunlinsol_dense.h"
#include "sunlinsol/sunlinsol_spbcgs.h"
#include "sunlinsol/sunlinsol_spgmr.h"
#include "sunlinsol/sunlinsol_sptfqmr.h"
//==============================================================================
namespace OpenCOR {
namespace CVODESSolver {
//==============================================================================
int rhsFunction(double pVoi, N_Vector pStates, N_Vector pRates, void *pUserData)
{
// Compute the RHS function
CvodesSolverUserData *userData = static_cast<CvodesSolverUserData *>(pUserData);
userData->computeRates()(pVoi, userData->constants(),
N_VGetArrayPointer_Serial(pRates),
N_VGetArrayPointer_Serial(pStates),
userData->algebraic());
return 0;
}
//==============================================================================
void errorHandler(int pErrorCode, const char *pModule, const char *pFunction,
char *pErrorMessage, void *pUserData)
{
Q_UNUSED(pModule);
Q_UNUSED(pFunction);
if (pErrorCode != CV_WARNING) {
// CVODES generated an error, so forward it to the CvodesSolver object
static_cast<CvodesSolver *>(pUserData)->emitError(pErrorMessage);
}
}
//==============================================================================
CvodesSolverUserData::CvodesSolverUserData(double *pConstants, double *pAlgebraic,
Solver::OdeSolver::ComputeRatesFunction pComputeRates) :
mConstants(pConstants),
mAlgebraic(pAlgebraic),
mComputeRates(pComputeRates)
{
}
//==============================================================================
double * CvodesSolverUserData::constants() const
{
// Return our constants array
return mConstants;
}
//==============================================================================
double * CvodesSolverUserData::algebraic() const
{
// Return our algebraic array
return mAlgebraic;
}
//==============================================================================
Solver::OdeSolver::ComputeRatesFunction CvodesSolverUserData::computeRates() const
{
// Return our compute rates function
return mComputeRates;
}
//==============================================================================
CvodesSolver::CvodesSolver() :
mSolver(0),
mStatesVector(0),
mMatrix(0),
mLinearSolver(0),
mUserData(0),
mInterpolateSolution(InterpolateSolutionDefaultValue)
{
}
//==============================================================================
CvodesSolver::~CvodesSolver()
{
// Make sure that the solver has been initialised
if (!mSolver)
return;
// Delete some internal objects
N_VDestroy_Serial(mStatesVector);
SUNLinSolFree(mLinearSolver);
SUNMatDestroy(mMatrix);
CVodeFree(&mSolver);
delete mUserData;
}
//==============================================================================
void CvodesSolver::initialize(const double &pVoiStart,
const int &pRatesStatesCount, double *pConstants,
double *pRates, double *pStates,
double *pAlgebraic,
ComputeRatesFunction pComputeRates)
{
if (!mSolver) {
// Retrieve some of the CVODES properties
double maximumStep = MaximumStepDefaultValue;
int maximumNumberOfSteps = MaximumNumberOfStepsDefaultValue;
QString integrationMethod = IntegrationMethodDefaultValue;
QString iterationType = IterationTypeDefaultValue;
QString linearSolver = LinearSolverDefaultValue;
QString preconditioner = PreconditionerDefaultValue;
int upperHalfBandwidth = UpperHalfBandwidthDefaultValue;
int lowerHalfBandwidth = LowerHalfBandwidthDefaultValue;
double relativeTolerance = RelativeToleranceDefaultValue;
double absoluteTolerance = AbsoluteToleranceDefaultValue;
if (mProperties.contains(MaximumStepId)) {
maximumStep = mProperties.value(MaximumStepId).toDouble();
} else {
emit error(tr("the 'maximum step' property value could not be retrieved"));
return;
}
if (mProperties.contains(MaximumNumberOfStepsId)) {
maximumNumberOfSteps = mProperties.value(MaximumNumberOfStepsId).toInt();
} else {
emit error(tr("the 'maximum number of steps' property value could not be retrieved"));
return;
}
if (mProperties.contains(IntegrationMethodId)) {
integrationMethod = mProperties.value(IntegrationMethodId).toString();
} else {
emit error(tr("the 'integration method' property value could not be retrieved"));
return;
}
if (mProperties.contains(IterationTypeId)) {
iterationType = mProperties.value(IterationTypeId).toString();
if (!iterationType.compare(NewtonIteration)) {
// We are dealing with a Newton iteration, so retrieve and check
// its linear solver
if (mProperties.contains(LinearSolverId)) {
linearSolver = mProperties.value(LinearSolverId).toString();
bool needUpperAndLowerHalfBandwidths = false;
if ( !linearSolver.compare(DenseLinearSolver)
|| !linearSolver.compare(DiagonalLinearSolver)) {
// We are dealing with a dense/diagonal linear solver,
// so nothing more to do
} else if (!linearSolver.compare(BandedLinearSolver)) {
// We are dealing with a banded linear solver, so we
// need both an upper and a lower half bandwidth
needUpperAndLowerHalfBandwidths = true;
} else {
// We are dealing with a GMRES/Bi-CGStab/TFQMR linear
// solver, so retrieve and check its preconditioner
if (mProperties.contains(PreconditionerId)) {
preconditioner = mProperties.value(PreconditionerId).toString();
} else {
emit error(tr("the 'preconditioner' property value could not be retrieved"));
return;
}
if (!preconditioner.compare(BandedPreconditioner)) {
// We are dealing with a banded preconditioner, so
// we need both an upper and a lower half bandwidth
needUpperAndLowerHalfBandwidths = true;
}
}
if (needUpperAndLowerHalfBandwidths) {
if (mProperties.contains(UpperHalfBandwidthId)) {
upperHalfBandwidth = mProperties.value(UpperHalfBandwidthId).toInt();
if ( (upperHalfBandwidth < 0)
|| (upperHalfBandwidth >= pRatesStatesCount)) {
emit error(tr("the 'upper half-bandwidth' property must have a value between 0 and %1").arg(pRatesStatesCount-1));
return;
}
} else {
emit error(tr("the 'upper half-bandwidth' property value could not be retrieved"));
return;
}
if (mProperties.contains(LowerHalfBandwidthId)) {
lowerHalfBandwidth = mProperties.value(LowerHalfBandwidthId).toInt();
if ( (lowerHalfBandwidth < 0)
|| (lowerHalfBandwidth >= pRatesStatesCount)) {
emit error(tr("the 'lower half-bandwidth' property must have a value between 0 and %1").arg(pRatesStatesCount-1));
return;
}
} else {
emit error(tr("the 'lower half-bandwidth' property value could not be retrieved"));
return;
}
}
} else {
emit error(tr("the 'linear solver' property value could not be retrieved"));
return;
}
}
} else {
emit error(tr("the 'iteration type' property value could not be retrieved"));
return;
}
if (mProperties.contains(RelativeToleranceId)) {
relativeTolerance = mProperties.value(RelativeToleranceId).toDouble();
if (relativeTolerance < 0) {
emit error(tr("the 'relative tolerance' property must have a value greater than or equal to 0"));
return;
}
} else {
emit error(tr("the 'relative tolerance' property value could not be retrieved"));
return;
}
if (mProperties.contains(AbsoluteToleranceId)) {
absoluteTolerance = mProperties.value(AbsoluteToleranceId).toDouble();
if (absoluteTolerance < 0) {
emit error(tr("the 'absolute tolerance' property must have a value greater than or equal to 0"));
return;
}
} else {
emit error(tr("the 'absolute tolerance' property value could not be retrieved"));
return;
}
if (mProperties.contains(InterpolateSolutionId)) {
mInterpolateSolution = mProperties.value(InterpolateSolutionId).toBool();
} else {
emit error(tr("the 'interpolate solution' property value could not be retrieved"));
return;
}
// Initialise the ODE solver itself
OpenCOR::Solver::OdeSolver::initialize(pVoiStart, pRatesStatesCount,
pConstants, pRates, pStates,
pAlgebraic, pComputeRates);
// Create the states vector
mStatesVector = N_VMake_Serial(pRatesStatesCount, pStates);
// Create the CVODES solver
bool newtonIteration = !iterationType.compare(NewtonIteration);
mSolver = CVodeCreate(!integrationMethod.compare(BdfMethod)?CV_BDF:CV_ADAMS,
newtonIteration?CV_NEWTON:CV_FUNCTIONAL);
// Use our own error handler
CVodeSetErrHandlerFn(mSolver, errorHandler, this);
// Initialise the CVODES solver
CVodeInit(mSolver, rhsFunction, pVoiStart, mStatesVector);
// Set some user data
mUserData = new CvodesSolverUserData(pConstants, pAlgebraic,
pComputeRates);
CVodeSetUserData(mSolver, mUserData);
// Set the maximum step
CVodeSetMaxStep(mSolver, maximumStep);
// Set the maximum number of steps
CVodeSetMaxNumSteps(mSolver, maximumNumberOfSteps);
// Set the linear solver, if needed
if (newtonIteration) {
if (!linearSolver.compare(DenseLinearSolver)) {
mMatrix = SUNDenseMatrix(pRatesStatesCount, pRatesStatesCount);
mLinearSolver = SUNDenseLinearSolver(mStatesVector, mMatrix);
CVDlsSetLinearSolver(mSolver, mLinearSolver, mMatrix);
} else if (!linearSolver.compare(BandedLinearSolver)) {
mMatrix = SUNBandMatrix(pRatesStatesCount,
upperHalfBandwidth, lowerHalfBandwidth,
upperHalfBandwidth+lowerHalfBandwidth);
mLinearSolver = SUNBandLinearSolver(mStatesVector, mMatrix);
CVDlsSetLinearSolver(mSolver, mLinearSolver, mMatrix);
} else if (!linearSolver.compare(DiagonalLinearSolver)) {
CVDiag(mSolver);
} else {
// We are dealing with a GMRES/Bi-CGStab/TFQMR linear solver
if (!preconditioner.compare(BandedPreconditioner)) {
if (!linearSolver.compare(GmresLinearSolver)) {
mLinearSolver = SUNSPGMR(mStatesVector, PREC_LEFT, 0);
CVSpilsSetLinearSolver(mSolver, mLinearSolver);
} else if (!linearSolver.compare(BiCgStabLinearSolver)) {
mLinearSolver = SUNSPBCGS(mStatesVector, PREC_LEFT, 0);
CVSpilsSetLinearSolver(mSolver, mLinearSolver);
} else {
mLinearSolver = SUNSPTFQMR(mStatesVector, PREC_LEFT, 0);
CVSpilsSetLinearSolver(mSolver, mLinearSolver);
}
CVBandPrecInit(mSolver, pRatesStatesCount, upperHalfBandwidth, lowerHalfBandwidth);
} else {
if (!linearSolver.compare(GmresLinearSolver)) {
mLinearSolver = SUNSPGMR(mStatesVector, PREC_NONE, 0);
CVSpilsSetLinearSolver(mSolver, mLinearSolver);
} else if (!linearSolver.compare(BiCgStabLinearSolver)) {
mLinearSolver = SUNSPBCGS(mStatesVector, PREC_NONE, 0);
CVSpilsSetLinearSolver(mSolver, mLinearSolver);
} else {
mLinearSolver = SUNSPTFQMR(mStatesVector, PREC_NONE, 0);
CVSpilsSetLinearSolver(mSolver, mLinearSolver);
}
}
}
}
// Set the relative and absolute tolerances
CVodeSStolerances(mSolver, relativeTolerance, absoluteTolerance);
} else {
// Reinitialise the CVODES object
CVodeReInit(mSolver, pVoiStart, mStatesVector);
}
}
//==============================================================================
void CvodesSolver::solve(double &pVoi, const double &pVoiEnd) const
{
// Solve the model
if (!mInterpolateSolution)
CVodeSetStopTime(mSolver, pVoiEnd);
CVode(mSolver, pVoiEnd, mStatesVector, &pVoi, CV_NORMAL);
// Compute the rates one more time to get up to date values for the rates
// Note: another way of doing this would be to copy the contents of the
// calculated rates in rhsFunction, but that's bound to be more time
// consuming since a call to CVode() is likely to generate at least a
// few calls to rhsFunction(), so that would be quite a few memory
// transfers while here we 'only' compute the rates one more time...
mComputeRates(pVoiEnd, mConstants, mRates,
N_VGetArrayPointer_Serial(mStatesVector), mAlgebraic);
}
//==============================================================================
} // namespace CVODESSolver
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================