从deSolve :: lsoda

时间:2016-10-14 12:18:47

标签: r error-handling ode differential-equations

我正在运行一些使用近似贝叶斯计算的算法(例如参见Toni等,2009),这些算法需要使用随机生成的一组输入参数重复求解Lotka-Volterra方程组。我正在使用deSolve package中的lsoda函数。

有时候这个函数会抛出一个错误,我希望使用try(..., silent = TRUE)函数来忽略它,尽管这似乎不起作用(参见下面的例子)。设置options(show.error.messages = FALSE)也不起作用。

如何禁止从deSolve :: lsoda打印错误消息?

require(deSolve)

# Differential equations defining the system
LV <- function(Time, State, Pars){

    with(as.list(c(State, Pars)), {

    dx <- a*x - x*y
    dy <- b*x*y - y

    return(list(c(dx, dy)))
    }
    )
}

# Parameters
pars <- c(a = 1.0, b = 1.0)

# Initial conditions
init <- c(x = 1.0, y = 0.5)

# Time steps
times <- seq(0, 15, length.out = 100)

problem_seeds <- c(7, 241, 361, 365, 468, 473, 649, 704, 724, 745, 838)

for (i in problem_seeds){
    set.seed(i)

    # Sample from pi(theta), prior for parameter vector (a, b)
    theta_star <- runif(2, -10, 10)
    names(theta_star) <- c("a", "b")

    # Simulate a dataset using these parameters (at the specified times)
    try(out <- lsoda(func = LV, 
            y = init, 
            parms = theta_star, 
            times = times), 
            silent = TRUE)
    dfs <- as.data.frame(out)
}

1 个答案:

答案 0 :(得分:2)

查看deSolve中插图的第44页,此类错误描述为here

您可以通过降低解决方案的绝对容差来解决此问题。在您的示例中,以下方法有效:

out <- lsoda(func = LV, 
             y = init, 
             parms = theta_star, 
             times = times,
             atol = 1e-3)

注意:您的data.frame dfs将在每个循环中被覆盖,如果您想在data.frame中输出problem_seeds,您可以运行apply系列的功能。从现在开始你不需要try功能。