Func2,次,y,rho错误

时间:2017-10-27 16:12:53

标签: r model ode

我一直收到错误:

Error in checkFunc(Func2, times, y, rho) : 
  The number of derivatives returned by func() (175) must equal the length of the initial conditions vector (51)

我正在尝试创建一个基于Brigatti等人2009的模型(具有空间成分的pred-prey模型)

x<-c(1:40000)

left_shift = function(x) {
  x[c(2:length(x), 1)]
}

right_shift = function(x) {
  x[c(length(x), 1:(length(x) - 1))]
}

laplace = function(x) {
  return(c(left_shift(x) + right_shift(x) - 2 * x))
}

dxdt <- function(time, state, pars) {
  prey = state[1:length(state) / 2]
  pred = state[(length(state) / 2 + 1):length(state)]
  dprey = pars[5] * laplace(prey) + pars[1] * prey - x[2] * prey * pred
  dpred = pars[5] * laplace(pred) + pars[3] * prey * pred - pars[4] *  pred
  list(c(prey, pred, dprey, dpred))
}

time <- seq(0, 600, by = 1)
pars <- c(alpha=1, 
      beta = .5, 
      gamma = .2, 
      delta = .6,
      D = 0.000008 #(0.004*0.004/2), #diffusion coefficient
        )

state <- rep(0.1, 51)

out <- as.data.frame(ode(func = dxdt, y = state, parms = pars, times =  time))

1 个答案:

答案 0 :(得分:1)

一些问题。首先,缺少括号。

prey = state[1:length(state) / 2]

应该阅读

prey = state[1:(length(state) / 2)]

其次,您的初始条件是奇数。 state应指定猎物捕食者的初始条件(按此顺序)。因此,对于每个位置,应该有两个值,因此,向量应始终是长度的两倍。

第三,您的函数dxdt应该返回list(c(dprey, dpred))。没有理由返回状态变量的值,因为ODE求解器将计算这些值。

修复这些,这就是你得到的:

left_shift = function(x) {
  x[c(2:length(x), 1)]
}

right_shift = function(x) {
  x[c(length(x), 1:(length(x) - 1))]
}

laplace = function(x) {
  return(c(left_shift(x) + right_shift(x) - 2 * x))
}

dxdt <- function(time, state, pars) {
  prey = state[1:(length(state) / 2)]
  pred = state[(length(state) / 2 + 1):length(state)]
  dprey = pars[5] * laplace(prey) + pars[1] * prey - x[2] * prey * pred
  dpred = pars[5] * laplace(pred) + pars[3] * prey * pred - pars[4] *  pred

  list(c(dprey, dpred))
}

time <- seq(0, 600, by = 1)
pars <- c(alpha=1, 
          beta = .5, 
          gamma = .2, 
          delta = .6,
          D = 0.000008 #(0.004*0.004/2), #diffusion coefficient
)

state <- rep(0.1, 50)

out <- as.data.frame(ode(func = dxdt, y = state, parms = pars, times =  time))