Update on first section

This commit is contained in:
mhjensen
2018-04-06 12:01:41 -04:00
parent 29e0a988e3
commit ae163d14ca
37 changed files with 2685 additions and 0 deletions
File diff suppressed because one or more lines are too long
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import random
# initialize the rng with a seed
random.seed()
# Hard coding of input parameters
Agents = 100
MCcounts = 1000
Transactions = 10000
startMoney = 1.0
Lambda = 0.0
FinancialAgents = startMoney*np.ones(Agents)
for i in range (1, MCcounts, 1):
for j in range (1, Transactions, 1):
agent_i = int(Agents*random.random())
agent_j = int(Agents*random.random())
epsilon = random.random()
if agent_i != agent_j:
m1 = Lambda*FinancialAgents[agent_i] + (1-Lambda)*epsilon* (FinancialAgents[agent_i] + FinancialAgents[agent_j])
m2 = Lambda*FinancialAgents[agent_j] + (1-Lambda)*(1-epsilon)*(FinancialAgents[agent_i] + FinancialAgents[agent_j])
FinancialAgents[agent_i] = m1
FinancialAgents[agent_j] = m2
# the histogram of the data
n, bins, patches = plt.hist(FinancialAgents, 20, facecolor='green')
plt.xlabel('$x$')
plt.ylabel('Distribution of wealth')
plt.title(r'Money')
plt.axis([0, 10, 0, 100])
plt.grid(True)
plt.show()
+22
View File
@@ -0,0 +1,22 @@
Year,Hares (x1000),Lynx (x1000)
1900,30.0,4.0
1901,47.2,6.1
1902,70.2,9.8
1903,77.4,35.2
1904,36.3,59.4
1905,20.6,41.7
1906,18.1,19.0
1907,21.4,13.0
1908,22.0,8.3
1909,25.4,9.1
1910,27.1,7.4
1911,40.3,8.0
1912,57,12.3
1913,76.6,19.5
1914,52.3,45.7
1915,19.5,51.1
1916,11.2,29.7
1917,7.6,15.8
1918,14.6,9.7
1919,16.2,10.1
1920,24.7,8.6
1 Year Hares (x1000) Lynx (x1000)
2 1900 30.0 4.0
3 1901 47.2 6.1
4 1902 70.2 9.8
5 1903 77.4 35.2
6 1904 36.3 59.4
7 1905 20.6 41.7
8 1906 18.1 19.0
9 1907 21.4 13.0
10 1908 22.0 8.3
11 1909 25.4 9.1
12 1910 27.1 7.4
13 1911 40.3 8.0
14 1912 57 12.3
15 1913 76.6 19.5
16 1914 52.3 45.7
17 1915 19.5 51.1
18 1916 11.2 29.7
19 1917 7.6 15.8
20 1918 14.6 9.7
21 1919 16.2 10.1
22 1920 24.7 8.6
+43
View File
@@ -0,0 +1,43 @@
import numpy as np
import matplotlib.pyplot as plt
def solver(m, H0, L0, dt, a, b, c, d, t0):
"""Solve the difference equations for H and L over m years
with time step dt (measured in years."""
num_intervals = int(m/float(dt))
t = np.linspace(t0, t0 + m, num_intervals+1)
H = np.zeros(t.size)
L = np.zeros(t.size)
print 'Init:', H0, L0, dt
H[0] = H0
L[0] = L0
for n in range(0, len(t)-1):
H[n+1] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n]
L[n+1] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n]
return H, L, t
# Load in data file
data = np.loadtxt('Hudson_Bay.csv', delimiter=',', skiprows=1)
# Make arrays containing x-axis and hares and lynx populations
t_e = data[:,0]
H_e = data[:,1]
L_e = data[:,2]
# Simulate using the model
H, L, t = solver(m=20, H0=34.91, L0=3.857, dt=0.1,
a=0.4807, b=0.02482, c=0.9272, d=0.02756,
t0=1900)
# Visualize simulations and data
plt.plot(t_e, H_e, 'b-+', t_e, L_e, 'r-o', t, H, 'm--', t, L, 'k--')
plt.xlabel('Year')
plt.ylabel('Numbers of hares and lynx')
plt.axis([1900, 1920, 0, 140])
plt.title(r'Population of hares and lynx 1900-1920 (x1000)')
plt.legend(('H_e', 'L_e', 'H', 'L'), loc='upper left')
plt.savefig('Hudson_Bay_sim.pdf')
plt.savefig('Hudson_Bay_sim.png')
plt.show()
+12
View File
@@ -0,0 +1,12 @@
import numpy as np
t = np.linspace(0, 10, 21) # 20 intervals in [0, 10]
dt = t[1] - t[0]
N = np.zeros(t.size)
N[0] = 1
r = 0.5
for n in range(0, N.size-1, 1):
N[n+1] = N[n] + r*dt*N[n]
print 'N[%d]=%.1f' % (n+1, N[n+1])
+11
View File
@@ -0,0 +1,11 @@
0,100
600,140
1200,250
1800,360
2400,480
3000,820
3600,1300
4200,1700
4800,2900
5400,3900
6000,7000
1 0 100
2 600 140
3 1200 250
4 1800 360
5 2400 480
6 3000 820
7 3600 1300
8 4200 1700
9 4800 2900
10 5400 3900
11 6000 7000
+27
View File
@@ -0,0 +1,27 @@
import numpy as np
# Estimate r
data = np.loadtxt('ecoli.csv', delimiter=',')
t_e = data[:,0]
N_e = data[:,1]
i = 2 # Data point (i,i+1) used to estimate r
r = (N_e[i+1] - N_e[i])/(N_e[i]*(t_e[i+1] - t_e[i]))
print 'Estimated r=%.5f' % r
# Can experiment with r values and see if the model can
# match the data better
T = 1200 # cell can divide after T sec
t_max = 5*T # 5 generations in experiment
t = np.linspace(0, t_max, 1000)
dt = t[1] - t[0]
N = np.zeros(t.size)
N[0] = 100
for n in range(0, len(t)-1, 1):
N[n+1] = N[n] + r*dt*N[n]
import matplotlib.pyplot as plt
plt.plot(t, N, 'r-', t_e, N_e, 'bo')
plt.xlabel('time [s]'); plt.ylabel('N')
plt.legend(['model', 'experiment'], loc='upper left')
plt.show()
+27
View File
@@ -0,0 +1,27 @@
import numpy as np
data = np.loadtxt('ecoli.csv', delimiter=',')
t_experiment = data[:,0]
N_experiment = data[:,1]
def error(p):
r = p[0]
T = 1200 # cell can divide after T sec
t_max = 5*T # 5 generations in experiment
t = np.linspace(0, t_max, len(t_experiment))
dt = (t[1] - t[0])
N = np.zeros(t.size)
N[0] = 100
for n in range(0, len(t)-1, 1):
N[n+1] = N[n] + r*dt*N[n]
e = np.sqrt(np.sum((N - N_experiment)**2))/N[0] # error measure
e = abs(N[-1] - N_experiment[-1])/N[0]
print 'r=', r, 'e=',e
return e
from scipy.optimize import minimize
p = minimize(error, [0.0006], tol=1E-5)
print p
+19
View File
@@ -0,0 +1,19 @@
import numpy as np
from matplotlib import pyplot as plt
# Load in data file
data = np.loadtxt('Hudson_Bay.dat', delimiter=',', skiprows=1)
# Make arrays containing x-axis and hares and lynx populations
year = data[:,0]
hares = data[:,1]
lynx = data[:,2]
plt.plot(year, hares ,'b-+', year, lynx, 'r-o')
plt.axis([1900,1920,0, 100.0])
plt.xlabel(r'Year')
plt.ylabel(r'Numbers of hares and lynx ')
plt.legend(('Hares','Lynx'), loc='upper right')
plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}')
plt.savefig('Hudson_Bay_data.pdf')
plt.savefig('Hudson_Bay_data.png')
plt.show()
+880
View File
@@ -499,5 +499,885 @@ text(0, 0.5, paste("y =x^ (", power, " +/- ", power.se, ")", sep = ""), pos = 4)
!eblock
!split
!split
===== Example: ecoli lab experiment =====
!bnotice Typical pattern:
The population grows faster and faster. "Why? Is there an underlying (general) mechanism":"http://www.zo.utexas.edu/courses/Thoc/PopGrowth.html"?
!enotice
!bblock
o Cells divide after $T$ seconds on average (one generation)
o $2N$ celles divide into twice as many new cells $\Delta N$ in a time
interval $\Delta t$ as $N$ cells would: $\Delta N \propto N$
o $N$ cells result in twice as many new individuals $\Delta N$ in
time $2\Delta t$ as in time $\Delta t$: $\Delta N \propto\Delta t$
o Same proportionality wrt death (repeat reasoning)
o Proposed model: $\Delta N = b\Delta t N - d\Delta tN$ for some unknown
constants $b$ (births) and $d$ (deaths)
o Describe evolution in discrete time: $t_n=n\Delta t$
o Program-friendly notation: $N$ at $t_n$ is $N^n$
o Math model: $N^{n+1} = N^n + r\Delta t\, N$ (with $\ r=b-d$)
o Program model: `N[n+1] = N[n] + r*dt*N[n]`
!eblock
!split
===== The program =====
!bblock
Let us solve the difference equation in as simple way as possible,
just to train some programming: $r=1.5$, $N^0=1$, $\Delta t=0.5$
@@@CODE ../../Programs/LifeScience/diffeq.py
!eblock
% if FORMAT != 'ipynb':
!split
===== The output =====
!bc
N[1]=1.2
N[2]=1.6
N[3]=2.0
N[4]=2.4
N[5]=3.1
N[6]=3.8
N[7]=4.8
N[8]=6.0
N[9]=7.5
N[10]=9.3
N[11]=11.6
N[12]=14.6
N[13]=18.2
N[14]=22.7
N[15]=28.4
N[16]=35.5
N[17]=44.4
N[18]=55.5
N[19]=69.4
N[20]=86.7
!ec
% endif
!split
===== Parameter estimation =====
!bblock
* We do not know $r$
* How can we estimate $r$ from data?
We can use the difference equation with the experimental data
!bt
\[ N^{n+1} = N^n + r\Delta t N^n\]
!et
Say $N^{n+1}$ and $N^n$ are known from data, solve wrt $r$:
!bt
\[ r = \frac{N^{n+1}-N^n}{N^n\Delta t} \]
!et
Use experimental data in the fraction, say $t_1=600$, $t_2=1200$,
$N^1=140$, $N^2=250$: $r=0.0013$.
!eblock
!split
===== A program relevant for the biological problem =====
# exact r = 0.000694
!bblock
@@@CODE ../../Programs/LifeScience/ecoli.py
Change `r` in the program and play around to make a better fit!
!eblock
!split
===== We shall model a very complex phenomenon by simple math.... =====
!bblock Assumptions:
* We consider a perfectly mixed population in a confined area
* No spatial transport, just temporal evolution
* We do not consider individuals, just a grand mix of them<linebreak>
(cf. statistical mechanics vs thermodynamics)
!eblock
!bpop
!bblock (small)
We consider very simple models, but these can be extended to full
models that are used world-wide by health authorities. Typical
diseases modeled are flu, measles, swine flu, HIV, ...
!eblock
!epop
!split
===== We keep track of 3 categories in the SIR model =====
!bblock
* _S_: susceptibles - who can get the disease
* _I_: infected - who have developed the disease and infect susceptibles
* _R_: recovered - who have recovered and become immune
!eblock
!bblock Mathematical quantities:
$S(t)$, $I(t)$, $R(t)$: no of people in each category
!eblock
!bblock Goal:
Find and solve equations for $S(t)$, $I(t)$, $R(t)$
!eblock
FIGURE: [fig/categories_SIR, width=400 frac=0.5]
!split
===== The traditional modeling approach is very mathematical - our idea is to model, program and experiment =====
!bblock
* Numerous books on mathematical biology treat the SIR model
* Quick modeling step (max 2 pages)
* Nonlinear differential equation model
* Cannot solve the equations, so focus is on discussing
stability (eigenvalues), qualitative properties, etc.
* Very few extensions of the model to real-life situations
!eblock
!split
===== Dynamics in a time interval $\Delta t$: $\Delta t\,\beta SI$ people move from S to I =====
!bblock S-I interaction:
* In a mix of S and I people, there are $SI$ possible pairs
* A certain fraction $\Delta t\,\beta$ of $SI$ meet in a (small)
time interval $\Delta t$, with the result that the infected
``successfully'' infects the susceptible
* The loss $\Delta t\,\beta SI$ in the S catogory is a corresponding
gain in the I category
!eblock
!bpop
!bblock (small) Remark
It is reasonable that the fraction depends on $\Delta t$
(twice as many infected in $2\Delta t$ as in $\Delta t$).
$\beta$ is some unknown parameter we must measure, supposed to not
depend on $\Delta t$, but maybe time $t$.
$\beta$ lumps *a lot* of biological and sociological effects into
one number.
!eblock
!epop
!split
===== For practical calculations, we must express the S-I interaction with symbols =====
Loss in $S(t)$ from time $t$ to $t+\Delta t$:
!bt
\[ S(t+\Delta t) = S(t) - \Delta t\,\beta S(t)I(t)\]
!et
Gain in $I(t)$:
!bt
\[ I(t+\Delta t) = I(t) + \Delta t\,\beta S(t)I(t)\]
!et
!split
===== Modeling the interaction between R and I =====
!bblock R-I interaction:
* After some days, the infected has recovered and moves to the R category
* A simple model: in a small time $\Delta t$ (say 1 day),
a fraction $\Delta t\,\nu$ of the infected are removed
($\nu$ must be measured)
!eblock
We must subtract this fraction in the balance equation for $I$:
!bt
\[ I(t+\Delta t) = I(t) + \Delta t\,\beta S(t)I(t) -\Delta t\,\nu I(t) \]
!et
The loss $\Delta t\,\nu I$ is a gain in $R$:
!bt
\[ R(t+\Delta t) = R(t) + \Delta t\,\nu I(t)\]
!et
!split
===== We have three equations for $S$, $I$, and $R$ =====
!bt
\begin{align}
S(t+\Delta t) &= S(t) - \Delta t\,\beta S(t)I(t)
label{SIR1:S}\\
I(t+\Delta t) &= I(t) + \Delta t\,\beta S(t)I(t) -\Delta t\nu I(t)
label{SIR1:I}\\
R(t+\Delta t) &= R(t) + \Delta t\,\nu I(t)
label{SIR1:R}
\end{align}
!et
FIGURE: [fig/categories_SIR, width=400 frac=0.5]
Before we can compute with these, we must
* know $\beta$ and $\nu$
* know $S(0)$ (many), $I(0)$ (few), $R(0)$ (0?)
* choose $\Delta t$
!split
===== The computation involves just simple arithmetics =====
* Set $\Delta t=6$ minutes
* Set $\beta =0.0013$, $\nu =0.8333$
* Set $S(0)=50$, $I(0)=1$, $R(0)=0$
!bt
\begin{align*}
S(\Delta t) &= S(0) - \Delta t\,\beta S(0)I(0)\approx 49.99\\
I(\Delta t) &= I(0) + \Delta t\,\beta S(0)I(0) -\Delta t\,\nu I(0)\approx 1.002\\
R(\Delta t) &= R(0) + \Delta t\,\nu I(0)\approx 0.0008333
\end{align*}
!et
!bpop
* In reality, $S$, $I$, $R$ are integers and events are discrete (meet, get sick)
* In the model, we work with real numbers and continuous events
* Reasonable approximation in a not too small population
!epop
!split
===== And we can continue... =====
!bt
\begin{align*}
S(2\Delta t) &= S(\Delta t) - \Delta t\,\beta S(\Delta t)I(\Delta t)\approx 49.87\\
I(2\Delta t) &= I(\Delta t) + \Delta t\,\beta S(\Delta t)I(\Delta t) -\Delta t\,\nu I(\Delta t)\approx 1.011\\
R(2\Delta t) &= R(\Delta t) + \Delta t\,\nu I(\Delta t)\approx 0.00167
\end{align*}
!et
Repeat...
!bt
\begin{align*}
S(3\Delta t) &= S(2\Delta t) - \Delta t\,\beta S(2\Delta t)I(2\Delta t)\approx 49.98\\
I(3\Delta t) &= I(2\Delta t) + \Delta t\,\beta S(2\Delta t)I(2\Delta t) -\Delta t\,\nu I(2\Delta t)\approx 1.017\\
R(3\Delta t) &= R(2\Delta t) + \Delta t\,\nu I(2\Delta t)\approx 0.0025
\end{align*}
!et
!bpop
But this is getting boring! Let's ask a computer to do the work!
!epop
!split
===== First, some handy notation =====
!bt
\[ S^n = S(n\Delta t),\quad I^n = I(n\Delta t),\quad R^n = R(n\Delta t)\]
!et
!bt
\[ S^{n+1} = S((n+1)\Delta t),\quad I^{n+1} = I((n+1)\Delta t),\quad R^{n+1} = R((n+1)\Delta t)\]
!et
The equations can now be written more compactly (and computer friendly):
!bt
\begin{align}
S^{n+1} &= S^n - \Delta t\,\beta S^nI^n
label{SIR1:Sc}\\
I^{n+1} &= I^n + \Delta t\,\beta S^nI^n -\Delta t\,\nu I^n
label{SIR1:Ic}\\
R^{n+1} &= R^n + \Delta t\,\nu I^n
label{SIR1:Rc}
\end{align}
!et
!split
===== With variables, arrays, and a loop we can program =====
Suppose we want to compute until $t=N\Delta t$, i.e., for $n=0,1,\ldots,N-1$.
We can store $S^0, S^1, S^2, \ldots, S^N$ in an array (or list).
Python (Matlab):
!bc pycod
t = linspace(0, N*dt, N+1) # all time points
S = zeros(N+1)
I = zeros(N+1)
R = zeros(N+1)
for n in range(N):
S[n+1] = S[n] - dt*beta*S[n]*I[n]
I[n+1] = I[n] + dt*beta*S[n]*I[n] - dt*nu*I[n]
R[n+1] = R[n] + dt*nu*I[n]
!ec
!split
===== Here is the complete program =====
!bc pycod
beta = 0.0013
nu =0.8333
dt = 0.1 # 6 min (time measured in hours)
D = 30 # simulate for D days
N = int(D*24/dt) # corresponding no of hours
from numpy import zeros, linspace
t = linspace(0, N*dt, N+1)
S = zeros(N+1)
I = zeros(N+1)
R = zeros(N+1)
for n in range(N):
S[n+1] = S[n] - dt*beta*S[n]*I[n]
I[n+1] = I[n] + dt*beta*S[n]*I[n] - dt*nu*I[n]
R[n+1] = R[n] + dt*nu*I[n]
# Plot the graphs
from matplotlib.pyplot import *
plot(t, S, 'k-', t, I, 'b-', t, R, 'r-')
legend(['S', 'I', 'R'], loc='lower right')
xlabel('hours')
show()
!ec
!split
===== We have predicted a disease! =====
FIGURE: [fig/SIR1, width=800]
!split
===== How much math and programming did we use? =====
!bblock Math:
* Plain arithmetics
* The concept of a graph (i.e., discrete function in time)
* Units
* Greek letters
!eblock
!bblock Programming:
* Variable
* Array
* Loop
* Plotting
!eblock
!split
===== Detour: The standard mathematical approach =====
We had from intuition established
!bt
\begin{align*}
S(t+\Delta t) &= S(t) - \Delta t\,\beta S(t)I(t)\\
I(t+\Delta t) &= I(t) + \Delta t\,\beta S(t)I(t) -\Delta t\,\nu I(t)\\
R(t+\Delta t) &= R(t) + \Delta t\,\nu R(t)
\end{align*}
!et
The mathematician will now make *differential equations*.
Divide by $\Delta t$ and rearrange:
!bt
\begin{align*}
\frac{S(t+\Delta t) - S(t)}{\Delta t} &= - \beta S(t)I(t)\\
\frac{I(t+\Delta t) - I(t)}{\Delta t} &= \beta t S(t)I(t) -\nu I(t)\\
\frac{R(t+\Delta t) - R(t)}{\Delta t} &= \nu R(t)
\end{align*}
!et
!split
===== A derivative arises as $\Delta t\rightarrow 0$ =====
In any calculus book, the derivative of $S$ at $t$ is defined as
!bt
\[ S'(t) = \lim_{t\rightarrow 0}\frac{S(t+\Delta t) - S(t)}{\Delta t}\]
!et
If we let $\Delta t\rightarrow 0$, we get derivatives on the left-hand side:
!bt
\begin{align*}
S'(t) &= - \beta S(t)I(t)\\
I'(t) &= \beta t S(t)I(t) -\nu I(t)\\
R'(t) &= \nu R(t)
\end{align*}
!et
This is a 3x3 system of differential equations for the functions
$S(t)$, $I(t)$, $R(t)$. For a unique solution, we need
$S(0)$, $I(0)$, $R(0)$.
!split
===== Bad news: we cannot solve these equations! =====
!bblock Time to ask a numerical methods expert:
Replace the derivative with a *finite difference*, e.g.,
!bt
\[ S'(t) \approx \frac{S(t+\Delta t) - S(t)}{\Delta t}\]
!et
which is accurate for small $\Delta t$.
!eblock
This brings us back to the first model, which we can solve
on a computer!
% if EXTRA:
!split
===== SIR is an ideal model for teaching modeling =====
!bquestion
``I believe genes are important for spreading of diseases. It's not
included in the model.''
!equestion
% endif
!split
===== Parameter estimation is needed for predictive modeling =====
* Any small $\Delta t$ will do
* One can reason about $\nu$ and say that $1/\nu$ is the mean
recovery time for the disease (e.g., 1 week for a flu)
* $\beta$ must in some way be measured, but we don't know what it means...
!bblock So, what if we don't know $\beta$?
* Can still learn about the *dynamics* of diseases
* Can find the sensitivity to and influence of $\beta$
* Can apply *parameter estimation* procedures to fit $\beta$ to data
!eblock
!split
===== Let us extend the model: no life-long immunity =====
!bblock Assumption
After some time, people in the R category lose the immunity.
In a small time $\Delta t$ this gives a leakage $\Delta t\,\gamma R$
to the S category. ($1/\gamma$ is the mean time for immunity.)
!eblock
FIGURE: [fig/categories_SIR_feedback, width=400 frac=0.5]
!bt
\begin{align}
S^{n+1} &= S^n - \Delta t\,\beta S^nI^n + {\color{red}\Delta t\,\gamma R^n}
label{SIR2:S}\\
I^{n+1} &= I^n + \Delta t\,\beta S^nI^n -\Delta t\,\nu I^n
label{SIR2:I}\\
R^{n+1} &= R^n + \Delta t\,\nu R^n - {\color{red}\Delta t\,\gamma R^n}
label{SIR2:R}
\end{align}
!et
No complications in the computational model!
!split
===== The effect of loss of immunity =====
$1/\gamma = 50$ days. $\beta$ reduced by 2 and 4 (left and right, resp.):
FIGURE: [fig/SIR2, width=950]
!split
===== What is the effect of vaccination? =====
!bblock Assumptions
A fraction $p$ of the S category, per time unit, is vaccinated with
success. Then in time $\Delta t$, $p\Delta t S$ will move to a
vaccinated category, V. This does not affect the I and R categories.
!eblock
FIGURE: [fig/categories_SIRV, width=400 frac=0.3]
!bt
\begin{align}
S^{n+1} &= S^n - \Delta t\,\beta S^nI^n + \Delta t\,\gamma R^n - {\color{red}p\Delta t S^n}
label{SIR3:S}\\
V^{n+1} &= V^n + {\color{red}p\Delta t S^n}
label{SIR3:V}\\
I^{n+1} &= I^n + \Delta t\,\beta S^nI^n -\Delta t\,\nu I^n
label{SIR3:I}\\
R^{n+1} &= R^n + \Delta t\,\nu R^n - \Delta t\,\gamma R^n
label{SIR3:R}
\end{align}
!et
# #if FORMAT not in ("latex", "pdflatex")
# Too much for Beamer...
Implementation: Just add array for $V^n$ and add equation.
# #endif
!split
===== Many possibilities for adjusting the model... =====
The effect of vaccination decreases over time, so we may move people back to
the S category (term proportional to $\Delta t V$).
FIGURE: [fig/categories_SIRV_feedback, width=400 frac=0.5]
!split
===== Effect of adding vaccination =====
FIGURE: [fig/SIRV1, width=800 frac=0.8]
($p=0.0005$)
!split
===== What is the effect of an intensive vaccination campaign? =====
10 times more intense vaccination for 10 days, 6 days after outbreak:
!bt
\begin{equation*} p(t) = \left\lbrace\begin{array}{ll}
0.005,& 6\leq t\leq 15,\\
0,& \hbox{otherwise} \end{array}\right.\end{equation*}
!et
Implementation: Let $p^n$ be an array as $V^n$. Set $p^n=0.05$ for
$n=6\cdot 24/0.1,\ldots, 15\cdot 24/0.1$ ($\mbox{days}\cdot 24 /\Delta t$, 24 is hours per day).
FIGURE: [fig/p_discont, width=400 frac=0.5]
!split
===== Effect of vaccination campaign =====
FIGURE: [fig/SIRV2, width=500 frac=0.6]
Note:
* Mathematicians would be scared by the cusps on the curves...
* Could now let the computer run a lot of cases and find the optimal
vaccination period
!split
===== We can experiment with other campaigns =====
!bslidecell 00 0.3
FIGURE: [fig/disease2.jpg, width=400]
!eslidecell
!bslidecell 01 0.7
Wearing masks lowers $\beta$:
!bt
\begin{equation*} \beta(t) = \left\lbrace\begin{array}{ll}
\beta_1,& 0\leq t < 5,\\
\beta_2 < \beta_1,& t \geq 5\end{array}\right.
\end{equation*}
!et
Very easy to implement. (Used to be complicated in differential
equation models...)
!eslidecell
!split
===== And now for something similar: zombification! =====
FIGURE: [fig/zombie1, width=900]
_Zombification_: The disease that turns you into a zombie.
!split
===== Zombie modeling is almost the same as SIR modeling =====
!bblock Categories
o S: susceptible humans who can become zombies
o I: infected humans, being bitten by zombies
o Z: zombies
o R: removed individuals, either conquered zombies or dead humans
!eblock
Mathematical quantities: $S(t)$, $I(t)$, $Z(t)$, $R(t)$
Zombie movie: *The Night of the Living Dead*, Geoerge A. Romero, 1968
!split
===== Dynamics of the zombie SIZR model =====
FIGURE: [fig/categories_SIZR, width=380 frac=0.4]
!bpop
o Susceptibles are infected by zombies: $-\Delta t\beta SZ$ in time $\Delta t$ (cf. the $\Delta t\,\beta SI$ term in the SIR model).
o Susceptibles die naturally or get killed and then enter the removed category. The no of deaths in time $\Delta t$ is $\Delta t\delta_S S$.
o We also allow new humans to enter the area with zombies (necessary in a war on zombies): $\Delta t\Sigma$ during a time $\Delta t$.
o Some infected turn into zombies (Z): $\Delta t\rho I$, while others die (R): $\delta_I\Delta t I$.
o Nobody from R can turn into Z (important - otherwise zombies win).
o Killed zombies go to R: $\Delta t\alpha SZ$.
!epop
!split
===== The four equations in the SIZR model for zombification =====
!bt
\begin{align*}
S^{n+1} &= S^n + \Delta t\,\Sigma - \Delta t\,\beta S^nZ - \Delta t\,\delta_S S^n\\
I^{n+1} &= I^n + \Delta t\,\beta S^nZ^n - \Delta t\,\rho I^n - \Delta t\,\delta_I I^n\\
Z^{n+1} &= Z^n + \Delta t\,\rho I^n - \Delta t\,\alpha S^nZ^n\\
R^{n+1} &= R^n + \Delta t\,\delta_S S^n + \Delta t\,\delta_I I^n +
\Delta t\,\alpha S^nZ^n
\end{align*}
!et
!bblock (small) Interpretation of parameters:
* $\Sigma$: no of new humans brought into the zombified area per unit time.
* $\beta$: the probability that a theoretically possible human-zombie pair actually meets physically, during a unit time interval, with the result that the human is infected.
* $\delta_S$: the probability that a susceptible human is killed or dies, in a unit time interval.
* $\delta_I$: the probability that an infected human is killed or dies, in a unit time interval.
* $\rho$: the probability that an infected human is turned into a zombie, during a unit time interval.
* $\alpha$: the probability that, during a unit time interval, a theoretically possible human-zombie pair fights and the human kills the zombie.
!eblock
!split
===== Simulate a zombie movie! =====
!bslidecell 00 0.6
!bblock Three fundamental phases
o The initial phase (4 h)
o The hysteric phase (24 h)
o The counter attack phase (5 h)
!eblock
!eslidecell
!bslidecell 01 0.4
FIGURE: [fig/TNotLD, width=300]
!eslidecell
!bpop
How do we do this? As $p$ in the vaccination campaign - the parameters
take on different constant values in different time intervals.
!epop
!bpop
H. P. Langtangen, K.-A. Mardal and P. Røtnes:
Escaping the Zombie Threat by Mathematics, in
A. Whelan et al.: *Zombies in the Academy - Living Death in Higher Education*,
University of Chicago Press, 2013
!epop
!split
===== Effective war on zombies =====
Introduce attacks on zombies at selected times $T_0, T_1, \ldots, T_m$.
Model: Replace $\alpha$ by
!bt
\[ \alpha_0 + \omega (t),\]
!et
where $\alpha_0$ is constant and $\omega(t)$ is a series of
Gaussian functions (peaks) in time:
!bt
\[ \omega(t) = a\sum_{i=0}^m \exp{\left(-\frac{1}{2}\left({t - T_i\over\sigma}\right)\right)}
\]
!et
Must experiment with values of $a$ (strength), $\sigma$ (duration is $6\sigma$),
point of attacks ($T_i$) - with proper values humans beat the zombies!
!split
===== Summary =====
* A complex spreading of diseases can be modeled by intuitive, simple
accounting of movement between categories
* Such models are knowns as *compartment models*
* Result: difference equations that are easy to simulate on a computer
* (Can let $\Delta t\rightarrow 0$ and get differential equations)
* Easy to add new effects (vaccination, campaigns, zombification)
===== Theoretical background and description of the system =====
The aim of this project is to simulate financial transactions among financial agents
using Monte Carlo methods. The final goal is to extract a distribution of income as function
of the income $m$. From Pareto's work ("V.~Pareto, 1897":"http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto") it is known from empirical studies
that the higher end of the distribution of money follows a distribution
!bt
\[
w_m\propto m^{-1-\alpha},
\]
!et
with $\alpha\in [1,2]$. We will here follow the analysis made by "Patriarca and collaborators":"http://www.sciencedirect.com/science/article/pii/S0378437104004327".
Here we will study numerically the relation between the micro-dynamic relations among financial
agents and the resulting macroscopic money distribution.
We assume we have $N$ agents that exchange money in pairs $(i,j)$. We assume also that all agents
start with the same amount of money $m_0 > 0$. At a given 'time step', we choose randomly a pair
of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes
to $m_i'$ and similarly we have $m_j\rightarrow m_j'$.
Money is conserved during a transaction, meaning that
!bt
\begin{equation}
m_i+m_j=m_i'+m_j'.
label{eq:conserve}
\end{equation}
!et
The change is done via a random reassignement (a random number) $\epsilon$, meaning that
!bt
\begin{equation*}
m_i' = \epsilon(m_i+m_j),
\end{equation*}
!et
leading to
!bt
\begin{equation*}
m_j'= (1-\epsilon)(m_i+m_j).
\end{equation*}
!et
The number $\epsilon$ is extracted from a uniform distribution.
In this simple model, no agents are left with a debt, that is $m\ge 0$.
Due to the conservation law above, one can show that the system relaxes toward an equilibrium
state given by a Gibbs distribution
!bt
\begin{equation*}
w_m=\beta \exp{(-\beta m)},
\end{equation*}
!et
with
!bt
\begin{equation*}
\beta = \frac{1}{\langle m\rangle},
\end{equation*}
!et
and $\langle m\rangle=\sum_i m_i/N=m_0$, the average money.
It means that after equilibrium has been reached that the majority of agents is left with a small
number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$,
exponentially decreases with $m'$.
We assume that we have $N=500$ agents. In each simulation, we need a sufficiently large number of transactions, say $10^7$. Our aim is find the final equilibrium distribution $w_m$. In order to do that we would need
several runs of the above simulations, at least $10^3-10^4$ runs (experiments).
=== Project 4a): Simulation of Transactions ===
Your task is to first set up an algorithm which simulates the above transactions with an initial
amount $m_0$.
The challenge here is to figure out a Monte Carlo simulation based on the
above equations.
You will in particular need to make an algorithm which sets up a histogram as function of $m$.
This histogram contains the number of times a value $m$ is registered and represents
$w_m\Delta m$. You will need to set up a value for the interval $\Delta m$ (typically $0.01-0.05$).
That means you need to account for the number of times you register an income in the interval
$m,m+\Delta m$. The number of times you register this income, represents the value that enters the histogram.
You will also need to find a criterion for when the equilibrium situation has been reached.
=== Project 4b): Recognizing the distribution ===
Make thereafter a plot of $\log{(w_m)}$ as function of $m$
and see if you get a straight line.
Comment the result.
=== Project 4c): Transactions and savings ===
We can then change our model to allow for a saving criterion, meaning that the agents save
a fraction $\lambda$ of the money they have before the transaction is made. The final distribution will then no longer be given by Gibbs distribution. It could also include a taxation on financial transactions.
The conservation law of Eq. (ref{eq:conserve}) holds, but the money to be shared in a transaction between
agent $i$ and agent $j$ is now $(1-\lambda)(m_i+m_j)$. This means that we have
!bt
\begin{equation*}
m_i' = \lambda m_i+\epsilon(1-\lambda)(m_i+m_j),
\end{equation*}
!et
and
!bt
\begin{equation*}
m_j' = \lambda m_j+(1-\epsilon)(1-\lambda)(m_i+m_j),
\end{equation*}
!et
which can be written as
!bt
\begin{equation*}
m_i'=m_i+\delta m
\end{equation*}
!et
and
!bt
\begin{equation*}
m_j'=m_j-\delta m,
\end{equation*}
!et
with
!bt
\begin{equation*}
\delta m=(1-\lambda)(\epsilon m_j-(1-\epsilon)m_i),
\end{equation*}
!et
showing how money is conserved during a transaction.
Select values of $\lambda =0.25,0.5$ and $\lambda=0.9$ and try to extract the corresponding
equilibrium distributions and compare these with the Gibbs distribution. Comment your results.
Extract a parametrization of the above curves, see for example "Patriarca and collaborators":"http://www.sciencedirect.com/science/article/pii/S0378437104004327" and see if you can parametrize the high-end tails of the distributions in terms of power laws. Comment your results.
=== Project 4d): Nearest neighbor interactions ===
In the rest of this project we will follow the work of "Goswami and Sen":"http://www.sciencedirect.com/science/article/pii/S0378437114006967".
In the studies above the agents were selected randomly, irrespective of whether we allowed for
saving or not during a transaction. What is often observed is that various agents tend to make preferences for for whom to interact with. We will now study the evolution of the distribution of wealth $w_m$ by assuming that there is a likelihood
!bt
\[
p_{ij} \propto \vert m_i-m_j\vert^{-\alpha},
\]
!et
for an interaction between agents $i$ and $j$ with respective wealths $m_i$ and $m_j$. The parameter $\alpha > 0$. For $\alpha=0$ we recover our model from part 5a).
Perform the same analysis as previously with $N=500$ as well as with $N=1000$ agents and study the distribution of wealth for $\alpha =0.5$, $\alpha =1.0$, $\alpha =1.5$ and $\alpha =2.0$.
You should try to reproduce Figure 1 of "Goswami and Sen":"http://www.sciencedirect.com/science/article/pii/S0378437114006967".
Extract the tail of the distribution and see if it follows a Pareto distribution
!bt
\[
w_m\propto m^{-1-\alpha}.
\]
!et
What happens if $\alpha \gg 1$?
Perform the analysis with and without a saving $\lambda$ on each transaction and comment your results.
=== Project 4e): Nearest neighbors and former transactions ===
We add to the previous probability the possibility that two agents who interact have performed similar transactions earlier. That is, in addition to being financially close, we assume that the likelihood for interacting increases if two agents have interacted earlier.
We add this feature by modifying the previous likelihood to
!bt
\[
p_{ij} \propto \vert m_i-m_j\vert^{-\alpha}\left(c_{ij}+1\right)^{\gamma},
\]
!et
where $c_{ij}$ represents the number of previous interactions that have taken place between $i$ and $j$. The factor $1$ is added in order to ensure that if they have not interacted earlier they can still interact. Perform similar studies as above with $N=1000$, $\alpha=1.0$ and $\alpha=2.0$ using $\gamma = 0.0, 1.0, 2.0, 3.0$ and $4.0$. Plot the wealth distributions for these cases and try to extract eventual power law tails with and without a saving $\lambda$ in each transaction. Comment your results and compare them with figures 5 and 6 of "Goswami and Sen":"http://www.sciencedirect.com/science/article/pii/S0378437114006967".
Finally, (this part is optional) if you have time, which features would you add to these models in order to make them even more realistic?
===== Background literature =====
* "V. Pareto, Cours d'economie politique, Lausanne, 1897":"http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto".
* "M. Patriarca, A. Chakraborti, K. Kaski, Physica A _340_, 334 (2004)":"http://www.sciencedirect.com/science/article/pii/S0378437104004327".
* "S. Goswami and P. Sen, Physica A _415_, 514 (2014)":"http://www.sciencedirect.com/science/article/pii/S0378437114006967".
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB