daspk: General solver for differential algebraic equations (DAE)
Description
Solves either:
- a system of ordinary differential equations (ODE) of the form $$y'=f(t,y,...)$$
- a system of differential algebraic equations (DAE) of the form $$F(t,y,y')=0$$
using a combination of backward differentiation formula (BDF) and a direct linear system solution method (dense or banded).
The Rfunction
daspk
provides an interface to the
Fortran DAE solver of the same name, written by Linda R. Petzold, Peter N. Brown, Alan C. Hindmarsh and Clement W. Ulrich.
The system of DE's is written as an Rfunction (which may, of course, use .C
, .Fortran
,
.Call
, etc., to call foreign code) or be defined in
compiled code that has been dynamically loaded.
daspk(y, times, func=NULL, parms, dy=NULL, res=NULL, nalg=0,
rtol=1e-6, atol=1e-8, jacfunc=NULL, jacres=NULL,
jactype="fullint", estini = NULL, verbose=FALSE,
tcrit=NULL, hmin=0, hmax=NULL, hini = 0, ynames =TRUE, maxord = 5,
bandup=NULL, banddown=NULL, maxsteps = 5000,
dllname=NULL, initfunc=dllname, initpar=parms,
rpar=NULL, ipar=NULL, nout= 0, outnames=NULL,
...)
- y
{the initial (state) values for the DE system. If y
has a name attribute, the names will be used to label the output matrix.}
- times
{time sequence for which output is wanted; the first value of times
must be the initial time; if only one step is to be taken; set times = NULL}
- func
{cannot be used if the model is a DAE system. If an ODE system, func
should be an R-function that computes the values of the
derivatives in the ODE system (the model definition) at time t.
func
must be defined as:
yprime = func(t, y, parms,...)
.
t
is the current time point
in the integration, 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
, unless ynames
is FALSE. parms
is
a vector or list of parameters. ... (optional) are any other arguments passed to the function.
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 are global values that are required at
each point in times
.
Note that it is not possible to define func
as a compiled function in a dynamically loaded
shared library. Use res
instead.}
- parms
{vector or list of parameters used in func
, jacfunc
, or res
}
- dy
{the initial derivatives of the state variables of the DE system. Ignored if an ODE.}
- res
{if a DAE system: either an R-function that computes the residual function F(t,y,y') of the DAE system (the model defininition) at time t,
or a character string giving the name of a compiled function in a dynamically loaded shared library.
If res
is a user-supplied R-function, it must be called as: F = func(t, y, dy, parms, ...).
Here t
is the current time point in the integration, y
is the current estimate of the variables in the ODE system, dy
are the corresponding rates of change.
If the initial y
or dy
have a names attribute, the names will be available inside func
, unless ynames
is FALSE.
parms
is a vector of parameters.
The return value of res
should be a list, whose first element is a vector containing the residuals of the DAE system, i.e. delta=F(t,y,y'),
and whose next elements contain output variables that are required at each point in times
.
If res
is a string, then dllname
must give the name
of the shared library (without extension) which must be loaded
before daspk()
is called. see package vignette for more information.
}
- nalg
{if a DAE system: the number of algebraic equations (equations not involving derivatives).
Algebraic equations should always be the last, i.e. preceeded by the differential equations.
Only used if estini
= 1}
- 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}
- jacfunc
{if not NULL
, an Rfunction that computes the jacobian of the system of differential equations. Only used in case the system is an ODE (y'=f(t,y)), specified by func
.
The Rcalling 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 Rand Fortran store matrices).
If the jacobian is banded, jacfunc
should return a matrix containing only the
nonzero bands of the jacobian, rotated row-wise. See first example of lsode.}
- jacres
{ jacres
and not jacfunc
should be used if the system is specified by the residual function F(t,y,y'), i.e. jacres
is used in
conjunction with res
.
If jacres
is an R-function, the calling sequence for jacres
is identical to that of res
, but with extra parameter cj
.
thus it should be called as: jacres = func(t, y, dy, parms, cj, ...).
Here t
is the current time point in the integration, y
is the current estimate of the variables in the ODE system, y'} are the corresponding rates of change and
code{cj} is a scalar, which is normally proportional to the inverse of the stepsize.
If the initial y or dy have a names attribute, the names will be available inside jacres, unless code{ynames} is FALSE.
code{parms} is a vector of parameters (which may have a names attribute).
cr If the jacobian is a full matrix, code{jacres} should
return the matrix dG/dy + cj*dG/dyprime, where the ith
row is the sum of the derivatives of eqn{G_i} with respect to eqn{y_j} and the scaled derivatives of eqn{G_i} with respect to eqn{dy_j}.
cr if the jacobian is banded, code{jacres} should return only the nonzero bands of the jacobian, rotated rowwise.
See details for the calling sequence when code{jacres} is a string.
}
item{jactype }{the structure of the jacobian, one of "fullint", "fullusr", "bandusr" or "bandint" - either full or banded and estimated internally or by the user}
item{estini }{only if a DAE system, and if initial values of code{y} and code{dy }are not consistent (i.e. F(t,y,dy) is not=0),
setting code{estini}=1 or 2, will solve for them.
If code{estini} = 1: dy and the algebraic variables are estimated from code{y}; in this case, the number of algebraic equations must be given (code{nalg}).
If code{estini} = 2: code{y} will be estimated from code{dy}. }
item{verbose }{if TRUE: full output to the screen, e.g. will output the settings of vector *istate* and *rstate* - see details}
item{tcrit }{the Fortran routine code{daspk} overshoots its targets (times points in the vector code{times}), and interpolates values
for the desired time points. If there is a time beyond which integration should not proceed (perhaps because of a singularity),
that should be provided in code{tcrit}.}
item{hmin }{an optional minimum value of the integration stepsize. In special situations this parameter may speed up computations with the cost of precision. Don't use hmin
if you don't know why!}
item{hmax }{an optional maximum value of the integration stepsize. If not specified, code{hmax} is set to the largest difference in code{times}, to avoid that the simulation possibly ignores short-term events. If 0, no maximal size is specified}
item{hini }{initial step size to be attempted; if 0, the initial step size is determined by the solver}
item{ynames }{if FALSE: names of state variables are not passed to function code{func} ; this may speed up the simulation especially for large models}
item{maxord }{the maximum order to be allowed. Reduce code{maxord} to save storage space (<=5) 500="" }="" item{bandup="" }{number="" of="" non-zero="" bands="" above="" the="" diagonal,="" in="" case="" jacobian="" is="" banded="" (and="" code{jactype}="" one="" "bandint","bandusr")}="" item{banddown="" below="" item{maxsteps="" }{maximal="" number="" steps="" during="" call="" to="" solver;="" will="" be="" recalculated="" at="" least="" and="" a="" multiple 500;="" solver="" give="" warning="" if="" more="" than="" are="" taken,="" but="" it="" continue="" till="" code{maxsteps}="" steps}="" item{dllname="" }{a="" string="" giving="" name="" shared="" library="" (without="" extension)="" that="" contains="" all="" compiled="" function="" or="" subroutine="" definitions="" referred="" code{func}="" code{res}="" code{jacfunc}.="" see="" package="" vignette}="" item{initfunc="" }{if="" not="" null,="" initialisation="" (which="" initialises="" values="" parameters),="" as="" provided="" file{dllname}.="" vignette.}="" item{initpar="" }{only="" when="" file{dllname}="" specified="" an="" code{initfunc}="" dll:="" parameters="" passed="" initialiser,="" initialise="" common="" blocks="" (fortran)="" global="" variables="" (c,="" c++)}="" item{rpar="" specified:="" vector="" with="" double="" precision="" dll-functions="" whose="" names="" by="" code{jacfunc}}="" item{ipar="" integer="" item{nout="" used="" model="" defined="" code:="" output="" calculated="" code{func},="" present="" library.="" note:="" automatically="" checked whether="" this="" indeed="" calculed="" dll="" -="" you="" have="" perform="" check="" code="" item{outnames="" code{nout}=""> 0: the names of output variables calculated in the compiled function code{func}, present in the shared library}
item{... }{additional arguments passed to code{func}, code{jacfunc}, code{res} and code{jacres}, allowing this to be a generic function}
}
A matrix with up to as many rows as elements in times and as many columns as elements in y
plus the number of "global" values returned
in the next elements of the return from func
or res
, plus an additional column (the first) for the time value.
There will be one row for each element in times
unless the Fortran routine `daspk' returns with an unrecoverable error.
If y
has a names attribute, it will be used to label the columns of the output value.
The output will have the attributes istate
, and rstate
, two vectors with several useful elements.
See details.
The first element of istate returns the conditions under which the last call to lsoda returned. Normal is istate[1] = 2
.
If verbose
= TRUE, the settings of istate and rstate will be written to the screen
author{Karline Soetaert }
examples{
#------------------------------------------------------
# Coupled chemical reactions including an equilibrium
# modeled as (1) an ODE and (2) as a DAE
#
# The model describes three chemical species A,B,D:
# subjected to equilibrium reaction D <-> A + B
# D is produced at a constant rate, prod
# B is consumed at 1s-t order rate, r
#------------------------------------------------------
# Dissociation constant
K = 1
# parameters
pars <- c(
ka = 1e6, # forward rate
r = 1,
prod = 0.1)
#-------------------------------------
# Chemical problem formulation 1: ODE
#-------------------------------------
Fun_ODE <- function (t,y,pars)
{
with (as.list(c(y,pars)), {
ra = ka*D # forward rate
rb = ka/K *A*B # backward rate
# rates of changes
dD = -ra + rb + prod
dA = ra - rb
dB = ra - rb - r*B
return(list(dy=c(dA,dB,dD),
CONC=A+B+D))
})
}
#-------------------------------------------------------
# Chemical problem formulation 2: DAE
# 1. get rid of the fast reactions ra and rb by taking
# linear combinations : dD+dA = prod (res1) and
# dB-dA = -r*B (res2)
# 2. In addition, the equilibrium condition (eq) reads:
# as ra=rb : ka*D=ka/K*A*B => K*D=A*B
#-------------------------------------------------------
Res_DAE <- function (t,y,yprime, pars)
{
with (as.list(c(y,yprime,pars)), {
# residuals of lumped rates of changes
res1 = -dD - dA + prod
res2 = -dB + dA - r*B
# and the equilibrium equation
eq = K*D - A*B
return(list(c(res1,res2,eq),
CONC=A+B+D))
})
}
times <- seq(0,100,by=2)
# Initial conc; D is in equilibrium with A,B
y <- c(A=2,B=3,D=2*3/K)
# ODE model solved with daspk
ODE <- as.data.frame(daspk(y=y,times=times,func=Fun_ODE,
parms=pars,atol=1e-10,rtol=1e-10))
# Initial rate of change
dy <- c(dA=0, dB=0, dD=0)
# DAE model solved with daspk
DAE <- as.data.frame(daspk(y=y,dy=dy,times=times,
res=Res_DAE,parms=pars,atol=1e-10,rtol=1e-10))
#------------------------------------------------------
# plotting output
#------------------------------------------------------
opa <- par(mfrow=c(2,2))
for (i in 2:5)
{
plot(ODE$time,ODE[,i],xlab="time",
ylab="conc",main=names(ODE)[i],type="l")
points(DAE$time,DAE[,i],col="red")
}
legend("bottomright",lty=c(1,NA),pch=c(NA,1),
col=c("black","red"),legend=c("ODE","DAE"))
# difference between both implementations:
max(abs(ODE-DAE))
#------------------------------------------------------
# same DAE model, now with the jacobian
#------------------------------------------------------
jacres_DAE <- function (t,y,yprime, pars,cj)
{
with (as.list(c(y,yprime,pars)), {
# res1 = -dD - dA + prod
PD[1,1] <- -1*cj #d(res1)/d(A)-cj*d(res1)/d(dA)
PD[1,2] <- 0 #d(res1)/d(B)-cj*d(res1)/d(dB)
PD[1,3] <- -1*cj #d(res1)/d(D)-cj*d(res1)/d(dD)
# res2 = -dB + dA - r*B
PD[2,1] <- 1*cj
PD[2,2] <- -r -1*cj
PD[2,3] <- 0
# eq = K*D - A*B
PD[3,1] <- -B
PD[3,2] <- -A
PD[3,3] <- K
return(PD)
})
}
PD <- matrix(nc= 3, nr=3,0)
DAE2 <- as.data.frame(daspk(y=y,dy=dy,times=times,
res=Res_DAE, jacres=jacres_DAE, jactype="fullusr",
parms=pars,atol=1e-10,rtol=1e-10))
max(abs(DAE-DAE2))
# See dynload subdirectory for a FORTRAN implementation of this model
}
references{item 1. L. R. Petzold, A Description of DASSL: A Differential/Algebraic
System Solver, in Scientific Computing, R. S. Stepleman et al.
(Eds.), North-Holland, Amsterdam, 1983, pp. 65-68.
item 2. K. E. Brenan, S. L. Campbell, and L. R. Petzold, Numerical
Solution of Initial-Value Problems in Differential-Algebraic
Equations, Elsevier, New York, 1989.
item 3. P. N. Brown and A. C. Hindmarsh, Reduced Storage Matrix Methods
in Stiff ODE Systems, J. Applied Mathematics and Computation,
31 (1989), pp. 40-91.
item 4. P. N. Brown, A. C. Hindmarsh, and L. R. Petzold, Using Krylov
Methods in the Solution of Large-Scale Differential-Algebraic
Systems, SIAM J. Sci. Comp., 15 (1994), pp. 1467-1488.
item 5. P. N. Brown, A. C. Hindmarsh, and L. R. Petzold, Consistent
Initial Condition Calculation for Differential-Algebraic
Systems, LLNL Report UCRL-JC-122175, August 1995; submitted to
SIAM J. Sci. Comp.
Netlib: url{http://www.netlib.org}}
details{The daspk solver uses the backward differentiation formulas of orders one through five (specified with code{maxord})
to solve either:
item an ODE system of the form deqn{y'=f(t,y,...)=5)>
for y = Y, or
- a DAE system of the form $$F(t,y,y') = 0$$ for y = Y and y' = YPRIME.
ODEs are specified in
func
, DAEs are specified in res
.
If a DAE system, Values for Y and YPRIME at the initial time must be given as input. Ideally,these values should be consistent,
that is, if T, Y, YPRIME are the given initial values, they should satisfy F(T,Y,YPRIME) = 0.
However, if consistent values are not known, in many cases daspk can solve for them: when estini
= 1,
y' and algebraic variables (their number specified with nalg
) will be estimated, when estini
= 2, y will be estimated.
The form of the jacobian can be specified by jactype
. This is one of:
- jactype = "fullint" : a full jacobian, calculated internally by daspk, the default
- jactype = "fullusr" : a full jacobian, specified by user function
jacfunc
or jacres
- jactype = "bandusr" : a banded jacobian, specified by user function
jacfunc
or jacres
; the size of the bands have to be specified by bandup
and banddown
- jactype = "bandint" : a banded jacobian, calculated by
daspk
; the size of the bands have to be specified by bandup
and banddown
if jactype= "fullusr" or "bandusr" then the user must supply a subroutine jacfunc
or jacres
.
The input parameters rtol
, and atol
determine the error control performed by the solver.
If the request for precision exceeds the capabilities of the machine,
daspk will return an error code. See lsoda
for details.
res and jacres may be defined in compiled C or Fortran code, as well as in an R-function. See package vignette for details.
Examples in Fortran are in the dynload subdirectory of
the deSolve
package directory.
The output will have the attributes *istate*, and *rstate*, two vectors with several useful elements.
if verbose
= TRUE, the settings of istate and rstate will be written to the screen.
the following elements of istate are meaningful:
- el 1 : returns the conditions under which the last call to daspk returned.
2 if daspk was successful, -1 if excess work done, -2 means excess accuracy requested. (Tolerances too small),
-3 means illegal input detected. (See printed message.), -4 means repeated error test failures. (Check all input),
-5 means repeated convergence failures. (Perhaps bad Jacobian supplied or wrong choice of MF or tolerances.),
-6 means error weight became zero during problem. (Solution component i vanished, and atol or atol(i) = 0.)
- el 12 : The number of steps taken for the problem so far.
- el 13 : The number of function evaluations for the problem so far.,
- el 14 : The number of Jacobian evaluations so far.,
- el 15 : The method order last used (successfully).,
- el 16 : The order to be attempted on the next step.,
- el 17 : if el 1 =-4,-5: the largest component in the error vector,
- el 20 : The number of matrix LU decompositions so far.,
- el 21 : The number of nonlinear (Newton) iterations so far.,
- el 22 : The number of convergence failures of the solver so far ,
- el 23 : The number of error test failures of the integrator so far.
rstate contains the following:
- 1: The step size in t last used (successfully).
- 2: The step size to be attempted on the next step.
- 3: The current value of the independent variable which the solver has actually reached, i.e. the
current internal mesh point in t.
- 4: A tolerance scale factor, greater than 1.0, computed when a request for too much accuracy was detected.
For more information about possible options, see the comments in the original code daspk.f
lsoda
, lsodar
, lsode
, lsodes
, vode
In this version, the krylov method is not (yet) supported.
math