To be able to edit code and run cells, you need to run the notebook yourself. Where would you like to run the notebook?

In the cloud (experimental)

Binder is a free, open source service that runs scientific notebooks in the cloud! It will take a while, usually 2-7 minutes to get a session.

On your computer

(Recommended if you want to store your changes.)

  1. Copy the notebook URL:
  2. Run Pluto

    (Also see: How to install Julia and Pluto)

  3. Paste URL in the Open box

Frontmatter

If you are publishing this notebook on the web, you can set the parameters below to provide HTML metadata. This is useful for search engines and social media.

Author 1

homework 4, version 0

👀 Reading hidden code
222 μs

Submission by: Jazzy Doe (jazz@mit.edu)

👀 Reading hidden code
17.3 ms

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!

👀 Reading hidden code
540 μs
👀 Reading hidden code
# edit the code below to set your name and kerberos ID (i.e. email without @mit.edu)

student = (name = "Jazzy Doe", kerberos_id = "jazz")

# you might need to wait until all other cells in this notebook have completed running.
# scroll around the page to see what's up
15.8 μs

Let's create a package environment:

👀 Reading hidden code
md"_Let's create a package environment:_"
221 μs
👀 Reading hidden code
begin
using Pkg
Pkg.activate(mktempdir())
end
❔
  Activating new project at `/tmp/jl_SHw1SH`
124 ms
begin
Pkg.add(["Plots", "PlutoUI",])

using Plots
plotly()
using PlutoUI
end
👀 Reading hidden code
Failed to load integration with PlotlyBase & PlotlyKaleido.
exception
Error message

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:

this suckz 💣
❔
    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
9.1 s
👀 Reading hidden code
126 μs





👀 Reading hidden code
8.8 μs

Exercise 1: Modelling recovery

In this exercise we will investigate a simple stochastic (probabilistic) model of recovery from an infection and the time τ needed to recover. Although this model can be easily studied analytically using probability theory, we will instead use computational methods. (If you know about this distribution already, try to ignore what you know about it!)

In this model, an individual who is infected has a constant probability p to recover each day. If they recover on day n then τ takes the value n. Each time we run a new experiment τ will take on different values, so τ is a (discrete) random variable. We thus need to study statistical properties of τ, such as its mean and its probability distribution.

Exercise 1.1 - Probability distributions

👉 Define the function bernoulli(p), which returns true with probability p and false with probability (1p).

👀 Reading hidden code
622 μs
bernoulli (generic function with 1 method)
function bernoulli(p::Number)
rand() < p
end
👀 Reading hidden code
390 μs
# function bernoulli(p::Number)
# return missing
# end
👀 Reading hidden code
15.2 μs

Got it!

Splendid!

👀 Reading hidden code
17.9 ms

👉 Write a function recovery_time(p) that returns the time taken until the person recovers.

👀 Reading hidden code
215 μs
recovery_time (generic function with 1 method)
function recovery_time(p)
if p ≤ 0
throw(ArgumentError("p must be positive: p = 0 cannot result in a recovery"))
end
recovered = bernoulli(p)
if recovered
1
else
1 + recovery_time(p)
end
end
👀 Reading hidden code
607 μs
# function recovery_time(p)
# if p ≤ 0
# throw(ArgumentError("p must be positive: p = 0 cannot result in a recovery"))
# end
# # Your code here. See the comment below about the p ≤ 0 case.
# return missing
# end
👀 Reading hidden code
15.7 μs

Got it!

Keep it up!

if !@isdefined(recovery_time)
not_defined(:recovery_time)
else
let
result = recovery_time(1.0)
if result isa Missing
still_missing()
elseif !(result isa Integer)
keep_working(md"Make sure that you return an integer: the recovery time.")
else
if result == 1
samples = [recovery_time(0.2) for _ in 1:256]
a, b = extrema(samples)
if a == 1 && b > 20
correct()
else
keep_working()
end
else
keep_working(md"`p = 1.0` should return `1`: the agent recovers after the first time step.")
end
end
end
end
👀 Reading hidden code
219 μs

Hint

Remember to always re-use work you have done previously: in this case you should re-use the function bernoulli.

👀 Reading hidden code
43.0 ms

We should always be aware of special cases (sometimes called "boundary conditions"). Make sure not to run the code with p=0! What would happen in that case? Your code should check for this and throw an ArgumentError as follows:

