void CVodesIntegrator::sensInit(double t0, FuncEval& func) { m_np = func.nparams(); size_t nv = func.neq(); m_sens_ok = false; doublereal* data; N_Vector y; y = N_VNew_Serial(static_cast<sd_size_t>(nv)); m_yS = N_VCloneVectorArray_Serial(static_cast<sd_size_t>(m_np), y); for (size_t n = 0; n < m_np; n++) { data = NV_DATA_S(m_yS[n]); for (size_t j = 0; j < nv; j++) { data[j] =0.0; } } int flag = CVodeSensInit(m_cvode_mem, static_cast<sd_size_t>(m_np), CV_STAGGERED, CVSensRhsFn(0), m_yS); if (flag != CV_SUCCESS) { throw CVodesErr("Error in CVodeSensMalloc"); } vector_fp atol(m_np, m_abstolsens); double rtol = m_reltolsens; flag = CVodeSensSStolerances(m_cvode_mem, rtol, atol.data()); }
void CVodesIntegrator::sensInit(double t0, FuncEval& func) { m_np = func.nparams(); m_sens_ok = false; N_Vector y = N_VNew_Serial(static_cast<sd_size_t>(func.neq())); m_yS = N_VCloneVectorArray_Serial(static_cast<sd_size_t>(m_np), y); for (size_t n = 0; n < m_np; n++) { N_VConst(0.0, m_yS[n]); } N_VDestroy_Serial(y); int flag = CVodeSensInit(m_cvode_mem, static_cast<sd_size_t>(m_np), CV_STAGGERED, CVSensRhsFn(0), m_yS); if (flag != CV_SUCCESS) { throw CanteraError("CVodesIntegrator::sensInit", "Error in CVodeSensInit"); } vector_fp atol(m_np); for (size_t n = 0; n < m_np; n++) { // This scaling factor is tuned so that reaction and species enthalpy // sensitivities can be computed simultaneously with the same abstol. atol[n] = m_abstolsens / func.m_paramScales[n]; } flag = CVodeSensSStolerances(m_cvode_mem, m_reltolsens, atol.data()); }
void CVodesIntegrator::sensInit(double t0, FuncEval& func) { m_np = func.nparams(); long int nv = func.neq(); doublereal* data; int n, j; N_Vector y; y = N_VNew_Serial(nv); m_yS = N_VCloneVectorArray_Serial(m_np, y); for (n = 0; n < m_np; n++) { data = NV_DATA_S(m_yS[n]); for (j = 0; j < nv; j++) { data[j] =0.0; } } int flag; #if defined(SUNDIALS_VERSION_22) || defined(SUNDIALS_VERSION_23) flag = CVodeSensMalloc(m_cvode_mem, m_np, CV_STAGGERED, m_yS); if (flag != CV_SUCCESS) { throw CVodesErr("Error in CVodeSensMalloc"); } vector_fp atol(m_np, m_abstolsens); double rtol = m_reltolsens; flag = CVodeSetSensTolerances(m_cvode_mem, CV_SS, rtol, DATA_PTR(atol)); #elif defined(SUNDIALS_VERSION_24) flag = CVodeSensInit(m_cvode_mem, m_np, CV_STAGGERED, CVSensRhsFn (0), m_yS); if (flag != CV_SUCCESS) { throw CVodesErr("Error in CVodeSensMalloc"); } vector_fp atol(m_np, m_abstolsens); double rtol = m_reltolsens; flag = CVodeSensSStolerances(m_cvode_mem, rtol, DATA_PTR(atol)); #endif }
int main(int argc, char *argv[]) { void *cvode_mem; UserData data; realtype t, tout; N_Vector y; int iout, flag, nthreads, nnz; realtype pbar[NS]; int is; N_Vector *yS; booleantype sensi, err_con; int sensi_meth; cvode_mem = NULL; data = NULL; y = NULL; yS = NULL; /* Process arguments */ ProcessArgs(argc, argv, &sensi, &sensi_meth, &err_con); /* User data structure */ data = (UserData) malloc(sizeof *data); if (check_flag((void *)data, "malloc", 2)) return(1); data->p[0] = RCONST(0.04); data->p[1] = RCONST(1.0e4); data->p[2] = RCONST(3.0e7); /* Initial conditions */ y = N_VNew_Serial(NEQ); if (check_flag((void *)y, "N_VNew_Serial", 0)) return(1); Ith(y,1) = Y1; Ith(y,2) = Y2; Ith(y,3) = Y3; /* Call CVodeCreate to create the solver memory and specify the Backward Differentiation Formula and the use of a Newton iteration */ cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON); if (check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1); /* Call CVodeInit to initialize the integrator memory and specify the user's right hand side function in y'=f(t,y), the initial time T0, and the initial dependent variable vector y. */ flag = CVodeInit(cvode_mem, f, T0, y); if (check_flag(&flag, "CVodeInit", 1)) return(1); /* Call CVodeWFtolerances to specify a user-supplied function ewt that sets the multiplicative error weights W_i for use in the weighted RMS norm */ flag = CVodeWFtolerances(cvode_mem, ewt); if (check_flag(&flag, "CVodeSetEwtFn", 1)) return(1); /* Attach user data */ flag = CVodeSetUserData(cvode_mem, data); if (check_flag(&flag, "CVodeSetUserData", 1)) return(1); /* Call CVKLU to specify the CVKLU sparse direct linear solver */ nthreads = 1; /* no. of threads to use when factoring the system*/ nnz = NEQ * NEQ; /* max no. of nonzeros entries in the Jac */ flag = CVSuperLUMT(cvode_mem, nthreads, NEQ, nnz); if (check_flag(&flag, "CVSuperLUMT", 1)) return(1); /* Set the Jacobian routine to Jac (user-supplied) */ flag = CVSlsSetSparseJacFn(cvode_mem, Jac); if (check_flag(&flag, "CVSlsSetSparseJacFn", 1)) return(1); printf("\n3-species chemical kinetics problem\n"); /* Sensitivity-related settings */ if (sensi) { /* Set parameter scaling factor */ pbar[0] = data->p[0]; pbar[1] = data->p[1]; pbar[2] = data->p[2]; /* Set sensitivity initial conditions */ yS = N_VCloneVectorArray_Serial(NS, y); if (check_flag((void *)yS, "N_VCloneVectorArray_Serial", 0)) return(1); for (is=0;is<NS;is++) N_VConst(ZERO, yS[is]); /* Call CVodeSensInit1 to activate forward sensitivity computations and allocate internal memory for COVEDS related to sensitivity calculations. Computes the right-hand sides of the sensitivity ODE, one at a time */ flag = CVodeSensInit1(cvode_mem, NS, sensi_meth, fS, yS); if(check_flag(&flag, "CVodeSensInit", 1)) return(1); /* Call CVodeSensEEtolerances to estimate tolerances for sensitivity variables based on the rolerances supplied for states variables and the scaling factor pbar */ flag = CVodeSensEEtolerances(cvode_mem); if(check_flag(&flag, "CVodeSensEEtolerances", 1)) return(1); /* Set sensitivity analysis optional inputs */ /* Call CVodeSetSensErrCon to specify the error control strategy for sensitivity variables */ flag = CVodeSetSensErrCon(cvode_mem, err_con); if (check_flag(&flag, "CVodeSetSensErrCon", 1)) return(1); /* Call CVodeSetSensParams to specify problem parameter information for sensitivity calculations */ flag = CVodeSetSensParams(cvode_mem, NULL, pbar, NULL); if (check_flag(&flag, "CVodeSetSensParams", 1)) return(1); printf("Sensitivity: YES "); if(sensi_meth == CV_SIMULTANEOUS) printf("( SIMULTANEOUS +"); else if(sensi_meth == CV_STAGGERED) printf("( STAGGERED +"); else printf("( STAGGERED1 +"); if(err_con) printf(" FULL ERROR CONTROL )"); else printf(" PARTIAL ERROR CONTROL )"); } else { printf("Sensitivity: NO "); } /* In loop over output points, call CVode, print results, test for error */ printf("\n\n"); printf("==========================================="); printf("============================\n"); printf(" T Q H NST y1"); printf(" y2 y3 \n"); printf("==========================================="); printf("============================\n"); for (iout=1, tout=T1; iout <= NOUT; iout++, tout *= TMULT) { flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL); if (check_flag(&flag, "CVode", 1)) break; PrintOutput(cvode_mem, t, y); /* Call CVodeGetSens to get the sensitivity solution vector after a successful return from CVode */ if (sensi) { flag = CVodeGetSens(cvode_mem, &t, yS); if (check_flag(&flag, "CVodeGetSens", 1)) break; PrintOutputS(yS); } printf("-----------------------------------------"); printf("------------------------------\n"); } /* Print final statistics */ PrintFinalStats(cvode_mem, sensi); /* Free memory */ N_VDestroy_Serial(y); /* Free y vector */ if (sensi) { N_VDestroyVectorArray_Serial(yS, NS); /* Free yS vector */ } free(data); /* Free user data */ CVodeFree(&cvode_mem); /* Free CVODES memory */ return(0); }
int main(int argc, char *argv[]) { void *cvode_mem; UserData data; realtype t, tout; N_Vector y; int iout, flag; realtype pbar[NS]; int is; N_Vector *yS; booleantype sensi, err_con; int sensi_meth; cvode_mem = NULL; data = NULL; y = NULL; yS = NULL; /* Process arguments */ ProcessArgs(argc, argv, &sensi, &sensi_meth, &err_con); /* User data structure */ data = (UserData) malloc(sizeof *data); if (check_flag((void *)data, "malloc", 2)) return(1); data->p[0] = RCONST(0.04); data->p[1] = RCONST(1.0e4); data->p[2] = RCONST(3.0e7); /* Initial conditions */ y = N_VNew_Serial(NEQ); if (check_flag((void *)y, "N_VNew_Serial", 0)) return(1); Ith(y,1) = Y1; Ith(y,2) = Y2; Ith(y,3) = Y3; /* Create CVODES object */ cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON); if (check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1); /* Allocate space for CVODES */ flag = CVodeMalloc(cvode_mem, f, T0, y, CV_WF, 0.0, NULL); if (check_flag(&flag, "CVodeMalloc", 1)) return(1); /* Use private function to compute error weights */ flag = CVodeSetEwtFn(cvode_mem, ewt, NULL); if (check_flag(&flag, "CVodeSetEwtFn", 1)) return(1); /* Attach user data */ flag = CVodeSetFdata(cvode_mem, data); if (check_flag(&flag, "CVodeSetFdata", 1)) return(1); /* Attach linear solver */ flag = CVDense(cvode_mem, NEQ); if (check_flag(&flag, "CVDense", 1)) return(1); flag = CVDenseSetJacFn(cvode_mem, Jac, data); if (check_flag(&flag, "CVDenseSetJacFn", 1)) return(1); printf("\n3-species chemical kinetics problem\n"); /* Sensitivity-related settings */ if (sensi) { pbar[0] = data->p[0]; pbar[1] = data->p[1]; pbar[2] = data->p[2]; yS = N_VCloneVectorArray_Serial(NS, y); if (check_flag((void *)yS, "N_VCloneVectorArray_Serial", 0)) return(1); for (is=0;is<NS;is++) N_VConst(ZERO, yS[is]); flag = CVodeSensMalloc(cvode_mem, NS, sensi_meth, yS); if(check_flag(&flag, "CVodeSensMalloc", 1)) return(1); flag = CVodeSetSensRhs1Fn(cvode_mem, fS, data); if (check_flag(&flag, "CVodeSetSensRhs1Fn", 1)) return(1); flag = CVodeSetSensErrCon(cvode_mem, err_con); if (check_flag(&flag, "CVodeSetSensErrCon", 1)) return(1); flag = CVodeSetSensParams(cvode_mem, NULL, pbar, NULL); if (check_flag(&flag, "CVodeSetSensParams", 1)) return(1); printf("Sensitivity: YES "); if(sensi_meth == CV_SIMULTANEOUS) printf("( SIMULTANEOUS +"); else if(sensi_meth == CV_STAGGERED) printf("( STAGGERED +"); else printf("( STAGGERED1 +"); if(err_con) printf(" FULL ERROR CONTROL )"); else printf(" PARTIAL ERROR CONTROL )"); } else { printf("Sensitivity: NO "); } /* In loop over output points, call CVode, print results, test for error */ printf("\n\n"); printf("==========================================="); printf("============================\n"); printf(" T Q H NST y1"); printf(" y2 y3 \n"); printf("==========================================="); printf("============================\n"); for (iout=1, tout=T1; iout <= NOUT; iout++, tout *= TMULT) { flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL); if (check_flag(&flag, "CVode", 1)) break; PrintOutput(cvode_mem, t, y); if (sensi) { flag = CVodeGetSens(cvode_mem, t, yS); if (check_flag(&flag, "CVodeGetSens", 1)) break; PrintOutputS(yS); } printf("-----------------------------------------"); printf("------------------------------\n"); } /* Print final statistics */ PrintFinalStats(cvode_mem, sensi); /* Free memory */ N_VDestroy_Serial(y); /* Free y vector */ if (sensi) { N_VDestroyVectorArray_Serial(yS, NS); /* Free yS vector */ } free(data); /* Free user data */ CVodeFree(&cvode_mem); /* Free CVODES memory */ return(0); }
int main(int argc, char *argv[]) { void *cvode_mem; UserData data; realtype abstol, reltol, t, tout; N_Vector y; int iout, flag; realtype *pbar; int is, *plist; N_Vector *uS; booleantype sensi, err_con; int sensi_meth; pbar = NULL; plist = NULL; uS = NULL; y = NULL; data = NULL; cvode_mem = NULL; /* Process arguments */ ProcessArgs(argc, argv, &sensi, &sensi_meth, &err_con); /* Problem parameters */ data = AllocUserData(); if(check_flag((void *)data, "AllocUserData", 2)) return(1); InitUserData(data); /* Initial states */ y = N_VNew_Serial(NEQ); if(check_flag((void *)y, "N_VNew_Serial", 0)) return(1); SetInitialProfiles(y, data->dx, data->dz); /* Tolerances */ abstol=ATOL; reltol=RTOL; /* Create CVODES object */ cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON); if(check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1); flag = CVodeSetFdata(cvode_mem, data); if(check_flag(&flag, "CVodeSetFdata", 1)) return(1); flag = CVodeSetMaxNumSteps(cvode_mem, 2000); if(check_flag(&flag, "CVodeSetMaxNumSteps", 1)) return(1); /* Allocate CVODES memory */ flag = CVodeMalloc(cvode_mem, f, T0, y, CV_SS, reltol, &abstol); if(check_flag(&flag, "CVodeMalloc", 1)) return(1); /* Attach CVSPGMR linear solver */ flag = CVSpgmr(cvode_mem, PREC_LEFT, 0); if(check_flag(&flag, "CVSpgmr", 1)) return(1); flag = CVSpilsSetPreconditioner(cvode_mem, Precond, PSolve, data); if(check_flag(&flag, "CVSpilsSetPreconditioner", 1)) return(1); printf("\n2-species diurnal advection-diffusion problem\n"); /* Forward sensitivity analysis */ if(sensi) { plist = (int *) malloc(NS * sizeof(int)); if(check_flag((void *)plist, "malloc", 2)) return(1); for(is=0; is<NS; is++) plist[is] = is; pbar = (realtype *) malloc(NS * sizeof(realtype)); if(check_flag((void *)pbar, "malloc", 2)) return(1); for(is=0; is<NS; is++) pbar[is] = data->p[plist[is]]; uS = N_VCloneVectorArray_Serial(NS, y); if(check_flag((void *)uS, "N_VCloneVectorArray_Serial", 0)) return(1); for(is=0;is<NS;is++) N_VConst(ZERO,uS[is]); flag = CVodeSensMalloc(cvode_mem, NS, sensi_meth, uS); if(check_flag(&flag, "CVodeSensMalloc", 1)) return(1); flag = CVodeSetSensErrCon(cvode_mem, err_con); if(check_flag(&flag, "CVodeSetSensErrCon", 1)) return(1); flag = CVodeSetSensRho(cvode_mem, ZERO); if(check_flag(&flag, "CVodeSetSensRho", 1)) return(1); flag = CVodeSetSensParams(cvode_mem, data->p, pbar, plist); if(check_flag(&flag, "CVodeSetSensParams", 1)) return(1); printf("Sensitivity: YES "); if(sensi_meth == CV_SIMULTANEOUS) printf("( SIMULTANEOUS +"); else if(sensi_meth == CV_STAGGERED) printf("( STAGGERED +"); else printf("( STAGGERED1 +"); if(err_con) printf(" FULL ERROR CONTROL )"); else printf(" PARTIAL ERROR CONTROL )"); } else { printf("Sensitivity: NO "); } /* In loop over output points, call CVode, print results, test for error */ printf("\n\n"); printf("========================================================================\n"); printf(" T Q H NST Bottom left Top right \n"); printf("========================================================================\n"); for (iout=1, tout = TWOHR; iout <= NOUT; iout++, tout += TWOHR) { flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL); if(check_flag(&flag, "CVode", 1)) break; PrintOutput(cvode_mem, t, y); if (sensi) { flag = CVodeGetSens(cvode_mem, t, uS); if(check_flag(&flag, "CVodeGetSens", 1)) break; PrintOutputS(uS); } printf("------------------------------------------------------------------------\n"); } /* Print final statistics */ PrintFinalStats(cvode_mem, sensi); /* Free memory */ N_VDestroy_Serial(y); if (sensi) { N_VDestroyVectorArray_Serial(uS, NS); free(pbar); free(plist); } FreeUserData(data); CVodeFree(&cvode_mem); return(0); }
int main(int argc, char *argv[]) { void *cvode_mem; UserData data; realtype dx, reltol, abstol, t, tout; N_Vector u; int iout, flag; realtype *pbar; int is, *plist; N_Vector *uS; booleantype sensi, err_con; int sensi_meth; cvode_mem = NULL; data = NULL; u = NULL; pbar = NULL; plist = NULL; uS = NULL; /* Process arguments */ ProcessArgs(argc, argv, &sensi, &sensi_meth, &err_con); /* Set user data */ data = (UserData) malloc(sizeof *data); /* Allocate data memory */ if(check_flag((void *)data, "malloc", 2)) return(1); data->p = (realtype *) malloc(NP * sizeof(realtype)); dx = data->dx = XMAX/((realtype)(MX+1)); data->p[0] = RCONST(1.0); data->p[1] = RCONST(0.5); /* Allocate and set initial states */ u = N_VNew_Serial(NEQ); if(check_flag((void *)u, "N_VNew_Serial", 0)) return(1); SetIC(u, dx); /* Set integration tolerances */ reltol = ZERO; abstol = ATOL; /* Create CVODES object */ cvode_mem = CVodeCreate(CV_ADAMS, CV_FUNCTIONAL); if(check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1); flag = CVodeSetUserData(cvode_mem, data); if(check_flag(&flag, "CVodeSetUserData", 1)) return(1); /* Allocate CVODES memory */ flag = CVodeInit(cvode_mem, f, T0, u); if(check_flag(&flag, "CVodeInit", 1)) return(1); flag = CVodeSStolerances(cvode_mem, reltol, abstol); if(check_flag(&flag, "CVodeSStolerances", 1)) return(1); printf("\n1-D advection-diffusion equation, mesh size =%3d\n", MX); /* Sensitivity-related settings */ if(sensi) { plist = (int *) malloc(NS * sizeof(int)); if(check_flag((void *)plist, "malloc", 2)) return(1); for(is=0; is<NS; is++) plist[is] = is; pbar = (realtype *) malloc(NS * sizeof(realtype)); if(check_flag((void *)pbar, "malloc", 2)) return(1); for(is=0; is<NS; is++) pbar[is] = data->p[plist[is]]; uS = N_VCloneVectorArray_Serial(NS, u); if(check_flag((void *)uS, "N_VCloneVectorArray_Serial", 0)) return(1); for(is=0;is<NS;is++) N_VConst(ZERO, uS[is]); flag = CVodeSensInit1(cvode_mem, NS, sensi_meth, NULL, uS); if(check_flag(&flag, "CVodeSensInit1", 1)) return(1); flag = CVodeSensEEtolerances(cvode_mem); if(check_flag(&flag, "CVodeSensEEtolerances", 1)) return(1); flag = CVodeSetSensErrCon(cvode_mem, err_con); if(check_flag(&flag, "CVodeSetSensErrCon", 1)) return(1); flag = CVodeSetSensDQMethod(cvode_mem, CV_CENTERED, ZERO); if(check_flag(&flag, "CVodeSetSensDQMethod", 1)) return(1); flag = CVodeSetSensParams(cvode_mem, data->p, pbar, plist); if(check_flag(&flag, "CVodeSetSensParams", 1)) return(1); printf("Sensitivity: YES "); if(sensi_meth == CV_SIMULTANEOUS) printf("( SIMULTANEOUS +"); else if(sensi_meth == CV_STAGGERED) printf("( STAGGERED +"); else printf("( STAGGERED1 +"); if(err_con) printf(" FULL ERROR CONTROL )"); else printf(" PARTIAL ERROR CONTROL )"); } else { printf("Sensitivity: NO "); } /* In loop over output points, call CVode, print results, test for error */ printf("\n\n"); printf("============================================================\n"); printf(" T Q H NST Max norm \n"); printf("============================================================\n"); for (iout=1, tout=T1; iout <= NOUT; iout++, tout += DTOUT) { flag = CVode(cvode_mem, tout, u, &t, CV_NORMAL); if(check_flag(&flag, "CVode", 1)) break; PrintOutput(cvode_mem, t, u); if (sensi) { flag = CVodeGetSens(cvode_mem, &t, uS); if(check_flag(&flag, "CVodeGetSens", 1)) break; PrintOutputS(uS); } printf("------------------------------------------------------------\n"); } /* Print final statistics */ PrintFinalStats(cvode_mem, sensi); /* Free memory */ N_VDestroy_Serial(u); if (sensi) { N_VDestroyVectorArray_Serial(uS, NS); free(plist); free(pbar); } free(data); CVodeFree(&cvode_mem); return(0); }
int main(void) { UserData data; void *mem; N_Vector yy, yp, id, q, *yyS, *ypS, *qS; realtype tret; realtype pbar[2]; realtype dp, G, Gm[2], Gp[2]; int flag, is; realtype atolS[NP]; id = N_VNew_Serial(NEQ); yy = N_VNew_Serial(NEQ); yp = N_VNew_Serial(NEQ); q = N_VNew_Serial(1); yyS= N_VCloneVectorArray(NP,yy); ypS= N_VCloneVectorArray(NP,yp); qS = N_VCloneVectorArray_Serial(NP, q); data = (UserData) malloc(sizeof *data); data->a = 0.5; /* half-length of crank */ data->J1 = 1.0; /* crank moment of inertia */ data->m2 = 1.0; /* mass of connecting rod */ data->m1 = 1.0; data->J2 = 2.0; /* moment of inertia of connecting rod */ data->params[0] = 1.0; /* spring constant */ data->params[1] = 1.0; /* damper constant */ data->l0 = 1.0; /* spring free length */ data->F = 1.0; /* external constant force */ N_VConst(ONE, id); NV_Ith_S(id, 9) = ZERO; NV_Ith_S(id, 8) = ZERO; NV_Ith_S(id, 7) = ZERO; NV_Ith_S(id, 6) = ZERO; printf("\nSlider-Crank example for IDAS:\n"); /* Consistent IC*/ setIC(yy, yp, data); for (is=0;is<NP;is++) { N_VConst(ZERO, yyS[is]); N_VConst(ZERO, ypS[is]); } /* IDA initialization */ mem = IDACreate(); flag = IDAInit(mem, ressc, TBEGIN, yy, yp); flag = IDASStolerances(mem, RTOLF, ATOLF); flag = IDASetUserData(mem, data); flag = IDASetId(mem, id); flag = IDASetSuppressAlg(mem, TRUE); flag = IDASetMaxNumSteps(mem, 20000); /* Call IDADense and set up the linear solver. */ flag = IDADense(mem, NEQ); flag = IDASensInit(mem, NP, IDA_SIMULTANEOUS, NULL, yyS, ypS); pbar[0] = data->params[0];pbar[1] = data->params[1]; flag = IDASetSensParams(mem, data->params, pbar, NULL); flag = IDASensEEtolerances(mem); IDASetSensErrCon(mem, TRUE); N_VConst(ZERO, q); flag = IDAQuadInit(mem, rhsQ, q); flag = IDAQuadSStolerances(mem, RTOLQ, ATOLQ); flag = IDASetQuadErrCon(mem, TRUE); N_VConst(ZERO, qS[0]); flag = IDAQuadSensInit(mem, rhsQS, qS); atolS[0] = atolS[1] = ATOLQ; flag = IDAQuadSensSStolerances(mem, RTOLQ, atolS); flag = IDASetQuadSensErrCon(mem, TRUE); /* Perform forward run */ printf("\nForward integration ... "); flag = IDASolve(mem, TEND, &tret, yy, yp, IDA_NORMAL); if (check_flag(&flag, "IDASolve", 1)) return(1); printf("done!\n"); PrintFinalStats(mem); IDAGetQuad(mem, &tret, q); printf("--------------------------------------------\n"); printf(" G = %24.16f\n", Ith(q,1)); printf("--------------------------------------------\n\n"); IDAGetQuadSens(mem, &tret, qS); printf("-------------F O R W A R D------------------\n"); printf(" dG/dp: %12.4le %12.4le\n", Ith(qS[0],1), Ith(qS[1],1)); printf("--------------------------------------------\n\n"); IDAFree(&mem); /* Finite differences for dG/dp */ dp = 0.00001; data->params[0] = ONE; data->params[1] = ONE; mem = IDACreate(); setIC(yy, yp, data); flag = IDAInit(mem, ressc, TBEGIN, yy, yp); flag = IDASStolerances(mem, RTOLFD, ATOLFD); flag = IDASetUserData(mem, data); flag = IDASetId(mem, id); flag = IDASetSuppressAlg(mem, TRUE); /* Call IDADense and set up the linear solver. */ flag = IDADense(mem, NEQ); N_VConst(ZERO, q); IDAQuadInit(mem, rhsQ, q); IDAQuadSStolerances(mem, RTOLQ, ATOLQ); IDASetQuadErrCon(mem, TRUE); IDASolve(mem, TEND, &tret, yy, yp, IDA_NORMAL); IDAGetQuad(mem,&tret,q); G = Ith(q,1); /*printf(" G =%12.6e\n", Ith(q,1));*/ /****************************** * BACKWARD for k ******************************/ data->params[0] -= dp; setIC(yy, yp, data); IDAReInit(mem, TBEGIN, yy, yp); N_VConst(ZERO, q); IDAQuadReInit(mem, q); IDASolve(mem, TEND, &tret, yy, yp, IDA_NORMAL); IDAGetQuad(mem, &tret, q); Gm[0] = Ith(q,1); /*printf("Gm[0]=%12.6e\n", Ith(q,1));*/ /**************************** * FORWARD for k * ****************************/ data->params[0] += (TWO*dp); setIC(yy, yp, data); IDAReInit(mem, TBEGIN, yy, yp); N_VConst(ZERO, q); IDAQuadReInit(mem, q); IDASolve(mem, TEND, &tret, yy, yp, IDA_NORMAL); IDAGetQuad(mem, &tret, q); Gp[0] = Ith(q,1); /*printf("Gp[0]=%12.6e\n", Ith(q,1));*/ /* Backward for c */ data->params[0] = ONE; data->params[1] -= dp; setIC(yy, yp, data); IDAReInit(mem, TBEGIN, yy, yp); N_VConst(ZERO, q); IDAQuadReInit(mem, q); IDASolve(mem, TEND, &tret, yy, yp, IDA_NORMAL); IDAGetQuad(mem, &tret, q); Gm[1] = Ith(q,1); /* Forward for c */ data->params[1] += (TWO*dp); setIC(yy, yp, data); IDAReInit(mem, TBEGIN, yy, yp); N_VConst(ZERO, q); IDAQuadReInit(mem, q); IDASolve(mem, TEND, &tret, yy, yp, IDA_NORMAL); IDAGetQuad(mem, &tret, q); Gp[1] = Ith(q,1); IDAFree(&mem); printf("\n\n Checking using Finite Differences \n\n"); printf("---------------BACKWARD------------------\n"); printf(" dG/dp: %12.4le %12.4le\n", (G-Gm[0])/dp, (G-Gm[1])/dp); printf("-----------------------------------------\n\n"); printf("---------------FORWARD-------------------\n"); printf(" dG/dp: %12.4le %12.4le\n", (Gp[0]-G)/dp, (Gp[1]-G)/dp); printf("-----------------------------------------\n\n"); printf("--------------CENTERED-------------------\n"); printf(" dG/dp: %12.4le %12.4le\n", (Gp[0]-Gm[0])/(TWO*dp) ,(Gp[1]-Gm[1])/(TWO*dp)); printf("-----------------------------------------\n\n"); /* Free memory */ free(data); N_VDestroy(id); N_VDestroy_Serial(yy); N_VDestroy_Serial(yp); N_VDestroy_Serial(q); return(0); }
/** * Solves an initial value problem using CVODES to integrate over a system of * ODEs with optional forward sensitivity analysis. The initial conditions for * the system and for the sensitivity analysis are expected to be in the first * rows of simdata and sensitivities, respectively. * * @param [in] rhs the right-hand side of the system of ODEs * @param [in] num_timepoints the number of timepoints * @param [in] num_species the number of independent variables * @param [in] num_sens the number of parameters to compute sensitivities * for (set to zero to disable sensitivity * calculations) * @param [in] timepoints the timepoints at which data is to be returned * @param [in] params parameters * @param [in] sensi the indices of the parameters to compute the * sensitivities for (may be NULL to compute the * sensitivities for all parameters) * @param [in] options additional options for the integrator * @param [out] simdata contains the state values for each species at * each timepoint in column-major order. * @param [out] sensitivities sensitivities of each parameter in sensi * with respect to each independent variable. * The sensitivity of parameter j with respect to * variable k at timepoint i is stored at * (j * num_species + k) * lds + i. * May be NULL if sensitivities are not to be * calculated. * @param [in] lds leading dimension of simdata and sensitivities * * @return 0 on success, * GMCMC_ENOMEM if there was not enough memory to create the solver, * GMCMC_EINVAL if there was an invalid argument to the function, * GMCMC_ELINAL if the solution could not be found. */ int cvodes_solve(gmcmc_ode_rhs rhs, size_t num_timepoints, size_t num_species, size_t num_params, size_t num_sens, const double * timepoints, const double * params, const size_t * sensi, const cvodes_options * options, double * simdata, double * sensitivities, size_t lds) { int error; // Set vector of initial values N_Vector y = N_VNew_Serial((long int)num_species); for (size_t j = 0; j < num_species; j++) NV_Ith_S(y, j) = simdata[j * lds]; // Create CVODES object void * cvode_mem; if ((cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON)) == NULL) GMCMC_ERROR("Failed to allocate ODE solver", GMCMC_ENOMEM); // Initialise CVODES solver if ((error = CVodeInit(cvode_mem, cvodes_rhs, timepoints[0], y)) != CV_SUCCESS) { CVodeFree(&cvode_mem); GMCMC_ERROR("Failed to initialise ODE solver", (error == CV_ILL_INPUT) ? GMCMC_EINVAL : GMCMC_ENOMEM); } // Set integration tolerances if ((error = CVodeSStolerances(cvode_mem, options->reltol, options->abstol)) != CV_SUCCESS) { CVodeFree(&cvode_mem); GMCMC_ERROR("Failed to set ODE solver integration tolerances", (error == CV_ILL_INPUT) ? GMCMC_EINVAL : GMCMC_ENOMEM); } // Create a copy of the parameters in case CVODES modifies them realtype * sens_params; if ((sens_params = malloc(num_params * sizeof(realtype))) == NULL) { CVodeFree(&cvode_mem); GMCMC_ERROR("Failed to allocate copy of parameter vector for sensitivity analysis", GMCMC_ENOMEM); } for (size_t i = 0; i < num_params; i++) sens_params[i] = (realtype)params[i]; // Set optional inputs cvodes_userdata userdata = { rhs, sens_params }; if ((error = CVodeSetUserData(cvode_mem, &userdata)) != CV_SUCCESS) { CVodeFree(&cvode_mem); free(sens_params); GMCMC_ERROR("Failed to set ODE solver user data", GMCMC_EINVAL); } // Attach linear solver module if ((error = CVLapackDense(cvode_mem, (int)num_species)) != CV_SUCCESS) { CVodeFree(&cvode_mem); free(sens_params); GMCMC_ERROR("Failed to attach ODE solver module", (error == CV_ILL_INPUT) ? GMCMC_EINVAL : GMCMC_ENOMEM); } N_Vector * yS = NULL; int * plist = NULL; if (num_sens > 0) { // Set sensitivity initial conditions yS = N_VCloneVectorArray_Serial((int)num_sens, y); for (size_t j = 0; j < num_sens; j++) { for (size_t i = 0; i < num_species; i++) NV_Ith_S(yS[j], i) = sensitivities[(j * num_species + i) * lds]; } // Activate sensitivity calculations // Use default finite differences if ((error = CVodeSensInit(cvode_mem, (int)num_sens, CV_SIMULTANEOUS, NULL, yS)) != CV_SUCCESS) { CVodeFree(&cvode_mem); free(sens_params); GMCMC_ERROR("Failed to activate ODE solver sensitivity calculations", (error == CV_ILL_INPUT) ? GMCMC_EINVAL : GMCMC_ENOMEM); } // Set sensitivity tolerances if ((error = CVodeSensEEtolerances(cvode_mem)) != CV_SUCCESS) { CVodeFree(&cvode_mem); free(sens_params); GMCMC_ERROR("Failed to set ODE solver sensitivity tolerances", (error == CV_ILL_INPUT) ? GMCMC_EINVAL : GMCMC_ENOMEM); } if (sensi != NULL) { if ((plist = malloc(num_sens * sizeof(int))) == NULL) { CVodeFree(&cvode_mem); free(sens_params); GMCMC_ERROR("Failed to allocate sensitivity parameter list", GMCMC_ENOMEM); } for (size_t i = 0; i < num_sens; i++) plist[i] = (int)sensi[i]; } // Set sensitivity analysis optional inputs if ((error = CVodeSetSensParams(cvode_mem, sens_params, NULL, plist)) != CV_SUCCESS) { CVodeFree(&cvode_mem); free(plist); free(sens_params); GMCMC_ERROR("Failed to set ODE solver sensitivity parameters", (error == CV_ILL_INPUT) ? GMCMC_EINVAL : GMCMC_ENOMEM); } } // Advance solution in time realtype tret; for (size_t i = 1; i < num_timepoints; i++) { if ((error = CVode(cvode_mem, timepoints[i], y, &tret, CV_NORMAL)) != CV_SUCCESS) { free(plist); free(sens_params); CVodeFree(&cvode_mem); GMCMC_ERROR("Failed to advance ODE solution", GMCMC_ELINAL); } for (size_t j = 0; j < num_species; j++) simdata[j * lds + i] = NV_Ith_S(y, j); // Extract the sensitivity solution if (yS != NULL) { if ((error = CVodeGetSens(cvode_mem, &tret, yS)) != CV_SUCCESS) { free(plist); free(sens_params); CVodeFree(&cvode_mem); GMCMC_ERROR("Failed to extract ODE sensitivity solution", GMCMC_ELINAL); } for (size_t j = 0; j < num_sens; j++) { for (size_t k = 0; k < num_species; k++) sensitivities[(j * num_species + k) * lds + i] = NV_Ith_S(yS[j], k); } } } N_VDestroy(y); if (yS != NULL) N_VDestroyVectorArray_Serial(yS, (int)num_sens); free(plist); free(sens_params); // Free solver memory CVodeFree(&cvode_mem); return 0; }