# This is the R version of program 6.4 from page 203 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. # This is a more complex stochastic model as 6 events are # possible: infection, recovery, birth, death of susceptible, death of # infected, death of recovered. # 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,6,1) Change = matrix(0,6,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) 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,] Iterate = c(step,new_value) } # Do the iterations using the full event driven stochastic methodology # Note that this could be written more generally (see Program 6.4) but # this version is kept simple for clarity Stoch_Iteration = function(time,initial,pars){ library(deSolve) TT = 0 X = initial[1] Y = initial[2] Z = initial[3] old=c(X,Y,Z) loop = 1 while (TT[loop]