def run(self, f, jac, y0, t0, t1, f_params, jac_params):
     if self.first_step:
         # copy initial state from input ndarray y0 to our nvector y
         self.y[:] = y0[:]
         # reinitialize cvode, now that we have func and t0, and actual values for y0
         _cvode.CVodeReInit(self.cvode_mem, cvode_rhs_func, t0, self.y, _cvode.CV_SS, self.rtol, self.atol)
         # tell cvode about our rhs function's user data
         f_data = ctypes.cast(ctypes.pointer(ctypes.py_object((f, f_params))), ctypes.c_void_p)
         _cvode.CVodeSetFdata(self.cvode_mem, f_data)
     tret = _cvode.realtype()
     flag = _cvode.CVode(self.cvode_mem, t1, self.y, tret, _cvode.CV_NORMAL)
     if flag < 0:
         self.success = 0
         print("cvodes error: %d (see SUNDIALS manual for more information)" % flag)
     return (self.y, t1)
Esempio n. 2
0
 def run(self, f, jac, y0, t0, t1, f_params, jac_params):
     if self.first_step:
         # copy initial state from input ndarray y0 to our nvector y
         self.y[:] = y0[:]
         # reinitialize cvode, now that we have func and t0, and actual values for y0
         _cvode.CVodeReInit(self.cvode_mem, cvode_rhs_func, t0, self.y,
                            _cvode.CV_SS, self.rtol, self.atol)
         # tell cvode about our rhs function's user data
         f_data = ctypes.cast(
             ctypes.pointer(ctypes.py_object((f, f_params))),
             ctypes.c_void_p)
         _cvode.CVodeSetFdata(self.cvode_mem, f_data)
     tret = _cvode.realtype()
     flag = _cvode.CVode(self.cvode_mem, t1, self.y, tret, _cvode.CV_NORMAL)
     if flag < 0:
         self.success = 0
         print "cvodes error: %d (see SUNDIALS manual for more information)" % flag
     return (self.y, t1)
Esempio n. 3
0
 def __init__(self, f_ode, t, y, reltol=1e-8, abstol=1e-8, nrtfn=None, 
     g_rtfn=None, f_data=None, g_data=None, chunksize=2000, maxsteps=1e4, 
     mupper=None, mlower=None):
     # Ensure that t and y can be indexed
     t = np.array(t, dtype=float, ndmin=1)
     try:
         y = np.array(y, dtype=float, ndmin=1)
     except ValueError:
         raise ValueError("State vector y not interpretable as float: %s" % y)
     # Ensure that f_ode assigns a value to all elements of the rate vector
     assert_assigns_all(f_ode, y, f_data)
     # Ensure that the function returns 0 on success and <0 on exception. 
     # (CVODE's convention is 
     # 0 = OK, >0 = recoverable error, <0 = unrecoverable error.)
     # If not, decorate as if with @cvodefun.
     self.f_ode = f_ode # store this for use in __repr__ etc.
     success_value = f_ode(t[0], nv(y), nv(y), f_data) # probably 0 or None
     try:
         error_value = f_ode(None, None, None, None) # <0 or raise exception
     except StandardError:
         error_value = None
         try:
             f_ode.traceback = ""
         except AttributeError:
             pass
     if (success_value == 0) and (error_value < 0):
         self.my_f_ode = f_ode
     else:
         self.my_f_ode = cvodefun(f_ode)
     # Variables y, tret, abstol are written by CVode functions, and their 
     # pointers must remain constant. They are assigned here; later 
     # assignments will copy values into the existing variables, like so:
     # self.tret.value = ...             (cvode.realtype)
     # self.y[:] = ...                   (cvode.NVector)
     self.y = nv(y)  # state vector (read/write)
     self.tret = cvode.realtype(0.0)  # actual time of return from solver
     if type(abstol) is cvode.realtype:
         self.abstol = abstol  # copy of abstol, used for ReInit
     elif np.isscalar(abstol):
         self.abstol = cvode.realtype(abstol)
     else:
         self.abstol = nv(abstol)
     self.t = t
     self.t0 = cvode.realtype(t[0]) # initial time
     self.tstop = t[-1] # end time
     self.n = len(y) # number of state variables
     self.reltol = reltol # copy of reltol, used for ReInit
     self.itol = cvode.CV_SV if (type(self.abstol) is nv) else cvode.CV_SS
     self.f_data = f_data # user data for right-hand-side of ODE
     self.g_data = g_data # user data for rootfinding function
     self.chunksize = chunksize
     self.maxsteps = maxsteps
     self.last_flag = None
     # CVODE solver object
     self.cvode_mem = cvode.CVodeCreate(cvode.CV_BDF, cvode.CV_NEWTON)
     cvode.CVodeMalloc(self.cvode_mem, self.my_f_ode, self.t0, self.y, 
         self.itol, self.reltol, self.abstol) # allocate & initialize memory
     if f_data is not None:
         cvode.CVodeSetFdata(self.cvode_mem, 
             np.ctypeslib.as_ctypes(self.f_data))
     cvode.CVodeSetStopTime(self.cvode_mem, self.tstop) # set stop time
     # Specify how the Jacobian should be approximated
     if mupper is None:
         cvode.CVDense(self.cvode_mem, self.n)
     else:
         cvode.CVBand(self.cvode_mem, self.n, mupper, mlower)        
     self.RootInit(nrtfn, g_rtfn, g_data)
