def Problem2(): nerr = 0 reltol = cvodes.realtype(0) abstol = cvodes.realtype(1.0e-6) t = cvodes.realtype(0) print "\n-------------------------------------------------------------" print "-------------------------------------------------------------" print "\nProblem 2: ydot = A * y, where A is a banded lower" print "triangular matrix derived from 2-D advection PDE\n" print " neq = %i, ml = %i, mu = %i"%(P2_NEQ, P2_ML, P2_MU) print " itol = %s, reltol = %.2g, abstol = %.2g"%("CV_SS", 0, 1.0e-6) print " t max.err qu hu \n" cvode_mem = cvodes.CVodeCreate(cvodes.CV_ADAMS, cvodes.CV_FUNCTIONAL) for miter in ["FUNC", "DIAG", "BAND_USER", "BAND_DQ"]: ero = 0 y = cvodes.NVector([0]*P2_NEQ) y[0] = 1.0 if miter == "FUNC": cvodes.CVodeMalloc(cvode_mem, f2, P2_T0, y, cvodes.CV_SS, reltol, abstol) else: cvodes.CVodeSetIterType(cvode_mem, cvodes.CV_NEWTON) cvodes.CVodeReInit(cvode_mem, f2, P2_T0, y, cvodes.CV_SS, reltol, abstol) PrepareNextRun(cvode_mem, cvodes.CV_ADAMS, miter, P2_MU, P2_ML) print "\n t max.err qu hu " iout = 1 tout = P2_T1 while iout <= 5: flag = cvodes.CVode(cvode_mem, tout, y, ctypes.byref(t), cvodes.CV_NORMAL) erm = MaxError(y, t) qu = cvodes.CVodeGetLastOrder(cvode_mem) hu = cvodes.CVodeGetLastStep(cvode_mem) print "%10.3F %12.4e %2i %12.4e"%(t.value, erm, qu, hu) if flag != cvodes.CV_SUCCESS: nerr += 1 break er = erm / abstol.value if er > ero: ero = er if er > P2_TOL_FACTOR: nerr += 1 PrintErrOutput(P2_TOL_FACTOR) iout += 1 tout *= P2_TOUT_MULT PrintFinalStats(cvode_mem, miter, ero) cvode_mem = cvodes.CVodeCreate(cvodes.CV_BDF, cvodes.CV_FUNCTIONAL) for miter in ["FUNC", "DIAG", "BAND_USER", "BAND_DQ"]: ero = 0 y[0] = 1.0 if miter == "FUNC": cvodes.CVodeMalloc(cvode_mem, f2, P2_T0, y, cvodes.CV_SS, reltol, abstol) else: cvodes.CVodeSetIterType(cvode_mem, cvodes.CV_NEWTON) cvodes.CVodeReInit(cvode_mem, f2, P2_T0, y, cvodes.CV_SS, reltol, abstol) PrepareNextRun(cvode_mem, cvodes.CV_BDF, miter, P2_MU, P2_ML) print "\n t max.err qu hu " iout = 1 tout = P2_T1 while iout <= 5: flag = cvodes.CVode(cvode_mem, tout, y, ctypes.byref(t), cvodes.CV_NORMAL) erm = MaxError(y, t) qu = cvodes.CVodeGetLastOrder(cvode_mem) hu = cvodes.CVodeGetLastStep(cvode_mem) print "%10.3F %12.4e %2i %12.4e"%(t.value, erm, qu, hu) if flag != cvodes.CV_SUCCESS: nerr += 1 break er = erm / abstol.value if er > ero: ero = er if er > P2_TOL_FACTOR: nerr += 1 PrintErrOutput(P2_TOL_FACTOR) iout += 1 tout *= P2_TOUT_MULT PrintFinalStats(cvode_mem, miter, ero) return nerr
print "\nFinal Statistics\n" print "nst = %5ld\n"%(nst) print "nfe = %5ld"%(nfe) print "netf = %5ld nsetups = %5ld"%(netf, nsetups) print "nni = %5ld ncfn = %5ld\n"%(nni, ncfn) if sensi: print "nfSe = %5ld nfeS = %5ld"%(nfSe, nfeS) print "netfs = %5ld nsetupsS = %5ld"%(netfS, nsetupsS) print "nniS = %5ld ncfnS = %5ld"%(nniS, ncfnS) sensi = False sensi_meth = -1 err_con = False t = cvodes.realtype(0) if len(sys.argv) < 2: WrongArgs(sys.argv[0]) if sys.argv[1] == "-nosensi": sensi = False elif sys.argv[1] == "-sensi": sensi = True else: WrongArgs(sys.argv[0]) if (sensi): if len(sys.argv) != 4: WrongArgs(sys.argv[0])
def PSolve(tn, u, fu, r, z, gamma, delta, lr, P_data, vtemp): data = ctypes.cast(P_data, PUserData).contents z[:] = r for jx in range(MX): for jy in range(MY): cvodes.denGETRS(data.P[jx][jy], NUM_SPECIES, data.pivot[jx][jy], z.ptrto(jx*NUM_SPECIES + jy*NSMX)) return 0 u = cvodes.NVector([0.0]*(NEQ)) #Allocate and initialise user data t = cvodes.realtype(0) data = UserData() for jx in range(MX): for jy in range(MY): data.P[jx][jy] = cvodes.denalloc(NUM_SPECIES, NUM_SPECIES) data.Jbd[jx][jy] = cvodes.denalloc(NUM_SPECIES, NUM_SPECIES) data.pivot[jx][jy] = cvodes.denallocpiv(NUM_SPECIES) data.om = PI/HALFDAY data.dx = (XMAX-XMIN)/(MX-1) data.dy = (YMAX-YMIN)/(MY-1) data.hdco = KH/(data.dx**2) data.haco = VEL/(2.0*data.dx) data.vdco = (1.0/(data.dy**2))*KV0 pdata = ctypes.pointer(data)
def Problem1(): nerr = 0 reltol = cvodes.realtype(0) abstol = cvodes.realtype(1.0e-6) t = cvodes.realtype(0) y = cvodes.NVector([0, 0]) print "Demonstration program for CVODE package - direct linear solvers\n\n" print "Problem 1: Van der Pol oscillator" print " xdotdot - 3*(1 - x^2)*xdot + x = 0, x(0) = 2, xdot(0) = 0" print " neq = %i, itol = %s, reltol = %.2g, abstol = %.2g"%(2, "CV_SS", 0, 1.0e-6) cvode_mem = cvodes.CVodeCreate(cvodes.CV_ADAMS, cvodes.CV_FUNCTIONAL) for miter in ["FUNC", "DENSE_USER", "DENSE_DQ", "DIAG"]: ero = 0 y[0] = 2.0 y[1] = 0 if miter == "FUNC": cvodes.CVodeMalloc(cvode_mem, f1, 0, y, cvodes.CV_SS, reltol, abstol) else: cvodes.CVodeSetIterType(cvode_mem, cvodes.CV_NEWTON) cvodes.CVodeReInit(cvode_mem, f1, 0, y, cvodes.CV_SS, reltol, abstol) PrepareNextRun(cvode_mem, cvodes.CV_ADAMS, miter, 0, 0) print "\n t x xdot qu hu " iout = 1 tout = P1_T1 while iout <= 4: flag = cvodes.CVode(cvode_mem, tout, y, ctypes.byref(t), cvodes.CV_NORMAL) qu = cvodes.CVodeGetLastOrder(cvode_mem) hu = cvodes.CVodeGetLastStep(cvode_mem) print "%10.6g %12.5e %12.5e %2i %6.4e"%(t.value, y[0], y[1], qu, hu) if flag != cvodes.CV_SUCCESS: nerr += 1 break if iout%2 == 0: er = abs(y[0])/abstol.value if er > ero: ero = er if er > P1_TOL_FACTOR: nerr += 1 PrintErrOutput(P1_TOL_FACTOR) iout += 1 tout += P1_DTOUT PrintFinalStats(cvode_mem, miter, ero) cvode_mem = cvodes.CVodeCreate(cvodes.CV_BDF, cvodes.CV_FUNCTIONAL) for miter in ["FUNC", "DENSE_USER", "DENSE_DQ", "DIAG"]: ero = 0 y[0] = 2.0 y[1] = 0 if miter == "FUNC": cvodes.CVodeMalloc(cvode_mem, f1, 0, y, cvodes.CV_SS, reltol, abstol) else: cvodes.CVodeSetIterType(cvode_mem, cvodes.CV_NEWTON) cvodes.CVodeReInit(cvode_mem, f1, 0, y, cvodes.CV_SS, reltol, abstol) PrepareNextRun(cvode_mem, cvodes.CV_BDF, miter, 0, 0) print "\n t x xdot qu hu " iout = 1 tout = P1_T1 while iout <= 4: flag = cvodes.CVode(cvode_mem, tout, y, ctypes.byref(t), cvodes.CV_NORMAL) qu = cvodes.CVodeGetLastOrder(cvode_mem) hu = cvodes.CVodeGetLastStep(cvode_mem) print "%10.6g %12.5e %12.5e %2i %6.4e"%(t.value, y[0], y[1], qu, hu) if flag != cvodes.CV_SUCCESS: nerr += 1 break if iout%2 == 0: er = abs(y[0])/abstol.value if er > ero: ero = er if er > P1_TOL_FACTOR: nerr += 1 PrintErrOutput(P1_TOL_FACTOR) iout += 1 tout += P1_DTOUT PrintFinalStats(cvode_mem, miter, ero) return nerr
GSIter(-gamma, z, vtemp, wdata) iv = 0 for jy in range(wdata.my): igy = wdata.jigy[jy] for jx in range(wdata.mx): igx = wdata.jigx[jx] ig = igx + igy*wdata.ngx cvodes.denGETRS(wdata.P[ig], wdata.mp, wdata.pivot[ig], z.ptrto(iv)) iv += wdata.mp return 0 tnext = 1e-08 t = cvodes.realtype(T0) ncheck = ctypes.c_int(0) rewt = cvodes.NVector([0]*NEQ) wdata = WebData() for i in range(NGRP): wdata.P[i] = cvodes.denalloc(NS,NS) wdata.pivot[i] = cvodes.denallocpiv(NS) wdata.rewt = rewt.data InitUserData(wdata) c = cvodes.NVector([0]*(NEQ)) CInit(c, wdata) print "\nCreate and allocate CVODES memory for forward run" cvode_mem = cvodes.CVodeCreate(cvodes.CV_BDF, cvodes.CV_NEWTON) wdata.cvode_memF = cvode_mem.obj
gout[1] = y[2] - 0.01 return 0 def Jac(N, J, t, y, fy, jac_data, tmp1, tmp2, tmp3): J[0][0] = -0.04 J[0][1] = 1.0e4*y[2] J[0][2] = 1.0e4*y[1] J[1][0] = 0.04 J[1][1] = -1.0e4*y[2]-6.0e7*y[1] J[1][2] = -1.0e4*y[1] J[2][1] = 6.0e7*y[1] return 0 y = cvodes.NVector([1.0, 0.0, 0.0]) abstol = cvodes.NVector([1.0e-8, 1.0e-14, 1.0e-6]) reltol = cvodes.realtype(1.0e-4) cvode_mem = cvodes.CVodeCreate(cvodes.CV_BDF, cvodes.CV_NEWTON) cvodes.CVodeMalloc(cvode_mem, f, 0.0, y, cvodes.CV_SV, reltol, abstol) cvodes.CVodeRootInit(cvode_mem, 2, g, None) cvodes.CVDense(cvode_mem, 3) cvodes.CVDenseSetJacFn(cvode_mem, Jac, None) print " \n3-species kinetics problem\n" iout = 0 tout = 0.4 t = cvodes.realtype(0.0) while True: flag = cvodes.CVode(cvode_mem, tout, y, ctypes.byref(t), cvodes.CV_NORMAL)
def run(self): """Do the actual simulation. The input is set using setters/constructor. The solution can be retrieved using self.get_solution() """ return_last = self.get_return_last() sensi = self.get_sensitivity_analysis() time_step = self.get_time_step() start_time = self.get_start_time() end_time = self.get_final_time() verbose = self.get_verbosity() model = self.get_model() if verbose >= self.WHISPER: print "Running simulation with interval (%s, %s)." \ % (start_time, end_time) if verbose >= self.NORMAL: print "Input before integration:", model.u print "States:", model.x print start_time, "to", end_time class UserData: """ctypes structure used to move data in (and out of?) the callback functions. """ def __init__(self): self.parameters = None self.model = None self.ignore_p = None self.t_sim_start = None self.t_sim_end = None self.t_sim_duration = None __slots__ = [ 'parameters', # parameters 'model', # The evaluation model # (RHS if you will). 'ignore_p', # Whether p should be ignored or # not used to reduce unnecessary # copying. 't_sim_start', # Start time for simulation. 't_sim_end', # End time for simulation. 't_sim_duration', # Time duration for simulation. ] # initial y (copying just in case) y = cvodes.NVector(model.x.copy()) # converting tolerances to C types abstol = cvodes.realtype(self.abstol) reltol = cvodes.realtype(self.reltol) t0 = cvodes.realtype(start_time) cvode_mem = cvodes.CVodeCreate(cvodes.CV_BDF, cvodes.CV_NEWTON) cvodes.CVodeMalloc(cvode_mem, self._sundials_f, t0, y, cvodes.CV_SS, reltol, abstol) cvodes.CVDense(cvode_mem, len(model.x)) # Set f_data data = UserData() data.model = model data.t_sim_start = start_time data.t_sim_end = end_time data.t_sim_duration = data.t_sim_end - data.t_sim_start if sensi: # Sensitivity indices used by sundials_f(...) data.parameters = self.get_sensitivity_indices() data.ignore_p = 0 else: data.ignore_p = 1 parameters = None # Needed for correct return self._data = data if sensi: NP = len(model.pi) # number of model parameters NU = len(model.u) # number of control signals/inputs NI = len(model.x) # number of initial states from # which sensitivity is calculated NS = NP + NI + NU # number of sensitivities to be calculated NEQ = len(model.x) assert NEQ == NI, "yS must be modified below to handle the" \ " inequality NEQ != NI" err_con = False # Use sensisitity for error control yS = nvecserial.NVectorArray([[0] * NEQ] * NP + N.eye(NI).tolist() + [[0] * NEQ] * NU) cvodes.CVodeSensMalloc(cvode_mem, NS, cvodes.CV_STAGGERED1, yS) cvodes.CVodeSetSensErrCon(cvode_mem, err_con) cvodes.CVodeSetSensDQMethod(cvode_mem, cvodes.CV_CENTERED, 0) model_parameters = model.pi cvodes.CVodeSetSensParams(cvode_mem, data.parameters.params, None, None) tout = start_time + time_step if tout > end_time: tout = end_time # initial time t = cvodes.realtype(t0.value) # used for collecting the y's for plotting if return_last == False: num_samples = int(math.ceil( (end_time - start_time) / time_step)) + 1 T = N.zeros(num_samples, dtype=pyjmi.c_jmi_real_t) ylist = N.zeros((num_samples, len(model.x)), dtype=pyjmi.c_jmi_real_t) ylist[0] = model.x.copy() T[0] = t0.value i = 1 while True: # run ODE solver flag = cvodes.CVode(cvode_mem, tout, y, ctypes.byref(t), cvodes.CV_NORMAL) if verbose >= self.SCREAM: print "At t = %-14.4e y =" % t.value, \ (" %-11.6e "*len(y)) % tuple(y) """Used for return.""" if return_last == False: T[i] = t.value ylist[i] = N.array(y) i = i + 1 if N.abs(tout - end_time) <= 1e-6: break if flag == cvodes.CV_SUCCESS: tout += time_step if tout > end_time: tout = end_time if return_last == False: assert i <= num_samples, "Allocated a too small array." \ " (%s > %s)" % (i, num_samples) num_samples = i ylist = ylist[:num_samples] T = T[:num_samples] if sensi: cvodes.CVodeGetSens(cvode_mem, t, yS) if verbose >= self.LOUD: # collecting lots of information about the execution and present it nst = cvodes.CVodeGetNumSteps(cvode_mem) nfe = cvodes.CVodeGetNumRhsEvals(cvode_mem) nsetups = cvodes.CVodeGetNumLinSolvSetups(cvode_mem) netf = cvodes.CVodeGetNumErrTestFails(cvode_mem) nni = cvodes.CVodeGetNumNonlinSolvIters(cvode_mem) ncfn = cvodes.CVodeGetNumNonlinSolvConvFails(cvode_mem) nje = cvodes.CVDenseGetNumJacEvals(cvode_mem) nfeLS = cvodes.CVDenseGetNumRhsEvals(cvode_mem) nge = cvodes.CVodeGetNumGEvals(cvode_mem) print "\nFinal Statistics:" print "nst = %-6i nfe = %-6i nsetups = %-6i nfeLS = %-6i nje = %i" % \ (nst, nfe, nsetups, nfeLS, nje) print "nni = %-6ld ncfn = %-6ld netf = %-6ld nge = %ld\n " % \ (nni, ncfn, netf, nge) if return_last: ylist = N.array(y).copy() T = t.value else: ylist = N.array(ylist) T = N.array(T) if sensi: self._set_sensitivities(N.array(yS)) else: self._set_sensitivities(None) self._set_solution(T, ylist)
else: iright = 1 c1lt = u[1-1 + (jx+ileft)*NUM_SPECIES + (jy)*NSMX] c2lt = u[2-1 + (jx+ileft)*NUM_SPECIES + (jy)*NSMX] c1rt = u[1-1 + (jx+iright)*NUM_SPECIES + (jy)*NSMX] c2rt = u[2-1 + (jx+iright)*NUM_SPECIES + (jy)*NSMX] hord1 = hordco*(c1rt - 1.0*c1 + c1lt) hord2 = hordco*(c2rt - 1.0*c2 + c2lt) horad1 = horaco*(c1rt - c1lt) horad2 = horaco*(c2rt - c2lt) udot[ 1-1 + ( jx)*NUM_SPECIES + ( jy)*NSMX] = vertd1 + hord1 + horad1 + rkin1 udot[ 2-1 + ( jx)*NUM_SPECIES + ( jy)*NSMX] = vertd2 + hord2 + horad2 + rkin2 return 0 t = cvodes.realtype(0) u = cvodes.NVector([0]*NEQ) data = UserData() InitUserData(data) SetInitialProfiles(u, data.dx, data.dy) abstol = cvodes.realtype(ATOL) reltol = RTOL cvode_mem = cvodes.CVodeCreate(cvodes.CV_BDF, cvodes.CV_NEWTON) cvodes.CVodeSetFdata(cvode_mem, ctypes.pointer(data)) cvodes.CVodeMalloc(cvode_mem, f, T0, u, cvodes.CV_SS, reltol, abstol) ml = mu = 2 bpdata = cvodes.CVBandPrecAlloc(cvode_mem, NEQ, mu, ml) cvodes.CVBPSpgmr(cvode_mem, cvodes.PREC_LEFT, 0, bpdata) PrintIntro(mu, ml)
print " dy2/dt = p1*y1 - p2*y2*y3 - p3*(y2)^2" print " dy3/dt = p3*(y2)^2\n" print "Find dG/dp for" print " G = int_t0^tB0 g(t,p,y) dt" print " g(t,p,y) = y3\n\n" data = UserData() data.p[0] = 0.04 data.p[1] = 1.0e4 data.p[2] = 3.0e7 y = cvodes.NVector([1.0, 0.0, 0.0]) q = cvodes.NVector([0.0]) reltolQ = cvodes.realtype(1.0e-6) abstolQ = cvodes.realtype(1.0e-6) print "Create and allocate CVODES memory for forward runs" cvode_mem = cvodes.CVodeCreate(cvodes.CV_BDF, cvodes.CV_NEWTON) cvodes.CVodeMalloc(cvode_mem, f, 0.0, y, cvodes.CV_WF, 0.0, None) cvodes.CVodeSetEwtFn(cvode_mem, ewt, None) cvodes.CVodeSetFdata(cvode_mem, ctypes.pointer(data)) cvodes.CVDense(cvode_mem, 3) cvodes.CVDenseSetJacFn(cvode_mem, Jac, ctypes.pointer(data)) cvodes.CVodeQuadMalloc(cvode_mem, fQ, q) cvodes.CVodeSetQuadFdata(cvode_mem, ctypes.pointer(data)) cvodes.CVodeSetQuadErrCon(cvode_mem, True, cvodes.CV_SS, reltolQ, abstolQ)