-
Notifications
You must be signed in to change notification settings - Fork 33
/
plot.py
3168 lines (2622 loc) · 129 KB
/
plot.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 os
import itertools
import collections
import numpy as np
import pandas as pd
import torch
from scipy import stats as sps
from scipy.interpolate import interp1d
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import ticker
import matplotlib.dates as mdates
from matplotlib.dates import date2num
from matplotlib.backends.backend_pgf import FigureCanvasPgf
from matplotlib.colors import ListedColormap
from matplotlib.transforms import ScaledTranslation
from matplotlib.ticker import FormatStrFormatter
from scipy.interpolate import griddata
import scipy.stats
import matplotlib.colors as colors
from lib.calibrationFunctions import downsample_cases, pdict_to_parr, load_state
from lib.data import collect_data_from_df
import botorch.utils.transforms as transforms
from lib.calibrationSettings import (
calibration_model_param_bounds_single,
calibration_start_dates,
calibration_lockdown_dates,
calibration_mob_paths,
)
from lib.calibrationFunctions import (
pdict_to_parr,
load_state,
downsample_cases,
CORNER_SETTINGS_SPACE,
)
from lib.data import collect_data_from_df
import botorch.utils.transforms as transforms
from lib.calibrationSettings import (
calibration_model_param_bounds_single,
calibration_start_dates,
calibration_lockdown_dates,
calibration_mob_paths,
)
from lib.rt import compute_daily_rts, R_T_RANGE
from lib.rt_nbinom import overdispersion_test
from lib.summary import *
TO_HOURS = 24.0
DPI = 200
NO_PLOT = False
TEST_LAG = 48.0 # hours
LINE_WIDTH = 7.0
COL_WIDTH = 3.333
FIG_SIZE_TRIPLE = (COL_WIDTH / 3, COL_WIDTH / 3 * 4/6)
FIG_SIZE_TRIPLE_TALL = (COL_WIDTH / 3, COL_WIDTH / 3 * 5/6)
FIG_SIZE_DOUBLE = (COL_WIDTH / 2, COL_WIDTH / 2 * 4/6)
FIG_SIZE_DOUBLE_TALL = (COL_WIDTH / 2, COL_WIDTH / 2 * 5/6)
CUSTOM_FIG_SIZE_FULL_PAGE_TRIPLE = (LINE_WIDTH / 3, COL_WIDTH / 2 * 5/6)
FIG_SIZE_FULL_PAGE_TRIPLE = (LINE_WIDTH / 3, LINE_WIDTH / 3 * 4/6)
FIG_SIZE_FULL_PAGE_TRIPLE_TALL = (LINE_WIDTH / 3, LINE_WIDTH / 3 * 5/6)
FIG_SIZE_FULL_PAGE_DOUBLE_ARXIV = (LINE_WIDTH / 2, LINE_WIDTH / 3 * 4/6) # 2
FIG_SIZE_FULL_PAGE_DOUBLE_ARXIV_TALL = (LINE_WIDTH / 2, LINE_WIDTH / 3 * 4.5/6) # 2 tall
FIG_SIZE_FULL_PAGE_TRIPLE_ARXIV = (LINE_WIDTH / 3.3, LINE_WIDTH / 3 * 3.5/6) # 4x3 full page
FIG_SIZE_FULL_PAGE_TRIPLE_ARXIV_SMALL = (LINE_WIDTH / 3.7, LINE_WIDTH / 3 * 2.5/6) # 6x4 full page
CUSTOM_FIG_SIZE_FULL_PAGE_QUAD = (LINE_WIDTH / 4, COL_WIDTH / 2 * 5/6)
SIGCONF_RCPARAMS_DOUBLE = {
# Fig params
"figure.autolayout": True, # Makes sure nothing the feature is neat & tight.
"figure.figsize": FIG_SIZE_DOUBLE, # Column width: 3.333 in, space between cols: 0.333 in.
"figure.dpi": 150, # Displays figures nicely in notebooks.
# Axes params
"axes.linewidth": 0.5, # Matplotlib's current default is 0.8.
"hatch.linewidth": 0.3,
"xtick.major.width": 0.5,
"xtick.minor.width": 0.5,
'xtick.major.pad': 1.0,
'xtick.major.size': 1.75,
'xtick.minor.pad': 1.0,
'xtick.minor.size': 1.0,
"ytick.major.width": 0.5,
"ytick.minor.width": 0.5,
'ytick.major.pad': 1.0,
'ytick.major.size': 1.75,
'ytick.minor.pad': 1.0,
'ytick.minor.size': 1.0,
"axes.labelpad": 0.5,
# Plot params
"lines.linewidth": 0.8, # Width of lines
"lines.markeredgewidth": 0.3,
# Legend params
"legend.fontsize": 8.5, # Make the legend/label fonts a little smaller
"legend.frameon": True, # Remove the black frame around the legend
"legend.handletextpad": 0.3,
"legend.borderaxespad": 0.2,
"legend.labelspacing": 0.1,
"patch.linewidth": 0.5,
# Font params
"text.usetex": True, # use LaTeX to write all text
"font.family": "serif", # use serif rather than sans-serif
"font.serif": "Linux Libertine O", # use "Linux Libertine" as the standard font
"font.size": 9,
"axes.titlesize": 8, # LaTeX default is 10pt font.
"axes.labelsize": 8, # LaTeX default is 10pt font.
"xtick.labelsize": 6,
"ytick.labelsize": 6,
# PDF settings
"pgf.texsystem": "xelatex", # Use Xelatex which is TTF font aware
"pgf.rcfonts": False, # Use pgf.preamble, ignore standard Matplotlib RC
"pgf.preamble": [
r'\usepackage{fontspec}',
r'\usepackage{unicode-math}',
r'\usepackage{libertine}',
r'\setmainfont{Linux Libertine O}',
r'\setmathfont{Linux Libertine O}',
]
}
SIGCONF_RCPARAMS_TRIPLE = {
# Fig params
"figure.autolayout": True, # Makes sure nothing the feature is neat & tight.
"figure.figsize": FIG_SIZE_TRIPLE, # Column width: 3.333 in, space between cols: 0.333 in.
"figure.dpi": 150, # Displays figures nicely in notebooks.
# Axes params
"axes.linewidth": 0.4, # Matplotlib's current default is 0.8.
"hatch.linewidth": 0.3,
"xtick.major.width": 0.4,
"xtick.minor.width": 0.4,
'xtick.major.pad': 1.0,
'xtick.major.size': 1.75,
'xtick.minor.pad': 1.0,
'xtick.minor.size': 1.0,
"ytick.major.width": 0.4,
"ytick.minor.width": 0.4,
'ytick.major.pad': 1.0,
'ytick.major.size': 1.75,
'ytick.minor.pad': 1.0,
'ytick.minor.size': 1.0,
"axes.labelpad": 0.5,
# Plot params
"lines.linewidth": 0.8, # Width of lines
"lines.markeredgewidth": 0.3,
# Legend
"legend.fontsize": 5.5, # Make the legend/label fonts a little smaller
"legend.frameon": True, # Remove the black frame around the legend
"legend.handletextpad": 0.5,
"legend.borderaxespad": 0.0,
"legend.labelspacing": 0.05,
"patch.linewidth": 0.3,
# Font params
"text.usetex": True, # use LaTeX to write all text
"font.family": "serif", # use serif rather than sans-serif
"font.serif": "Linux Libertine O", # use "Linux Libertine" as the standard font
"font.size": 6,
"axes.titlesize": 5, # LaTeX default is 10pt font.
"axes.labelsize": 5, # LaTeX default is 10pt font.
"xtick.labelsize": 5,
"ytick.labelsize": 5,
# PDF settings
"pgf.texsystem": "xelatex", # Use Xelatex which is TTF font aware
"pgf.rcfonts": False, # Use pgf.preamble, ignore standard Matplotlib RC
"pgf.preamble": [
r'\usepackage{fontspec}',
r'\usepackage{unicode-math}',
r'\usepackage{libertine}',
r'\setmainfont{Linux Libertine O}',
r'\setmathfont{Linux Libertine O}',
]
}
NEURIPS_LINE_WIDTH = 5.5 # Text width: 5.5in (double figure minus spacing 0.2in).
FIG_SIZE_NEURIPS_DOUBLE = (NEURIPS_LINE_WIDTH / 2, NEURIPS_LINE_WIDTH / 2 * 4/6)
FIG_SIZE_NEURIPS_TRIPLE = (NEURIPS_LINE_WIDTH / 3, NEURIPS_LINE_WIDTH / 3 * 4/6)
FIG_SIZE_NEURIPS_DOUBLE_TALL = (NEURIPS_LINE_WIDTH / 2, NEURIPS_LINE_WIDTH / 2 * 5/6)
FIG_SIZE_NEURIPS_TRIPLE_TALL = (NEURIPS_LINE_WIDTH / 3, NEURIPS_LINE_WIDTH / 3 * 5/6)
NEURIPS_RCPARAMS = {
"figure.autolayout": False, # Makes sure nothing the feature is neat & tight.
"figure.figsize": FIG_SIZE_NEURIPS_DOUBLE,
"figure.dpi": 150, # Displays figures nicely in notebooks.
# Axes params
"axes.linewidth": 0.5, # Matplotlib's current default is 0.8.
"xtick.major.width": 0.5,
"xtick.minor.width": 0.5,
"ytick.major.width": 0.5,
"ytick.minor.width": 0.5,
"hatch.linewidth": 0.3,
"xtick.major.width": 0.5,
"xtick.minor.width": 0.5,
'xtick.major.pad': 1.0,
'xtick.major.size': 1.75,
'xtick.minor.pad': 1.0,
'xtick.minor.size': 1.0,
'ytick.major.pad': 1.0,
'ytick.major.size': 1.75,
'ytick.minor.pad': 1.0,
'ytick.minor.size': 1.0,
"axes.labelpad": 0.5,
# Grid
"grid.linewidth": 0.3,
# Plot params
"lines.linewidth": 1.0,
"lines.markersize": 4,
'errorbar.capsize': 3.0,
# Font
"text.usetex": True, # use LaTeX to write all text
"font.family": "serif", # use serif rather than sans-serif
"font.serif": "Times New Roman", # use "Times New Roman" as the standard font
"font.size": 8.5,
"axes.titlesize": 8.5, # LaTeX default is 10pt font.
"axes.labelsize": 8.5, # LaTeX default is 10pt font.
"xtick.labelsize": 8,
"ytick.labelsize": 8,
# Legend
"legend.fontsize": 7, # Make the legend/label fonts a little smaller
"legend.frameon": True, # Remove the black frame around the legend
"legend.handletextpad": 0.3,
"legend.borderaxespad": 0.2,
"legend.labelspacing": 0.1,
"patch.linewidth": 0.5,
# PDF
"pgf.texsystem": "xelatex", # use Xelatex which is TTF font aware
"pgf.rcfonts": False, # Use pgf.preamble, ignore standard Matplotlib RC
"pgf.preamble": [
r'\usepackage{fontspec}',
r'\usepackage{unicode-math}',
r'\setmainfont{Times New Roman}',
],
}
def trans_data_to_axis(ax):
"""Compute the transform from data to axis coordinate system in axis `ax`"""
axis_to_data = ax.transAxes + ax.transData.inverted()
data_to_axis = axis_to_data.inverted()
return data_to_axis
def days_to_datetime(arr, start_date):
# timestamps
ts = arr * 24 * 60 * 60 + pd.Timestamp(start_date).timestamp()
return pd.to_datetime(ts, unit='s')
def lockdown_widget(ax, lockdown_at, start_date, lockdown_label_y, lockdown_label='Lockdown',
xshift=0.0, zorder=None, ls='--', color='black', text_off=False):
"""
Draw the lockdown widget corresponding to a vertical line at the desired location along with a
label. The data can be passed either in `float` or in `datetime` format.
Parameters
----------
ax
Axis to draw on
lockdown_at
Location of vertical lockdown line
start_date
Value of the origin of the x-axis
lockdown_label_y
Location of the text label on the y-axis
lockdown_label : str (optional, default: 'Lockdown')
Text label
xshift : float (optional, default: 0.0)
Shift in a-axis of the text label
zorder : int (optional, default: None)
z-order of the widget
ls : str (optional, default: '--')
Linestyle of the vertical line
color : str (optional, default: 'black')
color of the vertical line
text_off : bool (optional, default: False)
Indicate if the text label should be turned off
"""
if isinstance(start_date, float): # If plot with float x-axis
lckdn_x = start_date + lockdown_at
ax.axvline(lckdn_x, linestyle=ls, color=color, label='_nolegend_',
zorder=zorder)
else:
# If plot with datetime x-axis
lckdn_dt = days_to_datetime(lockdown_at, start_date=start_date) # str to datetime
lckdn_x_d = lckdn_dt.toordinal() # datetime to float in data coordinates
ax.axvline(lckdn_x_d, linestyle=ls, color=color, label='_nolegend_',
zorder=zorder)
# Display the text label
if not text_off:
if xshift == 0.0:
# Automatic shift of the text in the plot (normalized) axis coordinates
lckdn_x_a, _ = trans_data_to_axis(ax).transform([lckdn_x_d, 0.0]) # data coordinates to axis coordinates
ax.text(x=lckdn_x_a, y=lockdown_label_y, s=lockdown_label,
transform=ax.transAxes, rotation=90,
verticalalignment='bottom',
horizontalalignment='right')
else:
# NOTE: for backward-compatibility, manual shift of the text, should be removed
ax.text(x=lckdn_dt + pd.Timedelta(xshift, unit='d'),
y=lockdown_label_y, s=lockdown_label, rotation=90)
def target_widget(show_target,start_date, ax, zorder=None, ms=4.0, label='COVID-19 case data'):
txx = np.linspace(0, show_target.shape[0] - 1, num=show_target.shape[0])
txx = days_to_datetime(txx, start_date=start_date)
ax.plot(txx, show_target, ls='', marker='x', ms=ms,
color='black', label=label, zorder=zorder)
class CustomSitesProportionFixedLocator(plt.Locator):
"""
Custom locator to avoid tick font bug of matplotlib
"""
def __init__(self):
pass
def __call__(self):
return np.log(np.array([2, 5, 10, 25, 100]))
class Plotter(object):
"""
Plotting class
"""
def __init__(self):
# plot constants
# check out https://colorhunt.co/
self.color_expo = '#ffcc00'
self.color_iasy = '#00a8cc'
self.color_ipre = '#005082'
self.color_isym = '#000839'
self.color_testing = '#ffa41b'
self.color_posi = '#4daf4a'
self.color_nega = '#e41a1c'
self.color_all = '#ffa41b'
self.color_positive = '#00a8cc'
self.color_age = '#005082'
self.color_tracing = '#000839'
self.color_infected = '#000839'
self.filling_alpha = 0.2
self.color_different_scenarios = [
'#e41a1c',
'#377eb8',
'#4daf4a',
#'#984ea3',
'#ff7f00',
'#ffff33',
'#a65628',
'#f781bf',
'#999999'
]
self.color_different_scenarios_alt = [
'#a1dab4',
'#41b6c4',
'#2c7fb8',
'#253494',
]
self.color_model_fit_light = '#bdbdbd'
self.color_model_fit_dark = '#636363'
# 2D visualization
self.density_alpha = 0.7
self.marker_home = "^"
self.marker_site = "o"
self.color_home = '#000839'
self.color_site = '#000000'
self.size_home = 80
self.size_site = 300
def _set_matplotlib_params(self, format='double'):
# matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
if format == 'double':
plt.rcParams.update(SIGCONF_RCPARAMS_DOUBLE)
elif format == 'triple':
plt.rcParams.update(SIGCONF_RCPARAMS_TRIPLE)
if format == 'neurips-double':
plt.rcParams.update(NEURIPS_RCPARAMS)
else:
raise ValueError('Invalid figure format.')
def _set_default_axis_settings(self, ax):
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
def plot_cumulative_infected(self, sim, title='Example', filename='daily_inf_0',
figsize=(6, 5), errorevery=20, acc=1000, ymax=None,
lockdown_label='Lockdown', lockdown_at=None,
lockdown_label_y=None, show_target=None,
start_date='1970-01-01',
subplot_adjust=None, legend_loc='upper right'):
''''
Plots daily infected split by group
averaged over random restarts, using error bars for std-dev
'''
if acc > sim.max_time:
acc = int(sim.max_time)
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
ts, iasy_mu, iasy_sig = self.__comp_state_cumulative(sim, 'iasy', acc)
# _, ipre_mu, ipre_sig = self.__comp_state_cumulative(sim, 'ipre', acc)
_, isym_mu, isym_sig = self.__comp_state_cumulative(sim, 'isym', acc)
# _, expo_mu, iexpo_sig = self.__comp_state_cumulative(sim, 'expo', acc)
# _, posi_mu, posi_sig = self.__comp_state_cumulative(sim, 'posi', acc)
line_xaxis = np.zeros(ts.shape)
line_iasy = iasy_mu
line_isym = iasy_mu + isym_mu
error_isym = np.sqrt(iasy_sig**2 + isym_sig**2)
# Convert x-axis into posix timestamps and use pandas to plot as dates
ts = days_to_datetime(ts, start_date=start_date)
# lines
ax.plot(ts, line_iasy, c='black', linestyle='-')
ax.errorbar(ts, line_isym, yerr=error_isym, c='black', linestyle='-',
elinewidth=0.8, errorevery=errorevery, capsize=3.0)
# filling
ax.fill_between(ts, line_xaxis, line_iasy, alpha=self.filling_alpha, label='Asymptomatic',
edgecolor=self.color_iasy, facecolor=self.color_iasy, linewidth=0, zorder=0)
ax.fill_between(ts, line_iasy, line_isym, alpha=self.filling_alpha, label='Symptomatic',
edgecolor=self.color_isym, facecolor=self.color_isym, linewidth=0, zorder=0)
# limits
if ymax is None:
ymax = 1.5 * np.max(iasy_mu + isym_mu)
ax.set_ylim((0, ymax))
# ax.set_xlabel('Days')
ax.set_ylabel('People')
# extra
if lockdown_at is not None:
lockdown_widget(ax, lockdown_at, start_date,
lockdown_label_y,
lockdown_label)
if show_target is not None:
target_widget(show_target, start_date, ax)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
#set ticks every week
ax.xaxis.set_major_locator(mdates.WeekdayLocator())
#set major ticks format
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')
# legend
ax.legend(loc=legend_loc, borderaxespad=0.5)
subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}
plt.subplots_adjust(**subplot_adjust)
plt.draw()
plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,
dpi=DPI, bbox_inches='tight')
if NO_PLOT:
plt.close()
return
def plot_daily_infected(self, sim, title='Example', filename='daily_inf_0',
figsize=(6, 5), errorevery=20, acc=1000, ymax=None,
lockdown_label='Lockdown', lockdown_at=None,
lockdown_label_y=None, show_target=None,
lockdown_end=None,
start_date='1970-01-01',
subplot_adjust=None, legend_loc='upper right'):
''''
Plots daily infected split by group
averaged over random restarts, using error bars for std-dev
'''
if acc > sim.max_time:
acc = int(sim.max_time)
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
ts, iasy_mu, iasy_sig = comp_state_over_time(sim, 'iasy', acc)
_, ipre_mu, ipre_sig = comp_state_over_time(sim, 'ipre', acc)
_, isym_mu, isym_sig = comp_state_over_time(sim, 'isym', acc)
# _, expo_mu, iexpo_sig = comp_state_over_time(sim, 'expo', acc)
# _, posi_mu, posi_sig = comp_state_over_time(sim, 'posi', acc)
line_xaxis = np.zeros(ts.shape)
line_iasy = iasy_mu
line_ipre = iasy_mu + ipre_mu
line_isym = iasy_mu + ipre_mu + isym_mu
error_isym = np.sqrt(iasy_sig**2 + ipre_sig**2 + isym_sig**2)
# Convert x-axis into posix timestamps and use pandas to plot as dates
ts = days_to_datetime(ts, start_date=start_date)
# lines
ax.plot(ts, line_iasy,
c='black', linestyle='-')
ax.plot(ts, line_ipre,
c='black', linestyle='-')
ax.errorbar(ts, line_isym, yerr=error_isym, c='black', linestyle='-',
elinewidth=0.8, errorevery=errorevery, capsize=3.0)
# filling
ax.fill_between(ts, line_xaxis, line_iasy, alpha=0.5, label='Asymptomatic',
edgecolor=self.color_iasy, facecolor=self.color_iasy, linewidth=0, zorder=0)
ax.fill_between(ts, line_iasy, line_ipre, alpha=0.5, label='Pre-symptomatic',
edgecolor=self.color_ipre, facecolor=self.color_ipre, linewidth=0, zorder=0)
ax.fill_between(ts, line_ipre, line_isym, alpha=0.5, label='Symptomatic',
edgecolor=self.color_isym, facecolor=self.color_isym, linewidth=0, zorder=0)
# limits
if ymax is None:
ymax = 1.5 * np.max(iasy_mu + ipre_mu + isym_mu)
ax.set_ylim((0, ymax))
# ax.set_xlabel('Days')
ax.set_ylabel('People')
# extra
if lockdown_at is not None:
lockdown_widget(ax, lockdown_at, start_date,
lockdown_label_y,
lockdown_label)
if lockdown_end is not None:
lockdown_widget(ax=ax, lockdown_at=lockdown_end, start_date=start_date,
lockdown_label_y=lockdown_label_y,
lockdown_label='End of lockdown', ls='dotted')
if show_target is not None:
target_widget(show_target, start_date, ax)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
#set ticks every week
ax.xaxis.set_major_locator(mdates.WeekdayLocator())
#set major ticks format
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')
# legend
ax.legend(loc=legend_loc, borderaxespad=0.5)
subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}
plt.subplots_adjust(**subplot_adjust)
plt.draw()
plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,
dpi=DPI, bbox_inches='tight')
if NO_PLOT:
plt.close()
return
def plot_daily_tested(self, sim, title='Example', filename='daily_tested_0', figsize=(10, 10), errorevery=20,
acc=1000, ymax=None):
''''
Plots daily tested, positive daily tested, negative daily tested
averaged over random restarts, using error bars for std-dev
'''
if acc > sim.max_time:
acc = int(sim.max_time)
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
# automatically shifted by `test_lag` in the function
ts, posi_mu, posi_sig = comp_state_over_time(sim, 'posi', acc)
_, nega_mu, nega_sig = comp_state_over_time(sim, 'nega', acc)
line_xaxis = np.zeros(ts.shape)
line_posi = posi_mu
line_nega = posi_mu + nega_mu
error_posi = posi_sig
error_nega = nega_sig + posi_sig
T = posi_mu.shape[0]
# lines
ax.errorbar(ts, line_posi, yerr=posi_sig, elinewidth=0.8, errorevery=errorevery,
c='black', linestyle='dotted')
ax.errorbar(ts, line_nega, yerr=nega_sig, elinewidth=0.8, errorevery=errorevery,
c='black', linestyle='-')
# filling
ax.fill_between(ts, line_xaxis, line_posi, alpha=0.5, label=r'Positive tests',
edgecolor=self.color_posi, facecolor=self.color_posi, linewidth=0, zorder=0)
ax.fill_between(ts, line_posi, line_nega, alpha=0.5, label=r'Negative tests',
edgecolor=self.color_nega, facecolor=self.color_nega, linewidth=0, zorder=0)
# axis
ax.set_xlim((0, np.max(ts)))
if ymax is None:
ymax = 1.5 * np.max(posi_mu + nega_mu)
ax.set_ylim((0, ymax))
ax.set_xlabel(r'$t$ [days]')
ax.set_ylabel(r'Tests')
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
# legend
fig.legend(loc='center right', borderaxespad=0.1)
# Adjust the scaling factor to fit your legend text completely outside the plot
plt.subplots_adjust(right=0.70)
ax.set_title(title, pad=20)
plt.draw()
plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,
dpi=DPI, bbox_inches='tight')
if NO_PLOT:
plt.close()
return
def plot_daily_at_home(self, sim, title='Example', filename='daily_at_home_0', figsize=(10, 10), errorevery=20, acc=1000, ymax=None):
''''
Plots daily tested, positive daily tested, negative daily tested
averaged over random restarts, using error bars for std-dev
'''
if acc > sim.max_time:
acc = int(sim.max_time)
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
ts, all_mu, all_sig = comp_contained_over_time(sim, 'SocialDistancingForAllMeasure', acc)
_, positive_mu, positive_sig = comp_contained_over_time(sim, 'SocialDistancingForPositiveMeasure', acc)
_, age_mu, age_sig = comp_contained_over_time(sim, 'SocialDistancingByAgeMeasure', acc)
_, tracing_mu, tracing_sig = comp_contained_over_time(sim, 'SocialDistancingForSmartTracing', acc)
_, iasy_mu, iasy_sig = comp_state_over_time(sim, 'iasy', acc)
_, ipre_mu, ipre_sig = comp_state_over_time(sim, 'ipre', acc)
_, isym_mu, isym_sig = comp_state_over_time(sim, 'isym', acc)
line_xaxis = np.zeros(ts.shape)
line_all = all_mu
line_positive = positive_mu
line_age = age_mu
line_tracing = tracing_mu
line_infected = iasy_mu + ipre_mu + isym_mu
error_all = all_sig
error_positive = positive_sig
error_age = age_sig
error_tracing = tracing_sig
error_infected = np.sqrt(np.square(iasy_sig) + np.square(ipre_sig) + np.square(isym_sig))
# lines
ax.errorbar(ts, line_infected, label=r'Total infected', errorevery=errorevery, c=self.color_infected, linestyle='--', yerr=error_infected)
ax.errorbar(ts, line_all, yerr=error_all, elinewidth=0.8, errorevery=errorevery,
c='black', linestyle='-')
ax.errorbar(ts, line_positive, yerr=error_positive, elinewidth=0.8, errorevery=errorevery,
c='black', linestyle='-')
ax.errorbar(ts, line_age, yerr=error_age, elinewidth=0.8, errorevery=errorevery,
c='black', linestyle='-')
ax.errorbar(ts, line_tracing, yerr=error_tracing, elinewidth=0.8, errorevery=errorevery,
c='black', linestyle='-')
# filling
ax.fill_between(ts, line_xaxis, line_all, alpha=self.filling_alpha, label=r'SD for all',
edgecolor=self.color_all, facecolor=self.color_all, linewidth=0, zorder=0)
ax.fill_between(ts, line_xaxis, line_positive, alpha=self.filling_alpha, label=r'SD for positively tested',
edgecolor=self.color_positive, facecolor=self.color_positive, linewidth=0, zorder=0)
ax.fill_between(ts, line_xaxis, line_age, alpha=self.filling_alpha, label=r'SD for age group',
edgecolor=self.color_age, facecolor=self.color_age, linewidth=0, zorder=0)
ax.fill_between(ts, line_xaxis, line_tracing, alpha=self.filling_alpha, label=r'SD for traced contacts',
edgecolor=self.color_tracing, facecolor=self.color_tracing, linewidth=0, zorder=0)
# axis
ax.set_xlim((0, np.max(ts)))
if ymax is None:
ymax = 1.5 * np.max([all_mu, positive_mu, age_mu, tracing_mu])
ax.set_ylim((0, ymax))
ax.set_xlabel(r'$t$ [days]')
ax.set_ylabel(r'[people]')
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
# legend
fig.legend(loc='center right', borderaxespad=0.1)
# Adjust the scaling factor to fit your legend text completely outside the plot
plt.subplots_adjust(right=0.70)
ax.set_title(title, pad=20)
plt.draw()
plt.savefig('plots/' + filename + '.png', format='png', facecolor=None,
dpi=DPI, bbox_inches='tight')
if NO_PLOT:
plt.close()
return
def compare_total_infections(self, sims, titles, figtitle='Title', figformat='double',
filename='compare_inf_0', figsize=None, errorevery=20, acc=500, ymax=None, x_axis_dates=True,
lockdown_label='Lockdown', lockdown_at=None, lockdown_label_y=None, lockdown_xshift=0.0,
conditional_measures=None,
show_positives=False, show_legend=True, legend_is_left=False,
subplot_adjust=None, start_date='1970-01-01', xtick_interval=2, first_one_dashed=False,
show_single_runs=False, which_single_runs=None):
''''
Plots total infections for each simulation, named as provided by `titles`
to compare different measures/interventions taken. Colors taken as defined in __init__, and
averaged over random restarts, using error bars for std-dev
'''
assert isinstance(sims[0], str), '`sims` must be list of filepaths'
# Set double figure format
self._set_matplotlib_params(format=figformat)
# Draw figure
fig, ax = plt.subplots(1, 1, figsize=figsize)
for i, sim in enumerate(sims):
is_conditional = True if i == conditional_measures else False
try:
data = load_condensed_summary(sim, acc)
except FileNotFoundError:
acc = create_condensed_summary_from_path(sim, acc=acc)
data = load_condensed_summary(sim, acc)
ts = data['ts']
lockdown_at = data['lockdowns'] if is_conditional else lockdown_at
if x_axis_dates:
# Convert x-axis into posix timestamps and use pandas to plot as dates
ts = days_to_datetime(ts, start_date=start_date)
if not show_single_runs:
iasy_mu = data['iasy_mu']
iasy_sig = data['iasy_sig']
ipre_mu = data['ipre_mu']
ipre_sig = data['ipre_sig']
isym_mu = data['isym_mu']
isym_sig = data['isym_sig']
line_infected = iasy_mu + ipre_mu + isym_mu
error_infected = np.sqrt(np.square(iasy_sig) + np.square(ipre_sig) + np.square(isym_sig))
# lines
ax.plot(ts, line_infected, linestyle='-', label=titles[i], c=self.color_different_scenarios[i])
ax.fill_between(ts, np.maximum(line_infected - 2 * error_infected, 0), line_infected + 2 * error_infected,
color=self.color_different_scenarios[i], alpha=self.filling_alpha, linewidth=0.0)
else:
iasy = data['iasy']
ipre = data['ipre']
isym = data['isym']
lines_infected = iasy + ipre + isym
# lines
runs = [which_single_runs] if which_single_runs else range(min(show_single_runs, sim.random_repeats))
for k, r in enumerate(runs):
ax.plot(ts, lines_infected[:, r], linestyle='-', label=titles[i] if k == 0 else None,
c=self.color_different_scenarios[i])
# For conditional measures only
if lockdown_at:
for lockdown in lockdown_at[r]:
start_lockdown = lockdown[0] / TO_HOURS
end_lockdown = lockdown[1] / TO_HOURS
lockdown_widget(ax, start_lockdown, 0.0,
lockdown_label_y,
None)
lockdown_widget(ax, end_lockdown, 0.0,
lockdown_label_y,
None, ls='-')
# axis
ax.set_xlim(left=np.min(ts))
if ymax is None:
ymax = 1.5 * np.max(iasy_mu + ipre_mu + isym_mu)
ax.set_ylim((0, ymax))
# ax.set_xlabel('Days')
if x_axis_dates:
# set xticks every week
ax.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=1, interval=1))
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=1, interval=xtick_interval))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')
else:
ax.set_xlabel(r'$t$ [days]')
ax.set_ylabel('Infected')
if not isinstance(lockdown_at, list):
if lockdown_at is not None:
lockdown_widget(ax, lockdown_at, start_date,
lockdown_label_y,
lockdown_label,
xshift=lockdown_xshift)
# Set default axes style
self._set_default_axis_settings(ax=ax)
if show_legend:
# legend
if legend_is_left:
leg = ax.legend(loc='upper left',
bbox_to_anchor=(0.001, 0.999),
bbox_transform=ax.transAxes,
# prop={'size': 5.6}
)
else:
leg = ax.legend(loc='upper right',
bbox_to_anchor=(0.999, 0.999),
bbox_transform=ax.transAxes,
# prop={'size': 5.6}
)
subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}
plt.subplots_adjust(**subplot_adjust)
plt.savefig('plots/' + filename + '.pdf', format='pdf', facecolor=None,
dpi=DPI, bbox_inches='tight')
if NO_PLOT:
plt.close()
return
def compare_quantity(self, sims, labels, titles=None, quantity='infected', mode='total', ymax=None, colors=None,
start_date='1970-01-01', xtick_interval=3, x_axis_dates=False,
figformat='double', filename='compare_epidemics', figsize=None,
lockdown_label='Lockdown', lockdown_at=None, lockdown_label_y=None, lockdown_xshift=0.0,
show_legend=True, legend_is_left=False, subplot_adjust=None):
''''
Plots `quantity` in `mode` for each simulation, named as provided by `titles`
to compare different measures/interventions taken. Colors taken as defined in __init__, and
averaged over random restarts, using error bars for std-dev
'''
#assert isinstance(sims[0], str), '`sims` must be list of filepaths'
if isinstance(sims[0], str):
sims = [sims]
titles = [titles]
multiplot = False
else:
multiplot = True
assert mode in ['total', 'daily', 'cumulative', 'weekly incidence']
assert quantity in ['infected', 'hosp', 'dead']
labeldict = {'total': {'infected': 'Infected',
'hosp': 'Hospitalized',
'dead': 'Fatalities'},
'cumulative': {'infected': 'Cumulative Infections',
'hosp': 'Cumulative Hospitalizations',
'dead': 'Cumulative Fatalities'},
'daily': {'infected': 'Daily Infections',
'hosp': 'Daily Hospitalizations',
'dead': 'Daily Fatalities'},
'weekly incidence': {'infected': 'Weekly infection incidence'}
}
# Set double figure format
self._set_matplotlib_params(format=figformat)
# Draw figure
fig, axs = plt.subplots(1, len(sims), figsize=figsize)
if not multiplot:
axs = [axs]
for j, (paths, ax) in enumerate(zip(sims, axs)):
for i, sim in enumerate(paths):
data = load_condensed_summary_compat(sim)
line_cases, error_cases = get_plot_data(data, quantity=quantity, mode=mode)
if mode in ['daily', 'weekly incidence']:
ts = np.arange(0, len(line_cases))
if mode == 'daily':
error_cases = np.zeros(len(line_cases))
else:
ts = data['ts'] if not x_axis_dates else days_to_datetime(data['ts'], start_date=start_date)
if colors is None:
colors = self.color_different_scenarios[i]
# lines
ax.plot(ts, line_cases, linestyle='-', label=labels[i], c=colors[i])
ax.fill_between(ts, np.maximum(line_cases - 2 * error_cases, 0), line_cases + 2 * error_cases,
color=colors[i], alpha=self.filling_alpha, linewidth=0.0)
# axis
ax.set_xlim(left=np.min(ts))
if ymax is None:
ymax = 1.5 * np.max(line_cases)
ax.set_ylim((0, ymax))
if titles:
ax.set_title(titles[j])
if x_axis_dates:
# set xticks every week
ax.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=1, interval=1))
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=1, interval=xtick_interval))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
fig.autofmt_xdate(bottom=0.2, rotation=0, ha='center')
else:
ax.set_xlabel(r'$t$ [days]')
ylabel = labeldict[mode][quantity]
if j == 0:
ax.set_ylabel(ylabel)
if lockdown_at is not None:
lockdown_widget(ax, lockdown_at, start_date,
lockdown_label_y,
lockdown_label,
xshift=lockdown_xshift)
# Set default axes style
self._set_default_axis_settings(ax=ax)
if show_legend:
# legend
if legend_is_left is True:
leg = ax.legend(loc='upper left',
bbox_to_anchor=(0.001, 0.999),
bbox_transform=ax.transAxes,
# prop={'size': 5.6}
)
elif legend_is_left is False:
leg = ax.legend(loc='upper right',
bbox_to_anchor=(0.999, 0.999),
bbox_transform=ax.transAxes,
# prop={'size': 5.6}
)
if titles:
axs[-1].legend(loc='lower left', bbox_to_anchor=(1.08, 0.22),
borderaxespad=0, frameon=True)
subplot_adjust = subplot_adjust or {'bottom':0.14, 'top': 0.98, 'left': 0.12, 'right': 0.96}
plt.subplots_adjust(**subplot_adjust)
if multiplot:
plt.tight_layout()
plt.savefig('plots/' + filename + '.pdf', format='pdf', facecolor=None,
dpi=DPI, bbox_inches='tight')
if NO_PLOT: