SIR Model in D312 Feb 2015
When you move the slider marked “Number initially susceptible,” the simulation runs again with 1 initial infectious individual and the specified number of susceptible individuals. Similarly, when you change the value of the basic reproductive number, R0, the simulation also runs again for the new value of R0 and current value of S.
Right now, the model only runs for 20 steps and then stops. But I’d like to make a version that grows and shrinks the width of the bars to accommodate longer runs. But this one’s good enough for now.
This is the final result:
Not too shabby.
This is the code for the simulation model itself. It’s a pretty simple affair:
This is a simple version of a frequency dependent SIR model where the force of infection on each susceptible individual is the product of the number of infectious individuals (I) and the reproductive rate (in this case, b), divided by the size of the total population. We’re assuming here that everyone has a constant infectious period lasting one step of the model, so in this case b is the same as the mythical basic reproductive number R0. Note that the probability of infection p_inf is the exponential cumulative distribution function with rate equal to bI. This accounts for the discretization of time in our model, and translates our continuous-time rate b to a probability.
Most of the guts of the bar chart are pirated from Mike Bostock’s great series of Let’s Make a Bar Chart tutorials, so I won’t go over the definition of the bars, etc in any detail. One thing to note is that the bars highlighted in green are incoming bars added to the DOM after the last simulation, following the general update pattern for d3. This allows for smooth transitions between bars.
Aside from implementing a vanilla SIR model, one of my goals with this was to understand how to effectively use transitions to re-scale the bar heights and axes between simulations, and to use a slider to set and update the input parameters.
To do this, I put an “onchange” listener on the slider for the number of susceptibles as follows:
This grabs the value of the slider when the mouse is released and sends it to the update function. Note that we also grab the value for the reproductive number R to pass it to the update function.
But to continuously update the value the variable S next to the slider, we use an “oninput” event as follows:
I did the same thing for R0 but because the slider gives inputs only in integer values, we’ll set the range from 0 to 200 and divide by 100 to get a range from 0 to 2.0 by 0.1 increments.
The update function is itself pretty simple, just generating a new simulation and then re-calling the render function we used to build the plot in the first instance:
My next step is going to be to try to make some interactive disease maps in D3, so watch this space…