throw(ArgumentError("..."))  

with a suitable error message.

👀 Reading hidden code
337 μs

👉 What happens for p=1?

👀 Reading hidden code
197 μs

blablabla

interpretation_of_p_equals_one = md"""
blablabla
"""
👀 Reading hidden code
246 μs

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.

👀 Reading hidden code
256 μs
do_experiment (generic function with 1 method)
function do_experiment(p, N)
map(1:N) do _
recovery_time(p)
end
end
👀 Reading hidden code
836 μs
# function do_experiment(p, N)
# return missing
# end
👀 Reading hidden code
15.2 μs
small_experiment = do_experiment(0.5, 20)
👀 Reading hidden code
15.9 μs

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 1, in the sense that the total probability should be 1.

👀 Reading hidden code
527 μs
frequencies (generic function with 1 method)
function frequencies(values)
result = Dict()
for x in values
result[x] = get(result, x, 0) + 1/length(values)
end
result
end
👀 Reading hidden code
913 μs
# function frequencies(values)
# return missing
# end
👀 Reading hidden code
14.8 μs
frequencies(small_experiment)
👀 Reading hidden code
17.6 ms

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.

👀 Reading hidden code
274 μs

Let's run an experiment with p=0.25 and N=10,000.

👀 Reading hidden code
208 μs
large_experiment = do_experiment(0.25, 10_000)
# (10_000 is just 10000 but easier to read)
👀 Reading hidden code
296 μs

The frequencies dictionary is difficult to interpret on its own, so instead, we will plot it, i.e. plot P(τ=n) against n, where n is the recovery time.

Plots.jl comes with a function bar, which does exactly what we want:

👀 Reading hidden code
314 μs
bar(frequencies(large_experiment))
👀 Reading hidden code
4.2 s

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.

👀 Reading hidden code
564 μs
frequencies_plot_with_maximum (generic function with 1 method)
function frequencies_plot_with_maximum(data::Vector)
base = bar(frequencies(data))
vline!(base, [maximum(data)], label="maximum")
return base
end
👀 Reading hidden code
637 μs
frequencies_plot_with_maximum(large_experiment)
👀 Reading hidden code
218 ms

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 a Plots.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 function plot is a Plot 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 and tan 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:

  1. Create a new plot and store it in a variable

  2. Modify that plot to add more elements

  3. 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 and function. More on this later!

👀 Reading hidden code
539 μs

👉 Write the function frequencies_plot_with_mean that calculates the mean recovery time and displays it using a vertical line.

👀 Reading hidden code
207 μs
frequencies_plot_with_mean (generic function with 1 method)
function frequencies_plot_with_mean(data)
# start out by copying the frequencies_plot_with_maximum function
return missing
end
👀 Reading hidden code
349 μs
missing
frequencies_plot_with_mean(large_experiment)
👀 Reading hidden code
11.4 μs

👉 Write an interactive visualization that draws the histogram and mean for p between 0.01 (not 0!) and 1, and N between 1 and 100,000, say. To avoid a naming conflict, call them p_interactive and N_interactive, instead of just p and N.

👀 Reading hidden code
256 μs

👀 Reading hidden code
60.1 μs

As you separately vary p and N, what do you observe about the mean in each case? Does that make sense?

👀 Reading hidden code
242 μs

Exercise 1.5

👉 What shape does the distribution seem to have? Can you verify that by adding a second plot with the expected shape?

👀 Reading hidden code
247 μs

👀 Reading hidden code
66.4 μs
let
expected_shape(x) = .25exp.(-.3(x))
p = bar(frequencies(large_experiment))
plot!(p, LinRange(0.0, 30.0, 100), expected_shape)
end
👀 Reading hidden code
174 ms

👀 Reading hidden code
71.0 μs

👀 Reading hidden code
66.7 μs

Exercise 1.6

👉 Use N=10,000 to calculate the mean time τ(p) to recover as a function of p between 0.001 and 1 (say). Plot this relationship.

👀 Reading hidden code
267 μs

👀 Reading hidden code
74.9 μs

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:

👀 Reading hidden code
866 μs
@enum InfectionStatus S I R
👀 Reading hidden code
72.9 ms

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.

👀 Reading hidden code
293 μs
missing
test_status = missing
👀 Reading hidden code
11.5 μs

