12#include "cantera/numerics/sundials_headers.h"
18 return N_VNew_Serial(
static_cast<sd_size_t
>(N), context.get());
35 static int cvodes_rhs(sunrealtype t, N_Vector y, N_Vector ydot,
void* f_data)
41 #if SUNDIALS_VERSION_MAJOR >= 7
46 static void sundials_err(
int line,
const char *func,
const char *file,
47 const char *msg, SUNErrCode err_code,
48 void *err_user_data, SUNContext sunctx)
50 CVodesIntegrator* integrator = (CVodesIntegrator*) err_user_data;
51 integrator->m_error_message = fmt::format(
"{}: {}\n", func, msg);
58 static void cvodes_err(
int error_code,
const char* module,
59 const char* function,
char* msg,
void* eh_data)
67 static int cvodes_prec_setup(sunrealtype t, N_Vector y, N_Vector ydot,
68 sunbooleantype jok, sunbooleantype *jcurPtr,
69 sunrealtype gamma,
void *f_data)
71 FuncEval* f = (FuncEval*) f_data;
74 return f->preconditioner_setup_nothrow(t,
asSpan(y), gamma);
76 f->updatePreconditioner(gamma);
82 static int cvodes_prec_solve(sunrealtype t, N_Vector y, N_Vector ydot, N_Vector r,
83 N_Vector z, sunrealtype gamma, sunrealtype delta,
86 FuncEval* f = (FuncEval*) f_data;
87 return f->preconditioner_solve_nothrow(
asSpan(r),
asSpan(z));
99 static int cvodes_root(sunrealtype t, N_Vector y, sunrealtype* gout,
void* user_data)
101 auto* f =
static_cast<FuncEval*
>(user_data);
103 span<double>(gout, f->nRootFunctions()));
113CVodesIntegrator::~CVodesIntegrator()
122 SUNLinSolFree((SUNLinearSolver)
m_linsol);
126 N_VDestroy_Serial(
m_y);
129 N_VDestroy_Serial(m_abstol);
132 N_VDestroy_Serial(m_dky);
135 N_VDestroyVectorArray(m_yS,
static_cast<int>(m_np));
142 return NV_Ith_S(
m_y, k);
152 size_t n = abstol.size();
157 N_VDestroy_Serial(m_abstol);
161 for (
size_t i=0; i<n; i++) {
162 NV_Ith_S(m_abstol, i) = abstol[i];
166 int flag = CVodeSVtolerances(
m_cvode_mem, m_reltol, m_abstol);
167 checkError(flag,
"setTolerances",
"CVodeSVtolerances");
177 int flag = CVodeSStolerances(
m_cvode_mem, m_reltol, m_abstols);
178 checkError(flag,
"setTolerances",
"CVodeSStolerances");
184 m_reltolsens = reltol;
185 m_abstolsens = abstol;
187 vector<double> atol(m_np);
188 for (
size_t n = 0; n < m_np; n++) {
193 int flag = CVodeSensSStolerances(
m_cvode_mem, m_reltolsens, atol.data());
194 checkError(flag,
"setSensitivityTolerances",
"CVodeSensSStolerances");
205 throw CanteraError(
"CVodesIntegrator::setMethod",
"unknown method");
240 m_maxErrTestFails = n;
252 m_nRootFunctions = nroots;
258 CVRootFn root_cb = nroots ? &
cvodes_root :
nullptr;
259 int flag = CVodeRootInit(
m_cvode_mem,
static_cast<int>(nroots), root_cb);
260 checkError(flag,
"setRootFunctionCount",
"CVodeRootInit");
263void CVodesIntegrator::sensInit(
double t0,
FuncEval& func)
269 m_yS = N_VCloneVectorArray(
static_cast<int>(m_np), y);
270 for (
size_t n = 0; n < m_np; n++) {
271 N_VConst(0.0, m_yS[n]);
273 N_VDestroy_Serial(y);
275 int flag = CVodeSensInit(
m_cvode_mem,
static_cast<int>(m_np),
276 CV_STAGGERED, CVSensRhsFn(0), m_yS);
277 checkError(flag,
"sensInit",
"CVodeSensInit");
290 if (
m_prec_side != PreconditionerSide::NO_PRECONDITION) {
294 N_VDestroy_Serial(
m_y);
299 N_VDestroy_Serial(m_dky);
302 N_VConst(0.0, m_dky);
304 if (m_itol == CV_SV && m_nabs < m_neq) {
306 "not enough absolute tolerance values specified.");
318 "CVodeCreate failed.");
322 if (flag != CV_SUCCESS) {
323 if (flag == CV_MEM_FAIL) {
325 "Memory allocation failed.");
326 }
else if (flag == CV_ILL_INPUT) {
328 "Illegal value for CVodeInit input argument.");
331 "CVodeInit failed.");
334 #if SUNDIALS_VERSION_MAJOR >= 7
335 flag = SUNContext_PushErrHandler(
m_sundials_ctx.get(), &sundials_err,
this);
340 if (m_itol == CV_SV) {
341 flag = CVodeSVtolerances(
m_cvode_mem, m_reltol, m_abstol);
342 checkError(flag,
"initialize",
"CVodeSVtolerances");
344 flag = CVodeSStolerances(
m_cvode_mem, m_reltol, m_abstols);
345 checkError(flag,
"initialize",
"CVodeSStolerances");
349 checkError(flag,
"initialize",
"CVodeSetUserData");
351 m_nRootFunctions =
npos;
358 checkError(flag,
"initialize",
"CVodeSetSensParams");
363void CVodesIntegrator::reinitialize(
double t0,
FuncEval& func)
372 if (
m_prec_side != PreconditionerSide::NO_PRECONDITION) {
376 checkError(result,
"reinitialize",
"CVodeReInit");
377 m_nRootFunctions =
npos;
384 if (m_type ==
"DENSE") {
385 sd_size_t N =
static_cast<sd_size_t
>(m_neq);
386 SUNLinSolFree((SUNLinearSolver)
m_linsol);
391 "Unable to create SUNDenseMatrix of size {0} x {0}", N);
394 #if CT_SUNDIALS_USE_LAPACK
405 "Error creating Sundials dense linear solver object");
406 }
else if (flag != CV_SUCCESS) {
408 "Error connecting linear solver to CVODES. "
409 "Sundials error code: {}", flag);
413 if (
m_prec_side != PreconditionerSide::NO_PRECONDITION) {
415 "Preconditioning is not available with the specified problem type.");
417 }
else if (m_type ==
"DIAG") {
420 if (
m_prec_side != PreconditionerSide::NO_PRECONDITION) {
422 "Preconditioning is not available with the specified problem type.");
424 }
else if (m_type ==
"GMRES") {
425 SUNLinSolFree((SUNLinearSolver)
m_linsol);
429 if (
m_prec_side != PreconditionerSide::NO_PRECONDITION) {
430 SUNLinSol_SPGMRSetPrecType((SUNLinearSolver)
m_linsol,
432 CVodeSetPreconditioner(
m_cvode_mem, cvodes_prec_setup,
435 }
else if (m_type ==
"BAND") {
436 sd_size_t N =
static_cast<sd_size_t
>(m_neq);
437 sd_size_t nu = m_mupper;
438 sd_size_t nl = m_mlower;
439 SUNLinSolFree((SUNLinearSolver)
m_linsol);
444 "Unable to create SUNBandMatrix of size {} with bandwidths "
445 "{} and {}", N, nu, nl);
447 #if CT_SUNDIALS_USE_LAPACK
458 "unsupported linear solver flag '{}'", m_type);
463 checkError(flag,
"applyOptions",
"CVodeSetMaxOrd");
465 if (m_maxsteps > 0) {
474 if (m_maxErrTestFails > 0) {
475 CVodeSetMaxErrTestFails(
m_cvode_mem, m_maxErrTestFails);
483 }
else if (tout <
m_time) {
485 "Cannot integrate backwards in time.\n"
486 "Requested time {} < current time {}",
491 if (nsteps >= m_maxsteps) {
493 if (!f_errs.empty()) {
494 f_errs =
"\nExceptions caught during RHS evaluation:\n" + f_errs;
497 "Maximum number of timesteps ({}) taken without reaching output "
498 "time ({}).\nCurrent integrator time: {}{}",
502 if (flag != CV_SUCCESS && flag != CV_ROOT_RETURN) {
504 if (!f_errs.empty()) {
505 f_errs =
"Exceptions caught during RHS evaluation:\n" + f_errs;
508 "CVodes error encountered. Error code: {}\n{}\n"
510 "Components with largest weighted error estimates:\n{}",
513 if (flag == CV_ROOT_RETURN) {
524 double t_eval = tout;
534 if (flag != CV_SUCCESS && flag != CV_ROOT_RETURN) {
536 if (!f_errs.empty()) {
537 f_errs =
"Exceptions caught during RHS evaluation:\n" + f_errs;
540 "CVodes error encountered. Error code: {}\n{}\n"
542 "Components with largest weighted error estimates:\n{}",
553 int flag = CVodeGetDky(
m_cvode_mem, tout, n, m_dky);
554 checkError(flag,
"derivative",
"CVodeGetDky");
578 long int steps = 0, rhsEvals = 0, errTestFails = 0, jacEvals = 0, linSetup = 0,
579 linRhsEvals = 0, linIters = 0, linConvFails = 0, precEvals = 0,
580 precSolves = 0, jtSetupEvals = 0, jTimesEvals = 0, nonlinIters = 0,
581 nonlinConvFails = 0, orderReductions = 0, stepSolveFails = 0;
587 CVodeGetNonlinSolvStats(
m_cvode_mem, &nonlinIters, &nonlinConvFails);
588 CVodeGetNumErrTestFails(
m_cvode_mem, &errTestFails);
590 CVodeGetNumStabLimOrderReds(
m_cvode_mem, &orderReductions);
595 CVodeGetNumLinConvFails(
m_cvode_mem, &linConvFails);
598 CVodeGetNumJTSetupEvals(
m_cvode_mem, &jtSetupEvals);
600 CVodeGetNumStepSolveFails(
m_cvode_mem, &stepSolveFails);
602 stats[
"steps"] = steps;
603 stats[
"step_solve_fails"] = stepSolveFails;
604 stats[
"rhs_evals"] = rhsEvals;
605 stats[
"nonlinear_iters"] = nonlinIters;
606 stats[
"nonlinear_conv_fails"] = nonlinConvFails;
607 stats[
"err_test_fails"] = errTestFails;
609 stats[
"stab_order_reductions"] = orderReductions;
611 stats[
"jac_evals"] = jacEvals;
612 stats[
"lin_solve_setups"] = linSetup;
613 stats[
"lin_rhs_evals"] = linRhsEvals;
614 stats[
"lin_iters"] = linIters;
615 stats[
"lin_conv_fails"] = linConvFails;
616 stats[
"prec_evals"] = precEvals;
617 stats[
"prec_solves"] = precSolves;
618 stats[
"jt_vec_setup_evals"] = jtSetupEvals;
619 stats[
"jt_vec_prod_evals"] = jTimesEvals;
623double CVodesIntegrator::sensitivity(
size_t k,
size_t p)
631 checkError(flag,
"sensitivity",
"CVodeGetSens");
636 throw CanteraError(
"CVodesIntegrator::sensitivity",
637 "sensitivity: k out of range ({})", k);
640 throw CanteraError(
"CVodesIntegrator::sensitivity",
641 "sensitivity: p out of range ({})", p);
643 return NV_Ith_S(m_yS[p],k);
653 vector<tuple<double, double, size_t>> weightedErrors;
654 for (
size_t i=0; i<m_neq; i++) {
655 double err = NV_Ith_S(errs, i) * NV_Ith_S(errw, i);
656 weightedErrors.emplace_back(-abs(err), err, i);
661 N = std::min(N,
static_cast<int>(m_neq));
662 sort(weightedErrors.begin(), weightedErrors.end());
663 fmt::memory_buffer s;
664 for (
int i=0; i<N; i++) {
665 fmt_append(s,
"{}: {}\n",
666 get<2>(weightedErrors[i]), get<1>(weightedErrors[i]));
672 const string& cvodesMethod)
const
674 if (flag == CV_SUCCESS) {
676 }
else if (flag == CV_MEM_NULL) {
678 "CVODES integrator is not initialized");
680 const char* flagname = CVodeGetReturnFlagName(flag);
682 "{} returned error code {} ({}):\n{}",
A map of string keys to values whose type can vary at runtime.
Wrapper class for 'cvodes' integrator from LLNL.
span< double > solution() override
The current value of the solution of the system of equations.
double step(double tout) override
Integrate the system of equations.
void setMaxStepSize(double hmax) override
Set the maximum step size.
N_Vector m_y
The system state at m_time.
void * m_cvode_mem
CVODES internal memory object.
void setRootFunctionCount(size_t nroots) override
Configure how many event/root functions the integrator should monitor.
void * m_linsol
Sundials linear solver object.
int nEvals() const override
The number of function evaluations.
CVodesIntegrator()
Constructor.
double m_time
The current system time, corresponding to m_y.
bool m_sens_ok
Indicates whether the sensitivities stored in m_yS have been updated for at the current integrator ti...
int maxSteps() override
Returns the maximum number of time-steps the integrator can take before reaching the next output time...
SundialsContext m_sundials_ctx
SUNContext object for Sundials>=6.0.
void checkError(long flag, const string &ctMethod, const string &cvodesMethod) const
Check whether a CVODES method indicated an error.
void setSensitivityTolerances(double reltol, double abstol) override
Set the sensitivity error tolerances.
void applyOptions()
Applies user-specified options to the underlying CVODES solver.
int lastOrder() const override
Order used during the last solution step.
void setMinStepSize(double hmin) override
Set the minimum step size.
void integrate(double tout) override
Integrate the system of equations.
string m_error_message
Error message information provide by CVodes.
void setTolerances(double reltol, span< const double > abstol) override
Set error tolerances.
void setMaxErrTestFails(int n) override
Set the maximum permissible number of error test failures.
void setMaxSteps(int nmax) override
Set the maximum number of time-steps the integrator can take before reaching the next output time.
AnyMap solverStats() const override
Get solver stats from integrator.
void * m_linsol_matrix
matrix used by Sundials
double m_tInteg
The latest time reached by the integrator. May be greater than m_time.
void initialize(double t0, FuncEval &func) override
Initialize the integrator for a new problem.
string getErrorInfo(int N)
Returns a string listing the weighted error estimates associated with each solution component.
void setMethod(MethodType t) override
Set the solution method.
span< double > derivative(double tout, int n) override
n-th derivative of the output function at time tout.
Base class for exceptions thrown by Cantera classes.
Virtual base class for ODE/DAE right-hand-side function evaluators.
int evalRootFunctionsNoThrow(double t, span< const double > y, span< double > gout)
Wrapper for evalRootFunctions that converts exceptions to return codes.
vector< double > m_paramScales
Scaling factors for each sensitivity parameter.
void clearErrors()
Clear any previously-stored suppressed errors.
virtual void getState(span< double > y)
Fill in the vector y with the current state of the system.
virtual size_t neq() const =0
Number of equations.
int evalNoThrow(double t, span< const double > y, span< double > ydot)
Evaluate the right-hand side using return code to indicate status.
virtual size_t nRootFunctions() const
Number of event/root functions exposed to the integrator.
virtual size_t nparams() const
Number of sensitivity parameters.
string getErrors() const
Return a string containing the text of any suppressed errors.
vector< double > m_sens_params
Values for the problem parameters for which sensitivities are computed This is the array which is per...
shared_ptr< SystemJacobian > m_preconditioner
Pointer to preconditioner object used in integration which is set by setPreconditioner and initialize...
PreconditionerSide m_prec_side
Type of preconditioning used in applyOptions.
A wrapper for managing a SUNContext object.
static int cvodes_rhs(sunrealtype t, N_Vector y, N_Vector ydot, void *f_data)
Function called by cvodes to evaluate ydot given y.
Namespace for the Cantera kernel.
const size_t npos
index returned by functions to indicate "no position"
MethodType
Specifies the method used to integrate the system of equations.
@ BDF_Method
Backward Differentiation.
span< double > asSpan(Eigen::DenseBase< Derived > &v)
Convenience wrapper for accessing Eigen vector/array/map data as a span.
static int cvodes_root(sunrealtype t, N_Vector y, sunrealtype *gout, void *user_data)
SUNDIALS callback that forwards root evaluations to the FuncEval.
static void cvodes_err(int error_code, const char *module, const char *function, char *msg, void *eh_data)
Function called by CVodes when an error is encountered instead of writing to stdout.
Contains declarations for string manipulation functions within Cantera.