-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent_model.py
105 lines (80 loc) · 2.77 KB
/
agent_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
'''
Simple agent-based model in Python; compare with sir_model.py
'''
import numpy as np
import pylab as pl
# Set parameters
beta = 2.5 # Infection rate
gamma = 1.0 # Recovery rate
I0 = 5 # Number of people initially infected
N = 100 # Total population size
maxtime = 10 # How long to simulate for
npts = 100 # Number of time points during the simulation
dt = maxtime/npts # Timestep length
# Create the arrays -- one entry per timestep
x = np.arange(npts)
S = np.zeros(npts)
I = np.zeros(npts)
R = np.zeros(npts)
time = x*dt
S[0] = N - I0 # Set initial conditions
I[0] = I0
# Define each person
class Person:
def __init__(self):
self.S = True # People start off susceptible
self.I = False
self.R = False
def infect(self):
self.S = False
self.I = True
def recover(self):
self.I = False
self.R = True
def check_infect(self, other):
if self.S: # A person must be susceptible to be infected
if other.I: # The other person must be infectious
if np.random.rand() < beta/N*dt: # Infection is probabilistic
self.infect()
return
def check_recovery(self):
if self.I: # A person must be infected to recover
if np.random.rand() < gamma*dt: # Recovery is also probabilistic
self.recover()
return
# Define the population
class Population:
def __init__(self):
self.people = [Person() for i in range(N)] # Create all the people
for person in self.people[0:I0]: # Make the first I0 people infectious
person.infect() # Set the initial conditions
def count_S(self): # Count how many people are susceptible
return sum([person.S for person in self.people])
def count_I(self):
return sum([person.I for person in self.people])
def count_R(self):
return sum([person.R for person in self.people])
def check_infections(self): # CHeck which infectious occur
for person1 in self.people:
for person2 in self.people:
person1.check_infect(person2)
def check_recoveries(self): # Check which recoveries occur
for person in self.people:
person.check_recovery()
# Create the population
pop = Population()
# Run the simulation
for t in x[:-1]:
pop.check_infections() # CHeck which infectious occur
pop.check_recoveries() # Check which recoveries occur
S[t+1] = pop.count_S() # Count the current number of susceptible people
I[t+1] = pop.count_I()
R[t+1] = pop.count_R()
# Plot
pl.plot(time, S, label='Susceptible')
pl.plot(time, I, label='Infectious')
pl.plot(time, R, label='Recovered')
pl.legend()
pl.xlabel('Time')
pl.ylabel('Number of people')
pl.show()