👉 Use the typeof function to find the type of test_status.

👀 Reading hidden code
202 μs

👀 Reading hidden code
59.5 μs

👉 Convert x to an integer using the Integer function. What value does it have? What values do I and R have?

👀 Reading hidden code
234 μs

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:

👀 Reading hidden code
322 μs
mutable struct Agent
status::InfectionStatus
num_infected::Int64
end
👀 Reading hidden code
1.3 ms

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.

👀 Reading hidden code
334 μs

👀 Reading hidden code
60.0 μs

👉 Create an agent test_agent with status S and num_infected equal to 0.

👀 Reading hidden code
247 μs
missing
test_agent = missing
👀 Reading hidden code
11.0 μs

👉 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?

👀 Reading hidden code
417 μs
Error message

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

Stack trace

Here is what happened, the most recent locations are first:

  1. Agent()
You got this!
Agent()
👀 Reading hidden code
---

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.]

👀 Reading hidden code
315 μs
set_status! (generic function with 1 method)
function set_status!(agent::Agent, new_status::InfectionStatus)
end
👀 Reading hidden code
365 μs

Keep working on it!

The answer is not quite right.

👀 Reading hidden code
69.5 μs

👉 We will also need functions is_susceptible and is_infected that check if a given agent is in those respective states.

👀 Reading hidden code
225 μs
is_susceptible (generic function with 1 method)
function is_susceptible(agent::Agent)
return missing
end
👀 Reading hidden code
351 μs
is_infected (generic function with 1 method)
function is_infected(agent::Agent)
return missing
end
👀 Reading hidden code
376 μs

Here we go!

Replace missing with your answer.

👀 Reading hidden code
165 μs

Exericse 2.4

👉 Write a function generate_agents(N) that returns a vector of N freshly created Agents. They should all be initially susceptible, except one, chosen at random (i.e. uniformly), who is infectious.

👀 Reading hidden code
255 μs
generate_agents (generic function with 1 method)
function generate_agents(N::Integer)
agents = [Agent(S, 0) for _ in 1:N]
rand(agents).status = I
agents
end
👀 Reading hidden code
962 μs
# function generate_agents(N::Integer)
# return missing
# end
👀 Reading hidden code
15.0 μs
generate_agents(3)
👀 Reading hidden code
13.1 μs

Got it!

You got the right answer!

👀 Reading hidden code
94.3 ms

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.

👀 Reading hidden code
285 μs
abstract type AbstractInfection end
👀 Reading hidden code
331 μs
struct InfectionRecovery <: AbstractInfection
p_infection
p_recovery
end
👀 Reading hidden code
937 μs

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 the source is infectious, then the source infects our agent with the given infection probability. If the source successfully infects the other agent, then its num_infected record must be updated.

  • If the agent is infected then it recovers with the relevant probability.

  • Otherwise, nothing happens.

👀 Reading hidden code
680 μs
Error message

UndefVarError: Reinfection not defined

Stack trace

Here is what happened, the most recent locations are first:

  1. 	end	function interact!(agent::Agent, source::Agent, infection::Reinfection)		if agent.status == S && source.status == I
begin
function interact!(agent::Agent, source::Agent, infection::InfectionRecovery)
if agent.status == S && source.status == I
if bernoulli(infection.p_infection)
agent.status = I
source.num_infected += 1
end
elseif agent.status == I
if bernoulli(infection.p_recovery)
agent.status = R
end
end
end
function interact!(agent::Agent, source::Agent, infection::Reinfection)
if agent.status == S && source.status == I
if bernoulli(infection.p_infection)
agent.status = I
source.num_infected += 1
end
elseif agent.status == I
if bernoulli(infection.p_recovery)
agent.status = S
end
end
end
end
👀 Reading hidden code
---
# function interact!(agent::Agent, source::Agent, infection::InfectionRecovery)
# end
👀 Reading hidden code
15.4 μs

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.

👀 Reading hidden code
230 μs
let
agent = Agent(S, 0)
source = Agent(I, 0)
infection = InfectionRecovery(0.9, 0.5)
interact!(agent, source, infection)
(agent=agent, source=source)
end
👀 Reading hidden code
4.4 ms

Got it!

Your function treats the susceptible agent case correctly!

👀 Reading hidden code
5.0 ms

Got it!

