homework 4, version 0
Submission by: Jazzy Doe (jazz@mit.edu)
Homework 4: Epidemic modeling I
18.S191
, fall 2020
This notebook contains built-in, live answer checks! In some exercises you will see a coloured box, which runs a test case on your code, and provides feedback based on the result. Simply edit the code, run it, and the check runs again.
For MIT students: there will also be some additional (secret) test cases that will be run as part of the grading process, and we will look at your notebook and write comments.
Feel free to ask questions!
"Jazzy Doe"
"jazz"
Let's create a package environment:
Activating new project at `/tmp/jl_SHw1SH`
Failed to load integration with PlotlyBase & PlotlyKaleido.
The package PlotlyBase.jl could not load because it failed to initialize.
That's not nice! Things you could try:
- Restart the notebook.
- Try a different Julia version.
- Contact the developers of PlotlyBase.jl about this error.
You might find useful information in the package installation log:
Updating registry at `~/.julia/registries/General.toml` Resolving package versions... Updating `/tmp/jl_SHw1SH/Project.toml` [91a5bcdd] + Plots v1.40.14 [7f904dfe] + PlutoUI v0.7.64 Updating `/tmp/jl_SHw1SH/Manifest.toml` [6e696c72] + AbstractPlutoDingetjes v1.3.2 [66dad0bd] + AliasTables v1.1.3 [d1d4a3ce] + BitFlags v0.1.9 [d360d2e6] + ChainRulesCore v1.25.1 [9e997f8a] + ChangesOfVariables v0.1.10 [944b1d66] + CodecZlib v0.7.8 [35d6a980] + ColorSchemes v3.29.0 [3da002f7] + ColorTypes v0.12.1 [c3611d14] + ColorVectorSpace v0.11.0 [5ae59095] + Colors v0.13.1 [34da2185] + Compat v4.16.0 [f0e56b4a] + ConcurrentUtilities v2.5.0 [187b0558] + ConstructionBase v1.5.8 [d38c429a] + Contour v0.6.3 [9a962f9c] + DataAPI v1.16.0 [864edb3b] + DataStructures v0.18.22 [ffbed154] + DocStringExtensions v0.9.5 [460bff9d] + ExceptionUnwrapping v0.1.11 [c87230d0] + FFMPEG v0.4.2 [53c48c17] + FixedPointNumbers v0.8.5 [1fa38f19] + Format v1.3.7 [28b8d3ca] + GR v0.73.6 [42e2da0e] + Grisu v1.0.2 [cd3eb016] + HTTP v1.10.16 [47d2ed2b] + Hyperscript v0.0.5 [ac1192a8] + HypertextLiteral v0.9.5 [b5f81e59] + IOCapture v0.2.5 [3587e190] + InverseFunctions v0.1.17 [92d709cd] + IrrationalConstants v0.2.4 [1019f520] + JLFzf v0.1.11 [692b3bcd] + JLLWrappers v1.7.0 [682c06a0] + JSON v0.21.4 [b964fa9f] + LaTeXStrings v1.4.0 [23fbe1c1] + Latexify v0.16.8 [2ab3a3ac] + LogExpFunctions v0.3.28 [e6f89c97] + LoggingExtras v1.1.0 [6c6e2e6c] + MIMEs v1.1.0 [1914dd2f] + MacroTools v0.5.16 [739be429] + MbedTLS v1.1.9 [442fdcdd] + Measures v0.3.2 [e1d29d7a] + Missings v1.2.0 [77ba4419] + NaNMath v1.0.3 [4d8831e6] + OpenSSL v1.5.0 [bac558e1] + OrderedCollections v1.8.1 [69de0a69] + Parsers v2.8.3 [ccf2f8ad] + PlotThemes v3.3.0 [995b91a9] + PlotUtils v1.4.3 [91a5bcdd] + Plots v1.40.14 [7f904dfe] + PlutoUI v0.7.64 [aea7be01] + PrecompileTools v1.2.1 [21216c6a] + Preferences v1.4.3 [43287f4e] + PtrArrays v1.3.0 [3cdcf5f2] + RecipesBase v1.3.4 [01d81517] + RecipesPipeline v0.6.12 [189a3867] + Reexport v1.2.2 [05181044] + RelocatableFolders v1.0.1 [ae029012] + Requires v1.3.1 [6c6a2e73] + Scratch v1.2.1 [992d4aef] + Showoff v1.0.3 [777ac1f9] + SimpleBufferStream v1.2.0 [a2af1166] + SortingAlgorithms v1.2.1 [860ef19b] + StableRNGs v1.0.3 [82ae8749] + StatsAPI v1.7.1 [2913bbd2] + StatsBase v0.34.4 [62fd8b95] + TensorCore v0.1.1 [3bb67fe8] + TranscodingStreams v0.11.3 [410a4b4d] + Tricks v0.1.10 [5c2747f8] + URIs v1.5.2 [1cfade01] + UnicodeFun v0.4.1 [1986cc42] + Unitful v1.23.1 [45397f5d] + UnitfulLatexify v1.7.0 [41fe7b60] + Unzip v0.2.0 [6e34b625] + Bzip2_jll v1.0.9+0 [83423d85] + Cairo_jll v1.18.5+0 [ee1fde0b] + Dbus_jll v1.16.2+0 [2702e6a9] + EpollShim_jll v0.0.20230411+1 [2e619515] + Expat_jll v2.6.5+0 [b22a6f82] + FFMPEG_jll v4.4.4+1 [a3f928ae] + Fontconfig_jll v2.16.0+0 [d7e528f0] + FreeType2_jll v2.13.4+0 [559328eb] + FriBidi_jll v1.0.17+0 [0656b61e] + GLFW_jll v3.4.0+2 [d2c73de3] + GR_jll v0.73.6+0 [78b55507] + Gettext_jll v0.21.0+0 [7746bdde] + Glib_jll v2.84.0+0 [3b182d85] + Graphite2_jll v1.3.15+0 [2e76f6c2] + HarfBuzz_jll v8.5.1+0 [aacddb02] + JpegTurbo_jll v3.1.1+0 [c1c5ebd0] + LAME_jll v3.100.2+0 [88015f11] + LERC_jll v3.0.0+1 [1d63c593] + LLVMOpenMP_jll v18.1.8+0 [dd4b983a] + LZO_jll v2.10.3+0 [e9f186c6] + Libffi_jll v3.4.7+0 [7e76a0d4] + Libglvnd_jll v1.7.1+1 [94ce4f54] + Libiconv_jll v1.18.0+0 [4b2f31a3] + Libmount_jll v2.41.0+0 [89763e89] + Libtiff_jll v4.5.1+1 [38a345b3] + Libuuid_jll v2.41.0+0 [e7412a2a] + Ogg_jll v1.3.5+1 [458c3c95] + OpenSSL_jll v3.5.0+0 [91d4177d] + Opus_jll v1.3.3+0 [36c8627f] + Pango_jll v1.56.3+0 [30392449] + Pixman_jll v0.44.2+0 [c0090381] + Qt6Base_jll v6.7.1+1 [a44049a8] + Vulkan_Loader_jll v1.3.243+0 [a2964d1f] + Wayland_jll v1.23.1+0 [2381bf8a] + Wayland_protocols_jll v1.44.0+0 [02c8fc9c] + XML2_jll v2.13.6+1 [ffd25f8a] + XZ_jll v5.8.1+0 [f67eecfb] + Xorg_libICE_jll v1.1.2+0 [c834827a] + Xorg_libSM_jll v1.2.6+0 [4f6342f7] + Xorg_libX11_jll v1.8.12+0 [0c0b7dd1] + Xorg_libXau_jll v1.0.13+0 [935fb764] + Xorg_libXcursor_jll v1.2.4+0 [a3789734] + Xorg_libXdmcp_jll v1.1.6+0 [1082639a] + Xorg_libXext_jll v1.3.7+0 [d091e8ba] + Xorg_libXfixes_jll v6.0.1+0 [a51aa0fd] + Xorg_libXi_jll v1.8.3+0 [d1454406] + Xorg_libXinerama_jll v1.1.6+0 [ec84b674] + Xorg_libXrandr_jll v1.5.5+0 [ea2f1a96] + Xorg_libXrender_jll v0.9.12+0 [c7cfdc94] + Xorg_libxcb_jll v1.17.1+0 [cc61e674] + Xorg_libxkbfile_jll v1.1.3+0 [e920d4aa] + Xorg_xcb_util_cursor_jll v0.1.4+0 [12413925] + Xorg_xcb_util_image_jll v0.4.1+0 [2def613f] + Xorg_xcb_util_jll v0.4.1+0 [975044d2] + Xorg_xcb_util_keysyms_jll v0.4.1+0 [0d47668e] + Xorg_xcb_util_renderutil_jll v0.3.10+0 [c22f9ab0] + Xorg_xcb_util_wm_jll v0.4.2+0 [35661453] + Xorg_xkbcomp_jll v1.4.7+0 [33bec58e] + Xorg_xkeyboard_config_jll v2.44.0+0 [c5fb5394] + Xorg_xtrans_jll v1.6.0+0 [3161d3a3] + Zstd_jll v1.5.7+1 [35ca27e7] + eudev_jll v3.2.14+0 [214eeab7] + fzf_jll v0.61.1+0 [a4ae2306] + libaom_jll v3.11.0+0 [0ac62f75] + libass_jll v0.15.2+0 [1183f4f0] + libdecor_jll v0.2.2+0 [2db6ffa8] + libevdev_jll v1.13.4+0 [f638f0a6] + libfdk_aac_jll v2.0.3+0 [36db933b] + libinput_jll v1.28.1+0 [b53b4c65] + libpng_jll v1.6.49+0 [f27f6e37] + libvorbis_jll v1.3.7+2 [009596ad] + mtdev_jll v1.1.7+0 [1270edf5] + x264_jll v2021.5.5+0 [dfaa095f] + x265_jll v3.5.0+0 [d8fb68d0] + xkbcommon_jll v1.8.1+0 [0dad84c5] + ArgTools [56f22d72] + Artifacts [2a0f44e3] + Base64 [ade2ca70] + Dates [8bb1440f] + DelimitedFiles [f43a241f] + Downloads [7b1f6079] + FileWatching [b77e0a4c] + InteractiveUtils [b27032c2] + LibCURL [76f85450] + LibGit2 [8f399da3] + Libdl [37e2e46d] + LinearAlgebra [56ddb016] + Logging [d6f4376e] + Markdown [a63ad114] + Mmap [ca575930] + NetworkOptions [44cfe95a] + Pkg [de0858da] + Printf [3fa0cd96] + REPL [9a3f8284] + Random [ea8e919c] + SHA [9e88b42a] + Serialization [6462fe0b] + Sockets [2f01184e] + SparseArrays [10745b16] + Statistics [fa267f1f] + TOML [a4e569a6] + Tar [8dfed614] + Test [cf7118a7] + UUIDs [4ec0a83e] + Unicode [e66e0078] + CompilerSupportLibraries_jll [deac9b47] + LibCURL_jll [29816b5a] + LibSSH2_jll [c8ffd9c3] + MbedTLS_jll [14a3606d] + MozillaCACerts_jll [4536629a] + OpenBLAS_jll [05823500] + OpenLibm_jll [efcefdf7] + PCRE2_jll [83775a58] + Zlib_jll [8e850b90] + libblastrampoline_jll [8e850ede] + nghttp2_jll [3f19e933] + p7zip_jll
Exercise 1: Modelling recovery
In this exercise we will investigate a simple stochastic (probabilistic) model of recovery from an infection and the time
In this model, an individual who is infected has a constant probability
Exercise 1.1 - Probability distributions
👉 Define the function bernoulli(p)
, which returns true
with probability false
with probability
bernoulli (generic function with 1 method)
Got it!
Splendid!
👉 Write a function recovery_time(p)
that returns the time taken until the person recovers.
recovery_time (generic function with 1 method)
Got it!
Keep it up!
Hint
Remember to always re-use work you have done previously: in this case you should re-use the function bernoulli
.
We should always be aware of special cases (sometimes called "boundary conditions"). Make sure not to run the code with ArgumentError
as follows:
throw(ArgumentError("..."))
with a suitable error message.
👉 What happens for
blablabla
Exercise 1.2
👉 Write a function do_experiment(p, N)
that runs the function recovery_time
N
times and collects the results into a vector.
do_experiment (generic function with 1 method)
1
1
1
1
5
1
2
1
2
1
1
1
3
3
1
4
1
5
3
3
Exercise 1.3
👉 Write a function frequencies(data)
that calculates and returns the frequencies (i.e. probability distribution) of input data.
The input will be an array of integers, with duplicates, and the result will be a dictionary that maps each occured value to its frequency in the data.
For example,
frequencies([7, 8, 9, 7])
should give
Dict(
7 => 0.5,
8 => 0.25,
9 => 0.25
)
As with any probability distribution, it should be normalised to
frequencies (generic function with 1 method)
5
0.1
4
0.05
2
0.1
3
0.2
1
0.55
Hint
Do you remember how we worked with dictionaries in Homework 3? You can create an empty dictionary using Dict()
. You may want to use either the function haskey
or the function get
on your dictionary – check the documentation for how to use these functions.
Let's run an experiment with
5
1
9
2
4
1
1
13
4
3
3
7
9
2
5
6
1
16
1
10
1
2
6
6
3
5
1
11
8
2
The frequencies dictionary is difficult to interpret on its own, so instead, we will plot it, i.e. plot
Plots.jl comes with a function bar
, which does exactly what we want:
Great! Feel free to experiment with this function, try giving it a different array as argument. Plots.jl is pretty clever, it even works with an array of strings!
Exercise 1.4
Next, we want to add a new element to our plot: a vertical line. To demonstrate how this works, here we added a vertical line at the maximum value.
To write this function, we first create a base plot, we then modify that plot to add the vertical line, and finally, we return the plot. More on this in the next info box.
frequencies_plot_with_maximum (generic function with 1 method)
Note about plotting
Plots.jl has an interesting property: a plot is an object, not an action. Functions like
plot
,bar
,histogram
don't draw anything on your screen - they just return aPlots.Plot
. This is a struct that contains the description of a plot (what data should be plotted in what way?), not the picture.So a Pluto cell with a single line,
plot(1:10)
, will show a plot, because the result of the functionplot
is aPlot
object, and Pluto just shows the result of a cell.Modifying plots
Nice plots are often formed by overlaying multiple plots. In Plots.jl, this is done using the modifying functions:
plot!
,bar!
,vline!
, etc. These take an extra (first) argument: a previous plot to modify.For example, to plot the
sin
,cos
andtan
functions in the same view, we do:
function sin_cos_plot() T = -1.0:0.01:1.0 result = plot(T, sin.(T)) plot!(result, T, cos.(T)) plot!(result, T, tan.(T)) return result end
💡 This example demonstrates a useful pattern to combine plots:
Create a new plot and store it in a variable
Modify that plot to add more elements
Return the plot
It is recommended that these 3 steps happen within a single cell. This can prevent some strange glitches when re-running cells. There are three ways to group expressions together into a single cell:
begin
,let
andfunction
. More on this later!
👉 Write the function frequencies_plot_with_mean
that calculates the mean recovery time and displays it using a vertical line.
frequencies_plot_with_mean (generic function with 1 method)
missing
👉 Write an interactive visualization that draws the histogram and mean for p_interactive
and N_interactive
, instead of just p
and N
.
As you separately vary
Exercise 1.5
👉 What shape does the distribution seem to have? Can you verify that by adding a second plot with the expected shape?
Exercise 1.6
👉 Use
Exercise 2: Agent-based model for an epidemic outbreak – types
In this and the following exercises we will develop a simple stochastic model for combined infection and recovery in a population, which may exhibit an epidemic outbreak (i.e. a large spike in the number of infectious people). The population is well mixed, i.e. everyone is in contact with everyone else. [An example of this would be a small school or university in which people are constantly moving around and interacting with each other.]
The model is an individual-based or agent-based model: we explicitly keep track of each individual, or agent, in the population and their infection status. For the moment we will not keep track of their position in space; we will just assume that there is some mechanism, not included in the model, by which they interact with other individuals.
Exercise 2.1
Each agent will have its own internal state, modelling its infection status, namely "susceptible", "infectious" or "recovered". We would like to code these as values S
, I
and R
, respectively. One way to do this is using an enumerated type or enum. Variables of this type can take only a pre-defined set of values; the Julia syntax is as follows:
We have just defined a new type InfectionStatus
, as well as names S
, I
and R
that are the (only) possible values that a variable of this type can take.
👉 Define a variable test_status
whose value is S
.
missing
👉 Use the typeof
function to find the type of test_status
.
👉 Convert x
to an integer using the Integer
function. What value does it have? What values do I
and R
have?
Exercise 2.2
For each agent we want to keep track of its infection status and the number of other agents that it infects during the simulation. A good solution for this is to define a new type Agent
to hold all of the information for one agent, as follows:
When you define a new type like this, Julia automatically defines one or more constructors, which are methods of a generic function with the same name as the type. These are used to create objects of that type.
👉 Use the methods
function to check how many constructors are pre-defined for the Agent
type.
👉 Create an agent test_agent
with status S
and num_infected
equal to 0.
missing
👉 For convenience, define a new constructor (i.e. a new method for the function) that takes no arguments and creates an Agent
with status S
and number infected 0, by calling one of the default constructors that Julia creates. This new method lives outside (not inside) the definition of the struct
. (It is called an outer constructor.)
(In Pluto, multiple methods for the same function need to be combined in a single cell using a begin end
block.)
Let's check that the new method works correctly. How many methods does the constructor have now?
MethodError: no method matching Main.workspace#4.Agent()
Closest candidates are:
Main.workspace#4.Agent(::Main.workspace#4.InfectionStatus, ::Int64) at ~/work/disorganised-mess/disorganised-mess/hw4 some solutions.jl#==#ae4ac4b4-041f-11eb-14f5-1bcde35d18f2:2
Main.workspace#4.Agent(::Any, ::Any) at ~/work/disorganised-mess/disorganised-mess/hw4 some solutions.jl#==#ae4ac4b4-041f-11eb-14f5-1bcde35d18f2:2
Here is what happened, the most recent locations are first:
Exercise 2.3
👉 Write functions set_status!(a)
and set_num_infected!(a)
which modify the respective fields of an Agent
. Check that they work. [Note the bang ("!
") at the end of the function names to signify that these functions modify their argument.]
set_status! (generic function with 1 method)
Keep working on it!
The answer is not quite right.
👉 We will also need functions is_susceptible
and is_infected
that check if a given agent is in those respective states.
is_susceptible (generic function with 1 method)
is_infected (generic function with 1 method)
Here we go!
Replace missing
with your answer.
Exericse 2.4
👉 Write a function generate_agents(N)
that returns a vector of N
freshly created Agent
s. They should all be initially susceptible, except one, chosen at random (i.e. uniformly), who is infectious.
generate_agents (generic function with 1 method)
I::InfectionStatus = 1
0
S::InfectionStatus = 0
0
S::InfectionStatus = 0
0
Got it!
You got the right answer!
We will also need types representing different infections.
Let's define an (immutable) struct
called InfectionRecovery
with parameters p_infection
and p_recovery
. We will make it a subtype of an abstract AbstractInfection
type, because we will define more infection types later.
Exercise 2.5
👉 Write a function interact!
that takes an affected agent
of type Agent
, an source
of type Agent
and an infection
of type InfectionRecovery
. It implements a single (one-sided) interaction between two agents:
If the
agent
is susceptible and thesource
is infectious, then thesource
infects ouragent
with the given infection probability. If thesource
successfully infects the other agent, then itsnum_infected
record must be updated.If the
agent
is infected then it recovers with the relevant probability.Otherwise, nothing happens.
UndefVarError: Reinfection not defined
Here is what happened, the most recent locations are first:
Play around with the test case below to test your function! Try changing the definitions of agent
, source
and infection
. Since we are working with randomness, you might want to run the cell multiple times.
I::InfectionStatus = 1
0
I::InfectionStatus = 1
1
Got it!
Your function treats the susceptible agent case correctly!
Got it!
Your function treats the infectious agent case correctly!
Got it!
Your function treats the recovered agent case correctly!
Exercise 3: Agent-based model for an epidemic outbreak – Monte Carlo simulation
In this exercise we will build on Exercise 2 to write a Monte Carlo simulation of how an infection propagates in a population.
Make sure to re-use the functions that we have already written, and introduce new ones if they are helpful! Short functions make it easier to understand what the function does and build up new functionality piece by piece.
You should not use any global variables inside the functions: Each function must accept as arguments all the information it requires to carry out its task. You need to think carefully about what the information each function requires.
Exercise 3.1
👉 Write a function step!
that takes a vector of Agent
s and an infection
of type InfectionRecovery
. It implements a single step of the infection dynamics as follows:
Choose two random agents: an
agent
and asource
.Apply
interact!(agent, source, infection)
.Return
agents
.
step! (generic function with 1 method)
👉 Write a function sweep!
. It runs step!
sweep! (generic function with 1 method)
👉 Write a function simulation
that does the following:
Generate the
agents.Run
sweep!
a number of times. Calculate and store the total number of agents with each status at each step in variablesS_counts
,I_counts
andR_counts
.Return the vectors
S_counts
,I_counts
andR_counts
in a named tuple, with keysS
,I
andR
.
You've seen an example of named tuples before: the student
variable at the top of the notebook!
Feel free to store the counts in a different way, as long as the return type is the same.
simulation (generic function with 1 method)
2
0
0
0
0
0
0
0
0
0
1
3
2
1
1
1
1
1
1
1
0
0
1
2
2
2
2
2
2
2
99
99
99
99
99
99
99
99
99
99
1
1
0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
We used a let
block in this cell to group multiple expressions together, but how is it different from begin
or function
?
function vs. begin vs. let
Writing functions is a way to group multiple expressions (i.e. lines of code) together into a mini-program. Note the following about functions:
A function always returns one object.[1] This object can be given explicitly by writing
return x
, or implicitly: Julia functions always return the result of the last expression by default. Sof(x) = x+2
is the same asf(x) = return x+2
.Variables defined inside a function are not accessible outside the function. We say that function bodies have a local scope. This helps to keep your program easy to read and write: if you define a local variable, then you don't need to worry about it in the rest of the notebook.
There are two other ways to group epxressions together that you might have seen before:
begin
andlet
.begin
begin
will group expressions together, and it takes the value of its last subexpression.We use it in this notebook when we want multiple expressions to always run together.
let
let
also groups multiple expressions together into one, but variables defined inside of it are local: they don't affect code outside of the block. So likebegin
, it is just a block of code, but likefunction
, it has a local variable scope.We use it when we want to define some local (temporary) variables to produce a complicated result, without interfering with other cells. Pluto allows only one definition per global variable of the same name, but you can define local variables with the same names whenever you wish!
1
Even a function like
f(x) = return
returns one object: the object
nothing
— try it out!
Exercise 3.2
Alright! Every time that we run the simulation, we get slightly different results, because it is based on randomness. By running the simulation a number of times, you start to get an idea of the mean behaviour of our model. This is the essence of a Monte Carlo method! You use computer-generated randomness to generate samples.
Instead of pressing the button many times, let's have the computer repeat the simulation. In the next cells, we run your simulation num_simulations=20
times with
Every single simulation returns a named tuple with the status counts, so the result of multiple simulations will be an array of those. Have a look inside the result, simulations
, and make sure that its structure is clear.
repeat_simulations (generic function with 1 method)
99
99
99
99
99
0
1
1
1
1
1
22
0
0
0
0
0
78
99
99
99
99
99
1
1
1
1
1
1
39
0
0
0
0
0
60
99
99
99
99
99
0
1
1
1
1
1
29
0
0
0
0
0
71
99
99
99
99
99
99
1
1
1
1
1
0
0
0
0
0
0
1
99
99
99
98
98
0
1
1
1
2
2
18
0
0
0
0
0
82
99
99
99
99
99
0
1
1
1
1
1
29
0
0
0
0
0
71
99
99
99
99
99
0
1
1
1
1
1
22
0
0
0
0
0
78
99
99
99
99
98
0
1
1
1
1
2
23
0
0
0
0
0
77
99
99
99
99
99
0
1
1
1
1
1
29
0
0
0
0
0
71
99
99
99
99
99
0
1
1
1
1
1
23
0
0
0
0
0
77
99
99
99
99
99
99
1
1
1
0
0
0
0
0
0
1
1
1
99
99
99
99
99
0
1
1
1
1
1
13
0
0
0
0
0
87
99
99
99
99
99
0
1
1
1
1
1
28
0
0
0
0
0
72
99
99
99
98
98
0
1
1
1
2
2
30
0
0
0
0
0
70
99
99
99
99
99
0
1
1
1
1
1
23
0
0
0
0
0
77
99
99
99
99
99
99
1
1
1
1
1
0
0
0
0
0
0
1
99
97
97
97
97
0
1
3
3
3
3
19
0
0
0
0
0
81
99
99
99
99
99
0
1
1
1
1
1
38
0
0
0
0
0
62
99
99
99
99
99
0
1
1
1
1
1
21
0
0
0
0
0
79
99
99
99
99
99
0
1
1
1
1
1
43
0
0
0
0
0
57
In the cell below, we plot the evolution of the number of alpha=0.5
inside the plot command).
👉 Calculate the mean number of infectious agents of our simulations for each time step. Add it to the plot using a heavier line (lw=3
for "linewidth") by modifying the cell above.
Check the answer yourself: does your curve follow the average trend?
Hint
This exercise requires some creative juggling with arrays, anonymous functions, map
s, or whatever you see fit!
👉 Write a function sir_mean_plot
that returns a plot of the means of
sir_mean_plot (generic function with 1 method)
"(S = [0.99, 0.989, 0.989, 0.988, 0.9875, 0.9875, 0.9875, 0.987, 0.9865, 0.9865, 0.986, 0.9855, 0.985, 0.985, 0.985, 0.985, 0.985, 0.985, 0.985, 0.985, 0.985, 0.985, 0.985, 0.9845, 0.9845, 0.9835, 0.983, 0.982, 0.982, 0.982, 0.982, 0.9815, 0.9815, 0.981, 0.9805, 0.98, 0.98, 0.9795, 0.9795, 0.9795, " ⋯ 21644 bytes ⋯ "0.605, 0.606, 0.606, 0.606, 0.607, 0.6075, 0.6085, 0.609, 0.6095, 0.6095, 0.61, 0.61, 0.61, 0.6105, 0.611, 0.6115, 0.6125, 0.6135, 0.6145, 0.6145, 0.615, 0.615, 0.616, 0.616, 0.617, 0.6185, 0.619, 0.619, 0.619, 0.6205, 0.6205, 0.6205, 0.6205, 0.6215, 0.623, 0.6245, 0.6255, 0.626, 0.6265, 0.6265])"
👉 Allow
👉 Write a function sir_mean_error_plot
that does the same as sir_mean_plot
, which also computes the standard deviation yerr=σ
in the plot command; use transparency.
This should confirm that the distribution of
sir_mean_error_plot (generic function with 1 method)
Exercise 3.3
👉 Plot the probability distribution of num_infected
. Does it have a recognisable shape? (Feel free to increase the number of agents in order to get better statistics.)
Exercse 3.4
👉 What are three simple ways in which you could characterise the magnitude (size) of the epidemic outbreak? Find approximate values of these quantities for one of the runs of your simulation.
Exercise 4: Reinfection
In this exercise we will re-use our simulation infrastructure to study the dynamics of a different type of infection: there is no immunity, and hence no "recovery" rather, susceptible individuals may now be re-infected
Exercise 4.1
👉 Make a new infection type Reinfection
. This has the same two fields as InfectionRecovery
(p_infection
and p_recovery
). However, "recovery" now means "becomes susceptible again", instead of "moves to the R
class.
This new type Reinfection
should also be a subtype of AbstractInfection
. This allows us to reuse our previous functions, which are defined for the abstract supertype.
👉 Make a new method for the interact!
function that accepts the new infection type as argument, reusing as much functionality as possible from the previous version.
Write it in the same cell as our previous interact!
method, and use a begin
block to group the two definitions together.
Exercise 4.2
👉 Run the simulation 20 times and plot
Note that you should be able to re-use the sweep!
and simulation
functions , since those should be sufficiently generic to work with the new step!
function! (Modify them if they are not.)
👉 Run the new simulation and draw
Exercise 5 - Lecture transcript
(MIT students only) Please see the link for hw 4 transcript document on Canvas. We want each of you to correct about 400 lines, but don’t spend more than 15 minutes on it. See the the beginning of the document for more instructions. :point_right: Please mention the name of the video(s) and the line ranges you edited:
Abstraction, lines 1-219
Array Basics, lines 1-137
Course Intro, lines 1-44
(for example)
Before you submit
Remember to fill in your name and Kerberos ID at the top of this notebook.
Function library
Just some helper functions used in the notebook.
hint (generic function with 1 method)
almost (generic function with 1 method)
still_missing (generic function with 2 methods)
keep_working (generic function with 2 methods)
Fantastic!
Splendid!
Great!
Yay ❤
Great! 🎉
Well done!
Keep it up!
Good job!
Awesome!
You got the right answer!
Let's move on to the next section.
correct (generic function with 2 methods)
not_defined (generic function with 1 method)