Skip to content
Prev 258 / 696 Next

[R-sig-dyn-mod] changing state variable in simulations

Hi Andras:

How about this?

#Load library
require(deSolve)

#Define	parameters and initial conditions
plist<-matrix(c(0.08,0.07,0.09,15,20,25,3,5,6),ncol=3 )
colnames(plist)=c("K","V","state")

#Define	"forc" function prior to "derivs", so it isn't redefined every time "derivs" is	called
intimes<-c(0,0.5,12)
input<-c(1200,0,0)
forc<-approxfun(intimes, input, method="constant",rule=2)

#Derivatives to be integrated
derivs<-function(t,state,pars){
  with(as.list(pars),{
    inp <- forc(t)
    dy1 <- inp/V - K * state[1]
    return(list(c(dy1)))
  })
}

#Define	output times
times=seq(0,13,by=0.05)

#Model wrapper
model<-function(pars) {
  state<-pars[3]
  return(ode(y=state,times=times,func=derivs,parms=pars[1:2],method="vode",rtol=1e-8,atol=1e-8,hmax=0.05))
}

#Empty matrix
modelout<-matrix(ncol=nrow(plist),nrow=length(times))

#Loop through parameters & initial conditions
for(i in 1:nrow(plist))
  modelout[,i]<-model(plist[i,])[,2]

#Plot output
plot(times,modelout[,1],type="l",lty="solid")
lines(times,modelout[,2],lty="dashed")
lines(times,modelout[,3],lty="dotted")

Cheers,
Daniel


_______________________________
Daniel C. Reed, PhD.
Postdoctoral Fellow,
Dept. of Earth & Environmental Sciences,
University of Michigan,
Ann Arbor, MI, USA.
email: reeddc at umich.edu
web: www.danielreed.org
On Sep 13, 2013, at 1:34 PM, Andras Farkas <motyocska at yahoo.com> wrote: