epirecipes / sir-julia

Various implementations of the classical SIR model in Julia
MIT License
195 stars 39 forks source link

Add RCall RHS of an odin model #119

Closed sdwfrost closed 2 months ago

sdwfrost commented 2 months ago

Here is the model using the R library odin:

library(odin)
sir_ode <- odin::odin({
  ## Derivatives
  deriv(S) <- -beta*cee*S*I/N
  deriv(I) <- beta*cee*S*I/N-gamma*I
  deriv(R) <- gamma*I
  N <- S + I + R

  ## Initial conditions
  initial(S) <- 990.0
  initial(I) <- 10.0
  initial(R) <- 0.0

  ## parameters
  beta <- 0.05
  cee <- 10.0
  gamma <- 0.25
}, target="c")
mod <- sir_ode$new()
t <- seq(0, 40, length.out = 401)
y <- mod$run(t)

The derivatives for (t,y) can be obtained as follows:

mod$deriv(0,c(990,10,0))

The main issue is how to modify the parameters of the model outside of compiling the odin object.

sdwfrost commented 2 months ago

After reading the odin docs more, I came across user. Here is code that can be readily wrapped in Julia:

sir_ode_odin <- odin::odin({
  ## Derivatives
  deriv(S) <- -beta*cee*S*I/N
  deriv(I) <- beta*cee*S*I/N-gamma*I
  deriv(R) <- gamma*I
  N <- S + I + R

  ## Initial conditions
  initial(S) <- S_ini
  initial(I) <- I_ini
  initial(R) <- R_ini

  ## parameters
  S_ini <- user(990.0)
  I_ini <- user(10.0)
  R_ini <- user(0.0)
  beta <- user(0.05)
  cee <- user(10.0)
  gamma <- user(0.25)
}, target="c")

sir_ode_model <- sir_ode_odin$new()

sir_ode_r <- function(u,p,t){
    sir_ode_model$set_user(user=list(beta=p[1],cee=p[2],gamma=p[3]))
    return(sir_ode_model$deriv(t,u))
}
sdwfrost commented 2 months ago

Closed with 8045d5c020b47bbb8443622edff787f749cf1f92