Search code examples
rdifferential-equationsequation-solving

desolve differential equations not working


I've written some code that has a logistic growth component (i.e. as N approaches the 'carrying capacity' it grows at a slower rate, until when it reaches the 'carrying capacity' it stops growing). However, when I run it in R it doesn't seem to be working. Some populations end up being larger than the carrying capacity. I've looked at the maths and its all OK. So I think that the problem is that dN/dt is only being calculated once for each population. Does anyone know how to fix this problem?

Any help would be greatly appreciated!

Example code below:

library('optimbase')
library('deSolve')
library('tidyverse')
K = 150000                 #carrying capacity         
deaths = 0.2567534        #death rate        
treesize = 0.23523        #resource size        
K_mat = K*ones(10, 1)  #matrix of Ks         
death_mat = deaths*ones(10, 1) #matrix of deathrates
tree_mat = treesize*ones(11, 1) #matrix of resources 
for_mat <- matrix(rbinom(11 * 10, 1, 0.2), ncol = 11, nrow = 10) #connection 
 #matrix of foraging
parameters <- c(for_mat, tree_mat, death_mat, K_mat) #outline parameters
N <- runif(10,0,K) 
state <- N #starting state

nestchange <- function(t, state, parameters){
      with(as.list(c(state, parameters)),{
    r = for_mat %*% tree_mat - death_mat 
    dNdt = r*N  - r*N*(N/K_mat)
    list(c(dNdt))
  })
}
times <- seq(0,100)

out <- ode (y  = state, 
            times = times, 
            func = nestchange, 
            parms = parameters)

results <- as.data.frame(out)
results <- gather(results, 'nest', 'N', 2:11) 

ggplot(data=results,
       aes(x=time, y=N, colour=nest)) +
  geom_line() +
  theme_bw()

Solution

  • Should your function actually be,

    nestchange <- function(t, state, parameters){
          with(as.list(c(state, parameters)),{
        r <- for_mat %*% tree_mat - death_mat 
        dNdt <- r*state  - r*state*(state/K_mat)
        list(c(dNdt))
      })
    }
    

    as the ODE solver is passing state to the function at each time step, yet the function is using the variable N for the calculations instead which isn't updated by the ODE solver.