forked from covid19-model/simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
measures.py
1290 lines (1070 loc) · 49.5 KB
/
measures.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 abc
from collections import namedtuple, defaultdict
import numpy as np
import math
from interlap import InterLap
# from utils import enforce_init_run # use this for unit testing
from lib.utils import enforce_init_run
# Tuple representing an interval, FIXME: duplicates mobilitysim Interval
Interval = namedtuple('Interval', ('left', 'right'))
# Small time subtracted from the end of time windows to avoid matching at
# limit between two measures, because interlap works with closed intervals
EPS = 1e-15
# Small object remembering result and intended action of a test
TestResult = namedtuple('TestResult', (
'is_positive_test', # Boolean of test result (True = positive)
'trigger_tracing_if_positive', # Boolean of whether or not contact tracing should be triggered if positive
))
class Measure(metaclass=abc.ABCMeta):
def __init__(self, t_window):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
"""
if not isinstance(t_window, Interval):
raise ValueError('`t_window` must be an Interval namedtuple')
self.t_window = t_window
# Set init run attribute
self._is_init = False
def init_run(self, **kwargs):
"""Init the measure for this run with whatever is needed"""
raise NotImplementedError(("Must be implemented in child class. If you"
" get this error, it's probably a bug."))
def _in_window(self, t):
"""Indicate if the measure is valid, i.e. if time `t` is in the time
window of the measure"""
return (t >= self.t_window.left) and (t < self.t_window.right)
"""
=========================== SOCIAL DISTANCING ===========================
"""
class SocialDistancingForAllMeasure(Measure):
"""
Social distancing measure. All the population is advised to stay home. Each
visit of each individual respects the measure with some probability.
"""
def __init__(self, t_window, p_stay_home):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_stay_home : float
Probability of respecting the measure, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probability of respecting measure
if (not isinstance(p_stay_home, float)) or (p_stay_home < 0):
raise ValueError("`p_stay_home` should be a non-negative float")
self.p_stay_home = p_stay_home
def init_run(self, n_people, n_visits):
"""Init the measure for this run by sampling the outcome of each visit
for each individual
Parameters
----------
n_people : int
Number of people in the population
n_visits : int
Maximum number of visits of an individual
"""
# Sample the outcome of the measure for each visit of each individual
self.bernoulli_stay_home = np.random.binomial(
1, self.p_stay_home, size=(n_people, n_visits))
self._is_init = True
@enforce_init_run
def is_contained(self, *, j, j_visit_id, t):
"""Indicate if individual `j` respects measure for visit `j_visit_id`
"""
is_home_now = self.bernoulli_stay_home[j, j_visit_id]
return is_home_now and self._in_window(t)
@enforce_init_run
def is_contained_prob(self, *, j, t):
"""Returns probability of containment for individual `j` at time `t`
"""
if self._in_window(t):
return self.p_stay_home
return 0.0
def exit_run(self):
""" Deletes bernoulli array. """
if self._is_init:
self.bernoulli_stay_home = None
self._is_init = False
class UpperBoundCasesSocialDistancing(SocialDistancingForAllMeasure):
def __init__(self, t_window, p_stay_home, max_pos_tests_per_week_per_100k, intervention_times=None, init_active=False):
"""
Additional parameters:
----------------------
max_pos_test_per_week : int
If the number of positive tests per week exceeds this number the measure becomes active
intervention_times : list of floats
List of points in time at which measures can become active. If 'None' measures can be changed at any time
"""
super().__init__(t_window, p_stay_home)
self.max_pos_tests_per_week_per_100k = max_pos_tests_per_week_per_100k
self.intervention_times = intervention_times
self.intervention_history = InterLap()
if init_active:
self.intervention_history.update([(t_window.left, t_window.left + 7 * 24 - EPS, True)])
def init_run(self, n_people, n_visits):
super().init_run(n_people, n_visits)
self.scaled_test_threshold = self.max_pos_tests_per_week_per_100k / 100000 * n_people
def _is_measure_active(self, t, t_pos_tests):
# If measures can only become active at 'intervention_times'
if self.intervention_times is not None:
# Find largest 'time' in intervention_times s.t. t > time
intervention_times = np.asarray(self.intervention_times)
idx = np.where(t - intervention_times > 0, t - intervention_times, np.inf).argmin()
t = intervention_times[idx]
t_in_history = list(self.intervention_history.find((t, t)))
if t_in_history:
is_active = t_in_history[0][2]
else:
is_active = self._are_cases_above_threshold(t, t_pos_tests)
if is_active:
self.intervention_history.update([(t, t + 7 * 24 - EPS, True)])
return is_active
def _are_cases_above_threshold(self, t, t_pos_tests):
# Count positive tests in last 7 days from last intervention time
tmin = t - 7 * 24
num_pos_tests = np.sum(np.greater(t_pos_tests, tmin) * np.less(t_pos_tests, t))
is_above_threshold = num_pos_tests > self.scaled_test_threshold
return is_above_threshold
@enforce_init_run
def is_contained(self, *, j, j_visit_id, t, t_pos_tests):
"""Indicate if individual `j` respects measure for visit `j_visit_id`
"""
if not self._in_window(t):
return False
is_home_now = self.bernoulli_stay_home[j, j_visit_id]
return is_home_now and self._is_measure_active(t, t_pos_tests)
@enforce_init_run
def is_contained_prob(self, *, j, t, t_pos_tests):
"""Returns probability of containment for individual `j` at time `t`
"""
if not self._in_window(t):
return 0.0
if self._is_measure_active(t, t_pos_tests):
return self.p_stay_home
return 0.0
class SocialDistancingPerStateMeasure(SocialDistancingForAllMeasure):
"""
Social distancing measure. Only the population in a given 'state' is advised
to stay home. Each visit of each individual respects the measure with some
probability.
NOTE: This is the same as a SocialDistancingForAllMeasure but `is_contained` query also checks that the state 'state'
of individual j is True
"""
def __init__(self, t_window, p_stay_home, state_label):
# Init time window
super().__init__(t_window, p_stay_home)
self.state_label = state_label
@enforce_init_run
def is_contained(self, *, j, j_visit_id, t, state_dict):
"""Indicate if individual `j` is in state 'state' and respects measure for
visit `j_visit_id`
r : int
Id of realization
j : int
Id of individual
j_visit_id : int
Id of visit
t : float
Query time
state_dict : dict
Dict with states of all individuals in `DiseaseModel`
"""
is_home_now = self.bernoulli_stay_home[j, j_visit_id]
# only isolate at home while at state `state`
return is_home_now and state_dict[self.state_label][j] and self._in_window(t)
@enforce_init_run
def is_contained_prob(self, *, j, t, state_started_at_dict, state_ended_at_dict):
"""Returns probability of containment for individual `j` at time `t`
"""
if self._in_window(t) and state_started_at_dict[self.state_label][j] <= t <= \
state_ended_at_dict[self.state_label][j]:
return self.p_stay_home
return 0.0
class SocialDistancingBySiteTypeForAllMeasure(Measure):
"""
Social distancing measure. All the population is advised to stay home. Each
visit of each individual respects the measure with some probability.
"""
def __init__(self, t_window, p_stay_home_dict):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_stay_home_dict : dict of site_type : float
Probability of respecting the measure for a given site type, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probabilities of respecting measure
if (not isinstance(p_stay_home_dict, dict)) or any([p < 0.0 or p > 1.0 for p in p_stay_home_dict.values()]):
raise ValueError("`p_stay_home_dict` should contain non-negative floats between 0 and 1")
self.p_stay_home_dict = p_stay_home_dict
def init_run(self, n_people, n_visits):
"""Init the measure for this run by sampling the outcome of each visit
for each individual
Parameters
----------
n_people : int
Number of people in the population
n_visits : int
Maximum number of visits of an individual
"""
# Sample the outcome of the measure for each visit of each individual
self.bernoulli_stay_home_type = {
k : np.random.binomial(1, p, size=(n_people, n_visits))
for k, p in self.p_stay_home_dict.items()
}
self._is_init = True
@enforce_init_run
def is_contained(self, *, j, j_visit_id, site_type, t):
"""Indicate if individual `j` respects measure for visit `j_visit_id`
"""
is_home_now = self.bernoulli_stay_home_type[site_type][j, j_visit_id]
return is_home_now and self._in_window(t)
@enforce_init_run
def is_contained_prob(self, *, j, site_type, t):
"""Returns probability of containment for individual `j` at time `t`
"""
if self._in_window(t):
return self.p_stay_home_dict[site_type]
return 0.0
def exit_run(self):
""" Deletes bernoulli array. """
if self._is_init:
self.bernoulli_stay_home = None
self._is_init = False
class SocialDistancingForPositiveMeasure(SocialDistancingForAllMeasure):
"""
Social distancing measure. Only the population of positive cases who are not
resistant or dead is advised to stay home. Each visit of each individual
respects the measure with some probability.
NOTE: This is the same as a SocialDistancingForAllMeasure but `is_contained` query also checks that the state 'posi' of individual j is True
"""
@enforce_init_run
def is_contained(self, *, j, j_visit_id, t, state_posi_started_at, state_posi_ended_at, state_resi_started_at, state_dead_started_at):
"""Indicate if individual `j` is positive and respects measure for
visit `j_visit_id`
r : int
Id of realization
j : int
Id of individual
j_visit_id : int
Id of visit
t : float
Query time
state_* : array
Array of indicators, it should be the array of `state` `*` of the `DiseaseModel`
"""
is_home_now = self.bernoulli_stay_home[j, j_visit_id]
# only isolate at home while positive and not resistant or dead
is_posi_now = (
t >= state_posi_started_at[j] and t < state_posi_ended_at[j] and # positive
t < state_resi_started_at[j] and t < state_dead_started_at[j] # not resistant or dead
)
return is_home_now and is_posi_now and self._in_window(t)
@enforce_init_run
def is_contained_prob(self, *, j, t, state_posi_started_at, state_posi_ended_at, state_resi_started_at, state_dead_started_at):
"""Returns probability of containment for individual `j` at time `t`
"""
if (self._in_window(t) and
t >= state_posi_started_at[j] and t < state_posi_ended_at[j] and # positive
t < state_resi_started_at[j] and t < state_dead_started_at[j]): # not resistant or dead
return self.p_stay_home
return 0.0
class SocialDistancingForPositiveMeasureHousehold(Measure):
"""
Social distancing measure. Isolate positive cases from household members.
Each individual respects the measure with some probability.
"""
def __init__(self, t_window, p_isolate):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_isolate : float
Probability of respecting the measure, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
self.p_isolate = p_isolate
def init_run(self):
"""Init the measure for this run is trivial
"""
self._is_init = True
@enforce_init_run
def is_contained(self, *, j, t, state_posi_started_at, state_posi_ended_at, state_resi_started_at, state_dead_started_at):
"""Indicate if individual `j` respects measure
"""
is_isolated = np.random.binomial(1, self.p_isolate)
# only isolate at home while positive and not resistant or dead
is_posi_now = (
t >= state_posi_started_at[j] and t < state_posi_ended_at[j] and # positive
t < state_resi_started_at[j] and t < state_dead_started_at[j] # not resistant or dead
)
return is_isolated and is_posi_now and self._in_window(t)
@enforce_init_run
def is_contained_prob(self, *, j, t, state_posi_started_at, state_posi_ended_at, state_resi_started_at, state_dead_started_at):
"""Returns probability of containment for individual `j` at time `t`
"""
if (self._in_window(t) and
t >= state_posi_started_at[j] and t <= state_posi_ended_at[j] and # positive
t < state_resi_started_at[j] and t < state_dead_started_at[j]): # not resistant or dead
return self.p_isolate
return 0.0
class SocialDistancingByAgeMeasure(Measure):
"""
Social distancing measure. The population is advised to stay at home based
on membership in a specific age group. The measure defines the probability
of staying at home for all age groups in the simulation.
"""
def __init__(self, t_window, p_stay_home):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_stay_home : float
Probability of respecting the measure, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probability of respecting measure
if (not isinstance(p_stay_home, list)) or (any(map(lambda x: x < 0, p_stay_home))):
raise ValueError("`p_stay_home` should be a list of only non-negative floats")
self.p_stay_home = p_stay_home
def init_run(self, num_age_groups, n_visits):
"""Init the measure for this run by sampling the outcome of each visit
for each individual
Parameters
----------
num_age_groups : int
Number of ages groups in the population
n_visits : int
Maximum number of visits of an individual
"""
if len(self.p_stay_home) != num_age_groups:
raise ValueError("`p_stay_home` list is different in DiseaseModel and MobilitySim")
# Sample the outcome of the measure for each visit of each individual
self.bernoulli_stay_home = np.random.binomial(
1, self.p_stay_home, size=(n_visits, num_age_groups))
self._is_init = True
@enforce_init_run
def is_contained(self, *, age, j_visit_id, t):
"""Indicate if individual of age `age` respects measure for visit `j_visit_id`
"""
is_home_now = self.bernoulli_stay_home[j_visit_id, age]
return is_home_now and self._in_window(t)
@enforce_init_run
def is_contained_prob(self, *, age, t):
"""Returns probability of containment for individual `j` at time `t`
"""
if self._in_window(t):
return self.p_stay_home[age]
return 0.0
def exit_run(self):
""" Deletes bernoulli array. """
if self._is_init:
self.bernoulli_stay_home = None
self._is_init = False
class SocialDistancingForSmartTracing(Measure):
"""
Social distancing measure. Only the population who intersected with positive cases
for ``smart_tracing_isolation_duration``. Each visit of each individual respects the measure with
some probability.
"""
def __init__(self, t_window, p_stay_home, smart_tracing_isolation_duration):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_stay_home : float
Probability of respecting the measure, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probability of respecting measure
if (not isinstance(p_stay_home, float)) or (p_stay_home < 0):
raise ValueError("`p_stay_home` should be a non-negative float")
self.p_stay_home = p_stay_home
self.smart_tracing_isolation_duration = smart_tracing_isolation_duration
def init_run(self, n_people, n_visits):
"""Init the measure for this run by sampling the outcome of each visit
for each individual
Parameters
----------
n_people : int
Number of people in the population
n_visits : int
Maximum number of visits of an individual
"""
# Sample the outcome of the measure for each visit of each individual
self.bernoulli_stay_home = np.random.binomial(1, self.p_stay_home, size=(n_people, n_visits))
self.intervals_stay_home = [InterLap() for _ in range(n_people)]
#self.got_contained = np.zeros([n_people, 2])
# self.got_contained = [[] for _ in range(n_people)]
self._is_init = True
@enforce_init_run
def is_contained(self, *, j, j_visit_id, state_nega_started_at, state_nega_ended_at, t):
"""Indicate if individual `j` respects measure for visit `j_visit_id`
Negatively tested are not isolated
"""
is_not_nega_now = not (state_nega_started_at[j] <= t and t < state_nega_ended_at[j])
if self._in_window(t) and self.bernoulli_stay_home[j, j_visit_id] and is_not_nega_now:
for interval in self.intervals_stay_home[j].find((t, t)):
return True
return False
@enforce_init_run
def start_containment(self, *, j, t):
self.intervals_stay_home[j].update([(t, t + self.smart_tracing_isolation_duration)])
# self.got_contained[j].append([t, t + self.smart_tracing_isolation_duration])
return
@enforce_init_run
def is_contained_prob(self, *, j, state_nega_started_at, state_nega_ended_at, t):
"""Returns probability of containment for individual `j` at time `t`
"""
is_not_nega_now = not (state_nega_started_at[j] <= t and t < state_nega_ended_at[j])
if self._in_window(t) and is_not_nega_now:
for interval in self.intervals_stay_home[j].find((t, t)):
return self.p_stay_home
return 0.0
def exit_run(self):
""" Deletes bernoulli array. """
if self._is_init:
self.bernoulli_stay_home = None
self._is_init = False
class SocialDistancingSymptomaticAfterSmartTracing(Measure):
"""
Social distancing measure. If an individual develops symptoms after they were identified
and isolated by contact tracing, the individual isolates until symptoms disappear.
"""
def __init__(self, t_window, p_stay_home, smart_tracing_isolation_duration):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_stay_home : float
Probability of respecting the measure, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probability of respecting measure
if (not isinstance(p_stay_home, float)) or (p_stay_home < 0):
raise ValueError("`p_stay_home` should be a non-negative float")
self.p_stay_home = p_stay_home
self.smart_tracing_isolation_duration = smart_tracing_isolation_duration
def init_run(self, n_people):
"""Init the measure for this run by sampling the outcome of each visit
for each individual
Parameters
----------
n_people : int
Number of people in the population
n_visits : int
Maximum number of visits of an individual
"""
# Sample the outcome of the measure for each visit of each individual
self.bernoulli_stay_home = np.random.binomial(1, self.p_stay_home, size=n_people)
self.got_contained = np.zeros(n_people, dtype='bool')
self._is_init = True
@enforce_init_run
def is_contained(self, *, j, state_isym_started_at, state_isym_ended_at, state_nega_started_at, state_nega_ended_at, t):
"""Indicate if individual `j` respects measure
Negatively tested are not isolated.
"""
is_not_nega_now = not (state_nega_started_at[j] <= t and t < state_nega_ended_at[j])
is_isym_now = (state_isym_started_at[j] <= t and t < state_isym_ended_at[j])
return self._in_window(t) and self.bernoulli_stay_home[j] and is_isym_now and is_not_nega_now and self.got_contained[j]
@enforce_init_run
def start_containment(self, *, j, t):
self.got_contained[j] = True
return
@enforce_init_run
def is_contained_prob(self, *, j, state_isym_started_at, state_isym_ended_at, state_nega_started_at, state_nega_ended_at, t):
"""Returns probability of containment for individual `j` at time `t`
"""
is_not_nega_now = not (state_nega_started_at[j] <= t and t < state_nega_ended_at[j])
is_isym_now = (state_isym_started_at[j] <= t and t < state_isym_ended_at[j])
if self._in_window(t) and is_isym_now and self.got_contained[j] and is_not_nega_now:
return self.p_stay_home
return 0.0
def exit_run(self):
""" Deletes bernoulli array. """
if self._is_init:
self.bernoulli_stay_home = None
self.got_contained = None
self._is_init = False
class SocialDistancingForSmartTracingHousehold(Measure):
"""
Social distancing measure. Isolate traced individuals cases from household members.
Only the population who intersected with positive cases for ``smart_tracing_isolation_duration``.
Each visit of each individual respects the measure with some probability.
"""
def __init__(self, t_window, p_isolate, smart_tracing_isolation_duration):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_isolate : float
Probability of respecting the measure, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probability of respecting measure
if (not isinstance(p_isolate, float)) or (p_isolate < 0):
raise ValueError("`p_isolate` should be a non-negative float")
self.p_isolate = p_isolate
self.smart_tracing_isolation_duration = smart_tracing_isolation_duration
def init_run(self, n_people):
"""Init the measure for this run. Sampling of Bernoulli of respecting the measure done online."""
self.intervals_isolated = [InterLap() for _ in range(n_people)]
self._is_init = True
@enforce_init_run
def is_contained(self, *, j, state_nega_started_at, state_nega_ended_at, t):
"""Indicate if individual `j` respects measure at time `t`
"""
is_not_nega_now = not (state_nega_started_at[j] <= t and t < state_nega_ended_at[j])
is_isolated = np.random.binomial(1, self.p_isolate)
if self._in_window(t) and is_isolated and is_not_nega_now:
for interval in self.intervals_isolated[j].find((t, t)):
return True
return False
@enforce_init_run
def start_containment(self, *, j, t):
self.intervals_isolated[j].update([(t, t + self.smart_tracing_isolation_duration)])
return
@enforce_init_run
def is_contained_prob(self, *, j, state_nega_started_at, state_nega_ended_at, t):
"""Returns probability of containment for individual `j` at time `t`
"""
is_not_nega_now = not (state_nega_started_at[j] <= t and t < state_nega_ended_at[j])
if self._in_window(t) and is_not_nega_now:
for interval in self.intervals_isolated[j].find((t, t)):
return self.p_isolate
return 0.0
def exit_run(self):
""" Deletes bernoulli array. """
if self._is_init:
self._is_init = False
class SocialDistancingSymptomaticAfterSmartTracingHousehold(Measure):
"""
Social distancing measure. If an individual develops symptoms after they were identified
and isolated by contact tracing, the individual isolates from household members
until symptoms disappear.
"""
def __init__(self, t_window, p_isolate, smart_tracing_isolation_duration):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_isolate : float
Probability of respecting the measure, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probability of respecting measure
if (not isinstance(p_isolate, float)) or (p_isolate < 0):
raise ValueError("`p_isolate` should be a non-negative float")
self.p_isolate = p_isolate
self.smart_tracing_isolation_duration = smart_tracing_isolation_duration
def init_run(self, n_people):
"""Init the measure for this run. Sampling of Bernoulli of respecting the measure done online."""
# Sample the outcome of the measure for each visit of each individual
self.got_contained = np.zeros(n_people, dtype='bool')
self._is_init = True
@enforce_init_run
def is_contained(self, *, j, state_isym_started_at, state_isym_ended_at, state_nega_started_at, state_nega_ended_at, t):
"""Indicate if individual `j` respects measure
"""
is_isolated = np.random.binomial(1, self.p_isolate)
is_isym_now = (state_isym_started_at[j] <= t and t < state_isym_ended_at[j])
is_not_nega_now = not (state_nega_started_at[j] <= t and t < state_nega_ended_at[j])
return self._in_window(t) and is_isolated and is_isym_now and self.got_contained[j] and is_not_nega_now
@enforce_init_run
def start_containment(self, *, j, t):
self.got_contained[j] = True
return
@enforce_init_run
def is_contained_prob(self, *, j, state_isym_started_at, state_isym_ended_at, state_nega_started_at, state_nega_ended_at, t):
"""Returns probability of containment for individual `j` at time `t`
"""
is_isym_now = (state_isym_started_at[j] <= t and t < state_isym_ended_at[j])
is_not_nega_now = not (state_nega_started_at[j] <= t and t < state_nega_ended_at[j])
if self._in_window(t) and is_isym_now and self.got_contained[j] and is_not_nega_now:
return self.p_isolate
return 0.0
def exit_run(self):
""" Deletes bernoulli array. """
if self._is_init:
self.got_contained = None
self._is_init = False
class SocialDistancingForKGroups(Measure):
"""
Social distancing measure where the population is based on K groups, here their IDs.
Each day 1 of K groups is allowed to go outside.
"""
def __init__(self, t_window, K):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
K : int
Number of groups having to stay home on different days
"""
# Init time window
super().__init__(t_window)
self.K = K
def init_run(self):
"""Init the measure for this run is trivial
"""
self._is_init = True
@enforce_init_run
def is_contained(self, *, j, t):
"""Indicate if individual `j` respects measure
"""
day = math.floor(t / 24.0)
is_home_now = ((j % self.K) != (day % self.K))
return is_home_now and self._in_window(t)
@enforce_init_run
def is_contained_prob(self, *, j, t):
"""Returns probability of containment for individual `j` at time `t`
"""
day = math.floor(t / 24.0)
is_home_now = ((j % self.K) != (day % self.K))
if is_home_now and self._in_window(t):
return 1.0
return 0.0
"""
=========================== SITE SPECIFIC MEASURES ===========================
"""
class BetaMultiplierMeasure(Measure):
def __init__(self, t_window, beta_multiplier):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
beta_multiplier : list of floats
List of multiplicative factor to infection rate at each site
"""
super().__init__(t_window)
if (not isinstance(beta_multiplier, dict)
or (min(beta_multiplier.values()) < 0)):
raise ValueError(("`beta_multiplier` should be dict of"
" non-negative floats"))
self.beta_multiplier = beta_multiplier
class BetaMultiplierMeasureBySite(BetaMultiplierMeasure):
def beta_factor(self, *, k, t):
"""Returns the multiplicative factor for site `k` at time `t`. The
factor is one if `t` is not in the active time window of the measure.
"""
return self.beta_multiplier[k] if self._in_window(t) else 1.0
class BetaMultiplierMeasureByType(BetaMultiplierMeasure):
def beta_factor(self, *, typ, t):
"""Returns the multiplicative factor for site type `typ` at time `t`. The
factor is one if `t` is not in the active time window of the measure.
"""
return self.beta_multiplier[typ] if self._in_window(t) else 1.0
class APrioriBetaMultiplierMeasureByType(Measure):
def __init__(self, beta_multiplier):
"""
Parameters
----------
beta_multiplier : list of floats
List of multiplicative factor to infection rate at each site
"""
super().__init__(Interval(0.0, np.inf))
if (not isinstance(beta_multiplier, dict)
or (min(beta_multiplier.values()) < 0)):
raise ValueError(("`beta_multiplier` should be dict of"
" non-negative floats"))
self.beta_multiplier = beta_multiplier
def beta_factor(self, *, typ):
"""Returns the multiplicative factor for site type `typ` independent of time `t`
"""
return self.beta_multiplier[typ]
class UpperBoundCasesBetaMultiplier(BetaMultiplierMeasure):
def __init__(self, t_window, beta_multiplier, max_pos_tests_per_week_per_100k, intervention_times=None, init_active=False):
"""
Additional parameters:
----------------------
max_pos_test_per_week : int
If the number of positive tests per week exceeds this number the measure becomes active
intervention_times : list of floats
List of points in time at which interventions can be changed. If 'None' interventions can be changed at any time
init_active : bool
If true measure is active in the first week of the simulation when there are no test counts yet
"""
super().__init__(t_window, beta_multiplier)
self.max_pos_tests_per_week_per_100k = max_pos_tests_per_week_per_100k
self.intervention_times = intervention_times
self.intervention_history = InterLap()
if init_active:
self.intervention_history.update([(t_window.left, t_window.left + 7 * 24 - EPS, True)])
def init_run(self, n_people, n_visits):
self.scaled_test_threshold = self.max_pos_tests_per_week_per_100k / 100000 * n_people
self._is_init = True
@enforce_init_run
def _is_measure_active(self, t, t_pos_tests):
# If measures can only become active at 'intervention_times'
if self.intervention_times is not None:
# Find largest 'time' in intervention_times s.t. t > time
intervention_times = np.asarray(self.intervention_times)
idx = np.where(t - intervention_times > 0, t - intervention_times, np.inf).argmin()
t = intervention_times[idx]
t_in_history = list(self.intervention_history.find((t, t)))
if t_in_history:
is_active = t_in_history[0][2]
else:
is_active = self._are_cases_above_threshold(t, t_pos_tests)
if is_active:
self.intervention_history.update([(t, t+7*24 - EPS, True)])
return is_active
@enforce_init_run
def _are_cases_above_threshold(self, t, t_pos_tests):
# Count positive tests in last 7 days from last intervention time
tmin = t - 7 * 24
num_pos_tests = np.sum(np.greater(t_pos_tests, tmin) * np.less(t_pos_tests, t))
is_above_threshold = num_pos_tests > self.scaled_test_threshold
return is_above_threshold
@enforce_init_run
def beta_factor(self, *, typ, t, t_pos_tests):
"""Returns the multiplicative factor for site type `typ` at time `t`. The
factor is one if `t` is not in the active time window of the measure.
"""
if not self._in_window(t):
return 1.0
is_measure_active = self._is_measure_active(t, t_pos_tests)
return self.beta_multiplier[typ] if is_measure_active else 1.0
"""
========================== INDIVIDUAL COMPLIANCE WITH TRACKING ===========================
"""
class ComplianceForAllMeasure(Measure):
"""
Compliance measure. All the population has a probability of not using tracking app. This
influences the ability of smart tracing to track contacts. Each individual uses a tracking
app with some probability.
"""
def __init__(self, t_window, p_compliance):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_compliance : float
Probability that individual is compliant, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probability of respecting measure
if (not isinstance(p_compliance, float)) or (p_compliance < 0):
raise ValueError("`compliance` should be a non-negative float")
self.p_compliance = p_compliance
def init_run(self, n_people):
"""Init the measure for this run by sampling the compliance of each individual
Parameters
----------
n_people : int
Number of people in the population
"""
# Sample the outcome of the measure for each individual
self.bernoulli_compliant = np.random.binomial(1, self.p_compliance, size=(n_people))
self._is_init = True
@enforce_init_run
def is_compliant(self, *, j, t):
"""Indicate if individual `j` is compliant
"""
return self.bernoulli_compliant[j] and self._in_window(t)
def exit_run(self):
""" Deletes bernoulli array. """
if self._is_init:
self.bernoulli_compliant = None
self._is_init = False
class ManualTracingReachabilityForAllMeasure(Measure):
"""
Reachability measure. All the population has a probability of being reachable in
manual tracing. If an individual i complies with this measure and the infector participating in manual tracing
recalls a contact with i, i gets traced even if i does not comply with any digital tracing technology.
"""
def __init__(self, t_window, p_reachable):
"""
Parameters
----------
t_window : Interval
Time window during which the measure is active
p_participate : float
Probability that individual is participating with manual contact tracing, should be in [0,1]
p_recall : float
Probability that individual recalls a given visit, should be in [0,1]
"""
# Init time window
super().__init__(t_window)
# Init probability of respecting measure
if (not isinstance(p_reachable, float)) or (p_reachable < 0):
raise ValueError("`p_reachable` should be a non-negative float")
self.p_reachable = p_reachable
def init_run(self, n_people, n_visits):
"""Init the measure for this run by sampling the compliance of each individual