Your function treats the infectious agent case correctly!

👀 Reading hidden code
181 μs

Got it!

Your function treats the recovered agent case correctly!

👀 Reading hidden code
178 μs

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 Agents and an infection of type InfectionRecovery. It implements a single step of the infection dynamics as follows:

  • Choose two random agents: an agent and a source.

  • Apply interact!(agent, source, infection).

  • Return agents.

👀 Reading hidden code
803 μs
step! (generic function with 1 method)
function step!(agents::Vector{Agent}, infection::AbstractInfection)
interact!(rand(agents), rand(agents), infection)
end
👀 Reading hidden code
477 μs
# function step!(agents::Vector{Agent}, infection::AbstractInfection)
# end
👀 Reading hidden code
14.1 μs

👉 Write a function sweep!. It runs step! N times, where N is the number of agents. Thus each agent acts, on average, once per sweep; a sweep is thus the unit of time in our Monte Carlo simulation.

👀 Reading hidden code
232 μs
sweep! (generic function with 1 method)
function sweep!(agents::Vector{Agent}, infection::AbstractInfection)
for _ in agents
step!(agents, infection)
end
end
👀 Reading hidden code
757 μs
# function sweep!(agents::Vector{Agent}, infection::AbstractInfection)
# end
👀 Reading hidden code
15.5 μs

👉 Write a function simulation that does the following:

  1. Generate the N agents.

  2. Run sweep! a number T of times. Calculate and store the total number of agents with each status at each step in variables S_counts, I_counts and R_counts.

  3. Return the vectors S_counts, I_counts and R_counts in a named tuple, with keys S, I and R.

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.

👀 Reading hidden code
1.5 ms
simulation (generic function with 1 method)
function simulation(N::Integer, T::Integer, infection::AbstractInfection)
agents = generate_agents(N)
S_counts = []
I_counts = []
R_counts = []
for _ in 1:T
push!(S_counts, sum(a -> a.status == S, agents))
push!(I_counts, sum(a -> a.status == I, agents))
push!(R_counts, sum(a -> a.status == R, agents))
sweep!(agents, infection)
end
return (S=S_counts, I=I_counts, R=R_counts)
end
👀 Reading hidden code
2.9 ms
# function simulation(N::Integer, T::Integer, infection::AbstractInfection)

