void RefSol(realtype tout, N_Vector yref) { void *cpode_mem; N_Vector yy, yp; realtype tol, t, th, thd; int flag; yy = N_VNew_Serial(2); yp = N_VNew_Serial(2); Ith(yy,1) = 0.0; /* theta */ Ith(yy,2) = 0.0; /* thetad */ tol = TOL_REF; cpode_mem = CPodeCreate(CP_EXPL, CP_BDF, CP_NEWTON); flag = CPodeSetMaxNumSteps(cpode_mem, 100000); flag = CPodeInit(cpode_mem, (void *)fref, NULL, 0.0, yy, yp, CP_SS, tol, &tol); flag = CPDense(cpode_mem, 2); flag = CPodeSetStopTime(cpode_mem, tout); flag = CPode(cpode_mem, tout, &t, yy, yp, CP_NORMAL_TSTOP); th = Ith(yy,1); thd = Ith(yy,2); Ith(yref,1) = cos(th); Ith(yref,2) = sin(th); Ith(yref,3) = -thd*sin(th); Ith(yref,4) = thd*cos(th); N_VDestroy_Serial(yy); N_VDestroy_Serial(yp); CPodeFree(&cpode_mem); return; }
void GetSol(void *cpode_mem, N_Vector yy0, realtype tol, realtype tout, booleantype proj, N_Vector yref) { N_Vector yy, yp; realtype t, x, y, xd, yd, g; int flag; long int nst, nfe, nsetups, nje, nfeLS, ncfn, netf; if (proj) { printf(" YES "); CPodeSetProjFrequency(cpode_mem, 1); } else { CPodeSetProjFrequency(cpode_mem, 0); printf(" NO "); } yy = N_VNew_Serial(4); yp = N_VNew_Serial(4); flag = CPodeReInit(cpode_mem, (void *)f, NULL, 0.0, yy0, NULL, CP_SS, tol, &tol); flag = CPode(cpode_mem, tout, &t, yy, yp, CP_NORMAL_TSTOP); x = Ith(yy,1); y = Ith(yy,2); g = ABS(x*x + y*y - 1.0); N_VLinearSum(1.0, yy, -1.0, yref, yy); N_VAbs(yy, yy); x = Ith(yy,1); y = Ith(yy,2); xd = Ith(yy,3); yd = Ith(yy,4); printf("%9.2e %9.2e %9.2e %9.2e | %9.2e |", Ith(yy,1),Ith(yy,2),Ith(yy,3),Ith(yy,4),g); CPodeGetNumSteps(cpode_mem, &nst); CPodeGetNumFctEvals(cpode_mem, &nfe); CPodeGetNumLinSolvSetups(cpode_mem, &nsetups); CPodeGetNumErrTestFails(cpode_mem, &netf); CPodeGetNumNonlinSolvConvFails(cpode_mem, &ncfn); CPDlsGetNumJacEvals(cpode_mem, &nje); CPDlsGetNumFctEvals(cpode_mem, &nfeLS); printf(" %6ld %6ld+%-4ld %4ld (%3ld) | %3ld %3ld\n", nst, nfe, nfeLS, nsetups, nje, ncfn, netf); N_VDestroy_Serial(yy); N_VDestroy_Serial(yp); return; }
int main(void) { realtype dx, dy, reltol, abstol, t, tout, umax; N_Vector u, up; UserData data; void *cvode_mem; int iout, flag; long int nst; u = NULL; data = NULL; cvode_mem = NULL; u = N_VNew_Serial(NEQ); up = N_VNew_Serial(NEQ); reltol = ZERO; abstol = ATOL; data = (UserData) malloc(sizeof *data); dx = data->dx = XMAX/(MX+1); dy = data->dy = YMAX/(MY+1); data->hdcoef = ONE/(dx*dx); data->hacoef = HALF/(TWO*dx); data->vdcoef = ONE/(dy*dy); SetIC(u, data); cvode_mem = CPodeCreate(CP_EXPL, CP_BDF, CP_NEWTON); flag = CPodeInit(cvode_mem, (void *)f, data, T0, u, NULL, CP_SS, reltol, &abstol); flag = CPLapackBand(cvode_mem, NEQ, MY, MY); flag = CPDlsSetJacFn(cvode_mem, (void *)Jac, data); /* In loop over output points: call CPode, print results, test for errors */ umax = N_VMaxNorm(u); PrintHeader(reltol, abstol, umax); for(iout=1, tout=T1; iout <= NOUT; iout++, tout += DTOUT) { flag = CPode(cvode_mem, tout, &t, u, up, CP_NORMAL); umax = N_VMaxNorm(u); flag = CPodeGetNumSteps(cvode_mem, &nst); PrintOutput(t, umax, nst); } PrintFinalStats(cvode_mem); N_VDestroy_Serial(u); CPodeFree(&cvode_mem); free(data); return(0); }
void OpenSMOKE_CVODE_Sundials<T>::MemoryAllocation(const int n) { this->n_ = n; // Number of equations this->y0_ = new double[this->n_]; this->y_ = new double[this->n_]; y0Sundials_ = N_VNew_Serial(this->n_); if (check_flag((void *)y0Sundials_, std::string("N_VNew_Serial"), 0)) exit(-1); ySundials_ = N_VNew_Serial(this->n_); if (check_flag((void *)ySundials_, std::string("N_VNew_Serial"), 0)) exit(-1); }
void SundialsInterface::init_memory(void* mem) const { Integrator::init_memory(mem); auto m = static_cast<SundialsMemory*>(mem); // Allocate n-vectors m->xz = N_VNew_Serial(nx_+nz_); m->q = N_VNew_Serial(nq_); m->rxz = N_VNew_Serial(nrx_+nrz_); m->rq = N_VNew_Serial(nrq_); // Allocate memory m->p.resize(np_); m->rp.resize(nrp_); }
static WebData AllocUserData(void) { int i, ngrp = NGRP, ns = NS; WebData wdata; wdata = (WebData) malloc(sizeof *wdata); for(i=0; i < ngrp; i++) { (wdata->P)[i] = newDenseMat(ns, ns); (wdata->pivot)[i] = newIndexArray(ns); } wdata->rewt = N_VNew_Serial(NEQ+1); wdata->vtemp = N_VNew_Serial(NEQ+1); return(wdata); }
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()); }
N_Vector Cvode::nvnew(long int n) { #if PARANEURON if (use_partrans_) { if (net_cvode_instance->use_long_double_) { return N_VNew_NrnParallelLD(0, n, global_neq_); }else{ return N_VNew_Parallel(0, n, global_neq_); } } #endif if (nctd_ > 1) { assert(n == neq_); if (!nthsizes_) { nthsizes_ = new long int[nrn_nthread]; for (int i = 0; i < nrn_nthread; ++i) { nthsizes_[i] = ctd_[i].nvsize_; } } #if 1 int sum = 0; for (int i=0; i < nctd_; ++i) { sum += nthsizes_[i];} assert(sum == neq_); #endif if (net_cvode_instance->use_long_double_) { return N_VNew_NrnThreadLD(n, nctd_, nthsizes_); }else{ return N_VNew_NrnThread(n, nctd_, nthsizes_); } } if (net_cvode_instance->use_long_double_) { return N_VNew_NrnSerialLD(n); }else{ return N_VNew_Serial(n); } }
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 SundialsInterface::init_memory(void* mem) const { Integrator::init_memory(mem); auto m = static_cast<SundialsMemory*>(mem); // Allocate n-vectors m->xz = N_VNew_Serial(nx_+nz_); m->q = N_VNew_Serial(nq_); m->rxz = N_VNew_Serial(nrx_+nrz_); m->rq = N_VNew_Serial(nrq_); // Reset linear solvers linsolF_.reset(get_function("jacF").sparsity_out(0)); if (nrx_>0) { linsolB_.reset(get_function("jacB").sparsity_out(0)); } }
int ViCaRS::init(SimEquations *eqns) { unsigned int num_local, i; int flag; _eqns = eqns; _num_equations = eqns->num_equations(); //flag = fill_greens_matrix(); //if (flag) return flag; num_local = (unsigned int)_bdata.size(); _vars = N_VNew_Serial(_num_global_blocks*_num_equations); if (_vars == NULL) return 1; // Init CVodes structures flag = _eqns->init(this); if (flag) return flag; for (i=0;i<_solvers.size();++i) _solvers[i]->init_solver(this); _cur_solver = 0; _cur_time = 0; return 0; }
static void Problem2(void) { void *fct; void *cpode_mem; N_Vector y, yp; realtype reltol=RTOL, abstol=ATOL, t, tout, erm, hu; int flag, iout, qu; y = NULL; yp = NULL; cpode_mem = NULL; y = N_VNew_Serial(P2_NEQ); N_VConst(ZERO, y); NV_Ith_S(y,0) = ONE; yp = N_VNew_Serial(P2_NEQ); if (ODE == CP_EXPL) { fct = (void *)f2; } else { fct = (void *)res2; f2(P2_T0, y, yp, NULL); } cpode_mem = CPodeCreate(ODE, CP_ADAMS, CP_FUNCTIONAL); /* flag = CPodeSetInitStep(cpode_mem, 2.0e-9);*/ flag = CPodeInit(cpode_mem, fct, NULL, P2_T0, y, yp, CP_SS, reltol, &abstol); printf("\n t max.err qu hu \n"); for(iout=1, tout=P2_T1; iout <= P2_NOUT; iout++, tout*=P2_TOUT_MULT) { flag = CPode(cpode_mem, tout, &t, y, yp, CP_NORMAL); if (flag != CP_SUCCESS) break; erm = MaxError(y, t); flag = CPodeGetLastOrder(cpode_mem, &qu); flag = CPodeGetLastStep(cpode_mem, &hu); printf("%10.3f %12.4le %2d %12.4le\n", t, erm, qu, hu); } PrintFinalStats(cpode_mem); CPodeFree(&cpode_mem); N_VDestroy_Serial(y); N_VDestroy_Serial(yp); return; }
int main() { void *fct; void *cpode_mem; N_Vector y, yp; realtype reltol=RTOL, abstol=ATOL, t, tout, hu; int flag, iout, qu; y = NULL; yp = NULL; cpode_mem = NULL; y = N_VNew_Serial(P1_NEQ); NV_Ith_S(y,0) = TWO; NV_Ith_S(y,1) = ZERO; yp = N_VNew_Serial(P1_NEQ); if (ODE == CP_EXPL) { fct = (void *)f; } else { fct = (void *)res; f(P1_T0, y, yp, NULL); } cpode_mem = CPodeCreate(ODE, CP_ADAMS, CP_FUNCTIONAL); /* flag = CPodeSetInitStep(cpode_mem, 4.0e-9);*/ flag = CPodeInit(cpode_mem, fct, NULL, P1_T0, y, yp, CP_SS, reltol, &abstol); printf("\n t x xdot qu hu \n"); for(iout=1, tout=P1_T1; iout <= P1_NOUT; iout++, tout += P1_DTOUT) { flag = CPode(cpode_mem, tout, &t, y, yp, CP_NORMAL); if (flag != CP_SUCCESS) break; flag = CPodeGetLastOrder(cpode_mem, &qu); flag = CPodeGetLastStep(cpode_mem, &hu); printf("%10.5f %12.5le %12.5le %2d %6.4le\n", t, NV_Ith_S(y,0), NV_Ith_S(y,1), qu, hu); } PrintFinalStats(cpode_mem); CPodeFree(&cpode_mem); N_VDestroy_Serial(y); N_VDestroy_Serial(yp); return 0; }
sdVector::sdVector(unsigned int N) { alloc = true; v = N_VNew_Serial(N); n = N; if (SundialsCvode::check_flag((void *)v, "N_VNew_Serial", 0)) { throw DebugException("sdVector: error allocating vector"); } }
int main() { void *cpode_mem; N_Vector yref, yy0; realtype tol, tout; int i, flag; tout = 30.0; /* Get reference solution */ yref = N_VNew_Serial(4); RefSol(tout, yref); /* Initialize solver */ tol = TOL; cpode_mem = CPodeCreate(CP_EXPL, CP_BDF, CP_NEWTON); yy0 = N_VNew_Serial(4); Ith(yy0,1) = 1.0; /* x */ Ith(yy0,2) = 0.0; /* y */ Ith(yy0,3) = 0.0; /* xd */ Ith(yy0,4) = 0.0; /* yd */ flag = CPodeInit(cpode_mem, (void *)f, NULL, 0.0, yy0, NULL, CP_SS, tol, &tol); flag = CPodeSetMaxNumSteps(cpode_mem, 50000); flag = CPodeSetStopTime(cpode_mem, tout); flag = CPodeProjDefine(cpode_mem, proj, NULL); flag = CPDense(cpode_mem, 4); for (i=0;i<5;i++) { printf("\n\n%.2e\n", tol); GetSol(cpode_mem, yy0, tol, tout, TRUE, yref); GetSol(cpode_mem, yy0, tol, tout, FALSE, yref); tol /= 10.0; } N_VDestroy_Serial(yref); CPodeFree(&cpode_mem); return(0); }
void CVodesIntegrator::setTolerances(double reltol, int n, double* abstol) { m_itol = CV_SV; m_nabs = n; if (n != m_neq) { if (m_abstol) N_VDestroy_Serial(nv(m_abstol)); m_abstol = reinterpret_cast<void*>(N_VNew_Serial(n)); } for (int i=0; i<n; i++) { NV_Ith_S(nv(m_abstol), i) = abstol[i]; } m_reltol = reltol; }
static WebData AllocUserData(void) { int i, ngrp = NGRP, ns = NS; WebData wdata; wdata = (WebData) malloc(sizeof *wdata); for(i=0; i < ngrp; i++) { (wdata->P)[i] = denalloc(ns); (wdata->pivot)[i] = denallocpiv(ns); } wdata->rewt = N_VNew_Serial(NEQ+1); return(wdata); }
//main int main(int argc, char **argv){ int i, j, n, pv=0; char* file_name; cs *jac; N_Vector u; Gen *gens; double *u0; //load ps file, populate ps, and grab some data if(argc > 1) file_name = argv[1]; else{ printf("Please specify PS data file."); return 1; } PS ps=GetPS(file_name); if(ps==NULL){ printf("Unable to build PS data.\n"); return 1; } n=(ps->num_buses-1)<<1; gens=ps->gens; u=N_VNew_Serial(n); u0=NV_DATA_S(u); //create an initial condition if(gens[pv].index==ps->swing_bus)pv++; for(i=0;i<ps->ybus->n;i++){ if(i==ps->swing_bus) continue; j=(i>ps->swing_bus?(i-1)<<1:i<<1); if(gens[pv].index==i){ u0[j]=0.1; u0[j+1]=0.1; pv++; if(pv<ps->num_gens&&gens[pv].index==ps->swing_bus)pv++; continue; } u0[j]=1.0; u0[j+1]=0.1; } //numerically evaluate the jacobian at initial condition jac=CheckDerivativeN(n, n, ComputeF, u, (void*)ps); cs_di_print(jac, 0); //free memory and return N_VDestroy_Serial(u); return 0; }
void CVodesIntegrator::setTolerances(double reltol, size_t n, double* abstol) { m_itol = CV_SV; m_nabs = n; if (n != m_neq) { if (m_abstol) { N_VDestroy_Serial(m_abstol); } m_abstol = N_VNew_Serial(static_cast<sd_size_t>(n)); } for (size_t i=0; i<n; i++) { NV_Ith_S(m_abstol, i) = abstol[i]; } m_reltol = reltol; }
string CVodesIntegrator::getErrorInfo(int N) { N_Vector errs = N_VNew_Serial(static_cast<sd_size_t>(m_neq)); N_Vector errw = N_VNew_Serial(static_cast<sd_size_t>(m_neq)); CVodeGetErrWeights(m_cvode_mem, errw); CVodeGetEstLocalErrors(m_cvode_mem, errs); vector<tuple<double, double, size_t> > weightedErrors; for (size_t i=0; i<m_neq; i++) { double err = NV_Ith_S(errs, i) * NV_Ith_S(errw, i); weightedErrors.emplace_back(-abs(err), err, i); } N_VDestroy(errs); N_VDestroy(errw); N = std::min(N, static_cast<int>(m_neq)); sort(weightedErrors.begin(), weightedErrors.end()); stringstream s; for (int i=0; i<N; i++) { s << get<2>(weightedErrors[i]) << ": " << get<1>(weightedErrors[i]) << endl; } return s.str(); }
N_Vector NewVector(long int n) { N_Vector v; long int nlocal, nglobal; if (sundials_VecType == 1) { v = N_VNew_Serial((long int)n); } else { nlocal = n; MPI_Allreduce(&nlocal, &nglobal, 1, MPI_INT, MPI_SUM, sundials_comm); v = N_VNew_Parallel(sundials_comm, nlocal, nglobal); } return(v); }
N_Vector *N_VNewVectorArray_Serial(int count, long int length) { N_Vector *vs; int j; if (count <= 0) return(NULL); vs = (N_Vector *) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j=0; j<count; j++) { vs[j] = N_VNew_Serial(length); if (vs[j] == NULL) { N_VDestroyVectorArray_Serial(vs, j-1); return(NULL); } } return(vs); }
void KinsolSolver::initialize(ComputeSystemFunction pComputeSystem, double *pParameters, int pSize, void *pUserData) { if (mSolver) // The solver has already been initialised, so reset things... reset(); // Initialise the ODE solver itself OpenCOR::CoreSolver::CoreNlaSolver::initialize(pComputeSystem, pParameters, pSize); // Create some vectors mParametersVector = N_VMake_Serial(pSize, pParameters); mOnesVector = N_VNew_Serial(pSize); N_VConst(1.0, mOnesVector); // Create the KINSOL solver mSolver = KINCreate(); // Use our own error handler KINSetErrHandlerFn(mSolver, errorHandler, this); // Initialise the KINSOL solver KINInit(mSolver, systemFunction, mParametersVector); // Set some user data mUserData = new KinsolSolverUserData(pUserData, pComputeSystem); KINSetUserData(mSolver, mUserData); // Set the linear solver KINDense(mSolver, pSize); }
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 }
N_Vector N_VNew_NrnThread(long int length, int nthread, long int* sizes) { int i; N_Vector v; N_Vector data; N_VectorContent_NrnThread* content; v = N_VNewEmpty_NrnThread(length, nthread, sizes); if (v == NULL) return(NULL); /* Create data */ if (length > 0) { /* Allocate memory */ NV_OWN_DATA_NT(v) = TRUE; for (i=0; i < nthread; ++i) { data = N_VNew_Serial(sizes[i]); if(data == NULL) {N_VDestroy_NrnThread(v);return(NULL);} NV_SUBVEC_NT(v, i) = data; } } return(v); }
int main() { void *mem; UserData data; N_Vector uu, up, constraints, res; int ier, iout; realtype rtol, atol, t0, t1, tout, tret; long int netf, ncfn, ncfl; mem = NULL; data = NULL; uu = up = constraints = res = NULL; /* Allocate N-vectors and the user data structure. */ uu = N_VNew_Serial(NEQ); if(check_flag((void *)uu, "N_VNew_Serial", 0)) return(1); up = N_VNew_Serial(NEQ); if(check_flag((void *)up, "N_VNew_Serial", 0)) return(1); res = N_VNew_Serial(NEQ); if(check_flag((void *)res, "N_VNew_Serial", 0)) return(1); constraints = N_VNew_Serial(NEQ); if(check_flag((void *)constraints, "N_VNew_Serial", 0)) return(1); data = (UserData) malloc(sizeof *data); data->pp = NULL; if(check_flag((void *)data, "malloc", 2)) return(1); /* Assign parameters in the user data structure. */ data->mm = MGRID; data->dx = ONE/(MGRID-ONE); data->coeff = ONE/(data->dx * data->dx); data->pp = N_VNew_Serial(NEQ); if(check_flag((void *)data->pp, "N_VNew_Serial", 0)) return(1); /* Initialize uu, up. */ SetInitialProfile(data, uu, up, res); /* Set constraints to all 1's for nonnegative solution values. */ N_VConst(ONE, constraints); /* Assign various parameters. */ t0 = ZERO; t1 = RCONST(0.01); rtol = ZERO; atol = RCONST(1.0e-3); /* Call IDACreate and IDAMalloc to initialize solution */ mem = IDACreate(); if(check_flag((void *)mem, "IDACreate", 0)) return(1); ier = IDASetUserData(mem, data); if(check_flag(&ier, "IDASetUserData", 1)) return(1); ier = IDASetConstraints(mem, constraints); if(check_flag(&ier, "IDASetConstraints", 1)) return(1); N_VDestroy_Serial(constraints); ier = IDAInit(mem, resHeat, t0, uu, up); if(check_flag(&ier, "IDAInit", 1)) return(1); ier = IDASStolerances(mem, rtol, atol); if(check_flag(&ier, "IDASStolerances", 1)) return(1); /* Call IDASpgmr to specify the linear solver. */ ier = IDASpgmr(mem, 0); if(check_flag(&ier, "IDASpgmr", 1)) return(1); ier = IDASpilsSetPreconditioner(mem, PsetupHeat, PsolveHeat); if(check_flag(&ier, "IDASpilsSetPreconditioner", 1)) return(1); /* Print output heading. */ PrintHeader(rtol, atol); /* * ------------------------------------------------------------------------- * CASE I * ------------------------------------------------------------------------- */ /* Print case number, output table heading, and initial line of table. */ printf("\n\nCase 1: gsytpe = MODIFIED_GS\n"); printf("\n Output Summary (umax = max-norm of solution) \n\n"); printf(" time umax k nst nni nje nre nreLS h npe nps\n" ); printf("----------------------------------------------------------------------\n"); /* Loop over output times, call IDASolve, and print results. */ for (tout = t1,iout = 1; iout <= NOUT ; iout++, tout *= TWO) { ier = IDASolve(mem, tout, &tret, uu, up, IDA_NORMAL); if(check_flag(&ier, "IDASolve", 1)) return(1); PrintOutput(mem, tret, uu); } /* Print remaining counters. */ ier = IDAGetNumErrTestFails(mem, &netf); check_flag(&ier, "IDAGetNumErrTestFails", 1); ier = IDAGetNumNonlinSolvConvFails(mem, &ncfn); check_flag(&ier, "IDAGetNumNonlinSolvConvFails", 1); ier = IDASpilsGetNumConvFails(mem, &ncfl); check_flag(&ier, "IDASpilsGetNumConvFails", 1); printf("\nError test failures = %ld\n", netf); printf("Nonlinear convergence failures = %ld\n", ncfn); printf("Linear convergence failures = %ld\n", ncfl); /* * ------------------------------------------------------------------------- * CASE II * ------------------------------------------------------------------------- */ /* Re-initialize uu, up. */ SetInitialProfile(data, uu, up, res); /* Re-initialize IDA and IDASPGMR */ ier = IDAReInit(mem, t0, uu, up); if(check_flag(&ier, "IDAReInit", 1)) return(1); ier = IDASpilsSetGSType(mem, CLASSICAL_GS); if(check_flag(&ier, "IDASpilsSetGSType",1)) return(1); /* Print case number, output table heading, and initial line of table. */ printf("\n\nCase 2: gstype = CLASSICAL_GS\n"); printf("\n Output Summary (umax = max-norm of solution) \n\n"); printf(" time umax k nst nni nje nre nreLS h npe nps\n" ); printf("----------------------------------------------------------------------\n"); /* Loop over output times, call IDASolve, and print results. */ for (tout = t1,iout = 1; iout <= NOUT ; iout++, tout *= TWO) { ier = IDASolve(mem, tout, &tret, uu, up, IDA_NORMAL); if(check_flag(&ier, "IDASolve", 1)) return(1); PrintOutput(mem, tret, uu); } /* Print remaining counters. */ ier = IDAGetNumErrTestFails(mem, &netf); check_flag(&ier, "IDAGetNumErrTestFails", 1); ier = IDAGetNumNonlinSolvConvFails(mem, &ncfn); check_flag(&ier, "IDAGetNumNonlinSolvConvFails", 1); ier = IDASpilsGetNumConvFails(mem, &ncfl); check_flag(&ier, "IDASpilsGetNumConvFails", 1); printf("\nError test failures = %ld\n", netf); printf("Nonlinear convergence failures = %ld\n", ncfn); printf("Linear convergence failures = %ld\n", ncfl); /* Free Memory */ IDAFree(&mem); N_VDestroy_Serial(uu); N_VDestroy_Serial(up); N_VDestroy_Serial(res); N_VDestroy_Serial(data->pp); free(data); return(0); }
int main() { realtype abstol, reltol, t, tout; N_Vector u; UserData data; void *cvode_mem; int flag, iout, jpre; long int ml, mu; u = NULL; data = NULL; cvode_mem = NULL; /* Allocate and initialize u, and set problem data and tolerances */ u = N_VNew_Serial(NEQ); if(check_flag((void *)u, "N_VNew_Serial", 0)) return(1); data = (UserData) malloc(sizeof *data); if(check_flag((void *)data, "malloc", 2)) return(1); InitUserData(data); SetInitialProfiles(u, data->dx, data->dy); abstol = ATOL; reltol = RTOL; /* 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); /* Set the pointer to user-defined data */ flag = CVodeSetUserData(cvode_mem, data); if(check_flag(&flag, "CVodeSetUserData", 1)) return(1); /* Call CVodeInit to initialize the integrator memory and specify the * user's right hand side function in u'=f(t,u), the inital time T0, and * the initial dependent variable vector u. */ flag = CVodeInit(cvode_mem, f, T0, u); if(check_flag(&flag, "CVodeInit", 1)) return(1); /* Call CVodeSStolerances to specify the scalar relative tolerance * and scalar absolute tolerances */ flag = CVodeSStolerances(cvode_mem, reltol, abstol); if (check_flag(&flag, "CVodeSStolerances", 1)) return(1); /* Call CVSpgmr to specify the linear solver CVSPGMR with left preconditioning and the maximum Krylov dimension maxl */ flag = CVSpgmr(cvode_mem, PREC_LEFT, 0); if(check_flag(&flag, "CVSpgmr", 1)) return(1); /* Call CVBandPreInit to initialize band preconditioner */ ml = mu = 2; flag = CVBandPrecInit(cvode_mem, NEQ, mu, ml); if(check_flag(&flag, "CVBandPrecInit", 0)) return(1); PrintIntro(mu, ml); /* Loop over jpre (= PREC_LEFT, PREC_RIGHT), and solve the problem */ for (jpre = PREC_LEFT; jpre <= PREC_RIGHT; jpre++) { /* On second run, re-initialize u, the solver, and CVSPGMR */ if (jpre == PREC_RIGHT) { SetInitialProfiles(u, data->dx, data->dy); flag = CVodeReInit(cvode_mem, T0, u); if(check_flag(&flag, "CVodeReInit", 1)) return(1); flag = CVSpilsSetPrecType(cvode_mem, PREC_RIGHT); check_flag(&flag, "CVSpilsSetPrecType", 1); printf("\n\n-------------------------------------------------------"); printf("------------\n"); } printf("\n\nPreconditioner type is: jpre = %s\n\n", (jpre == PREC_LEFT) ? "PREC_LEFT" : "PREC_RIGHT"); /* In loop over output points, call CVode, print results, test for error */ for (iout = 1, tout = TWOHR; iout <= NOUT; iout++, tout += TWOHR) { flag = CVode(cvode_mem, tout, u, &t, CV_NORMAL); check_flag(&flag, "CVode", 1); PrintOutput(cvode_mem, u, t); if (flag != CV_SUCCESS) { break; } } /* Print final statistics */ PrintFinalStats(cvode_mem); } /* End of jpre loop */ /* Free memory */ N_VDestroy_Serial(u); free(data); CVodeFree(&cvode_mem); return(0); }
int nlsKinsolAllocate(int size, NONLINEAR_SYSTEM_DATA *nlsData, int linearSolverMethod) { int i, flag, printLevel; NLS_KINSOL_DATA *kinsolData = (NLS_KINSOL_DATA*) malloc(sizeof(NLS_KINSOL_DATA)); /* allocate system data */ nlsData->solverData = (void*)kinsolData; kinsolData->size = size; kinsolData->linearSolverMethod = linearSolverMethod; kinsolData->solved = 0; kinsolData->fnormtol = sqrt(newtonFTol); /* function tolerance */ kinsolData->scsteptol = sqrt(newtonXTol); /* step tolerance */ kinsolData->initialGuess = N_VNew_Serial(size); kinsolData->xScale = N_VNew_Serial(size); kinsolData->fScale = N_VNew_Serial(size); kinsolData->fRes = N_VNew_Serial(size); kinsolData->kinsolMemory = KINCreate(); /* setup user defined functions */ KINSetErrHandlerFn(kinsolData->kinsolMemory, nlsKinsolErrorPrint, kinsolData); KINSetInfoHandlerFn(kinsolData->kinsolMemory, nlsKinsolInfoPrint, kinsolData); KINSetUserData(kinsolData->kinsolMemory, (void*)&(kinsolData->userData)); flag = KINInit(kinsolData->kinsolMemory, nlsKinsolResiduals, kinsolData->initialGuess); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } /* Specify linear solver and/or corresponding jacobian function*/ if (kinsolData->linearSolverMethod == 3) { if(nlsData->isPatternAvailable) { kinsolData->nnz = nlsData->sparsePattern.numberOfNoneZeros; flag = KINKLU(kinsolData->kinsolMemory, size, kinsolData->nnz); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } flag = KINSlsSetSparseJacFn(kinsolData->kinsolMemory, nlsSparseJac); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL Sparse Solver!"); } } else { flag = KINDense(kinsolData->kinsolMemory, size); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } } } else if (kinsolData->linearSolverMethod == 1) { flag = KINDense(kinsolData->kinsolMemory, size); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } } else if (kinsolData->linearSolverMethod == 2) { flag = KINDense(kinsolData->kinsolMemory, size); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } flag = KINDlsSetDenseJacFn(kinsolData->kinsolMemory, nlsDenseJac); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL Sparse Solver!"); } } /* configuration */ nlsKinsolConfigSetup(kinsolData); /* debug print level of kinsol */ if (ACTIVE_STREAM(LOG_NLS)) printLevel = 1; else if (ACTIVE_STREAM(LOG_NLS_V)) printLevel = 3; else printLevel = 0; KINSetPrintLevel(kinsolData->kinsolMemory, printLevel); return 0; }
/* creates CVODES forward sensitivity solver structures return 1 => success return 0 => failure */ int IntegratorInstance_createCVODESSolverStructures(integratorInstance_t *engine) { int i, j, flag, neq, ns; realtype *ydata, *abstoldata, *ySdata, *senstoldata; odeModel_t *om = engine->om; cvodeData_t *data = engine->data; cvodeSolver_t *solver = engine->solver; cvodeSettings_t *opt = engine->opt; /* realtype pbar[data->nsens+1]; */ /*int *plist; removed by AMF 8/11/05 realtype *pbar; ASSIGN_NEW_MEMORY_BLOCK(plist, data->nsens+1, int, 0) ASSIGN_NEW_MEMORY_BLOCK(pbar, data->nsens+1, realtype, 0)*/ /***** adding sensitivity specific structures ******/ /** * construct sensitivity related structures */ /* free sensitivity from former runs (changed for non-default cases!) */ ODEModel_freeSensitivity(om); /* if jacobian matrix has been constructed successfully, construct sensitivity matrix dx/dp, sets om->sensitivity to 1 if successful, 0 otherwise */ /*!!! this function will require additional input for non-default case, via sensitivity input settings! !!!*/ if ( om->jacobian ) ODEModel_constructSensitivity(om); else { om->sensitivity = 0; om->jacob_sens = NULL; om->nsens = om->nconst; ASSIGN_NEW_MEMORY_BLOCK(om->index_sens, om->nsens, int, 0); /*!!! non-default case: these values should be passed for other cases !!!*/ for ( i=0; i<om->nsens; i++ ) om->index_sens[i] = om->neq + om->nass + i; } engine->solver->nsens = data->nsens; solver->yS = N_VNewVectorArray_Serial(data->nsens, data->neq); if (check_flag((void *)solver->yS, "N_VNewVectorArray_Serial", 1, stderr)) return(0); /* * (re)initialize ySdata sensitivities */ /* absolute tolerance for sensitivity error control */ solver->senstol = N_VNew_Serial(data->nsens); abstoldata = NV_DATA_S(solver->senstol); for ( j=0; j<data->nsens; j++ ) { abstoldata[j] = 1e-4; ySdata = NV_DATA_S(solver->yS[j]); for ( i=0; i<data->neq; i++ ) ySdata[i] = data->sensitivity[i][j]; } /* * set method */ if ( opt->SensMethod == 0 ) flag =CVodeSensMalloc(solver->cvode_mem,data->nsens, CV_SIMULTANEOUS, solver->yS); else if ( opt->SensMethod == 1 ) flag = CVodeSensMalloc(solver->cvode_mem, data->nsens, CV_STAGGERED, solver->yS); else if ( opt->SensMethod == 2 ) flag = CVodeSensMalloc(solver->cvode_mem, data->nsens, CV_STAGGERED1, solver->yS); if(check_flag(&flag, "CVodeSensMalloc", 1, stderr)) { return 0; /* ERROR HANDLING CODE if failes */ } /* *** set parameter values or R.H.S function fS *****/ /* NOTES: */ /* !!! plist could later be used to specify requested parameters for sens.analysis !!! */ /* was construction of Jacobian and parametric matrix successfull ? */ if ( om->sensitivity && om->jacobian ) { flag = CVodeSetSensRhs1Fn(solver->cvode_mem, fS); if (check_flag(&flag, "CVodeSetSensRhs1Fn", 1, stderr)) { return 0; /* ERROR HANDLING CODE if failes */ } flag = CVodeSetSensFdata(solver->cvode_mem, data); if (check_flag(&flag, "CVodeSetSensFdata", 1, stderr)) { return 0; /* ERROR HANDLING CODE if failes */ } data->p = NULL; } else { ASSIGN_NEW_MEMORY_BLOCK(data->p, data->nsens, realtype, 0); for ( i=0; i<data->nsens; i++ ) { /* data->p is only required if R.H.S. fS cannot be supplied */ /* plist[i] = i+1; */ data->p[i] = data->value[om->index_sens[i]]; /* pbar[i] = abs(data->p[i]); */ /*??? WHAT IS PBAR ???*/ } flag = CVodeSetSensParams(solver->cvode_mem, data->p, NULL, NULL); if (check_flag(&flag, "CVodeSetSensParams", 1, stderr)) { return 0; /* ERROR HANDLING CODE if failes */ } flag = CVodeSetSensRho(solver->cvode_mem, 0.0); /* what is it? */ if (check_flag(&flag, "CVodeSetSensRhs1Fn", 1, stderr)) { /* ERROR HANDLING CODE if failes */ return 0; } } /* CVodeSetSensTolerances(solver->cvode_mem, CV_SS, */ /* solver->reltol, &solver->senstol); */ /* difference FALSE/TRUE ? */ flag = CVodeSetSensErrCon(solver->cvode_mem, FALSE); if (check_flag(&flag, "CVodeSetSensFdata", 1, stderr)) { return 0; /* ERROR HANDLING CODE if failes */ } return 1; /* OK */ }
int main() { realtype abstol=ATOL, reltol=RTOL, t, tout; N_Vector c; WebData wdata; void *cvode_mem; booleantype firstrun; int jpre, gstype, flag; int ns, mxns, iout; c = NULL; wdata = NULL; cvode_mem = NULL; /* Initializations */ c = N_VNew_Serial(NEQ); if(check_flag((void *)c, "N_VNew_Serial", 0)) return(1); wdata = AllocUserData(); if(check_flag((void *)wdata, "AllocUserData", 2)) return(1); InitUserData(wdata); ns = wdata->ns; mxns = wdata->mxns; /* Print problem description */ PrintIntro(); /* Loop over jpre and gstype (four cases) */ for (jpre = PREC_LEFT; jpre <= PREC_RIGHT; jpre++) { for (gstype = MODIFIED_GS; gstype <= CLASSICAL_GS; gstype++) { /* Initialize c and print heading */ CInit(c, wdata); PrintHeader(jpre, gstype); /* Call CVodeInit or CVodeReInit, then CVSpgmr to set up problem */ firstrun = (jpre == PREC_LEFT) && (gstype == MODIFIED_GS); if (firstrun) { cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON); if(check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1); wdata->cvode_mem = cvode_mem; flag = CVodeSetUserData(cvode_mem, wdata); if(check_flag(&flag, "CVodeSetUserData", 1)) return(1); flag = CVodeInit(cvode_mem, f, T0, c); if(check_flag(&flag, "CVodeInit", 1)) return(1); flag = CVodeSStolerances(cvode_mem, reltol, abstol); if (check_flag(&flag, "CVodeSStolerances", 1)) return(1); flag = CVSpgmr(cvode_mem, jpre, MAXL); if(check_flag(&flag, "CVSpgmr", 1)) return(1); flag = CVSpilsSetGSType(cvode_mem, gstype); if(check_flag(&flag, "CVSpilsSetGSType", 1)) return(1); flag = CVSpilsSetEpsLin(cvode_mem, DELT); if(check_flag(&flag, "CVSpilsSetEpsLin", 1)) return(1); flag = CVSpilsSetPreconditioner(cvode_mem, Precond, PSolve); if(check_flag(&flag, "CVSpilsSetPreconditioner", 1)) return(1); } else { flag = CVodeReInit(cvode_mem, T0, c); if(check_flag(&flag, "CVodeReInit", 1)) return(1); flag = CVSpilsSetPrecType(cvode_mem, jpre); check_flag(&flag, "CVSpilsSetPrecType", 1); flag = CVSpilsSetGSType(cvode_mem, gstype); if(check_flag(&flag, "CVSpilsSetGSType", 1)) return(1); } /* Print initial values */ if (firstrun) PrintAllSpecies(c, ns, mxns, T0); /* Loop over output points, call CVode, print sample solution values. */ tout = T1; for (iout = 1; iout <= NOUT; iout++) { flag = CVode(cvode_mem, tout, c, &t, CV_NORMAL); PrintOutput(cvode_mem, t); if (firstrun && (iout % 3 == 0)) PrintAllSpecies(c, ns, mxns, t); if(check_flag(&flag, "CVode", 1)) break; if (tout > RCONST(0.9)) tout += DTOUT; else tout *= TOUT_MULT; } /* Print final statistics, and loop for next case */ PrintFinalStats(cvode_mem); } } /* Free all memory */ CVodeFree(&cvode_mem); N_VDestroy_Serial(c); FreeUserData(wdata); return(0); }