Esempio n. 4
0
def annlodesolve(model, tfinal, envlist, params, useparams=None, tinit = 0.0, ic=True):
    '''
    the ODE equation solver tailored to work with the annealing algorithm
    model: the model object
    envlist: the list returned from annlinit
    params: the list of parameters that are being optimized with annealing 
    useparams: the parameter number to which params[i] corresponds
    tinit: initial time
    reltol: relative tolerance
    abstol: absolute tolerance
    ic: reinitialize initial conditions to a value in params or useparams
    '''
    (f, rhs_exprs, y, odesize, data, xout, yout, nsteps, cvode_mem, yzero, reltol, abstol) = envlist

    #set the initial values and params in each run
    #all parameters are used in annealing. initial conditions are not, here
    if useparams is None:
        for i in range(len(params)):
            data.p[i] = params[i]
    else:
        #only a subset of parameters are used for annealing
        for i in range(len(useparams)):
            #print("changing parameter", model.parameters[useparams[i]],"data.p", data.p[useparams[i]],"to", params[i])
            data.p[useparams[i]] = params[i]

    # update yzero if initial conditions are being modified as part of the parameters
    # did it this way b/c yzero and data.p may not always want to be modified at the same time
    #
    if ic is True:
        for cplxptrn, ic_param in model.initial_conditions:
            speci = model.get_species_index(cplxptrn)
            yzero[speci] = ic_param.value
            
    #reset initial concentrations
    y = cvode.NVector(yzero)

    # Reinitialize the memory allocations, DOES NOT REALLOCATE
    cvode.CVodeReInit(cvode_mem, f, 0.0, y, cvode.CV_SS, reltol, abstol)
    
    tadd = tfinal/nsteps

    t = cvode.realtype(tinit)
    tout = tinit + tadd

    for step in range(1, nsteps):
        ret = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
        if ret !=0:
            print("CVODE ERROR %i"%(ret))
            break

        xout[step]= tout
        for i in range(0, odesize):
            yout[step][i] = y[i]

        # increase the time counter
        tout += tadd
    #print("Integration finished")

    #now deal with observables
    obs_names = [name for name, rp in model.observable_patterns]
    yobs = numpy.zeros([len(obs_names), nsteps])
    
    #sum up the correct entities
    for i, name in enumerate(obs_names):
        factors, species = zip(*model.observable_groups[name])
        yobs[i] = (yout[:, species] * factors).sum(axis = 1)

    #merge the x and y arrays for easy visualization
    xyobs = numpy.vstack((xout, yobs))

    return (xyobs,xout,yout, yobs)
Esempio n. 5
0
c = cvode.NVector([0]*NEQ)
rewt = cvode.NVector([0]*NEQ)
wdata = WebData()
for i in range(NGRP):
	wdata.P[i] = cvode.denalloc(NS,NS)
	wdata.pivot[i] = cvode.denallocpiv(NS)
wdata.rewt = rewt.data
InitUserData(wdata)
ns = wdata.ns
mxns = wdata.mxns

PrintIntro()

for jpre in range(cvode.PREC_LEFT, cvode.PREC_RIGHT+1):
	for gstype in range(cvode.MODIFIED_GS,cvode.CLASSICAL_GS+1):
		t = cvode.realtype(T0)
		CInit(c, wdata)
		PrintHeader(jpre, gstype)
		
		firstrun = (jpre == cvode.PREC_LEFT and gstype == cvode.MODIFIED_GS)
		if firstrun:
			cvode_mem = cvode.CVodeCreate(cvode.CV_BDF, cvode.CV_NEWTON)
			wdata.cvode_mem = cvode_mem.obj
			cvode.CVodeSetFdata(cvode_mem, ctypes.pointer(wdata))
			cvode.CVodeMalloc(cvode_mem, f, t.value, c, cvode.CV_SS, RTOL, ATOL)
			cvode.CVSpgmr(cvode_mem, jpre, MAXL)
			cvode.CVSpilsSetGSType(cvode_mem, gstype)
			cvode.CVSpilsSetDelt(cvode_mem, DELT)
			cvode.CVSpilsSetPreconditioner(cvode_mem, Precond, PSolve, ctypes.pointer(wdata))
		
			PrintAllSpecies(c, ns, mxns, t)
Esempio n. 6
0
def odesolve(model,
             tfinal,
             envlist,
             params,
             useparams=None,
             tinit=0.0,
             ic=True):
    '''
    the ODE equation solver tailored to work with the annealing algorithm
    model: the model object
    envlist: the list returned from annlinit
    params: the list of parameters that are being optimized with annealing 
    useparams: the parameter number to which params[i] corresponds
    tinit: initial time
    reltol: relative tolerance
    abstol: absolute tolerance
    ic: reinitialize initial conditions to a value in params or useparams
    '''
    (f, rhs_exprs, y, odesize, data, xout, yout, nsteps, cvode_mem, yzero,
     reltol, abstol) = envlist

    #set the initial values and params in each run
    #all parameters are used in annealing. initial conditions are not, here
    if useparams is None:
        for i in range(len(params)):
            data.p[i] = params[i]
    else:
        #only a subset of parameters are used for annealing
        for i in range(len(useparams)):
            #print "changing parameter", model.parameters[useparams[i]],"data.p", data.p[useparams[i]],"to", params[i]
            data.p[useparams[i]] = params[i]

    # FIXME:
    # update yzero if initial conditions are being modified as part of the parameters
    # did it this way b/c yzero and data.p may not always be modified at the same time
    # the params list should NOT contain the initial conditions if they are not
    # to be used in the annealing... so this is a hack based on the fact that the
    # initial conditions are contained as part of the model.parameters list.
    #
    if ic is True:
        for cplxptrn, ic_param in model.initial_conditions:
            speci = model.get_species_index(cplxptrn)
            yzero[speci] = ic_param.value

    #reset initial concentrations
    y = cvode.NVector(yzero)

    # Reinitialize the memory allocations, DOES NOT REALLOCATE
    cvode.CVodeReInit(cvode_mem, f, 0.0, y, cvode.CV_SS, reltol, abstol)

    tadd = tfinal / nsteps

    t = cvode.realtype(tinit)
    tout = tinit + tadd

    #print "Beginning integration"
    #print "TINIT:", tinit, "TFINAL:", tfinal, "TADD:", tadd, "ODESIZE:", odesize
    #print "Integrating Parameters:\n", params
    #print "y0:", yzero

    for step in range(1, nsteps):
        ret = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
        if ret != 0:
            print "CVODE ERROR %i" % (ret)
            break

        xout[step] = tout
        for i in range(0, odesize):
            yout[step][i] = y[i]

        # increase the time counter
        tout += tadd
    #print "Integration finished"

    #now deal with observables
    #obs_names = [name for name, rp in model.observable_patterns]
    yobs = numpy.zeros([len(model.observables), nsteps])

    #sum up the correct entities
    for i, obs in enumerate(model.observables):
        coeffs = obs.coefficients
        specs = obs.species
        yobs[i] = (yout[:, specs] * coeffs).sum(1)

    #merge the x and y arrays for easy analysis
    xyobs = numpy.vstack((xout, yobs))

    return (xyobs, xout, yout, yobs)