# return (S=missing, I=missing, R=missing)
# end
👀 Reading hidden code
15.1 μs
simulation(3, 20, InfectionRecovery(0.9, 0.2))
👀 Reading hidden code
25.0 μs
simulation(100, 1000, InfectionRecovery(0.005, 0.2))
👀 Reading hidden code
1.6 ms
let
run_basic_sir
N = 100
T = 1000
sim = simulation(N, T, InfectionRecovery(0.02, 0.002))
result = plot(1:T, sim.S, ylim=(0, N), label="Susceptible")
plot!(result, 1:T, sim.I, ylim=(0, N), label="Infectious")
plot!(result, 1:T, sim.R, ylim=(0, N), label="Recovered")
end
👀 Reading hidden code
243 ms
👀 Reading hidden code
212 ms

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. So f(x) = x+2 is the same as f(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 and let.

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 like begin, it is just a block of code, but like function, 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!

👀 Reading hidden code
670 μs

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 N=100, pinfection=0.02, pinfection=0.002 and T=1000.

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.

👀 Reading hidden code
444 μs
repeat_simulations (generic function with 1 method)
function repeat_simulations(N, T, infection, num_simulations)
N = 100
T = 1000
map(1:num_simulations) do _
simulation(N, T, infection)
end
end
👀 Reading hidden code
1.1 ms
simulations = repeat_simulations(100, 1000, InfectionRecovery(0.02, 0.002), 20)
👀 Reading hidden code
46.2 ms

In the cell below, we plot the evolution of the number of I individuals as a function of time for each of the simulations on the same plot using transparency (alpha=0.5 inside the plot command).

👀 Reading hidden code
213 μs
let
p = plot()
for sim in simulations
plot!(p, 1:1000, sim.I, alpha=.5, label=nothing)
end
p
end
👀 Reading hidden code
90.0 ms

👉 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, maps, or whatever you see fit!

👀 Reading hidden code
586 μs

👉 Write a function sir_mean_plot that returns a plot of the means of S, I and R as a function of time on a single graph.

👀 Reading hidden code
216 μs
sir_mean_plot (generic function with 1 method)
function sir_mean_plot(simulations::Vector{<:NamedTuple})
T = length(first(simulations).S)
all_S_counts = map(result -> result.S, simulations)
all_I_counts = map(result -> result.I, simulations)
all_R_counts = map(result -> result.R, simulations)
p = plot()
plot!(p, 1:T, sum(all_S_counts) ./ length(simulations), lw=5, label="S")
plot!(p, 1:T, sum(all_I_counts) ./ length(simulations), lw=5, label="I")
plot!(p, 1:T, sum(all_R_counts) ./ length(simulations), lw=5, label="R")
p
end
👀 Reading hidden code
3.3 ms
# function sir_mean_plot(simulations::Vector{<:NamedTuple})
# # you might need T for this function, here's a trick to get it:
# T = length(first(simulations).S)
# return missing
# end
👀 Reading hidden code
14.6 μs
sir_mean_plot(simulations)
👀 Reading hidden code
272 ms
"(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])"
let
T = length(first(simulations).S)
all_S_counts = map(result -> result.S, simulations)
all_I_counts = map(result -> result.I, simulations)
all_R_counts = map(result -> result.R, simulations)
(S=round.(sum(all_S_counts) ./ length(simulations) ./ 100, digits=4),
I=round.(sum(all_I_counts) ./ length(simulations) ./ 100, digits=4),
R=round.(sum(all_R_counts) ./ length(simulations) ./ 100, digits=4))
end |> string
👀 Reading hidden code
213 ms

👉 Allow pinfection and precovery to be changed interactively and find parameter values for which you observe an epidemic outbreak.

👀 Reading hidden code
218 μs

👀 Reading hidden code
60.5 μs

👉 Write a function sir_mean_error_plot that does the same as sir_mean_plot, which also computes the standard deviation σ of S, I, R at each step. Add this to the plot using error bars, using the option yerr=σ in the plot command; use transparency.

This should confirm that the distribution of I at each step is pretty wide!

👀 Reading hidden code
377 μs
sir_mean_error_plot (generic function with 1 method)
function sir_mean_error_plot(simulations::Vector{<:NamedTuple})
# you might need T for this function, here's a trick to get it:
T = length(first(simulations).S)
return missing
end
👀 Reading hidden code
627 μs

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.)

👀 Reading hidden code
249 μs

👀 Reading hidden code
62.1 μs

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.

👀 Reading hidden code
280 μs

👀 Reading hidden code
60.0 μs

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.

👀 Reading hidden code
659 μs

👀 Reading hidden code
60.5 μs

👉 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.

👀 Reading hidden code
369 μs

Exercise 4.2

👉 Run the simulation 20 times and plot I as a function of time for each one, together with the mean over the 20 simulations (as you did in the previous exercises).

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.)

👀 Reading hidden code
357 μs

👀 Reading hidden code
59.4 μs

👉 Run the new simulation and draw I (averaged over runs) as a function of time. Is the behaviour qualitatively the same or different? Describe what you see.

👀 Reading hidden code
203 μs

👀 Reading hidden code
60.0 μs

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:

👀 Reading hidden code
392 μs

Abstraction, lines 1-219

Array Basics, lines 1-137

Course Intro, lines 1-44

(for example)

lines_i_edited = md"""
Abstraction, lines 1-219

Array Basics, lines 1-137

Course Intro, lines 1-44

(_for example_)
"""
👀 Reading hidden code
393 μs





👀 Reading hidden code
10.6 μs

Before you submit

Remember to fill in your name and Kerberos ID at the top of this notebook.

👀 Reading hidden code
350 μs

Function library

Just some helper functions used in the notebook.

👀 Reading hidden code
220 μs
hint (generic function with 1 method)
👀 Reading hidden code
482 μs
almost (generic function with 1 method)
👀 Reading hidden code
967 μs
still_missing (generic function with 2 methods)
👀 Reading hidden code
838 μs
keep_working (generic function with 2 methods)
👀 Reading hidden code
832 μs
👀 Reading hidden code
10.8 ms
correct (generic function with 2 methods)
👀 Reading hidden code
718 μs
not_defined (generic function with 1 method)
👀 Reading hidden code
829 μs
👀 Reading hidden code
26.7 μs