无法在R中运行ODE模型,其中包括随时间变化的参数(强制函数)

时间:2019-03-27 14:38:41

标签: r ode forcing

我正在尝试使用deSolve拟合合理的基本ODE模型,其中包括随时间变化的参数(感染力; FOI)。在没有此参数的情况下运行模型效果很好,但是包含时间相关参数会产生错误(请参见下文)。

我对R和数学建模还比较陌生,并且已经尝试解决此问题已有一段时间了。

我已将FOI参数创建为值矩阵,然后使用近似函数进行插值(如我所见,此函数适用于强制函数,例如https://rdrr.io/rforge/deSolve/man/forcings.html)。

没有此与时间相关的参数的模型运行时没有任何错误,但是尝试包含该模型会出现错误:

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

我无法弄清楚该错误的解决方法,因为我只有两个初始条件,并且似乎包括此与时间相关的FOI参数会生成更多的导数。

我知道其他人也提出了类似的问题,但是我没有发现这个问题与强制功能有关。

在此先感谢您的任何建议。

# Forcing function data

foi <- matrix(ncol=2,byrow=TRUE,data=c(
  0, 0.003, 2, 0.03, 3, 0.08, 4,0.1,  5, 0.12, 6, 0.15, 
  8, 0.16, 10, 0.14,12, 0.12,14,0.08,15, 0.06,16, 0.03,
  17, 0.01,18,0.003,19,0.003,20,0.003,30,0.003,40,0.003,
  50,0.003,60,0.003,65,0.01, 70,0.08,  72,0.095,74,0.10, 
  76,0.1, 78,0.08,  80,0.06))

age <- seq(0, 80, by = 1)

input <- approxfun(x = foi[,1], y = foi[,2], method = "constant", rule = 2)

# Function
ab <- function(time, state, pars) {
  with(as.list(c(state, pars)), {

import<-c(input(t))

diggP<- (import *iggN) - iggR*iggP   
diggN<- (-import*iggN) + iggR*iggP

return(list(c(diggP, diggN))) 
  })
}


# Initial values
yini  <- c(iggP=0, iggN=1) 

# Parameters
pars  <- c(iggR = 0, import)

# ODE solver
results<- ode(y=yini, times=age, func=foi_model, pars)

我希望建立一个模型,其中在每个时间点(或在这种情况下为年龄),FOI都会根据我在FOI矩阵中输入的值而变化。因此,我想了解随着时间变化的FOI会如何影响微分方程的输出。

1 个答案:

答案 0 :(得分:1)

您的主要问题是您正在向t传递参数input,但是该变量在您的代码中不存在。时间作为称为time的参数传递给您的模型。 (此外,您的模型被称为ab而不是foi_model,正如对ode的调用中所述,加上pars不需要import,应为传递给ode。)

# Load library
library(deSolve)

# Create FOI matrix
foi <- matrix(ncol=2,byrow=TRUE,data=c(
  0, 0.003, 2, 0.03, 3, 0.08, 4,0.1,  5, 0.12, 6, 0.15, 
  8, 0.16, 10, 0.14,12, 0.12,14,0.08,15, 0.06,16, 0.03,
  17, 0.01,18,0.003,19,0.003,20,0.003,30,0.003,40,0.003,
  50,0.003,60,0.003,65,0.01, 70,0.08,  72,0.095,74,0.10, 
  76,0.1, 78,0.08,  80,0.06))

# Times for model solution
age <- seq(0, 80, by = 1)

# Linear interpolation function from FOI data
input <- approxfun(x = foi[,1], y = foi[,2], method = "constant", rule = 2)

# Model to be integrated
ab <- function(time, state, parms) {
  with(as.list(c(state, parms)), {

    ##### IMPORTANT #####
    import<-input(time) #<- 'time' was previously 't'
    #####################

    # Derivatives
    diggP<- (import *iggN) - iggR*iggP   
    diggN<- (-import*iggN) + iggR*iggP

    # Return results
    return(list(c(diggP, diggN))) 
  })
}

# Initial values
yini  <- c(iggP=0, iggN=1) 

# Parameters
pars  <- c(iggR = 0)

# Solve model
results<- ode(y=yini, times=age, func=ab, parms = pars)

# Plot results
plot(results)

reprex package(v0.2.1)于2019-03-27创建