stode {rootSolve} | R Documentation |
Estimates the steady-state condition for a system of ordinary differential equations (ODE) written in the form:
dy/dt = f(t,y)
i.e. finds the values of y
for which f(t,y) = 0.
Uses a newton-raphson method, implemented in Fortran 77.
The system of ODE's is written as an R function or defined in compiled code that has been dynamically loaded.
stode(y, time=0, func, parms=NULL, rtol=1e-6, atol=1e-8, ctol=1e-8, jacfunc=NULL, jactype="fullint", verbose=FALSE, bandup=1, banddown=1, positive=FALSE, maxiter=100, ynames=TRUE, dllname=NULL, initfunc=dllname, initpar=parms, rpar=NULL, ipar=NULL, nout=0, outnames = NULL,...)
y |
the initial guess of (state) values for the ode system, a vector. If y has a name attribute, the names will be used to label the output matrix. |
time |
time for which steady-state is wanted; the default is time =0 |
func |
either a user-supplied function that computes the values of the
derivatives in the ode system (the model definition) at time time , or a character string
giving the name of a compiled function in a dynamically loaded
shared library.
If func is a user-supplied function, it must be called as:
yprime = func(t, y, parms, ...) . t is the time point
at which the steady-state is wanted, y is the current estimate of the variables
in the ode system. If the initial values y has a names
attribute, the names will be available inside func . parms is
a vector of parameters (which may have a names attribute).
The return value of func should be a list, whose first element is a
vector containing the derivatives of y with respect to
time , and whose next elements (possibly with a
names attribute) are global values that are required as
output.
If func is a string, then dllname must give the name
of the shared library (without extension) which must be loaded
before stode() is called. see Details for more information. |
parms |
other parameters passed to func and jacfunc |
rtol |
relative error tolerance, either a scalar or a vector, one value for each y |
atol |
absolute error tolerance, either a scalar or a vector, one value for each y |
ctol |
if between two iterations, the maximal change in y is less than this amount, steady-state is assumed to be reached |
jacfunc |
if not NULL , either a user-supplied R function that estimates
the Jacobian of the system of differential equations dydot(i)/dy(j),
or a character string giving the name of a compiled function in a dynamically loaded shared library as provided in
dllname . In some circumstances, supplying
jacfunc can speed up the computations. The R calling sequence for
jacfunc is identical to that of func .
If the Jacobian is a full matrix, jacfunc should return a matrix dydot/dy, where the ith
row contains the derivative of dy_i/dt with respect to y_j,
or a vector containing the matrix elements by columns (the way R and Fortran store matrices).
If the Jacobian is banded, jacfunc should return a matrix containing only the
nonzero bands of the jacobian, (dydot/dy), rotated row-wise. |
jactype |
the structure of the Jacobian, one of "fullint", "fullusr", "bandusr", or "bandint" - either full or banded and estimated internally or by user |
verbose |
if TRUE: full output to the screen, e.g. will output the steady-state settings |
bandup |
number of non-zero bands above the diagonal, in case the Jacobian is banded |
banddown |
number of non-zero bands below the diagonal, in case the jacobian is banded |
positive |
either a logical or a vector with indices of the state variables that have to be non-negative; if TRUE, all state variables y are forced to be non-negative numbers |
maxiter |
maximal number of iterations during one call to the solver |
ynames |
if FALSE: names of state variables are not passed to function func ; this may speed up the simulation especially for multi-D models |
dllname |
a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions referred to in func and jacfunc . |
initfunc |
if not NULL, the name of the initialisation function (which initialises values of parameters), as provided in ‘dllname’. See details. |
initpar |
only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser, to initialise the common blocks (FORTRAN) or global variables (C, C++) |
rpar |
only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by func and jacfunc |
ipar |
only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc |
nout |
only used if ‘dllname’ is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func , present in the shared library. Note:
it is not automatically checked whether this is indeed the number of output variables calculed in the dll - you have to perform this check in the code - see help of daspk or lsoda |
outnames |
only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func , present in the shared library |
... |
additional arguments passed to func and jacfunc allowing this to be a generic function |
The work is done by a Fortran 77 routine that implements the Newton-Raphson method. It uses code from LINPACK.
The form of the Jacobian can be specified by jactype
which can take the following values:
jacfunc
jacfunc
; the size of the bands specified by bandup
and banddown
bandup
and banddown
if jactype
= "fullusr" or "bandusr" then the user must supply a subroutine jacfunc
.
The input parameters rtol
, atol
and ctol
determine the error
control performed by the solver.
The solver will control the vector
e of estimated local errors in y, according to an
inequality of the form max-norm of ( e/ewt )
<= 1, where ewt is a vector of positive error
weights. The values of rtol
and atol
should all be
non-negative.
The form of ewt is:
rtol * abs(y) + atol
where multiplication of two vectors is element-by-element.
In addition, the solver will stop if between two iterations, the maximal change in the values of y is less than ctol
.
Models may be defined in compiled C or Fortran code, as well as in R.
If func
or jacfunc
are a string, then they are assumed to be compiled code.
In this case, dllname
must give the name of the shared library (without extension) which must be loaded before lsode() is called.
If func
is a user-supplied R-function, it must be called as: yprime = func(t, y, parms,...).
t is the time
at which the steady-state should be estimated, y
is the current estimate of the variables in the ode system.
The return value of func
should be a list, whose first element is a vector containing the derivatives of y
with respect to time
,
and whose next elements contains output variables whose values at steady-state are also required .
An example is given below:
model<-function(t,y,pars)
{
with (as.list(c(y,pars)),{
Min = r*OM
oxicmin = Min*(O2/(O2+ks))
anoxicmin = Min*(1-O2/(O2+ks))* SO4/(SO4+ks2
dOM = Flux - oxicmin - anoxicmin
dO2 = -oxicmin -2*rox*HS*(O2/(O2+ks)) + D*(BO2-O2)
dSO4 = -0.5*anoxicmin +rox*HS*(O2/(O2+ks)) + D*(BSO4-SO4)
dHS = 0.5*anoxicmin -rox*HS*(O2/(O2+ks)) + D*(BHS-HS)
list(c(dOM,dO2,dSO4,dHS),SumS=SO4+HS)
})
}
This model can be solved as follows:
pars <- c(D=1,Flux=100,r=0.1,rox =1,
ks=1,ks2=1,BO2=100,BSO4=10000,BHS = 0)
y<-c(OM=1,O2=1,SO4=1,HS=1)
ST <- stode(y=y,func=model,parms=pars,pos=TRUE))
For code written in C, the calling sequence for func
must be as follows:
void anoxmod(int *neq, double *t, double *y, double *ydot,
double *yout, int *ip)
{
double OM, O2, SO4, HS;
double Min, oxicmin, anoxicmin;
if (ip[0] <1) error("nout should be at least 1");
OM = y[0];
O2 = y[1];
SO4 = y[2];
HS = y[3];
Min = r*OM;
oxicmin = Min*(O2/(O2+ks));
anoxicmin = Min*(1-O2/(O2+ks))* SO4/(SO4+ks2);
ydot[0] = Flux - oxicmin - anoxicmin;
ydot[1] = -oxicmin -2*rox*HS*(O2/(O2+ks)) + D*(BO2-O2);
ydot[2] = -0.5*anoxicmin +rox*HS*(O2/(O2+ks)) + D*(BSO4-SO4);
ydot[3] = 0.5*anoxicmin -rox*HS*(O2/(O2+ks)) + D*(BHS-HS);
yout[0] = SO4+HS;
}
where *neq
is the number of equations, *t
is the value
of the independent variable, y
points to a double precision
array of length *neq
that contains the current value of the
state variables, and ydot
points to an array that will contain
the calculated derivatives.
yout
points to a double precision vector whose first nout
values are other output variables (different from the state variables y
),
and the next values are double precision values as passed by parameter rpar
when calling the steady-state solver. The key to the elements of yout
is set in *ip
.
*ip
points to an integer vector whose length is at least 3; the first element contains the number of output values (which should be equal to nout
),
its second element contains the length of *yout
, and the third element contains the length of *ip
;
next are integer values, as passed by parameter ipar
when calling the steady-state solver.
For code written in Fortran, the calling sequence for func
must be as in the following
example:
subroutine model (neq, t, y, ydot, yout, ip)
double precision t, y(4), ydot(4), yout(*)
double precision OM,O2,SO4,HS
double precision min, oxicmin, anoxicmin
integer neq, ip(*)
double precision D, Flux, r, rox, ks, ks2, BO2, BSO4, BHS
common /myparms/D, Flux, r, rox, ks, ks2, BO2, BSO4, BHS
IF (ip(1) < 1) call rexit("nout should be at least 1")
OM = y(1)
O2 = y(2)
SO4 = y(3)
HS = y(4)
Min = r*OM
oxicmin = Min*(O2/(O2+ks))
anoxicmin = Min*(1-O2/(O2+ks))* SO4/(SO4+ks2)
ydot(1) = Flux - oxicmin - anoxicmin
ydot(2) = -oxicmin -2*rox*HS*(O2/(O2+ks)) + D*(BO2-O2)
ydot(3) = -0.5*anoxicmin +rox*HS*(O2/(O2+ks)) + D*(BSO4-SO4
ydot(4) = 0.5*anoxicmin -rox*HS*(O2/(O2+ks)) + D*(BHS-HS)
yout(1) = SO4+HS
return
end
Note that we start by checking whether enough room is allocated for the output variables, else an error is passed to R (rexit
) and the integration is stopped.
In this example, parameters are kept in a common block (called myparms
) in the Fortran code
In order to put parameters in the common block from the calling R code, an initialisation subroutine as specified in initfunc
should be defined. This function has as its sole argument a function steadyparms
that fills a double array with double precision
values. In the example here, the initialisation subroutine is called myinit
:
subroutine myinit(steadyparms)
external steadyparms
double precision parms(9)
common /myparms/parms
call steadyparms(9, parms)
return
end
Here myinit
just calls steadyparms
with the dimension of the parameter vector, and the array parms
that will contain the parameter values.
The corresponding C-code is:
void initanox (void (* steadyparms)(int *, double *))
{
int N = 9;
steadyparms(&N, parms);
}
If it is desired to supply a Jacobian to the solver, then the Jacobian must be defined in compiled code if the ode system is. The C function call for such a function must be as follows:
void myjac(int *neq, double *t, double *y, int *ml,
int *mu, double *pd, int *nrowpd, double *yout, int *ip)
The corresponding subroutine call in Fortran is:
subroutine myjac (neq, t, y, ml, mu, pd, nrowpd, yout, ip)
integer neq, ml, mu, nrowpd, ip(*)
double precision y(*), pd(nrowpd,*), yout(*)
To run the model using e.g. the Fortran code, the code in anoxmod.f must first be compiled.
This can be done in R itself:
system("R CMD SHLIB anoxmod.f")
which will create file anoxmod.dll
After loading the DLL, the model can be solved:
dyn.load("anoxmod.dll")
ST2 <- stode(y=y,func="model",parms=pars,)
dllname="anoxmod",initfunc="myinit",pos=TRUE,nout=1)
Examples in both C and Fortran are in the ‘dynload’ subdirectory of
the rootSolve
package directory.
A list containing
y |
A vector with the state variable values from the last iteration during estimation of steady-state condition of the system of equations.
If y has a names attribute, it will be used to label the output values. |
... |
the number of "global" values returned |
The output will have the attribute steady
, which returns TRUE, if steady-state has been reached and the attribute
precis
with an estimate of the precision attained during each iteration, the mean absolute rate of change (sum(abs(dy))/n).
The implementation of stode
and substantial parts of the help file is similar to the implementation of the integration routines (e.g. lsode
) from package deSolve.
Karline Soetaert <k.soetaert@nioo.knaw.nl>
For a description of the Newton-Raphson method, e.g.
Press, WH, Teukolsky, SA, Vetterling, WT, Flannery, BP, 1996. Numerical Recipes in FORTRAN. The Art of Scientific computing. 2nd edition. Cambridge University Press.
The algorithm uses LINPACK code:
Dongarra, J.J., J.R. Bunch, C.B. Moler and G.W. Stewart, 1979. LINPACK user's guide, SIAM, Philadelphia.
stodes
, for steady-state estimation using the Newton-Raphson method, when the jacobian matrix is sparse.
runsteady
, for steady-state estimation by dynamically running till the derivatives become 0.
steady.band
, for steady-state estimation, when the jacobian matrix is banded, and where the state variables need NOT to be rearranged
steady.1D
, for steady-state estimation, when the jacobian matrix is banded, and where the state variables need to be rearranged
##################################################### # Example 1. A simple sediment biogeochemical model ##################################################### model<-function(t,y,pars) { with (as.list(c(y,pars)),{ Min = r*OM oxicmin = Min*(O2/(O2+ks)) anoxicmin = Min*(1-O2/(O2+ks))* SO4/(SO4+ks2) dOM = Flux - oxicmin - anoxicmin dO2 = -oxicmin -2*rox*HS*(O2/(O2+ks)) + D*(BO2-O2) dSO4 = -0.5*anoxicmin +rox*HS*(O2/(O2+ks)) + D*(BSO4-SO4) dHS = 0.5*anoxicmin -rox*HS*(O2/(O2+ks)) + D*(BHS-HS) list(c(dOM,dO2,dSO4,dHS),SumS=SO4+HS) }) } # parameter values pars <- c(D=1,Flux=100,r=0.1,rox =1, ks=1,ks2=1,BO2=100,BSO4=10000,BHS = 0) # initial conditions y<-c(OM=1,O2=1,SO4=1,HS=1) # direct iteration - enforces positivitiy.. ST <- stode(y=y,func=model,parms=pars,pos=TRUE) ST ##################################################### # Example 2. 1000 simultaneous equations ##################################################### model <- function (time,OC,parms,decay,ing) { # model describing organic Carbon (C) in a sediment, # Upper boundary = imposed flux, lower boundary = zero-gradient Flux <- v * c(OC[1] ,OC) + # advection -Kz*diff(c(OC[1],OC,OC[N]))/dx # diffusion; Flux[1]<- flux # imposed flux # Rate of change= Flux gradient and first-order consumption dOC <- -diff(Flux)/dx - decay*OC # Fraction of OC in first 5 layers is translocated to mean depth dOC[1:5] <- dOC[1:5] - ing*OC[1:5] dOC[N/2] <- dOC[N/2] + ing*sum(OC[1:5]) list(dOC) } v <- 0.1 # cm/yr flux <- 10 dx <- 0.01 N <- 1000 dist <- seq(dx/2,by=dx,len=N) Kz <- 1 #bioturbation (diffusion), cm2/yr print( system.time( ss <- stode(runif(N),func=model,parms=NULL,positive=TRUE, decay=5,ing=20))) plot(ss$y[1:N],dist,ylim=rev(range(dist)),type="l",lwd=2, xlab="Nonlocal exchange",ylab="sediment depth",main="stode, full jacobian")