Repository navigation
Expand file tree
/
Copy pathvic-2021.py
More file actions
981 lines (849 loc) · 31.6 KB
/
Copy pathvic-2021.py
File metadata and controls
981 lines (849 loc) · 31.6 KB
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
import sys
from datetime import datetime
from pytz import timezone
from pathlib import Path
import json
import pickle
from scipy.signal import convolve
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.units as munits
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import pandas as pd
from reff_plots_common import (
covidlive_case_data,
covidlive_new_cases,
covidlive_doses_per_100,
exponential,
determine_smoothed_cases_and_Reff,
exponential_with_vax,
exponential_with_infection_immunity,
get_SIR_projection,
get_exp_projection,
whiten,
th,
)
# Our uncertainty calculations are stochastic. Make them reproducible, at least:
np.random.seed(0)
converter = mdates.ConciseDateConverter()
munits.registry[np.datetime64] = converter
munits.registry[datetime.date] = converter
munits.registry[datetime] = converter
POP_OF_VIC = 6.681e6
VAX = 'vax' in sys.argv
LGA_IX = None
LGA = None
OLD = 'old' in sys.argv
if not VAX and sys.argv[1:]:
if len(sys.argv) == 2:
LGA_IX = int(sys.argv[1])
elif OLD and len(sys.argv) == 3:
OLD_END_IX = int(sys.argv[2])
else:
raise ValueError(sys.argv[1:])
if OLD:
VAX = True
# Data from DHHS by diagnosis date
def lga_data():
url = "https://www.dhhs.vic.gov.au/ncov-covid-cases-by-lga-source-csv"
df = pd.read_csv(url)
LGAs = set(df['Localgovernmentarea'])
cases_by_lga = {}
for lga in LGAs:
cases_by_date = {
d: 0
for d in np.arange(
np.datetime64(df['diagnosis_date'].min()),
np.datetime64(df['diagnosis_date'].max()) + 1,
)
}
for _, row in df[df['Localgovernmentarea'] == lga].iterrows():
cases_by_date[np.datetime64(row['diagnosis_date'])] += 1
dates = np.array(list(cases_by_date.keys()))
new = np.array(list(cases_by_date.values()))
cases_by_lga[lga.split(' (')[0]] = new
# Last day is incomplete data, ignore it:
# dates = dates[:-1]
# cases_by_lga = {lga: cases[:-1] for lga, cases in cases_by_lga.items()}
return dates, cases_by_lga
def statewide_data(start_date=np.datetime64('2021-05-10')):
url = "https://www.dhhs.vic.gov.au/ncov-covid-cases-by-source-csv"
df = pd.read_csv(url)
cases_by_date = {
d: 0
for d in np.arange(
np.datetime64(df['diagnosis_date'].min()),
np.datetime64(df['diagnosis_date'].max()) + 1,
)
}
for _, row in df[df['acquired'] != "Travel overseas"].iterrows():
cases_by_date[np.datetime64(row['diagnosis_date'])] += 1
dates = np.array(list(cases_by_date.keys()))
cases = np.array(list(cases_by_date.values()))
covidlive_dates, covidlive_cases = covidlive_case_data('VIC', start_date=start_date)
# Fill in missing data from covidlive. In the mornings this will usually only be one
# number, but sometimes when DH fail to update the official dataset for a whole day
# it might be two
covidlive_more_recent = covidlive_dates > dates[-1]
if covidlive_more_recent.any():
dates = np.append(dates, covidlive_dates[covidlive_more_recent])
cases = np.append(cases, covidlive_cases[covidlive_more_recent])
cases = cases[dates >= start_date]
dates = dates[dates >= start_date]
return dates, cases
def projected_vaccine_immune_population(t, historical_doses_per_100):
"""compute projected future susceptible population, given an array
historical_doses_per_100 for cumulative doses doses per 100 population prior to and
including today (length doesn't matter, so long as it goes back longer than
VAX_ONSET_MU plus 3 * VAX_ONSET_SIGMA), and assuming a certain vaccine efficacy and
rollout schedule"""
# We assume vaccine effectiveness after each dose ramps up the integral of a
# Gaussian with the following mean and stddev in days:
VAX_ONSET_MU = 10.5
VAX_ONSET_SIGMA = 3.5
SEP = np.datetime64('2021-09-01').astype(int) - dates[-1].astype(int)
OCT = np.datetime64('2021-10-01').astype(int) - dates[-1].astype(int)
doses_per_100 = np.zeros_like(t)
doses_per_100[0] = historical_doses_per_100[-1]
# History of previously projected rates, so I can remake old projections:
if dates[-1] >= np.datetime64('2021-11-21'):
AUG_RATE = None
SEP_RATE = None
OCT_RATE = 0.2
elif dates[-1] >= np.datetime64('2021-11-09'):
AUG_RATE = None
SEP_RATE = None
OCT_RATE = 0.5
elif dates[-1] >= np.datetime64('2021-10-30'):
AUG_RATE = None
SEP_RATE = None
OCT_RATE = 0.75
elif dates[-1] >= np.datetime64('2021-09-12'):
AUG_RATE = None
SEP_RATE = 1.4
OCT_RATE = 1.8
else:
AUG_RATE = 1.0
SEP_RATE = 1.2
OCT_RATE = 1.4
for i in range(1, len(doses_per_100)):
if i < SEP:
doses_per_100[i] = doses_per_100[i - 1] + AUG_RATE
elif i < OCT:
doses_per_100[i] = doses_per_100[i - 1] + SEP_RATE
else:
doses_per_100[i] = doses_per_100[i - 1] + OCT_RATE
if dates[-1] >= np.datetime64('2021-11-21'):
MAX_DOSES_PER_100 = 2 * 80.0
else:
MAX_DOSES_PER_100 = 2 * 85.0
doses_per_100 = np.clip(doses_per_100, 0, MAX_DOSES_PER_100)
all_doses_per_100 = np.concatenate([historical_doses_per_100, doses_per_100])
# The "prepend=0" makes it as if all the doses in the initial day were just
# administered all at once, but as long as historical_doses_per_100 is long enough
# for it to have taken full effect, it doesn't matter.
daily = np.diff(all_doses_per_100, prepend=0)
# convolve daily doses with a transfer function for delayed effectiveness of vaccnes
pts = int(VAX_ONSET_MU + 3 * VAX_ONSET_SIGMA)
x = np.arange(-pts, pts + 1, 1)
kernel = np.exp(-((x - VAX_ONSET_MU) ** 2) / (2 * VAX_ONSET_SIGMA ** 2))
kernel /= kernel.sum()
convolved = convolve(daily, kernel, mode='same')
effective_doses_per_100 = convolved.cumsum()
immune = 0.4 * effective_doses_per_100[len(historical_doses_per_100):] / 100
return immune
if LGA_IX is not None:
today = np.datetime64(datetime.now(), 'D')
LGA_DATA_CACHE = Path(f'VIC_LGA_DATA_{today}.temp.pickle')
if not LGA_DATA_CACHE.exists():
dates, cases_by_lga = lga_data()
LGA_DATA_CACHE.write_bytes(pickle.dumps((dates, cases_by_lga)))
dates, cases_by_lga = pickle.loads(LGA_DATA_CACHE.read_bytes())
# Sort LGAs in reverse order by last 14d cases
sorted_lgas = sorted(
cases_by_lga.keys(), key=lambda k: -cases_by_lga[k][-14:].sum()
)
# print(sorted_lgas)
# for lga in sorted_lgas:
# print(lga, cases_by_lga[lga][-14:].sum())
if LGA_IX is not None:
LGA = sorted_lgas[LGA_IX]
new = cases_by_lga[LGA]
else:
# dates, new = statewide_data()
# Switch to total daily cases after about May 6th:
if not OLD or OLD_END_IX > 250:
dates, new = covidlive_new_cases('VIC', start_date=np.datetime64('2021-05-10'))
else:
dates, new = covidlive_case_data('VIC', start_date=np.datetime64('2021-05-10'))
if dates[-1] >= np.datetime64('2022-01-16'):
# Data corrections as of the afternoon of Jan 16th:
new[dates==np.datetime64('2021-12-31')] += 71
new[dates==np.datetime64('2022-01-01')] += 624
new[dates==np.datetime64('2022-01-02')] += 2_149
new[dates==np.datetime64('2022-01-03')] += 5_784
new[dates==np.datetime64('2022-01-04')] += 8_289
new[dates==np.datetime64('2022-01-05')] += 10_626
new[dates==np.datetime64('2022-01-06')] += 13_223
new[dates==np.datetime64('2022-01-07')] += 14_894
new[dates==np.datetime64('2022-01-08')] += 16_310
new[dates==np.datetime64('2022-01-09')] += 15_523
new[dates==np.datetime64('2022-01-10')] += 15_804
new[dates==np.datetime64('2022-01-11')] += 14_159
new[dates==np.datetime64('2022-01-12')] += 13_352
new[dates==np.datetime64('2022-01-13')] += 11_935
new[dates==np.datetime64('2022-01-14')] += 9_678
new[dates==np.datetime64('2022-01-15')] += 6_202
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
new[dates==np.datetime64('2022-01-09')] -= 17_190
new[dates==np.datetime64('2022-01-10')] -= 18_503
new[dates==np.datetime64('2022-01-11')] -= 18_434
new[dates==np.datetime64('2022-01-12')] -= 16_843
new[dates==np.datetime64('2022-01-13')] -= 15_440
new[dates==np.datetime64('2022-01-14')] -= 12_857
new[dates==np.datetime64('2022-01-15')] -= 10_337
elif dates[-1] == np.datetime64('2022-01-15'):
# Data corrections as of the afternoon of Jan 15th:
new[dates==np.datetime64('2021-12-31')] += 71
new[dates==np.datetime64('2022-01-01')] += 624
new[dates==np.datetime64('2022-01-02')] += 2_149
new[dates==np.datetime64('2022-01-03')] += 5_784
new[dates==np.datetime64('2022-01-04')] += 8_289
new[dates==np.datetime64('2022-01-05')] += 10_626
new[dates==np.datetime64('2022-01-06')] += 13_223
new[dates==np.datetime64('2022-01-07')] += 14_894
new[dates==np.datetime64('2022-01-08')] += 16_310
new[dates==np.datetime64('2022-01-09')] += 15_089
new[dates==np.datetime64('2022-01-10')] += 15_370
new[dates==np.datetime64('2022-01-11')] += 13_725
new[dates==np.datetime64('2022-01-12')] += 12_918
new[dates==np.datetime64('2022-01-13')] += 10_960
new[dates==np.datetime64('2022-01-14')] += 7_714
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
new[dates==np.datetime64('2022-01-09')] -= 17_190
new[dates==np.datetime64('2022-01-10')] -= 18_503
new[dates==np.datetime64('2022-01-11')] -= 18_434
new[dates==np.datetime64('2022-01-12')] -= 16_843
new[dates==np.datetime64('2022-01-13')] -= 15_440
new[dates==np.datetime64('2022-01-14')] -= 12_857
elif dates[-1] == np.datetime64('2022-01-14'):
# Data corrections as of the afternoon of Jan 14th:
new[dates==np.datetime64('2021-12-31')] += 71
new[dates==np.datetime64('2022-01-01')] += 624
new[dates==np.datetime64('2022-01-02')] += 2_149
new[dates==np.datetime64('2022-01-03')] += 5_784
new[dates==np.datetime64('2022-01-04')] += 8_289
new[dates==np.datetime64('2022-01-05')] += 10_626
new[dates==np.datetime64('2022-01-06')] += 13_223
new[dates==np.datetime64('2022-01-07')] += 14_894
new[dates==np.datetime64('2022-01-08')] += 15_745
new[dates==np.datetime64('2022-01-09')] += 14_523
new[dates==np.datetime64('2022-01-10')] += 14_804
new[dates==np.datetime64('2022-01-11')] += 13_159
new[dates==np.datetime64('2022-01-12')] += 12_352
new[dates==np.datetime64('2022-01-13')] += 8_646
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
new[dates==np.datetime64('2022-01-09')] -= 17_190
new[dates==np.datetime64('2022-01-10')] -= 18_503
new[dates==np.datetime64('2022-01-11')] -= 18_434
new[dates==np.datetime64('2022-01-12')] -= 16_843
new[dates==np.datetime64('2022-01-13')] -= 15_440
elif dates[-1] == np.datetime64('2022-01-13'):
# Data corrections as of the afternoon of Jan 13th:
new[dates==np.datetime64('2021-12-31')] += 71
new[dates==np.datetime64('2022-01-01')] += 624
new[dates==np.datetime64('2022-01-02')] += 2_149
new[dates==np.datetime64('2022-01-03')] += 5_784
new[dates==np.datetime64('2022-01-04')] += 8_289
new[dates==np.datetime64('2022-01-05')] += 10_626
new[dates==np.datetime64('2022-01-06')] += 13_223
new[dates==np.datetime64('2022-01-07')] += 14_153
new[dates==np.datetime64('2022-01-08')] += 15_004
new[dates==np.datetime64('2022-01-09')] += 13_782
new[dates==np.datetime64('2022-01-10')] += 14_063
new[dates==np.datetime64('2022-01-11')] += 12_417
new[dates==np.datetime64('2022-01-12')] += 9_264
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
new[dates==np.datetime64('2022-01-09')] -= 17_190
new[dates==np.datetime64('2022-01-10')] -= 18_503
new[dates==np.datetime64('2022-01-11')] -= 18_434
new[dates==np.datetime64('2022-01-12')] -= 16_843
elif dates[-1] == np.datetime64('2022-01-12'):
# Data corrections as of the afternoon of Jan 12th:
new[dates==np.datetime64('2021-12-31')] += 71
new[dates==np.datetime64('2022-01-01')] += 624
new[dates==np.datetime64('2022-01-02')] += 2_149
new[dates==np.datetime64('2022-01-03')] += 5_784
new[dates==np.datetime64('2022-01-04')] += 8_289
new[dates==np.datetime64('2022-01-05')] += 10_626
new[dates==np.datetime64('2022-01-06')] += 12_348
new[dates==np.datetime64('2022-01-07')] += 13_277
new[dates==np.datetime64('2022-01-08')] += 14_128
new[dates==np.datetime64('2022-01-09')] += 12_906
new[dates==np.datetime64('2022-01-10')] += 13_187
new[dates==np.datetime64('2022-01-11')] += 9_217
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
new[dates==np.datetime64('2022-01-09')] -= 17_190
new[dates==np.datetime64('2022-01-10')] -= 18_503
new[dates==np.datetime64('2022-01-11')] -= 18_434
elif dates[-1] == np.datetime64('2022-01-11'):
# Data corrections as of the afternoon of Jan 11th:
new[dates==np.datetime64('2021-12-31')] += 71
new[dates==np.datetime64('2022-01-01')] += 624
new[dates==np.datetime64('2022-01-02')] += 2_149
new[dates==np.datetime64('2022-01-03')] += 5_784
new[dates==np.datetime64('2022-01-04')] += 8_289
new[dates==np.datetime64('2022-01-05')] += 9_520
new[dates==np.datetime64('2022-01-06')] += 11_242
new[dates==np.datetime64('2022-01-07')] += 12_171
new[dates==np.datetime64('2022-01-08')] += 13_022
new[dates==np.datetime64('2022-01-09')] += 11_800
new[dates==np.datetime64('2022-01-10')] += 9_500
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
new[dates==np.datetime64('2022-01-09')] -= 17_190
new[dates==np.datetime64('2022-01-10')] -= 18_503
elif dates[-1] == np.datetime64('2022-01-10'):
# Data corrections as of the afternoon of Jan 10th:
new[dates==np.datetime64('2021-12-31')] += 71
new[dates==np.datetime64('2022-01-01')] += 624
new[dates==np.datetime64('2022-01-02')] += 2_149
new[dates==np.datetime64('2022-01-03')] += 5_784
new[dates==np.datetime64('2022-01-04')] += 7_089
new[dates==np.datetime64('2022-01-05')] += 8_320
new[dates==np.datetime64('2022-01-06')] += 10_041
new[dates==np.datetime64('2022-01-07')] += 10_970
new[dates==np.datetime64('2022-01-08')] += 11_821
new[dates==np.datetime64('2022-01-09')] += 8_800
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
new[dates==np.datetime64('2022-01-09')] -= 17_190
elif dates[-1] == np.datetime64('2022-01-09'):
# Data corrections as of the afternoon of Jan 9th:
new[dates==np.datetime64('2021-12-31')] += 71
new[dates==np.datetime64('2022-01-01')] += 624
new[dates==np.datetime64('2022-01-02')] += 2_149
new[dates==np.datetime64('2022-01-03')] += 4_706
new[dates==np.datetime64('2022-01-04')] += 6_011
new[dates==np.datetime64('2022-01-05')] += 7_242
new[dates==np.datetime64('2022-01-06')] += 8_963
new[dates==np.datetime64('2022-01-07')] += 9_892
new[dates==np.datetime64('2022-01-08')] += 8_821
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
elif dates[-1] == np.datetime64('2022-01-08'):
# no RATs on this date:
new[dates==np.datetime64('2022-01-07')] -= 26_428
new[dates==np.datetime64('2022-01-08')] -= 22_051
elif dates[-1] == np.datetime64('2022-01-07'):
# no RATs on this date:
new[dates==np.datetime64('2022-01-07')] -= 26_428
if dates[-1] >= np.datetime64('2022-03-25'):
TEST_DETECTION_RATE = 0.35
elif dates[-1] >= np.datetime64('2022-01-09'):
TEST_DETECTION_RATE = 0.27
else:
TEST_DETECTION_RATE = 0.2
START_VAX_PROJECTIONS = 111 # August 29, when I started making vaccine projections
all_dates = dates
all_new = new
doses_per_100 = covidlive_doses_per_100(
n=len(dates),
state='VIC',
population=POP_OF_VIC,
)
if OLD:
dates = dates[:START_VAX_PROJECTIONS + OLD_END_IX]
new = new[:START_VAX_PROJECTIONS + OLD_END_IX]
doses_per_100 = doses_per_100[:START_VAX_PROJECTIONS + OLD_END_IX]
START_PLOT = np.datetime64('2021-05-20')
END_PLOT = np.datetime64('2022-07-01') if VAX else dates[-1] + 28
tau = 5 # reproductive time of the virus in days
R_clip = 50
immune = projected_vaccine_immune_population(np.arange(100), doses_per_100)
s = 1 - immune
dk_dt = 1 / tau * (s[1] / s[0] - 1)
# Keep the old methodology for old plots:
if dates[-1] >= np.datetime64('2022-06-16'):
padding_model = exponential
elif dates[-1] >= np.datetime64('2022-01-04'):
padding_model = lambda x, A, k: exponential_with_infection_immunity(
x,
A,
k,
cumulative_cases=new.sum(),
tau=tau,
effective_population=TEST_DETECTION_RATE * POP_OF_VIC,
)
elif dates[-1] >= np.datetime64('2021-10-07'):
padding_model = lambda x, A, k: exponential_with_vax(x, A, k, dk_dt)
else:
padding_model = exponential
# Usually fit 14, but switched to 10 temporarily, to decrease influence of the
# likely-temporary grand-final-weekend surge
if dates[-1] >= np.datetime64('2021-10-11'):
x0 = -14
elif dates[-1] >= np.datetime64('2021-10-07'):
x0 = -10
else:
x0 = -14
# Whether or not to do a 5dma of data prior to the fit. Change of methodology as of
# 2021-11-19, so keep old methodology for remaking plots prior to then. Changed
# methodology back on 2021-12-11.
if dates[-1] > np.datetime64('2021-12-10'):
PRE_FIT_SMOOTHING = None
elif dates[-1] > np.datetime64('2021-11-18'):
PRE_FIT_SMOOTHING = 5
else:
PRE_FIT_SMOOTHING = None
# Where the magic happens, estimate everything:
(
new_smoothed,
u_new_smoothed,
R,
u_R,
cov,
shot_noise_factor,
) = determine_smoothed_cases_and_Reff(
new,
fit_pts=min(20, len(dates[dates >= START_PLOT])),
x0=x0,
pre_fit_smoothing=PRE_FIT_SMOOTHING,
padding_model=padding_model,
R_clip=R_clip,
tau=tau,
)
# Fudge what would happen with a different R_eff:
# cov_R_new_smoothed[-1] *= 0.05 / np.sqrt(variance_R[-1])
# R[-1] = 0.75
# variance_R[-1] = 0.05**2
R = R.clip(0, None)
R_upper = (R + u_R).clip(0, R_clip)
R_lower = (R - u_R).clip(0, R_clip)
new_smoothed = new_smoothed.clip(0, None)
new_smoothed_upper = (new_smoothed + u_new_smoothed).clip(0, None)
new_smoothed_lower = (new_smoothed - u_new_smoothed).clip(0, None)
# Projection of daily case numbers:
days_projection = (END_PLOT - dates[-1]).astype(int)
t_projection = np.linspace(0, days_projection, days_projection + 1)
if VAX:
# Fancy stochastic SIR model
(
new_projection,
new_projection_lower,
new_projection_upper,
R_eff_projection,
R_eff_projection_lower,
R_eff_projection_upper,
total_cases,
total_cases_lower,
total_cases_upper,
) = get_SIR_projection(
current_caseload=new_smoothed[-1],
cumulative_cases=new.sum(),
R_eff=R[-1],
tau=tau,
population=POP_OF_VIC,
test_detection_rate=TEST_DETECTION_RATE,
vaccine_immunity=projected_vaccine_immune_population(
t_projection, doses_per_100
),
n_days=days_projection + 1,
n_trials=1000 if OLD else 10000, # just save some time if we're animating
cov=cov,
)
else:
# Simple model, no vaccines or community immunity
new_projection, new_projection_lower, new_projection_upper = get_exp_projection(
t_projection=t_projection,
current_caseload=new_smoothed[-1],
R_eff=R[-1],
cov=cov,
tau=tau,
)
PREV_LOCKDOWN = np.datetime64('2021-05-28')
PREV_EASING_1 = PREV_LOCKDOWN + 21
PREV_EASING_2 = np.datetime64('2021-07-09')
LOCKDOWN = np.datetime64('2021-07-16')
EASING_1 = np.datetime64('2021-07-28')
LOCKDOWN_AGAIN = np.datetime64('2021-08-06')
CURFEW = np.datetime64('2021-08-16')
CONSTRUCTION_SHUTDOWN = np.datetime64('2021-09-21')
END_CONSTRUCTION_SHUTDOWN = CONSTRUCTION_SHUTDOWN + 14
PHASE_B = np.datetime64('2021-10-22')
PHASE_C = np.datetime64('2021-10-30')
PHASE_D = np.datetime64('2021-11-19')
MASKS_AGAIN = np.datetime64('2021-12-24')
DENSITY_LIMITS = np.datetime64('2022-01-07')
END_DENSITY_LIMITS = np.datetime64('2022-02-19')
END_MASKS = np.datetime64('2022-02-26')
fig1 = plt.figure(figsize=(10, 6))
ax1 = plt.axes()
ax1.fill_betweenx(
[-10, 10],
[PREV_LOCKDOWN, PREV_LOCKDOWN],
[PREV_EASING_1, PREV_EASING_1],
color=whiten("red", 0.35),
linewidth=0,
label="Lockdown",
)
ax1.fill_betweenx(
[-10, 10],
[PREV_EASING_1, PREV_EASING_1],
[PREV_EASING_2, PREV_EASING_2],
color=whiten("orange", 0.5),
linewidth=0,
label="Eased stay-at-home orders",
)
ax1.fill_betweenx(
[-10, 10],
[PREV_EASING_2, PREV_EASING_2],
[LOCKDOWN, LOCKDOWN],
color=whiten("yellow", 0.5),
linewidth=0,
label="Phase B/Density limits",
)
ax1.fill_betweenx(
[-10, 10],
[LOCKDOWN, LOCKDOWN],
[EASING_1, EASING_1],
color=whiten("red", 0.35),
linewidth=0,
# label="Lockdown",
)
ax1.fill_betweenx(
[-10, 10],
[EASING_1, EASING_1],
[LOCKDOWN_AGAIN, LOCKDOWN_AGAIN],
color=whiten("orange", 0.5),
linewidth=0,
# label="Eased stay-at-home orders",
)
ax1.fill_betweenx(
[-10, 10],
[LOCKDOWN_AGAIN, LOCKDOWN_AGAIN],
[CURFEW, CURFEW],
color=whiten("red", 0.35),
linewidth=0,
# label="Eased stay-at-home orders",
)
ax1.fill_betweenx(
[-10, 10],
[CURFEW, CURFEW],
[CONSTRUCTION_SHUTDOWN, CONSTRUCTION_SHUTDOWN],
color=whiten("red", 0.35),
edgecolor=whiten("red", 0.45),
hatch="//////",
linewidth=0,
label="Curfew",
)
ax1.fill_betweenx(
[-10, 10],
[CONSTRUCTION_SHUTDOWN, CONSTRUCTION_SHUTDOWN],
[END_CONSTRUCTION_SHUTDOWN, END_CONSTRUCTION_SHUTDOWN],
color="red",
alpha=0.45,
linewidth=0,
label="Construction shutdown",
)
ax1.fill_betweenx(
[-10, 10],
[END_CONSTRUCTION_SHUTDOWN, END_CONSTRUCTION_SHUTDOWN],
[PHASE_B, PHASE_B],
color=whiten("red", 0.35),
edgecolor=whiten("red", 0.45),
hatch="//////",
linewidth=0,
# label="Curfew",
)
ax1.fill_betweenx(
[-10, 10],
[PHASE_B, PHASE_B],
[PHASE_C, PHASE_C],
color=whiten("yellow", 0.5),
linewidth=0,
)
ax1.fill_betweenx(
[-10, 10],
[PHASE_C, PHASE_C],
[PHASE_D, PHASE_D],
color=whiten("green", 0.5),
label="Phase C/Mask mandate",
linewidth=0,
)
ax1.fill_betweenx(
[-10, 10],
[PHASE_D, PHASE_D],
[MASKS_AGAIN, MASKS_AGAIN],
color=whiten("green", 0.25),
linewidth=0,
label="Phase D",
)
ax1.fill_betweenx(
[-10, 10],
[MASKS_AGAIN, MASKS_AGAIN],
[DENSITY_LIMITS, DENSITY_LIMITS],
color=whiten("green", 0.5),
linewidth=0,
)
ax1.fill_betweenx(
[-10, 10],
[DENSITY_LIMITS, DENSITY_LIMITS],
[END_DENSITY_LIMITS, END_DENSITY_LIMITS],
color=whiten("yellow", 0.5),
linewidth=0,
)
ax1.fill_betweenx(
[-10, 10],
[END_DENSITY_LIMITS, END_DENSITY_LIMITS],
[END_MASKS, END_MASKS],
color=whiten("green", 0.5),
linewidth=0,
)
ax1.fill_betweenx(
[-10, 10],
[END_MASKS, END_MASKS],
[END_PLOT, END_PLOT],
color=whiten("green", 0.25),
linewidth=0,
)
ax1.fill_between(
dates[1:] + 1,
R,
label=R"$R_\mathrm{eff}$",
step='pre',
color='C0',
)
if VAX:
ax1.fill_between(
np.concatenate([dates[1:].astype(int), dates[-1].astype(int) + t_projection]) + 1,
np.concatenate([R_lower, R_eff_projection_lower]),
np.concatenate([R_upper, R_eff_projection_upper]),
label=R"$R_\mathrm{eff}$/projection uncertainty",
color='cyan',
edgecolor='blue',
alpha=0.2,
step='pre',
zorder=2,
hatch="////",
)
ax1.fill_between(
dates[-1].astype(int) + t_projection + 1,
R_eff_projection,
label=R"$R_\mathrm{eff}$ (projection)",
step='pre',
color='C0',
linewidth=0,
alpha=0.75
)
else:
ax1.fill_between(
dates[1:] + 1,
R_lower,
R_upper,
label=R"$R_\mathrm{eff}$ uncertainty",
color='cyan',
edgecolor='blue',
alpha=0.2,
step='pre',
zorder=2,
hatch="////",
)
ax1.axhline(1.0, color='k', linewidth=1)
ax1.axis(xmin=START_PLOT, xmax=END_PLOT, ymin=0, ymax=5)
ax1.grid(True, linestyle=":", color='k', alpha=0.5)
ax1.set_ylabel(R"$R_\mathrm{eff}$")
u_R_latest = (R_upper[-1] - R_lower[-1]) / 2
R_eff_string = fR"$R_\mathrm{{eff}}={R[-1]:.02f} \pm {u_R_latest:.02f}$"
latest_update_day = datetime.fromisoformat(str(dates[-1] + 1))
latest_update_day = f'{latest_update_day.strftime("%B")} {th(latest_update_day.day)}'
if VAX:
title_lines = [
f"SIR model of Victoria as of {latest_update_day}",
f"Starting from currently estimated {R_eff_string}",
]
else:
if LGA:
region = LGA
else:
region = "Victoria"
title_lines = [
f"$R_\\mathrm{{eff}}$ in {region} as of {latest_update_day}, with Melbourne restriction levels and daily cases",
f"Latest estimate: {R_eff_string}",
]
ax1.set_title('\n'.join(title_lines))
ax1.yaxis.set_major_locator(mticker.MultipleLocator(0.25))
ax2 = ax1.twinx()
if OLD:
ax2.step(all_dates + 1, all_new + 0.02, color='purple', alpha=0.5)
ax2.step(dates + 1, new + 0.02, color='purple', label='Daily cases')
ax2.plot(
dates.astype(int) + 0.5,
new_smoothed,
color='magenta',
label='Daily cases (smoothed)',
)
ax2.fill_between(
dates.astype(int) + 0.5,
new_smoothed_lower,
new_smoothed_upper,
color='magenta',
alpha=0.3,
linewidth=0,
zorder=10,
label=f'Smoothing/{"projection" if VAX else "trend"} uncertainty',
)
ax2.plot(
dates[-1].astype(int) + 0.5 + t_projection,
new_projection.clip(0, 1e6), # seen SVG rendering issues when this is big
color='magenta',
linestyle='--',
label=f'Daily cases ({"SIR projection" if VAX else "exponential trend"})',
)
ax2.fill_between(
dates[-1].astype(int) + 0.5 + t_projection,
new_projection_lower.clip(0, 1e6), # seen SVG rendering issues when this is big
new_projection_upper.clip(0, 1e6),
color='magenta',
alpha=0.3,
linewidth=0,
)
ax2.set_ylabel("Daily cases (log scale)")
ax2.set_yscale('log')
ax2.axis(ymin=1, ymax=100_000)
fig1.tight_layout(pad=1.8)
handles, labels = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
handles += handles2
labels += labels2
if VAX:
order = [7, 9, 8, 10, 11, 13, 12, 6, 5, 2, 1, 0, 3, 4]
else:
order = [7, 8, 9, 10, 12, 11, 6, 5, 2, 1, 0, 3, 4]
ax2.legend(
# handles,
# labels,
[handles[idx] for idx in order],
[labels[idx] for idx in order],
loc='upper left',
ncol=1,
prop={'size': 8},
)
ax2.yaxis.set_major_formatter(mticker.EngFormatter())
ax2.yaxis.set_minor_formatter(mticker.EngFormatter())
ax2.tick_params(axis='y', which='minor', labelsize='x-small')
plt.setp(ax2.get_yminorticklabels()[1::2], visible=False)
locator = mdates.DayLocator([1, 15])
ax1.xaxis.set_major_locator(locator)
formatter = mdates.ConciseDateFormatter(locator, show_offset=False)
ax1.xaxis.set_major_formatter(formatter)
ax2.tick_params(axis='y', colors='purple', which='both')
ax1.spines['right'].set_color('purple')
ax2.spines['right'].set_color('purple')
ax2.yaxis.label.set_color('purple')
ax1.tick_params(axis='y', colors='C0', which='both')
ax1.spines['left'].set_color('C0')
ax2.spines['left'].set_color('C0')
ax1.yaxis.label.set_color('C0')
axpos = ax1.get_position()
text = fig1.text(
0.99,
0.02,
"@chrisbilbo | chrisbillington.net/COVID_VIC_2021",
size=8,
alpha=0.5,
color=(0, 0, 0.25),
fontfamily="monospace",
horizontalalignment="right"
)
text.set_bbox(dict(facecolor='white', alpha=0.8, linewidth=0))
if VAX:
total_cases_range = f"{total_cases_lower/1000:.0f}k—{total_cases_upper/1000:.0f}k"
text = fig1.text(
0.64,
0.83,
"\n".join(
[
f"Projected total cases in outbreak: {total_cases/1000:.0f}k",
f" 68% range: {total_cases_range}",
]
),
fontsize='small',
)
text.set_bbox(dict(facecolor='white', alpha=0.8, linewidth=0))
suffix = '_vax'
elif LGA:
suffix=f'_LGA_{LGA_IX}'
else:
suffix = ''
if OLD:
fig1.savefig(f'vic_animated/{OLD_END_IX:04d}.png', dpi=133)
else:
fig1.savefig(f'COVID_VIC_2021{suffix}.svg')
fig1.savefig(f'COVID_VIC_2021{suffix}.png', dpi=133)
if not LGA:
ax2.set_yscale('linear')
maxproj = new_projection[t_projection < (END_PLOT - dates[-1]).astype(int)].max()
if OLD and dates[-1] < np.datetime64('2021-12-24'):
ymax = 4000
elif OLD and dates[-1] < np.datetime64('2022-01-15'):
ymax = 100_000
elif VAX:
ymax = 50_000
else:
ymax = 50_000
ax2.axis(ymin=0, ymax=ymax)
ax2.yaxis.set_major_locator(mticker.MultipleLocator(ymax / 10))
ax2.yaxis.set_major_formatter(mticker.EngFormatter())
ax2.set_ylabel("Daily confirmed cases (linear scale)")
if OLD:
fig1.savefig(f'vic_animated_linear/{OLD_END_IX:04d}.png', dpi=133)
else:
fig1.savefig(f'COVID_VIC_2021{suffix}_linear.svg')
fig1.savefig(f'COVID_VIC_2021{suffix}_linear.png', dpi=133)
# Save some deets to a file for the auto reddit posting to use:
try:
# Add to existing file if already present
stats = json.loads(Path("latest_vic_stats.json").read_text())
except FileNotFoundError:
stats = {}
if not LGA:
stats['R_eff'] = R[-1]
stats['u_R_eff'] = u_R_latest
stats['today'] = str(np.datetime64(datetime.now(), 'D'))
if VAX:
# Case number predictions
stats['projection'] = []
# in case I ever want to get the orig projection range not expanded - like to
# compare past projections:
stats['SHOT_NOISE_FACTOR'] = shot_noise_factor
for i, cases in enumerate(new_projection):
date = dates[-1] + i
lower = new_projection_lower[i]
upper = new_projection_upper[i]
lower = lower - shot_noise_factor * np.sqrt(lower)
upper = upper + shot_noise_factor * np.sqrt(upper)
lower = max(lower, 0)
stats['projection'].append(
{'date': str(date), 'cases': cases, 'upper': upper, 'lower': lower}
)
if i < 8:
print(f"{cases:.0f} {lower:.0f}—{upper:.0f}")
if not OLD:
# Only save data if this isn't a re-run on old data
Path("latest_vic_stats.json").write_text(json.dumps(stats, indent=4))
# Update the date in the HTML
html_file = 'COVID_VIC_2021.html'
html_lines = Path(html_file).read_text().splitlines()
now = datetime.now(timezone('Australia/Melbourne')).strftime('%Y-%m-%d %H:%M')
for i, line in enumerate(html_lines):
if 'Last updated' in line:
html_lines[i] = f' Last updated: {now} Melbourne time'
Path(html_file).write_text('\n'.join(html_lines) + '\n')
plt.show()