Esempio n. 7
0
def Problem2():
	nerr = 0
	reltol = cvode.realtype(0)
	abstol = cvode.realtype(1.0e-6)
	t = cvode.realtype(0)

	print "\n\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 "
	
	cvode_mem = cvode.CVodeCreate(cvode.CV_ADAMS, cvode.CV_FUNCTIONAL)
	
	for miter in ["FUNC", "DIAG", "BAND_USER", "BAND_DQ"]:
		ero = 0
		y = cvode.NVector([0]*P2_NEQ)
		y[0] = 1.0
		
		if miter == "FUNC":
			cvode.CVodeMalloc(cvode_mem, f2, P2_T0, y, cvode.CV_SS, reltol, abstol)
		else:
			cvode.CVodeSetIterType(cvode_mem, cvode.CV_NEWTON)
			cvode.CVodeReInit(cvode_mem, f2, P2_T0, y, cvode.CV_SS, reltol, abstol)
		
		PrepareNextRun(cvode_mem, cvode.CV_ADAMS, miter, P2_MU, P2_ML)
		
		print "\n      t        max.err      qu     hu "
		
		iout = 1
		tout = P2_T1
		while iout <= 5:
			flag = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
			erm = MaxError(y, t)
			qu = cvode.CVodeGetLastOrder(cvode_mem)
			hu = cvode.CVodeGetLastStep(cvode_mem)
			print "%10.3F  %12.4e   %2i   %12.4e"%(t.value, erm, qu, hu)
			if flag != cvode.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 = cvode.CVodeCreate(cvode.CV_BDF, cvode.CV_FUNCTIONAL)
	
	for miter in ["FUNC", "DIAG", "BAND_USER", "BAND_DQ"]:
		ero = 0
		y[0] = 1.0
		
		if miter == "FUNC":
			cvode.CVodeMalloc(cvode_mem, f2, P2_T0, y, cvode.CV_SS, reltol, abstol)
		else:
			cvode.CVodeSetIterType(cvode_mem, cvode.CV_NEWTON)
			cvode.CVodeReInit(cvode_mem, f2, P2_T0, y, cvode.CV_SS, reltol, abstol)
		
		PrepareNextRun(cvode_mem, cvode.CV_BDF, miter, P2_MU, P2_ML)
		
		print "\n      t        max.err      qu     hu "
		
		iout = 1
		tout = P2_T1
		while iout <= 5:
			flag = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
			erm = MaxError(y, t)
			qu = cvode.CVodeGetLastOrder(cvode_mem)
			hu = cvode.CVodeGetLastStep(cvode_mem)
			print "%10.3F  %12.4e   %2i   %12.4e"%(t.value, erm, qu, hu)
			if flag != cvode.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
Esempio n. 8
0
def Problem1():
	nerr = 0
	reltol = cvode.realtype(0)
	abstol = cvode.realtype(1.0e-6)
	t = cvode.realtype(0)

	y = cvode.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 = cvode.CVodeCreate(cvode.CV_ADAMS, cvode.CV_FUNCTIONAL)
	
	for miter in ["FUNC", "DENSE_USER", "DENSE_DQ", "DIAG"]:
		ero = 0
		y[0] = 2.0
		y[1] = 0
	
		if miter == "FUNC": 
			cvode.CVodeMalloc(cvode_mem, f1, 0, y, cvode.CV_SS, reltol, abstol)
		else:
			cvode.CVodeSetIterType(cvode_mem, cvode.CV_NEWTON)
			cvode.CVodeReInit(cvode_mem, f1, 0, y, cvode.CV_SS, reltol, abstol)
		
		PrepareNextRun(cvode_mem, cvode.CV_ADAMS, miter, 0, 0)
	
		print "\n     t           x              xdot         qu     hu "
	
		iout = 1
		tout = P1_T1
		while iout <= 4:
			flag = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
			qu = cvode.CVodeGetLastOrder(cvode_mem)
			hu = cvode.CVodeGetLastStep(cvode_mem)
			print "%10.6g  %14.5e %14.5e   %2i    %6.4e"%(t.value, y[0], y[1], qu, hu)
			if flag != cvode.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 = cvode.CVodeCreate(cvode.CV_BDF, cvode.CV_FUNCTIONAL)
	
	for miter in ["FUNC", "DENSE_USER", "DENSE_DQ", "DIAG"]:
		ero = 0
		y[0] = 2.0
		y[1] = 0
	
		if miter == "FUNC": 
			cvode.CVodeMalloc(cvode_mem, f1, 0, y, cvode.CV_SS, reltol, abstol)
		else:
			cvode.CVodeSetIterType(cvode_mem, cvode.CV_NEWTON)
			cvode.CVodeReInit(cvode_mem, f1, 0, y, cvode.CV_SS, reltol, abstol)
			
		PrepareNextRun(cvode_mem, cvode.CV_BDF, miter, 0, 0)
		
		print "\n     t           x              xdot         qu     hu "
			
		iout = 1
		tout = P1_T1
		while iout <= 4:
			flag = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
			qu = cvode.CVodeGetLastOrder(cvode_mem)
			hu = cvode.CVodeGetLastStep(cvode_mem)
			print "%10.6g  %14.5e %14.5e   %2i    %6.4e"%(t.value, y[0], y[1], qu, hu)
			if flag != cvode.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
Esempio n. 9
0
def annlodesolve(model, tfinal, envlist, params, tinit = 0.0, ic=True):
    '''
    the ODE equation solver tailored to work with the annealing algorithm
    model: the model object
    envlist: the list returned from annlinit
    params: the list of parameters that are being optimized with annealing 
    tinit: initial time
    reltol: relative tolerance
    abstol: absolute tolerance
    ic: reinitialize initial conditions to a value in params 
    '''
    (f, rhs_exprs, y, odesize, data, xout, yout, nsteps, cvode_mem, yzero, reltol, abstol) = envlist

    #set the initial values and params in each run
    #all parameters are used in annealing. 
    for i in range(len(params)):
        data.p[i] = params[i]
        
    # update yzero if initial conditions are being modified as part of the parameters
    # did it this way b/c yzero and data.p may not always want to be modified at the same time
    # FIXME: this is not the best way to do this.
    # the params list should NOT contain the initial conditions if they are not
    # to be used in the annealing... so this is a hack based on the fact that the
    # initial conditions are contained as part of the model.parameters list.
    # FIXME
    #
    if ic is True:
        for cplxptrn, ic_param in model.initial_conditions:
            speci = model.get_species_index(cplxptrn)
            yzero[speci] = ic_param.value
            
    #reset initial concentrations
    y = cvode.NVector(yzero)

    # Reinitialize the memory allocations, DOES NOT REALLOCATE
    cvode.CVodeReInit(cvode_mem, f, 0.0, y, cvode.CV_SS, reltol, abstol)
    
    tadd = tfinal/nsteps

    t = cvode.realtype(tinit)
    tout = tinit + tadd
    
    #print "Beginning integration"
    #print "TINIT:", tinit, "TFINAL:", tfinal, "TADD:", tadd, "ODESIZE:", odesize
    #print "Integrating Parameters:\n", params
    #print "y0:", yzero

    for step in range(1, nsteps):
        ret = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
        if ret !=0:
            print "CVODE ERROR %i"%(ret)
            break

        xout[step]= tout
        for i in range(0, odesize):
            yout[step][i] = y[i]

        # increase the time counter
        tout += tadd
    #print "Integration finished"

    #now deal with observables
    yobs = numpy.zeros([len(model.observables), nsteps])
    
    #sum up the correct entities
    for i, obs in enumerate(model.observables):
        coeffs = obs.coefficients
        specs  = obs.species
        yobs[i] = (yout[:, specs] * coeffs).sum(1)

    #merge the x and y arrays for easy analysis
    xyobs = numpy.vstack((xout, yobs))

    return (xyobs,xout,yout, yobs)
