Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/notebooks/chap11.ipynb
Views: 531
Modeling and Simulation in Python
Chapter 11
Copyright 2017 Allen Downey
SIR implementation
We'll use a State
object to represent the number (or fraction) of people in each compartment.
To convert from number of people to fractions, we divide through by the total.
make_system
creates a System
object with the given parameters.
Here's an example with hypothetical values for beta
and gamma
.
The update function takes the state during the current time step and returns the state during the next time step.
To run a single time step, we call it like this:
Now we can run a simulation by calling the update function for each time step.
The result is the state of the system at t_end
Exercise Suppose the time between contacts is 4 days and the recovery time is 5 days. After 14 weeks, how many students, total, have been infected?
Hint: what is the change in S
between the beginning and the end of the simulation?
Using TimeSeries objects
If we want to store the state of the system at each time step, we can use one TimeSeries
object for each state variable.
Here's how we call it.
And then we can plot the results.
Here's what they look like.
Using a DataFrame
Instead of making three TimeSeries
objects, we can use one DataFrame
.
We have to use row
to selects rows, rather than columns. But then Pandas does the right thing, matching up the state variables with the columns of the DataFrame
.
Here's how we run it, and what the result looks like.
We can extract the results and plot them.
Exercises
Exercise Suppose the time between contacts is 4 days and the recovery time is 5 days. Simulate this scenario for 14 weeks and plot the results.