【问题标题】:Trouble interpretting R code for Lotka-Volterra无法解释 Lotka-Volterra 的 R 代码
【发布时间】:2023-03-13 17:42:03
【问题描述】:

我得到了这个代码来创建一个 Lotka Volterra 捕食者-猎物模型。此代码运行良好并生成我希望获得的图形类型,但是,我不明白某些代码在做什么,因此不知道在其他规模的其他数据上使用它时需要修改什么.

我不明白的两部分是:

    for (n1 in seq((0.1*k[1]),(1.2*k[1]),100)){
  for (n2 in seq(.1*k[2],1.2*k[2],.1*k[2])){

以及这一行中的 if 语句:

    (n1==100&n2==100){plot(y[,2],y[,3],type="l",xlim=c(0,1000)

任何帮助解释这一点,以便我更好地理解代码是如何工作的,将不胜感激!

    library(deSolve)
    r<<-matrix(c(1,1),ncol=1)
    k<<-matrix(c(1000,1000),ncol=1)
    alpha<<-matrix(c(1,1.5,.5,1),ncol=2)
    t_stop<-100
    color="blue"
    for (n1 in seq((0.1*k[1]),(1.2*k[1]),100)){
      for (n2 in seq(.1*k[2],1.2*k[2],.1*k[2])){
    lvcomp2<-function(t,n,params){ w=n[1]; z=n[2]
    return(list(c(r[1]*n[1]*(k[1]-n[1]-alpha[1,2]*n[2])/k[1],r[2]*n[2]*(k[2]-n[2]- 
    alpha[2,1]*n[1])/k[2])))}
    y<-lsoda(c(n1,n2),c(seq(0,t_stop,1)),lvcomp2,NA)
    if (n1==100&n2==100){plot(y[,2],y[,3],type="l",xlim=c(0,1000), 
    ylim=c(0,1000),col=color,xlab="Abundance of species 1",ylab="Abundance of species 2")}
    if (n2==1200) {lines(y[,2],y[,3], col=color)}
    if (n1==1200){lines(y[,2],y[,3], col=color)}
    if (n2==100) {lines(y[,2],y[,3], col=color)}
    if (n1==100) {lines(y[,2],y[,3], col=color)}}} 

【问题讨论】:

    标签: r modeling


    【解决方案1】:

    该代码在混淆过程方面做得很好。其中一些有问题的做法,例如超级赋值&lt;&lt;-、循环中不必要的操作等。这是代码的简化版本,我们可以通过逐步进行并将事物移出循环,在它们不改变的地方填充常量值并应用样式指南来获得它。

    library(deSolve)
    
    # in the sample code, both loops iterate over the same thing:
    s <- seq(from = 100, to = 1200, by = 100)
    lsoda_times <- seq(0, 100, 1)
    
    # all combinations of s to solve an Ordinary Differential Equation for
    grid <- expand.grid(s, s)
    grid <- subset(grid, Var1 %in% c(1200, 100) | Var2 %in% c(1200, 100))
    
    lvcomp2 <- function(t, n, parms, ...) { # use lsoda convention ..., see ?lsoda
      list(c( # list output to satisfy lsoda requirements
        n[1] * (1000-n[1] - 0.5*n[2]) / 1000, # derivatives
        n[2] * (1000-n[2] - 1.5*n[1]) / 1000
      ))
    }
    
    y <- lsoda(c(100, 100), seq(0, 100, 1), lvcomp2, NA)
    # make base plot
    plot(y[, 2], y[, 3], type = "l", xlim = c(0, 1000), ylim = c(0, 1000),
         col = "blue", xlab = "Abundance of species 1", ylab = "Abundance of species 2"
    )
    
    # add lines to the plot
    for (i in 1:nrow(grid)) {
      y <- lsoda(c(grid[i, 1], grid[i, 2]), lsoda_times, lvcomp2, NA)
      lines(y[, 2], y[, 3], col = "blue")
    }
    

    根据@tpetzoldt 评论 - 更新为更有效的方法,首先删除 100 次对 lsoda 的不必要调用

    【讨论】:

    • 不错的方法,但仍有一件事需要改进:代码应避免对lsoda 进行过时且可能占用大量CPU 的调用。可以通过预先减少网格或在同一“f”子句中包含lsodalines来完成。我把它留给原来的回答者来实现。
    • 完美。顺便说一句,相平面分析也可以使用包 phaseR cran.r-project.org/web/packages/phaseR/vignettes/… 完成,但这当然不是最初的问题。
    猜你喜欢
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    相关资源
    最近更新 更多