# This is the R version of program 6.5 from page 204 of # "Modeling Infectious Disease in humans and animals" # by Keeling & Rohani. # It is the SIR model (including births and deaths) with # (event-driven) demographic stochasticity approximated using the tau-leap # method and assuming Poisson distributions. # 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 Tau_leap = function(old,pars){ X=old[1] Y=old[2] Z=old[3] Rate = matrix(0,6,1) Change = matrix(0,6,3) Rate[1] = mu*N0 Change[1,]=c(1,0,0) Rate[2] = beta*X*Y/N0 Change[2,]=c(-1,1,0) Rate[3] = gamma*Y Change[3,]=c(0,-1,1) 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) new_value=old for (i in 1:6){ Num=rpois(1,Rate[i]*tau) # Make sure things don't go negative Use=min(c(Num,new_value[which(Change[i,]<0)])) new_value=new_value+Change[i,]*Use } Tau_leap = 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) TT = matrix(0,time[2]+1,1) P = matrix(0,time[2]+1,3) colnames(P) = c('X','Y','Z') TT=seq(0,time[2],tau) P[1,]=initial X = initial[1] Y = initial[2] Z = initial[3] old=c(X,Y,Z) loop = 1 while (TT[loop]