# This is the R version of program 6.6 from page 210 of # "Modeling Infectious Disease in humans and animals" # by Keeling & Rohani. # It is the SIR model (including births and deaths) with full # (event-driven) demographic stochasticity. Two forms of imports (governed # by the parameters epsilon and delta) are implemented. # This is a more complex stochastic model as 8 events are # possible: infection, recovery, birth, death of susceptible, death of # infected, death of recovered and two forms of imports # Note: by default we are using a very small population size to highlight # the stochasticity. # Do the iteration step Iterate = function(old,pars){ X=old[1] Y=old[2] Z=old[3] Rate = matrix(0,8,1) Change = matrix(0,8,3) Rate[1] = beta*X*Y/N0 Change[1,]=c(-1,1,0) Rate[2] = gamma*Y Change[2,]=c(0,-1,1) Rate[3] = mu*N0 Change[3,]=c(1,0,0) Rate[4] = mu*X Change[4,]=c(-1,0,0) Rate[5] = mu*Y Change[5,]=c(0,-1,0) Rate[6] = mu*Z Change[6,]=c(0,0,-1) Rate[7] = epsilon*X Change[7,] = c(-1,1,0) Rate[8] = delta Change[8,] = c(0,1,0) R1 = runif(1) R2 = runif(1) step = -log(R2)/(sum(Rate)) # find which event to do m=min(which(cumsum(Rate)>=R1*sum(Rate))) new_value=old+Change[m,] dt = 0 et = 0 if(m==7){et = 1} if(m==8){dt = 1} Iterate = c(step,et,dt,new_value) } # Do the iterations using the full event driven stochastic methodology # This is a relatively general version of the event-driven methodology # known as Gillespie's Direct Algorithm Stoch_Iteration = function(time,initial,pars){ library(deSolve) ET = 0 DT = 0 TT = 0 X = initial[1] Y = initial[2] Z = initial[3] old=c(X,Y,Z) loop = 1 while (TT[loop]0) r = rep(0,length(m)) out2 = as.data.frame(cbind(r,out[m,1])) n = which(DT>0) s = rep(0,length(n)) s = s+Q[2] out3 = as.data.frame(cbind(s,out[n,1])) p2 = p2 + geom_point(data=out2,aes(y=r,x=out2[,2]/365,fill="Epsilon Imports"),shape=21)+ geom_point(data=out3,aes(y=s,x=out3[,2]/365,fill="Delta Imports"),shape=21) + scale_fill_manual(name = "", values = c("Epsilon Imports" = "blue", "Delta Imports" = "red")) + theme(legend.title = element_blank(),legend.position = c(0.87,0.7), legend.box.background = element_rect(color = "black"), legend.spacing.y = unit(0, "mm")) + theme(panel.border = element_rect(color = "black", fill = NA, linewidth = 0.6)) library(patchwork) p1/p2