Esempio n. 10
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):
			cvode.denGETRS(data.P[jx][jy], NUM_SPECIES, data.pivot[jx][jy], z.ptrto(jx*NUM_SPECIES + jy*NSMX))

	return 0

u = cvode.NVector([0.0]*(NEQ))

#Allocate and initialise user data
t = cvode.realtype(0)
data = UserData()
for jx in range(MX):
	for jy in range(MY):
		data.P[jx][jy] = cvode.denalloc(NUM_SPECIES, NUM_SPECIES)
		data.Jbd[jx][jy] = cvode.denalloc(NUM_SPECIES, NUM_SPECIES)
		data.pivot[jx][jy] = cvode.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)
Esempio n. 11
0
data.vdcoef = 1.0/(data.dy**2)

cvode_mem = cvode.CVodeCreate(cvode.CV_BDF, cvode.CV_NEWTON);
cvode.CVodeMalloc(cvode_mem, f, 0.0, u, cvode.CV_SS, reltol, abstol)
cvode.CVodeSetFdata(cvode_mem, ctypes.pointer(data));
cvode.CVBand(cvode_mem, 50, 5, 5);
cvode.CVBandSetJacFn(cvode_mem, Jac, ctypes.pointer(data));

umax = max(abs(u))
print "\n2-D Advection-Diffusion Equation"
print "Mesh dimensions = %d X %d"%(10,5)
print "Total system size = %d"%(50)
print "Tolerance parameters: reltol = %lg   abstol = %lg\n"%(reltol, abstol)
print "At t = %lg      max.norm(u) =%14.6le"%(0.0, umax)

t = cvode.realtype(0)
iout = 1
tout = 0.1
while iout <= 10:
	cvode.CVode(cvode_mem, tout, u, ctypes.byref(t), cvode.CV_NORMAL)
	umax = max(abs(u))
	nst = cvode.CVodeGetNumSteps(cvode_mem)
  	print "At t = %4.2f   max.norm(u) =%14.6le   nst = %4ld"%(t.value, umax, nst)
	iout +=1
	tout += 0.1

nst = cvode.CVodeGetNumSteps(cvode_mem)
nfe = cvode.CVodeGetNumRhsEvals(cvode_mem)
nsetups = cvode.CVodeGetNumLinSolvSetups(cvode_mem)
netf = cvode.CVodeGetNumErrTestFails(cvode_mem)
nni = cvode.CVodeGetNumNonlinSolvIters(cvode_mem)
Esempio n. 12
0
	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 = cvode.NVector([1.0, 0.0, 0.0])
abstol = cvode.NVector([1.0e-8, 1.0e-14, 1.0e-6])
reltol = cvode.realtype(1.0e-4)

cvode_mem = cvode.CVodeCreate(cvode.CV_BDF, cvode.CV_NEWTON)
cvode.CVodeMalloc(cvode_mem, f, 0.0, y, cvode.CV_SV, reltol, abstol)
cvode.CVodeRootInit(cvode_mem, 2, g, None)
cvode.CVDense(cvode_mem, 3)
cvode.CVDenseSetJacFn(cvode_mem, Jac, None)

print " \n3-species kinetics problem\n"

iout = 0
tout = 0.4
t = cvode.realtype(0.0)

while True:
	flag = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
Esempio n. 13
0
			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 = cvode.realtype(0)
u = cvode.NVector([0]*NEQ)
data = UserData()
InitUserData(data)
SetInitialProfiles(u, data.dx, data.dy)
abstol = cvode.realtype(ATOL)
reltol = RTOL

cvode_mem = cvode.CVodeCreate(cvode.CV_BDF, cvode.CV_NEWTON)
cvode.CVodeSetFdata(cvode_mem, ctypes.pointer(data))
cvode.CVodeMalloc(cvode_mem, f, T0, u, cvode.CV_SS, reltol, abstol)
ml = mu = 2
bpdata = cvode.CVBandPrecAlloc(cvode_mem, NEQ, mu, ml)
cvode.CVBPSpgmr(cvode_mem, cvode.PREC_LEFT, 0, bpdata)
PrintIntro(mu, ml)