I am trying to do an ODE solver but I am having issues with the vectors between my equations in the lotka()
function and the initial parameters I set in the TLfit()
function. I don't understand why it says I have a length 1 vector when I have 3 parameters listed. Could anyone offer some insight?
require(deSolve); # for ODE solver
# define the right-hand side of the ODE
lotka <- function(t,y,parms) {
S=y[1]
I=y[2]
R=y[3]
B=parms[1]; G=parms[2]; # parameters, like before
dN=numeric(3) # vector to hold the derivatives
dN[1]=-B*S*I
dN[2]=B*S*I-(G*I)
dN[3]=G*I
return(list(dN))
}
# data
mydata <- read.csv('PlagueBombay.csv')
tvals <- mydata$Week
xvals <-mydata$WeeklyDeaths
# Least squares objective function
TLfit=function(logp) {
p=exp(logp);
parms=p[1:2]; I0=p[3]; times=1:32;
out=ode(I0,times,lotka,parms);
mse=mean((out[,2]-xvals)^2);
return(mse);
}
p0=c(B=.5,G=.5,I0=.5); # initial guess at parameters
logp0=log(p0);
fit=optim(logp0,TLfit);
I get the error:
Error in checkFunc(Func2, times, y, rho) :
The number of derivatives returned by func() (3) must equal the length of the initial conditions vector (1)
You did exactly as the error says, your initial value is
I0=p[3]
which is a single scalar. You probably want something likey0=[1-I0,I0,0]
as initial value.