forked from hnekoeiq/covid_p2p_simulation
/
base.py
229 lines (189 loc) · 7.43 KB
/
base.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import simpy
import datetime
import itertools
from orderedset import OrderedSet
from config import TICK_MINUTE, MAX_DAYS_CONTAMINATION
from utils import compute_distance
class Env(simpy.Environment):
def __init__(self, initial_timestamp):
super().__init__()
self.initial_timestamp = initial_timestamp
def time(self):
return self.now
@property
def timestamp(self):
return self.initial_timestamp + datetime.timedelta(
minutes=self.now * TICK_MINUTE)
def minutes(self):
return self.timestamp.minute
def hour_of_day(self):
return self.timestamp.hour
def day_of_week(self):
return self.timestamp.weekday()
def is_weekend(self):
return self.day_of_week() in [0, 6]
def time_of_day(self):
return self.timestamp.isoformat()
class City(object):
def __init__(self, stores, parks, humans, miscs):
self.stores = stores
self.parks = parks
self.humans = humans
self.miscs = miscs
self._compute_preferences()
@property
def events(self):
return list(itertools.chain(*[h.events for h in self.humans]))
def _compute_preferences(self):
""" compute preferred distribution of each human for park, stores, etc."""
for h in self.humans:
h.stores_preferences = [(compute_distance(h.household, s) + 1e-1) ** -1 for s in self.stores]
h.parks_preferences = [(compute_distance(h.household, s) + 1e-1) ** -1 for s in self.parks]
class Location(simpy.Resource):
def __init__(self, env, rng, capacity=simpy.core.Infinity, name='Safeway', location_type='stores', lat=None,
lon=None, area=None, cont_prob=None, surface_prob=[0.2, 0.2, 0.2, 0.2, 0.2]):
super().__init__(env, capacity)
self.humans = OrderedSet() #OrderedSet instead of set for determinism when iterating
self.name = name
self.rng = rng
self.lat = lat
self.lon = lon
self.area = area
self.location_type = location_type
self.social_contact_factor = cont_prob
self.env = env
self.contamination_timestamp = datetime.datetime.min
self.contaminated_surface_probability = surface_prob
self.max_day_contamination = 0
def infectious_human(self):
return any([h.is_infectious for h in self.humans])
def __repr__(self):
return f"{self.name} - occ:{len(self.humans)}/{self.capacity} - I:{self.infectious_human()}"
def add_human(self, human):
self.humans.add(human)
if human.is_infectious:
self.contamination_timestamp = self.env.timestamp
rnd_surface = float(self.rng.choice(a=MAX_DAYS_CONTAMINATION, size=1, p=self.contaminated_surface_probability))
self.max_day_contamination = max(self.max_day_contamination, rnd_surface)
def remove_human(self, human):
self.humans.remove(human)
@property
def is_contaminated(self):
return self.env.timestamp - self.contamination_timestamp <= datetime.timedelta(days=self.max_day_contamination)
@property
def contamination_probability(self):
if self.is_contaminated:
lag = (self.env.timestamp - self.contamination_timestamp)
lag /= datetime.timedelta(days=1)
p_infection = 1 - lag / self.max_day_contamination # linear decay; &envrionmental_contamination
return self.social_contact_factor * p_infection
return 0.0
def __hash__(self):
return hash(self.name)
class Event:
test = 'test'
encounter = 'encounter'
symptom_start = 'symptom_start'
contamination = 'contamination'
recovered = 'recovered'
@staticmethod
def members():
return [Event.test, Event.encounter, Event.symptom_start, Event.contamination]
@staticmethod
def log_encounter(human1, human2, location, duration, distance, time):
h_obs_keys = ['obs_lat', 'obs_lon', 'age', 'reported_symptoms', 'test_results', 'has_app']
h_unobs_keys = ['carefullness', 'viral_load', 'infectiousness', 'symptoms', 'is_exposed', 'is_infectious']
loc_obs_keys = ['location_type', 'lat', 'lon']
loc_unobs_keys = ['contamination_probability', 'social_contact_factor']
obs, unobs = [], []
for human in [human1, human2]:
o = {key:getattr(human, key) for key in h_obs_keys}
obs.append(o)
u = {key:getattr(human, key) for key in h_unobs_keys}
u['is_infected'] = human.is_exposed or human.is_infectious
u['human_id'] = human.name
unobs.append(u)
loc_obs = {key:getattr(location, key) for key in loc_obs_keys}
loc_unobs = {key:getattr(location, key) for key in loc_unobs_keys}
loc_unobs['location_p_infection'] = location.contamination_probability / location.social_contact_factor
other_obs = {'duration':duration, 'distance':distance}
both_have_app = human1.has_app and human2.has_app
for i, human in [(0, human1), (1, human2)]:
if both_have_app:
obs_payload = {**loc_obs, **other_obs, 'human1':obs[i], 'human2':obs[1-i]}
unobs_payload = {**loc_unobs, 'human1':unobs[i], 'human2':unobs[1-i]}
else:
obs_payload = {}
unobs_payload = { **loc_obs, **loc_unobs, **other_obs, 'human1':{**obs[i], **unobs[i]},
'human2': {**obs[1-i], **unobs[1-i]} }
human.events.append({
'human_id':human.name,
'event_type':Event.encounter,
'time':time,
'payload':{ 'observed':obs_payload, 'unobserved':unobs_payload }
})
@staticmethod
def log_test(human, result, time):
human.events.append(
{
'human_id': human.name,
'event_type': Event.test,
'time': time,
'payload': {
'observed':{
'result': result,
},
'unobserved':{
}
}
}
)
@staticmethod
def log_symptom_start(human, covid, time):
human.events.append(
{
'human_id': human.name,
'event_type': Event.symptom_start,
'time': time,
'payload': {
'observed':{
},
'unobserved':{
'covid': covid
}
}
}
)
@staticmethod
def log_exposed(human, time):
human.events.append(
{
'human_id': human.name,
'event_type': Event.contamination,
'time': time,
'payload': {
'observed':{
},
'unobserved':{
'exposed': True
}
}
}
)
@staticmethod
def log_recovery(human, time, death):
human.events.append(
{
'human_id': human.name,
'event_type': Event.recovered,
'time': time,
'payload': {
'observed':{
},
'unobserved':{
'recovered': not death,
'death': death
}
}
}
)