-
Notifications
You must be signed in to change notification settings - Fork 33
/
dynamics.py
2094 lines (1703 loc) · 94.5 KB
/
dynamics.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import bisect
import numpy as np
import pandas as pd
import networkx as nx
import scipy
import scipy.optimize
import scipy as sp
import os, math
import matplotlib.pyplot as plt
from joblib import Parallel, delayed
from sympy import Symbol, integrate, lambdify, exp, Max, Min, Piecewise, log
import pprint
from collections import Counter
from lib.priorityqueue import PriorityQueue
from lib.measures import *
TO_HOURS = 24.0
class DiseaseModel(object):
"""
Simulate continuous-time SEIR epidemics with exponentially distributed inter-event times.
All units in the simulator are in hours for numerical stability, though disease parameters are
assumed to be in units of days as usual in epidemiology
"""
def __init__(self, mob, distributions):
"""
Init simulation object with parameters
Arguments:
---------
mob:
object of class MobilitySimulator providing mobility data
"""
# cache settings
self.mob = mob
self.d = distributions
assert(np.allclose(np.array(self.d.delta), np.array(self.mob.delta), atol=1e-3))
# parse distributions object
self.lambda_0 = self.d.lambda_0
self.gamma = self.d.gamma
self.fatality_rates_by_age = self.d.fatality_rates_by_age
self.p_hospital_by_age = self.d.p_hospital_by_age
self.delta = self.d.delta
# parse mobility object
self.n_people = mob.num_people
self.n_sites = mob.num_sites
self.max_time = mob.max_time
# special state variables from mob object
self.people_age = mob.people_age
self.num_age_groups = mob.num_age_groups
self.site_type = mob.site_type
self.site_dict = mob.site_dict
self.num_site_types = mob.num_site_types
self.people_household = mob.people_household # j-th entry is household index of individual j
self.households = mob.households # {household index: [individuals in household]}
assert(self.num_age_groups == self.fatality_rates_by_age.shape[0])
assert(self.num_age_groups == self.p_hospital_by_age.shape[0])
# print
self.last_print = time.time()
self._PRINT_INTERVAL = 0.1
self._PRINT_MSG = (
't: {t:.2f} '
'| '
'{maxt:.2f} hrs '
'({maxd:.0f} d)'
)
def __print(self, t, force=False):
if ((time.time() - self.last_print > self._PRINT_INTERVAL) or force) and self.verbose:
print('\r', self._PRINT_MSG.format(t=t, maxt=self.max_time, maxd=self.max_time / 24),
sep='', end='', flush=True)
self.last_print = time.time()
def __init_run(self):
"""
Initialize the run of the epidemic
"""
self.queue = PriorityQueue()
self.testing_queue = PriorityQueue()
self.isolation_queue = PriorityQueue()
self.budget_testing_queue = PriorityQueue()
'''
State and queue codes (transition event into this state)
'susc': susceptible
'expo': exposed
'ipre': infectious pre-symptomatic
'isym': infectious symptomatic
'iasy': infectious asymptomatic
'posi': tested positive
'nega': tested negative
'resi': resistant
'dead': dead
'hosp': hospitalized
'test': event of i getting a test (transitions to posi if not susc)
'execute_tests': generic event indicating that testing queue should be processed
'''
self.legal_states = ['susc', 'expo', 'ipre', 'isym', 'iasy', 'posi', 'nega', 'resi', 'dead', 'hosp']
self.legal_preceeding_state = {
'expo' : ['susc',],
'ipre' : ['expo',],
'isym' : ['ipre',],
'iasy' : ['expo',],
'posi' : ['isym', 'ipre', 'iasy', 'expo'],
'nega' : ['susc', 'resi'],
'resi' : ['isym', 'iasy'],
'dead' : ['isym',],
'hosp' : ['isym',],
}
self.state = {
'susc': np.ones(self.n_people, dtype='bool'),
'expo': np.zeros(self.n_people, dtype='bool'),
'ipre': np.zeros(self.n_people, dtype='bool'),
'isym': np.zeros(self.n_people, dtype='bool'),
'iasy': np.zeros(self.n_people, dtype='bool'),
'posi': np.zeros(self.n_people, dtype='bool'),
'nega': np.zeros(self.n_people, dtype='bool'),
'resi': np.zeros(self.n_people, dtype='bool'),
'dead': np.zeros(self.n_people, dtype='bool'),
'hosp': np.zeros(self.n_people, dtype='bool'),
}
self.state_started_at = {
'susc': - np.inf * np.ones(self.n_people, dtype='float'),
'expo': np.inf * np.ones(self.n_people, dtype='float'),
'ipre': np.inf * np.ones(self.n_people, dtype='float'),
'isym': np.inf * np.ones(self.n_people, dtype='float'),
'iasy': np.inf * np.ones(self.n_people, dtype='float'),
'posi': np.inf * np.ones(self.n_people, dtype='float'),
'nega': np.inf * np.ones(self.n_people, dtype='float'),
'resi': np.inf * np.ones(self.n_people, dtype='float'),
'dead': np.inf * np.ones(self.n_people, dtype='float'),
'hosp': np.inf * np.ones(self.n_people, dtype='float'),
}
self.state_ended_at = {
'susc': np.inf * np.ones(self.n_people, dtype='float'),
'expo': np.inf * np.ones(self.n_people, dtype='float'),
'ipre': np.inf * np.ones(self.n_people, dtype='float'),
'isym': np.inf * np.ones(self.n_people, dtype='float'),
'iasy': np.inf * np.ones(self.n_people, dtype='float'),
'posi': np.inf * np.ones(self.n_people, dtype='float'),
'nega': np.inf * np.ones(self.n_people, dtype='float'),
'resi': np.inf * np.ones(self.n_people, dtype='float'),
'dead': np.inf * np.ones(self.n_people, dtype='float'),
'hosp': np.inf * np.ones(self.n_people, dtype='float'),
}
self.outcome_of_test = np.zeros(self.n_people, dtype='bool')
# infector of i
self.parent = -1 * np.ones(self.n_people, dtype='int')
# no. people i infected (given i was in a certain state)
self.children_count_iasy = np.zeros(self.n_people, dtype='int')
self.children_count_ipre = np.zeros(self.n_people, dtype='int')
self.children_count_isym = np.zeros(self.n_people, dtype='int')
# contact tracing
# records which contact caused the exposure of `i`
self.contact_caused_expo = [None for i in range(self.n_people)]
# list of tuples (i, contacts) where `contacts` were valid when `i` got tested positive
self.valid_contacts_for_tracing = []
# evaluates an integral of the exposure rate
self.exposure_integral = self.make_exposure_int_eval()
self.exposure_rate = self.make_exposure_rate_eval() # for sanity check
# DEBUG
self.risk_got_exposed = np.zeros(11)
self.risk_got_not_exposed = np.zeros(11)
def initialize_states_for_seeds(self):
"""
Sets state variables according to invariants as given by `self.initial_seeds`
NOTE: by the seeding heuristic using the reproductive rate
we assume that exposures already took place
"""
assert(isinstance(self.initial_seeds, dict))
for state, seeds_ in self.initial_seeds.items():
for i in seeds_:
assert(self.was_initial_seed[i] == False)
self.was_initial_seed[i] = True
# inital exposed
if state == 'expo':
self.__process_exposure_event(t=0.0, i=i, parent=None, contact=None)
# initial presymptomatic
elif state == 'ipre':
self.state['susc'][i] = False
self.state['expo'][i] = True
self.state_ended_at['susc'][i] = -1.0
self.state_started_at['expo'][i] = -1.0
self.bernoulli_is_iasy[i] = 0
# no exposures added due to heuristic `expo` seeds using reproductive rate
self.__process_presymptomatic_event(0.0, i, add_exposures=False)
# initial asymptomatic
elif state == 'iasy':
self.state['susc'][i] = False
self.state['expo'][i] = True
self.state_ended_at['susc'][i] = -1.0
self.state_started_at['expo'][i] = -1.0
self.bernoulli_is_iasy[i] = 1
# no exposures added due to heuristic `expo` seeds using reproductive rate
self.__process_asymptomatic_event(0.0, i, add_exposures=False)
# initial symptomatic
elif state == 'isym' or state == 'isym_notposi':
self.state['susc'][i] = False
self.state['ipre'][i] = True
self.state_ended_at['susc'][i] = -1.0
self.state_started_at['expo'][i] = -1.0
self.state_ended_at['expo'][i] = -1.0
self.state_started_at['ipre'][i] = -1.0
self.bernoulli_is_iasy[i] = 0
self.__process_symptomatic_event(0.0, i)
# initial symptomatic and positive
elif state == 'isym_posi':
self.state['susc'][i] = False
self.state['ipre'][i] = True
self.state['posi'][i] = True
self.state_ended_at['susc'][i] = -1.0
self.state_started_at['expo'][i] = -1.0
self.state_ended_at['expo'][i] = -1.0
self.state_started_at['ipre'][i] = -1.0
self.state_started_at['posi'][i] = -1.0
self.bernoulli_is_iasy[i] = 0
self.__process_symptomatic_event(0.0, i, apply_for_test=False)
# initial resistant and positive
elif state == 'resi_posi':
self.state['susc'][i] = False
self.state['isym'][i] = True
self.state['posi'][i] = True
self.state_ended_at['susc'][i] = -1.0
self.state_started_at['expo'][i] = -1.0
self.state_ended_at['expo'][i] = -1.0
self.state_started_at['ipre'][i] = -1.0
self.state_ended_at['ipre'][i] = -1.0
self.state_started_at['isym'][i] = -1.0
self.state_started_at['posi'][i] = -1.0
self.bernoulli_is_iasy[i] = 0
self.__process_resistant_event(0.0, i)
# initial resistant and positive
elif state == 'resi_notposi':
self.state['susc'][i] = False
self.state['isym'][i] = True
self.state_ended_at['susc'][i] = -1.0
self.state_started_at['expo'][i] = -1.0
self.state_ended_at['expo'][i] = -1.0
self.state_started_at['ipre'][i] = -1.0
self.state_ended_at['ipre'][i] = -1.0
self.state_started_at['isym'][i] = -1.0
self.bernoulli_is_iasy[i] = 0
self.__process_resistant_event(0.0, i)
else:
raise ValueError('Invalid initial seed state.')
def make_exposure_int_eval(self):
'''
Returns evaluatable numpy function that computes an integral
of the exposure rate. The function returned takes the following arguments
`j_from`: visit start of j
`j_to`: visit end of j
`inf_from`: visit start of infector
`inf_to`: visit end of infector
`beta_site`: transmission rate at site
'''
# define symbols in exposure rate
beta_sp = Symbol('beta')
base_rate_sp = Symbol('base_rate')
lower_sp = Symbol('lower')
upper_sp = Symbol('upper')
a_sp = Symbol('a')
b_sp = Symbol('b')
u_sp = Symbol('u')
t_sp = Symbol('t')
# symbolically integrate term of the exposure rate over [lower_sp, upper_sp]
expo_int_symb = Max(integrate(
beta_sp *
integrate(
base_rate_sp *
self.gamma *
Piecewise((1.0, (a_sp <= u_sp) & (u_sp <= b_sp)), (0.0, True)) *
exp(- self.gamma * (t_sp - u_sp)),
(u_sp, t_sp - self.delta, t_sp)),
(t_sp, lower_sp, upper_sp)
).simplify(), 0.0)
f_sp = lambdify((lower_sp, upper_sp, a_sp, b_sp, beta_sp, base_rate_sp), expo_int_symb, 'numpy')
# define function with named arguments
def f(*, j_from, j_to, inf_from, inf_to, beta_site, base_rate):
'''Shifts to 0.0 for numerical stability'''
return f_sp(0.0, j_to - j_from, inf_from - j_from, inf_to - j_from, beta_site, base_rate)
return f
def make_exposure_rate_eval(self):
'''
Returns evaluatable numpy function that computes an integral
of the exposure rate. The function returned takes the following arguments
`inf_from`: visit start of infector
`inf_to`: visit end of infector
`beta_site`: transmission rate at site
'''
# define symbols in exposure rate
a_sp = Symbol('a')
b_sp = Symbol('b')
u_sp = Symbol('u')
t_sp = Symbol('t')
# symbolically integrate term of the exposure rate over [lower_sp, upper_sp]
expo_rate_symb = Max(
integrate(
self.gamma * \
Piecewise((1.0, (a_sp <= u_sp) & (u_sp <= b_sp)), (0.0, True)) \
* exp(- self.gamma * (t_sp - u_sp)),
(u_sp, t_sp - self.delta, t_sp)).simplify(),
0.0)
f_sp = lambdify((t_sp, a_sp, b_sp), expo_rate_symb, 'numpy')
# define function with named arguments
def f(*, t, inf_from, inf_to):
return f_sp(t, inf_from, inf_to)
return f
def launch_epidemic(self, params, initial_counts, testing_params, measure_list, thresholds_roc=[], verbose=True):
"""
Run the epidemic, starting from initial event list.
Events are treated in order in a priority queue. An event in the queue is a tuple
the form
`(time, event_type, node, infector_node, location, metadata)`
"""
self.verbose = verbose
self.thresholds_roc = thresholds_roc
# optimized params
self.betas = params['betas']
self.mu = self.d.mu
self.alpha = self.d.alpha
# household param
if 'beta_household' in params:
self.beta_household = params['beta_household']
else:
self.beta_household = 0.0
self.num_household_exposures = 0
self.num_site_exposures = 0
# testing settings
self.testing_frequency = testing_params['testing_frequency']
self.test_targets = testing_params['test_targets']
self.test_queue_policy = testing_params['test_queue_policy']
self.test_reporting_lag = testing_params['test_reporting_lag']
self.tests_per_batch = testing_params['tests_per_batch']
self.testing_t_window = testing_params['testing_t_window']
self.t_pos_tests = []
self.test_fpr = testing_params['test_fpr']
self.test_fnr = testing_params['test_fnr']
# smart tracing settings
self.smart_tracing_actions = testing_params['smart_tracing_actions']
self.smart_tracing_households_only = testing_params['smart_tracing_households_only']
self.smart_tracing_contact_delta = testing_params['smart_tracing_contact_delta']
self.smart_tracing_policy_isolate = testing_params['smart_tracing_policy_isolate']
self.smart_tracing_isolation_duration = testing_params['smart_tracing_isolation_duration']
self.smart_tracing_isolated_contacts = testing_params['smart_tracing_isolated_contacts']
self.smart_tracing_isolation_threshold = testing_params['smart_tracing_isolation_threshold']
self.smart_tracing_policy_test = testing_params['smart_tracing_policy_test']
self.smart_tracing_tested_contacts = testing_params['smart_tracing_tested_contacts']
self.smart_tracing_testing_threshold = testing_params['smart_tracing_testing_threshold']
self.smart_tracing_testing_global_budget_per_day = testing_params['smart_tracing_testing_global_budget_per_day']
self.trigger_tracing_after_posi_trace_test = testing_params['trigger_tracing_after_posi_trace_test']
self.smart_tracing_stats_window = testing_params.get(
'smart_tracing_stats_window', (0.0, self.max_time))
self.smart_tracing_p_willing_to_share = testing_params['p_willing_to_share']
self.delta_manual_tracing = testing_params['delta_manual_tracing']
if 'isolate' in self.smart_tracing_actions \
and self.smart_tracing_isolated_contacts == 0:
print('Warning: `smart_tracing_isolated_contacts` is 0 even though '
'the policy ought to isolate traced contacts')
if 'test' in self.smart_tracing_actions \
and self.smart_tracing_tested_contacts == 0:
print('Warning: `smart_tracing_isolated_contacts` is 0 even though '
'the policy ought to isolate traced contacts')
if self.smart_tracing_policy_isolate == 'advanced-threshold' \
and self.smart_tracing_isolation_threshold == 1.0:
print('Warning: `smart_tracing_isolation_threshold` is 1.0 even though '
'the policy ought to isolate contacts with empirical risk above the threshold')
if self.smart_tracing_policy_test == 'advanced-threshold' \
and self.smart_tracing_testing_threshold == 1.0:
print('Warning: `smart_tracing_testing_threshold` is 1.0 even though '
'the policy ought to test contacts with empirical risk above the threshold')
# Set list of measures
if not isinstance(measure_list, MeasureList):
raise ValueError("`measure_list` must be a `MeasureList` object")
self.measure_list = measure_list
# Sample bernoulli outcome for all SocialDistancingForAllMeasure and conditional measures
self.measure_list.init_run(SocialDistancingForAllMeasure,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(SocialDistancingBySiteTypeForAllMeasure,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(UpperBoundCasesSocialDistancing,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(UpperBoundCasesBetaMultiplier,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(SocialDistancingPerStateMeasure,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(SocialDistancingForPositiveMeasure,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(SocialDistancingForPositiveMeasureHousehold)
self.measure_list.init_run(SocialDistancingByAgeMeasure,
num_age_groups=self.num_age_groups,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(ComplianceForAllMeasure,
n_people=self.n_people)
self.measure_list.init_run(ManualTracingReachabilityForAllMeasure,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(ManualTracingForAllMeasure,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(SocialDistancingForSmartTracing,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
self.measure_list.init_run(SocialDistancingForSmartTracingHousehold,
n_people=self.n_people)
self.measure_list.init_run(SocialDistancingSymptomaticAfterSmartTracing,
n_people=self.n_people)
self.measure_list.init_run(SocialDistancingSymptomaticAfterSmartTracingHousehold,
n_people=self.n_people)
self.measure_list.init_run(SocialDistancingForKGroups,
n_people=self.n_people,
n_visits=max(self.mob.visit_counts))
# Store the original beta values
self.betas_weighted_mean = sum([
self.betas[self.site_dict[k]]
* np.sum(self.site_type == k) / self.n_sites # relative frequency of site type k
for k in range(self.num_site_types)
])
# if specified, scale optimized betas a priori
apriori_beta = self.measure_list.find_first(APrioriBetaMultiplierMeasureByType)
if apriori_beta:
for k in range(self.num_site_types):
self.betas[self.site_dict[k]] *= apriori_beta.beta_factor(typ=self.site_dict[k])
# print('PanCast betas: ', self.betas)
# print('SPECTS betas: ', self.betas_weighted_mean)
# init state variables with seeds
self.__init_run()
self.was_initial_seed = np.zeros(self.n_people, dtype='bool')
total_seeds = sum(v for v in initial_counts.values())
initial_people = np.random.choice(self.n_people, size=total_seeds, replace=False)
ptr = 0
self.initial_seeds = dict()
for k, v in initial_counts.items():
self.initial_seeds[k] = initial_people[ptr:ptr + v].tolist()
ptr += v
# sample all iid events ahead of time in batch
batch_size = (self.n_people, )
self.delta_expo_to_ipre = self.d.sample_expo_ipre(size=batch_size)
self.delta_ipre_to_isym = self.d.sample_ipre_isym(size=batch_size)
self.delta_isym_to_resi = self.d.sample_isym_resi(size=batch_size)
self.delta_isym_to_dead = self.d.sample_isym_dead(size=batch_size)
self.delta_expo_to_iasy = self.d.sample_expo_iasy(size=batch_size)
self.delta_iasy_to_resi = self.d.sample_iasy_resi(size=batch_size)
self.delta_isym_to_hosp = self.d.sample_isym_hosp(size=batch_size)
self.bernoulli_is_iasy = np.random.binomial(1, self.alpha, size=batch_size)
self.bernoulli_is_fatal = self.d.sample_is_fatal(self.people_age, size=batch_size)
self.bernoulli_is_hospi = self.d.sample_is_hospitalized(self.people_age, size=batch_size)
# initial seed
self.initialize_states_for_seeds()
# not initially seeded
if self.lambda_0 > 0.0:
# sample non-contact exposure events
delta_susc_to_expo = self.d.sample_susc_baseexpo(size=self.n_people)
for i in range(self.n_people):
if not self.was_initial_seed[i] and delta_susc_to_expo[i] < self.max_time:
self.queue.push(
(delta_susc_to_expo[i], 'expo', i, None, None, None),
priority=delta_susc_to_expo[i])
# initialize test processing events: add 'update_test' event to queue for `testing_frequency` hour
for h in range(1, math.floor(self.max_time / self.testing_frequency)):
ht = h * self.testing_frequency
self.queue.push((ht, 'execute_tests', None, None, None, None), priority=ht)
# MAIN EVENT LOOP
t = 0.0
while self.queue:
# get next event to process
t, event, i, infector, k, metadata = self.queue.pop()
# check if testing processing
if event == 'execute_tests':
self.__update_testing_queue(t)
if self.smart_tracing_policy_isolate == 'advanced-global-budget':
self.__process_isolation_queue(t)
if self.smart_tracing_policy_test == 'advanced-global-budget':
self.__update_budget_testing_queue(t)
continue
# check termination
if t > self.max_time:
t = self.max_time
self.__print(t, force=True)
if self.verbose:
print(f'\n[Reached max time: {int(self.max_time)}h ({int(self.max_time // 24)}d)]')
break
if np.sum((1 - self.state['susc']) * (self.state['resi'] + self.state['dead'])) == self.n_people:
if self.verbose:
print('\n[Simulation ended]')
break
# process event
if event == 'expo':
i_susceptible = ((not self.state['expo'][i]) and (self.state['susc'][i]))
# base rate exposure
if (infector is None) and i_susceptible:
self.__process_exposure_event(t=t, i=i, parent=None, contact=None)
# household exposure
if (infector is not None) and i_susceptible and k == -1:
# 1) check whether infector recovered or dead
infector_recovered = \
(self.state['resi'][infector] or
self.state['dead'][infector])
# 2) check whether infector got hospitalized
infector_hospitalized = self.state['hosp'][infector]
# 3) check whether infector or i are not at home
infector_away_from_home = False
i_away_from_home = False
infector_visits = self.mob.mob_traces_by_indiv[infector].find((t, t))
i_visits = self.mob.mob_traces_by_indiv[i].find((t, t))
for v in infector_visits:
infector_away_from_home = \
((v.t_to > t) and # infector actually at a site, not just matching "environmental contact"
(not self.is_person_home_from_visit_due_to_measure(
t=t, i=infector, visit_id=v.id, site_type=self.site_dict[self.site_type[v.site]])))
if infector_away_from_home:
break
for v in i_visits:
i_away_from_home = i_away_from_home or \
((v.t_to > t) and # i actually at a site, not just matching "environmental contact"
(not self.is_person_home_from_visit_due_to_measure(
t=t, i=i, visit_id=v.id, site_type=self.site_dict[self.site_type[v.site]])))
away_from_home = (infector_away_from_home or i_away_from_home)
# 4) check whether infector or i were isolated from household members
infector_isolated_at_home = (
self.measure_list.is_contained(
SocialDistancingForPositiveMeasureHousehold, t=t,
j=infector,
state_posi_started_at=self.state_started_at['posi'],
state_posi_ended_at=self.state_ended_at['posi'],
state_resi_started_at=self.state_started_at['resi'],
state_dead_started_at=self.state_started_at['dead']) or
self.measure_list.is_contained(
SocialDistancingForSmartTracingHousehold, t=t,
state_nega_started_at=self.state_started_at['nega'],
state_nega_ended_at=self.state_ended_at['nega'],
j=infector) or
self.measure_list.is_contained(
SocialDistancingSymptomaticAfterSmartTracingHousehold, t=t,
state_isym_started_at=self.state_started_at['isym'],
state_isym_ended_at=self.state_ended_at['isym'],
state_nega_started_at=self.state_started_at['nega'],
state_nega_ended_at=self.state_ended_at['nega'],
j=infector)
)
i_isolated_at_home = (
self.measure_list.is_contained(
SocialDistancingForPositiveMeasureHousehold, t=t,
j=i,
state_posi_started_at=self.state_started_at['posi'],
state_posi_ended_at=self.state_ended_at['posi'],
state_resi_started_at=self.state_started_at['resi'],
state_dead_started_at=self.state_started_at['dead']) or
self.measure_list.is_contained(
SocialDistancingForSmartTracingHousehold, t=t,
state_nega_started_at=self.state_started_at['nega'],
state_nega_ended_at=self.state_ended_at['nega'],
j=i) or
self.measure_list.is_contained(
SocialDistancingSymptomaticAfterSmartTracingHousehold, t=t,
state_isym_started_at=self.state_started_at['isym'],
state_isym_ended_at=self.state_ended_at['isym'],
state_nega_started_at=self.state_started_at['nega'],
state_nega_ended_at=self.state_ended_at['nega'],
j=i)
)
somebody_isolated = (infector_isolated_at_home or i_isolated_at_home)
# "thinning"
# if none of 1), 2), 3), 4) are true, the event is valid
if (not infector_recovered) and \
(not infector_hospitalized) and \
(not away_from_home) and \
(not somebody_isolated):
self.__process_exposure_event(t=t, i=i, parent=infector, contact=None)
self.num_household_exposures += 1
# if 2), 3), or 4) were true, i.e. infector not recovered,
# a household exposure could happen at a later point, hence sample a new event
if (infector_hospitalized or away_from_home or somebody_isolated):
# find tmax for efficiency
if self.state['iasy'][infector]:
base_rate_infector = self.mu
tmax = self.state_started_at['iasy'][infector] + self.delta_iasy_to_resi[infector]
else:
base_rate_infector = 1.0
tmax = (self.state_started_at['ipre'][infector] + self.delta_ipre_to_isym[infector] +
(self.delta_isym_to_dead[infector] if self.bernoulli_is_fatal[infector] else self.delta_isym_to_resi[infector]))
# sample exposure at later point
if t < tmax:
self.__push_household_exposure_infector_to_j(
t=t, infector=infector, j=i, base_rate=base_rate_infector, tmax=tmax)
# contact exposure
if (infector is not None) and i_susceptible and k >= 0:
# for contact exposures, `contact` causing the exposure is passed
contact = metadata
i_visit_id, infector_visit_id = contact.id_tup
assert(k == contact.site)
# is_in_contact2, contact2 = self.mob.is_in_contact(indiv_i=i, indiv_j=infector, site=k, t=t)
# assert(is_in_contact2 and (contact == contact2))
# 1) check whether infector recovered or dead
infector_recovered = \
(self.state['resi'][infector] or
self.state['dead'][infector])
# 2) check whether infector stayed at home due to measures
# or got hospitalized
infector_contained = self.is_person_home_from_visit_due_to_measure(
t=t, i=infector, visit_id=infector_visit_id,
site_type=self.site_dict[self.site_type[k]]) \
or self.state['hosp'][infector]
# 3) check whether susceptible stayed at home due to measures
i_contained = self.is_person_home_from_visit_due_to_measure(
t=t, i=i, visit_id=i_visit_id,
site_type=self.site_dict[self.site_type[k]])
# 4) check whether infectiousness got reduced due to site specific
# measures and as a consequence this event didn't occur
rejection_prob = self.reject_exposure_due_to_measure(t=t, k=k)
site_avoided_infection = (np.random.uniform() < rejection_prob)
# "thinning"
# if none of 1), 2), 3), 4) are true, the event is valid
if (not infector_recovered) and \
(not infector_contained) and \
(not i_contained) and \
(not site_avoided_infection):
self.__process_exposure_event(t=t, i=i, parent=infector, contact=contact)
self.num_site_exposures += 1
# if any of 2), 3), 4) were true, i.e. infector not recovered,
# an exposure could happen at a later point, hence sample a new event
if (infector_contained or i_contained or site_avoided_infection):
# find tmax for efficiency
if self.state['iasy'][infector]:
base_rate_infector = self.mu
tmax = self.state_started_at['iasy'][infector] + \
self.delta_iasy_to_resi[infector]
else:
base_rate_infector = 1.0
tmax = (self.state_started_at['ipre'][infector] + self.delta_ipre_to_isym[infector] +
(self.delta_isym_to_dead[infector] if self.bernoulli_is_fatal[infector] else self.delta_isym_to_resi[infector]))
# sample exposure at later point
if t < tmax:
self.__push_contact_exposure_infector_to_j(
t=t, infector=infector, j=i, base_rate=base_rate_infector, tmax=tmax)
elif event == 'ipre':
self.__process_presymptomatic_event(t, i)
elif event == 'iasy':
self.__process_asymptomatic_event(t, i)
elif event == 'isym':
self.__process_symptomatic_event(t, i)
elif event == 'resi':
self.__process_resistant_event(t, i)
elif event == 'test':
self.__process_testing_event(t, i, metadata)
elif event == 'dead':
self.__process_fatal_event(t, i)
elif event == 'hosp':
# cannot get hospitalization if not ill anymore
valid_hospitalization = \
((not self.state['resi'][i]) and
(not self.state['dead'][i]))
if valid_hospitalization:
self.__process_hosp_event(t, i)
else:
# this should only happen for invalid exposure events
assert(event == 'expo')
# print
self.__print(t, force=True)
# print('% exposed in risk buckets: ', 100.0 * self.risk_got_exposed / (self.risk_got_exposed + self.risk_got_not_exposed))
'''Compute infection hotspot statistics'''
# every 14 days, for a 7-day window, until the end of the simulation
self.visit_expo_counts = self.compute_infection_hotspot_stats(slider_size=14 * 24.0, window_size=24.0 * 7, end_cutoff=0.0)
'''Compute ROC statistics'''
# tracing_stats [threshold][policy][action][stat]
self.tracing_stats = {}
if len(self.thresholds_roc) > 0:
for threshold in self.thresholds_roc:
self.tracing_stats[threshold] = self.compute_roc_stats(
threshold_isolate=threshold, threshold_test=threshold)
# stats = self.tracing_stats[self.thresholds_roc[0]]['sites']['isolate']
# print(" P {:5.2f} N {:5.2f}".format(
# (stats['fn'] + stats['tp']), (stats['fp'] + stats['tn'])
# ))
# free memory
self.valid_contacts_for_tracing = None
self.queue = None
def compute_infection_hotspot_stats(self, *, slider_size, window_size, end_cutoff):
'''
Counts the number of exposures caused per infectious visit in time window
Returns:
dict: (t0, t1) -> count array of exposures caused by each visit of an infectious individual in (t0, t1)
'''
# Build the range of time intervals to count for
t0_range = np.arange(0.0, self.max_time - window_size - end_cutoff, slider_size)
t1_range = t0_range + window_size
interval_range = list(zip(t0_range, t1_range))
# Collect infector visit id of each contact exposure in the simulation
visit_exposure_count = Counter()
for j in range(self.n_people):
if self.contact_caused_expo[j] is not None:
id_infector = self.contact_caused_expo[j].indiv_j
visit_id_infector = self.contact_caused_expo[j].id_tup[1]
visit_exposure_count[(id_infector, visit_id_infector)] += 1
# Count exposures for each infectious visit in time interval
total_expo_counts = dict()
for t0, t1 in interval_range:
expo_counts = []
for visit in self.mob.mob_traces.find((t0, t1)):
t = visit.t_from
if t < t0:
continue
# check whether individual was isolated/skipped visit; proxy: check visit interval end times
if (self.is_person_home_from_visit_due_to_measure(t=visit.t_from, i=visit.indiv, visit_id=visit.id, site_type=self.site_dict[self.site_type[visit.site]])
and self.is_person_home_from_visit_due_to_measure(t=visit.t_to, i=visit.indiv, visit_id=visit.id, site_type=self.site_dict[self.site_type[visit.site]])):
# no `assert` since it can raise `false negative` exception for KGroups measure due to frequent boundary effects of the above (imperfect) check for isolation
# assert (visit.indiv, visit.id) not in visit_exposure_count, f'Even though individual was home, an exposure occurred at: {visit}'
continue
# check whether individual was infectious at time of visit
indiv_is_infectious = (
((t >= self.state_started_at['iasy'][visit.indiv]) & (t < self.state_ended_at['iasy'][visit.indiv])) |
((t >= self.state_started_at['ipre'][visit.indiv]) & (t < self.state_ended_at['ipre'][visit.indiv])) |
((t >= self.state_started_at['isym'][visit.indiv]) & (t < self.state_ended_at['isym'][visit.indiv]))
)
# record exposures caused during visit, only if infectious
# this appends zero (0) if the visit did not cause any exposures
if indiv_is_infectious:
expo_counts.append(visit_exposure_count[(visit.indiv, visit.id)])
total_expo_counts[(t0, t1)] = np.array(sorted(expo_counts)) # only sorted for debugging purposes
return total_expo_counts
def compute_roc_stats(self, *, threshold_isolate, threshold_test):
'''
Recovers contacts for which trace/no-trace decision was made.
Then re-computes TP/FP/TN/FN for different decision thresholds, given
the label that a given person with contact got exposed.
Assumes `advanced-threshold` policy for both isolation and testing.
'''
stats = {
'sites' : {
'isolate' : {'tp' : 0, 'fp' : 0, 'tn' : 0, 'fn' : 0},
'test' : {'tp' : 0, 'fp' : 0, 'tn' : 0, 'fn' : 0},
},
'no_sites' : {
'isolate' : {'tp' : 0, 'fp' : 0, 'tn' : 0, 'fn' : 0},
'test' : {'tp' : 0, 'fp' : 0, 'tn' : 0, 'fn' : 0},
},
}
stats_with_sites = {
sitetype: {
'sites': {
'isolate': {'tp': 0, 'fp': 0, 'tn': 0, 'fn': 0},
'test': {'tp': 0, 'fp': 0, 'tn': 0, 'fn': 0},
},
'no_sites': {
'isolate': {'tp': 0, 'fp': 0, 'tn': 0, 'fn': 0},
'test': {'tp': 0, 'fp': 0, 'tn': 0, 'fn': 0},
},
}
for sitetype in self.mob.site_dict.values()
}
# c[sites/no_sites][isolate/test][False/True][j]
# i-j contacts due to which j was traced/not traced
c = {
'sites' : {
'isolate': {
False: [[] for _ in range(self.n_people)],
True: [[] for _ in range(self.n_people)],
},
'test': {
False: [[] for _ in range(self.n_people)],
True: [[] for _ in range(self.n_people)],
},
},
'no_sites' : {
'isolate': {
False: [[] for _ in range(self.n_people)],
True: [[] for _ in range(self.n_people)],
},
'test': {
False: [[] for _ in range(self.n_people)],
True: [[] for _ in range(self.n_people)],
},
},
}
individuals_traced = set()
# for each tracing call due to an `infector`, re-compute classification decision (tracing or not)
# under the decision threshold `thres`, and record decision in `contacts_caused_tracing_...` arrays by individual
for t, infector, valid_contacts_with_j in self.valid_contacts_for_tracing:
# inspect whether the infector was symptomatic or asymptomatic
if self.state_started_at['iasy'][infector] < np.inf:
base_rate_inf = self.mu
else:
base_rate_inf = 1.0
# compute empirical survival probability
emp_survival_prob = {
'sites' : dict(),
'no_sites' : dict()
}
for j, contacts_j in valid_contacts_with_j.items():
individuals_traced.add(j)
emp_survival_prob['sites'][j] = self.__compute_empirical_survival_probability(
t=t, i=infector, j=j, contacts_i_j=contacts_j, base_rate=base_rate_inf, ignore_sites=False)
emp_survival_prob['no_sites'][j] = self.__compute_empirical_survival_probability(
t=t, i=infector, j=j, contacts_i_j=contacts_j, base_rate=base_rate_inf, ignore_sites=True)
# compute tracing decision
for policy in ['sites', 'no_sites']:
for action in ['isolate', 'test']:
contacts_action, contacts_no_action = self.__tracing_policy_advanced_threshold(
t=t, contacts_with_j=valid_contacts_with_j,
threshold=threshold_isolate if action == 'isolate' else threshold_test,
emp_survival_prob=emp_survival_prob[policy])
for j, contacts_j in contacts_action:
c[policy][action][True][j].append((t, set(contacts_j)))
for j, contacts_j in contacts_no_action:
c[policy][action][False][j].append((t, set(contacts_j)))
# for each individual considered in tracing, compare label (contact exposure?) with classification (traced due to this contact?)
for j in individuals_traced: