-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathacm_analyzer.py
3163 lines (3034 loc) · 160 KB
/
acm_analyzer.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 dateutil
import platform
import isoweek
import datetime
import math
import re
import numpy
import scipy.optimize
import scipy.interpolate
import scipy.integrate
import pandas
import matplotlib.pyplot as plt
import matplotlib.dates
import matplotlib.ticker
import matplotlib.patches
import os
import sys
def init_latex():
global Y2021_COLOR_OFFSET
if False:
plt.style.use('seaborn')
Y2021_COLOR_OFFSET = 1
elif False:
plt.style.use('ggplot')
Y2021_COLOR_OFFSET = 0
else:
plt.style.use('bmh')
Y2021_COLOR_OFFSET = 0
# Documentation:
# https://matplotlib.org/stable/tutorials/introductory/customizing.html#the-default-matplotlibrc-file
plt.rcParams.update({
"text.usetex": False, # True if platform.system() != "Windows" else False,
#"text.latex.preamble": [
# r"\usepackage{graphics}",
# r"\usepackage{tgtermes}",
#],
# "font.family": "tgtermes" if platform.system() != "Windows" else "Times New Roman",
"font.family": "Times New Roman",
"font.serif": ["Times New Roman"],
"mathtext.fontset": "cm",
"mathtext.rm": "serif",
#"mathtext.fallback": "cm",
# Use 10pt font in plots, to match 10pt font in document
"axes.labelsize": 9,
"font.size": 9,
# Make the legend/label fonts a little smaller
"legend.fontsize": 7,
"xtick.labelsize": 7,
"ytick.labelsize": 7,
"grid.linewidth": 0.3,
"grid.alpha": 1.0,
})
# how to embed Matplitlib in Latex:
# https://jwalton.info/Embed-Publication-Matplotlib-Latex/
DAYS_IN_YEAR_EXACT = 365.24
WEEKS_IN_YEAR_EXACT = DAYS_IN_YEAR_EXACT / 7
BASELINE_START_DATE = datetime.date(2008, 1, 1)
BASELINE_CUTOFF_DATE = datetime.date(2021, 1, 1)
BASELINE_INTERVAL = datetime.timedelta(days=365*3)
T0_DATE = datetime.date(2021, 1, 1)
T0_DATETIME64 = numpy.datetime64("2021-01-01")
YEAR_WEEK_RE = re.compile(r'"(\d\d\d\d)W(\d\d)\*?"')
PAPER_WIDTH_PT = 483.7
PAPER_WIDTH_IN = PAPER_WIDTH_PT / 72.27
COLUMN_WIDTH_PT = 234.0
COLUMN_WIDTH_IN = COLUMN_WIDTH_PT / 72.27
DEFAULT_PAD_INCHES = 0.01
DEFAULT_LINEWIDTH = 0.5
DEFAULT_DPI = 300
EXCESS_MORTALITY_FILL_COLOR = "#ff2222"
LOW_MORTALITY_FILL_COLOR = "C6"
BASELINE_PLOT_HEIGHT = 1.1
BLUE_COLOR = "#3366ee"
ACM_CUSTOM_YLIM = (800, 1320)
ESTIMATION_PAST_YEARS=10
BASELINE_PLOT_START_DATE = BASELINE_START_DATE
BASELINE_PLOT_END_DATE = datetime.date(2022, 12, 31)
def get_date_from_isoweek(year, week):
return isoweek.Week(year, week).thursday()
def set_size(width, fraction=1, subplots=(1, 1), height_in_override=None):
"""Set figure dimensions to avoid scaling in LaTeX.
Parameters
----------
width: float or string
Document width in points, or string of predined document type
fraction: float, optional
Fraction of the width which you wish the figure to occupy
subplots: array-like, optional
The number of rows and columns of subplots.
Returns
-------
fig_dim: tuple
Dimensions of figure in inches
"""
width_pt = width
# Width of figure (in pts)
fig_width_pt = width_pt * fraction
# Convert from pt to inches
inches_per_pt = 1 / 72.27
# Golden ratio to set aesthetic figure height
# https://disq.us/p/2940ij3
golden_ratio = (5**.5 - 1) / 2
# Figure width in inches
fig_width_in = fig_width_pt * inches_per_pt
# Figure height in inches
if height_in_override is None:
fig_height_in = fig_width_in * golden_ratio * (subplots[0] / subplots[1])
else:
fig_height_in = height_in_override
return (fig_width_in, fig_height_in)
def save_fig(fig, fig_file_name):
pdf_file_name = fig_file_name + ".pdf"
fig.savefig(pdf_file_name,
dpi = DEFAULT_DPI,
# "bbox_inches": "tight",
pad_inches = DEFAULT_PAD_INCHES,
transparent = True)
print("Wrote %s" % (pdf_file_name,))
png_file_name = fig_file_name + ".png"
fig.savefig(png_file_name,
dpi = DEFAULT_DPI,
# "bbox_inches": "tight",
pad_inches = DEFAULT_PAD_INCHES,
transparent = True,
facecolor = "white")
print("Wrote %s" % (png_file_name,))
class WeekNumberLocator(matplotlib.dates.RRuleLocator):
"""
Make ticks on occurrences of week numbers.
"""
def __init__(self, byweekno=None, byweekday=dateutil.rrule.TH, interval=1, tz=None):
"""
Mark every ISO 8601 week number in *byweekno*; *byweekno* can be an int or
sequence. Default is ``range(1,53)``, i.e. every week.
*interval* is the interval between each iteration. For
example, if ``interval=2``, mark every second occurrence.
"""
if byweekno is None:
byweekno = range(1, 53)
elif isinstance(byweekno, numpy.ndarray):
# This fixes a bug in dateutil <= 2.3 which prevents the use of
# numpy arrays in (among other things) the bymonthday, byweekday
# and bymonth parameters.
byweekno = [x.item() for x in byweekno.astype(int)]
rule = matplotlib.dates.rrulewrapper(dateutil.rrule.WEEKLY, byweekno=byweekno, byweekday=byweekday,
interval=interval, **self.hms0d)
matplotlib.dates.RRuleLocator.__init__(self, rule, tz)
class WeekNumberFormatter(matplotlib.dates.DateFormatter):
def __init__(self, tz=None):
matplotlib.dates.DateFormatter.__init__(self, "%V", tz)
def __call__(self, x, pos=0):
return matplotlib.dates.DateFormatter.__call__(self, x, pos).lstrip("0")
# Parse CSV file downloaded from:
# https://pxnet2.stat.fi/PXWeb/pxweb/fi/Kokeelliset_tilastot/Kokeelliset_tilastot__vamuu_koke/koeti_vamuu_pxt_12ng.px/
#
# Choices for obtaining CSV:
# Alue = KOKO MAA
# Viikko = Valitse kaikki
# Ikä = Valitse kaikki
# Sukupuoli = Valitse kaikki
#
# Click Lataa taulukko > Lataa puolipiste-eroteltu csv-tiedosto (otsikollinen)
#
def parse_finland_acm_csv(csv_file, trim_weeks_from_end):
out_tuples = []
acm_by_category = {}
all_lines = list(csv_file.readlines())
heading_line = all_lines[2]
heading_cells = heading_line.strip().split(";")
assert heading_cells[0] == '"Alue"'
assert heading_cells[1] == '"Viikko"'
assert heading_cells[2] == '"Yhteensä Yhteensä Kuolleet"'
assert heading_cells[3] == '"Yhteensä Miehet Kuolleet"'
assert heading_cells[4] == '"Yhteensä Naiset Kuolleet"'
age_categories = ((0, 4, []),
(5, 9, ["5-19"]),
(10, 14, ["5-19"]),
(15, 19, ["5-19"]),
(20, 24, ["20-39", "20-64"]),
(25, 29, ["20-39", "20-64"]),
(30, 34, ["20-39", "20-64"]),
(35, 39, ["20-39", "20-64"]),
(40, 44, ["40-64", "20-64"]),
(45, 49, ["40-64", "20-64"]),
(50, 54, ["40-64", "20-64"]),
(55, 59, ["40-64", "20-64"]),
(60, 64, ["40-64", "20-64"]),
(65, 69, ["65-"]),
(70, 74, ["65-"]),
(75, 79, ["65-"]),
(80, 84, ["65-"]),
(85, 89, ["65-"]),
(90, None, ["65-"]))
column_idx = 5
for age_start, age_end, meta_categories in age_categories:
age_category_str = str(age_start) + " -"
if age_end:
age_category_str += " " + str(age_end)
assert heading_cells[column_idx] == '"%s Yhteensä Kuolleet"' % (age_category_str,)
assert heading_cells[column_idx+1] == '"%s Miehet Kuolleet"' % (age_category_str,)
assert heading_cells[column_idx+2] == '"%s Naiset Kuolleet"' % (age_category_str,)
category_key = str(age_start) + "-"
if age_end:
category_key += str(age_end)
acm_by_category[category_key] = []
acm_by_category[category_key + "_male"] = []
acm_by_category[category_key + "_female"] = []
for meta_category in meta_categories:
if meta_category not in acm_by_category:
acm_by_category[meta_category] = []
acm_by_category[meta_category + "_male"] = []
acm_by_category[meta_category + "_female"] = []
column_idx += 3
year = None
week = None
for line in all_lines[3:]:
line = line.strip()
if not line:
break
cells = line.strip().split(";")
assert cells[0] == '"KOKO MAA"'
year_week_match = YEAR_WEEK_RE.match(cells[1])
assert year_week_match, "No match: %s" % (cells[1],)
year = int(year_week_match.group(1))
week = int(year_week_match.group(2))
deaths = int(cells[2])
male_deaths = int(cells[3])
female_deaths = int(cells[4])
begin_date = get_date_from_isoweek(year, week)
# sanity check for data
assert year >= 1900 and year < 2100
assert week >= 1 and week <= 53
assert begin_date >= datetime.date(1900, 1, 1) and begin_date < datetime.date(2100, 1, 1)
assert deaths > 0 and deaths < 10000
out_tuples.append((begin_date, deaths))
category_deaths_sum = 0
male_deaths_sum = 0
female_deaths_sum = 0
column_idx = 5
output_meta_categories = dict()
for age_start, age_end, meta_categories in age_categories:
category_key = str(age_start) + "-"
if age_end:
category_key += str(age_end)
age_deaths = int(cells[column_idx])
age_male_deaths = int(cells[column_idx+1])
age_female_deaths = int(cells[column_idx+2])
assert age_deaths == age_male_deaths + age_female_deaths
category_deaths_sum += age_deaths
acm_by_category[category_key].append((begin_date, age_deaths))
male_deaths_sum += age_male_deaths
acm_by_category[category_key + "_male"].append((begin_date, age_male_deaths))
female_deaths_sum += age_female_deaths
acm_by_category[category_key + "_female"].append((begin_date, age_female_deaths))
for meta_category in meta_categories:
if meta_category not in output_meta_categories:
output_meta_categories[meta_category] = 0
output_meta_categories[meta_category + "_male"] = 0
output_meta_categories[meta_category + "_female"] = 0
output_meta_categories[meta_category] += age_deaths
output_meta_categories[meta_category + "_male"] += age_male_deaths
output_meta_categories[meta_category + "_female"] += age_female_deaths
column_idx += 3
for meta_category, meta_category_sum in output_meta_categories.items():
acm_by_category[meta_category].append((begin_date, meta_category_sum))
assert category_deaths_sum == deaths
assert male_deaths_sum == male_deaths
assert female_deaths_sum == female_deaths
# trim data from end because it is not final
return out_tuples[:-trim_weeks_from_end], dict(((k, v[:-trim_weeks_from_end]) for k, v in acm_by_category.items()))
THL_YEAR_WEEK_RE = re.compile(r"Vuosi (\d\d\d\d) Viikko (\d\d)")
# Parse CSV file downloaded from:
# https://sampo.thl.fi/pivot/prod/fi/epirapo/covid19case/fact_epirapo_covid19case?row=dateweek20200101-509030&column=measure-444833.445356.492118.&fo=1
#
# Click: Vie taulukko > CSV-tiedostoon
#
def parse_finland_thl_covid_data_csv(csv_file):
out_tuples = []
all_lines = list(csv_file.readlines())
heading_line = all_lines[0].strip()
assert heading_line == "Mittari;Aika;val"
cur_year = None
cur_week = None
cur_begin_date = None
cur_covid_cases = None
cur_covid_tests = None
for line_idx, line in enumerate(all_lines[1:]):
line_no = line_idx+2
line = line.strip()
if not line or ";Kaikki ajat;" in line:
break
cells = line.split(";")
line_type = cells[0]
year_week_match = THL_YEAR_WEEK_RE.fullmatch(cells[1])
assert year_week_match is not None
year = int(year_week_match.group(1))
week = int(year_week_match.group(2))
begin_date = get_date_from_isoweek(year, week)
if line_type == "Tapausten lukumäärä":
cur_covid_cases = int(cells[2] or 0)
assert cur_year == None
assert cur_week == None
assert cur_begin_date == None
cur_year = year
cur_week = week
cur_begin_date = begin_date
elif line_type == "Testausmäärä":
assert cur_year == year, "Year %s != %s on line %d" % (cur_year, year, line_no)
assert cur_week == week
assert cur_begin_date == begin_date
cur_covid_tests = int(cells[2] or 0)
elif line_type == "Kuolemantapausten lukumäärä":
assert cur_year == year
assert cur_week == week
assert cur_begin_date == begin_date
assert cur_covid_cases is not None
assert cur_covid_tests is not None
covid_deaths = int(cells[2] or 0)
out_tuples.append((begin_date, covid_deaths, cur_covid_cases, cur_covid_tests))
cur_year = None
cur_week = None
cur_begin_date = None
cur_covid_cases = None
cur_covid_tests = None
else:
assert False, "Unkown line type: %s" % (line_type,)
return out_tuples
# Parse CSV file downloaded from:
# https://sampo.thl.fi/pivot/prod/fi/epirapo/covid19case/fact_epirapo_covid19case?row=dateweek20200101-509030&column=measure-444833.445356.492118.816930.816957.&fo=1
#
# Click: Vie taulukko > CSV-tiedostoon
#
def parse_finland_thl_verified_covid_data_csv(csv_file):
out_tuples = []
all_lines = list(csv_file.readlines())
heading_line = all_lines[0].strip()
assert heading_line == "Mittari;Aika;val"
cur_year = None
cur_week = None
cur_begin_date = None
cur_covid_cases = None
cur_covid_tests = None
cur_covid_caused_deaths = None
for line_idx, line in enumerate(all_lines[1:]):
line_no = line_idx+2
line = line.strip()
if not line or ";Kaikki ajat;" in line:
break
cells = line.split(";")
line_type = cells[0]
year_week_match = THL_YEAR_WEEK_RE.fullmatch(cells[1])
assert year_week_match is not None
year = int(year_week_match.group(1))
week = int(year_week_match.group(2))
begin_date = get_date_from_isoweek(year, week)
if line_type == "Tapausten lukumäärä":
cur_covid_cases = int(cells[2] or 0)
assert cur_year == None
assert cur_week == None
assert cur_begin_date == None
cur_year = year
cur_week = week
cur_begin_date = begin_date
elif line_type == "Testausmäärä":
assert cur_year == year, "Year %s != %s on line %d" % (cur_year, year, line_no)
assert cur_week == week
assert cur_begin_date == begin_date
cur_covid_tests = int(cells[2] or 0)
elif line_type == "Koronaan ajallisesti liittyvät kuolemat (30 vrk), tartuntatautirekisteri":
continue
elif line_type == "Koronasta johtuvat kuolemat, kuolintodistus (alustava tieto)":
assert cur_year == year
assert cur_week == week
assert cur_begin_date == begin_date
assert cur_covid_cases is not None
assert cur_covid_tests is not None
cur_covid_caused_deaths = int(cells[2] or 0)
elif line_type == "Kuolemat joissa korona myötävaikuttavana tekijänä, kuolintodistus (alustava tieto)":
assert cur_year == year
assert cur_week == week
assert cur_begin_date == begin_date
assert cur_covid_cases is not None
assert cur_covid_tests is not None
assert cur_covid_tests is not None
assert cur_covid_caused_deaths is not None
covid_contributory_deaths = int(cells[2] or 0)
covid_caused_or_contributory_deaths = cur_covid_caused_deaths + covid_contributory_deaths
out_tuples.append((begin_date, cur_covid_caused_deaths, cur_covid_cases, cur_covid_tests,
cur_covid_caused_deaths, covid_contributory_deaths))
cur_year = None
cur_week = None
cur_begin_date = None
cur_covid_cases = None
cur_covid_tests = None
cur_covid_caused_deaths = None
else:
assert False, "Unkown line type: %s" % (line_type,)
return out_tuples
EUROMOMO_YEAR_WEEK_RE = re.compile(r"(\d\d\d\d)-(\d\d)")
# Parse CSV file downloaded from:
# https://www.euromomo.eu/graphs-and-maps/
#
# Click: Z-scores by country > All ages, Countries Finland > Download data
#
def parse_euromomo_zscores_csv(csv_file):
out_tuples = []
all_lines = list(csv_file.readlines())
heading_line = all_lines[0].strip()
assert heading_line == "country;group;week;zscore"
cur_begin_date = None
cur_item = None
for line_idx, line in enumerate(all_lines[1:]):
line_no = line_idx+2
line = line.strip()
if not line:
break
cells = line.split(";")
assert len(cells) == 4
country = cells[0]
assert country
line_type = cells[1]
if line_type != "Total":
continue
year_week_match = EUROMOMO_YEAR_WEEK_RE.fullmatch(cells[2])
assert year_week_match is not None
year = int(year_week_match.group(1))
week = int(year_week_match.group(2))
begin_date = get_date_from_isoweek(year, week)
if cells[3]:
z_score = float(cells[3])
if begin_date != cur_begin_date:
if cur_item:
out_tuples.append((cur_begin_date, cur_item))
cur_item = dict()
cur_begin_date = begin_date
cur_item[country] = z_score
if cur_item:
out_tuples.append((cur_begin_date, cur_item))
return out_tuples
# Parse CSV file downloaded from:
# https://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__vrm__vaerak/statfin_vaerak_pxt_11rd.px/
#
# Choices for obtaining CSV:
# Vuosi = Valitse kaikki
# Sukupuoli = Valitse kaikki
# Ikä = Valitse kaikki
#
# Click: Lataa taulukko > Lataa puolipiste-eroteltu csv-tiedosto (otsikollinen)
#
def parse_finland_tilastokeskus_population_csv(csv_file):
population_by_year_and_age = {}
all_lines = list(csv_file.readlines())
heading_line = all_lines[2].strip()
heading_cells = heading_line.split(";")
assert heading_cells[0] == '"Vuosi"'
assert heading_cells[1].startswith('"Yhteensä Yhteensä Väestö')
max_age = 112
for age in range(0, max_age+1):
assert heading_cells[2+age].startswith('"Yhteensä ' + str(age) + ' Väestö')
assert heading_cells[2+max_age+2+age].startswith('"Miehet ' + str(age) + ' Väestö')
assert heading_cells[2+2*(max_age+2)+age].startswith('"Naiset ' + str(age) + ' Väestö')
for line_idx, line in enumerate(all_lines[3:]):
cells = line.strip().split(";")
year = int(cells[0].strip('"'))
assert 1900 <= year <= 2100
year_total_population = int(cells[1])
year_population_sum = 0
assert year not in population_by_year_and_age
population_by_year_and_age[year] = {
"year_total": year_total_population,
}
for age in range(0, max_age+1):
age_population = int(cells[2+age].strip('"'))
assert 0 <= age_population < 1000000
age_male_population = int(cells[2+max_age+2+age].strip('"'))
assert 0 <= age_male_population < 1000000
age_female_population = int(cells[2+2*(max_age+2)+age].strip('"'))
assert 0 <= age_female_population < 1000000
assert age_male_population + age_female_population == age_population
assert age not in population_by_year_and_age[year]
population_by_year_and_age[year][age] = age_population, age_male_population, age_female_population
year_population_sum += age_population
assert year_total_population == year_population_sum
return population_by_year_and_age
# Parse CSV file downloaded from:
# https://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__vrm__vaenn/statfin_vaenn_pxt_139e.px/table/tableViewLayout1/
#
# Choices for obtaining CSV:
# Tiedot = Kuolleet
# Vuosi = 2007-2030
# Sukupuoli = Yhteensä
# Väestöennuste = Valitse kaikki
#
# Click: Lataa taulukko > Lataa puolipiste-eroteltu csv-tiedosto (otsikollinen)
#
def parse_finland_deaths_forecast_csv(csv_file):
all_lines = list(csv_file.readlines())
heading_line = all_lines[2].strip()
heading_cells = heading_line.split(";")
assert heading_cells[0] == '"Vuosi"'
assert heading_cells[1] == '"Tiedot"'
assert heading_cells[2] == '"Yhteensä Todelliset tiedot"'
years = (2021, 2019, 2018, 2015, 2012, 2009, 2007)
for index, year in enumerate(years):
assert heading_cells[3+index] == '"Yhteensä Väestöennuste ' + str(year) + '"'
def _parse_int(s):
if s == ".":
return None
else:
return int(s)
result = []
for line_idx, line in enumerate(all_lines[3:]):
cells = line.strip().split(";")
year = int(cells[0].strip('"'))
assert 1900 <= year <= 2100
assert cells[1] == '"Kuolleet"'
deaths_actual = _parse_int(cells[2])
output = {
"year": year,
"deaths_actual": deaths_actual,
}
for index, year in enumerate(years):
deaths_forecast = _parse_int(cells[3+index])
output["deaths_forecast_" + str(year)] = deaths_forecast
result.append(output)
return result
# Parse CSV file downloaded from:
# https://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__vrm__vamuu/statfin_vamuu_pxt_11ll.px/
#
# Choices for obtaining CSV:
# Tiedot = Kuolleet, Väkiluku
# Kuukausi = Valitse kaikki
#
# Click: Lataa taulukko > Lataa puolipiste-eroteltu csv-tiedosto (otsikollinen)
#
def parse_finland_deaths_and_population_by_month_csv(csv_file, trim_months_from_end):
all_lines = list(csv_file.readlines())
heading_line = all_lines[2].strip()
heading_cells = heading_line.split(";")
assert heading_cells[0] == '"Kuukausi"'
assert heading_cells[1] == '"Kuolleet"'
assert heading_cells[2] == '"Väkiluku"'
result = []
for line_idx, line in enumerate(all_lines[3:]):
if line == "\n":
break
cells = line.strip().split(";")
year_month_name = cells[0].strip('"').rstrip("*")
year_s, month_s = year_month_name.split("M")
year = int(year_s)
month = int(month_s)
assert 1900 <= year <= 2100
assert 1 <= month <= 12
deaths = int(cells[1])
population = int(cells[2])
output = {
"year": year,
"month": month,
"deaths": deaths,
"population": population,
"deaths_per_100k": deaths / (population / 100000),
}
result.append(output)
return result[:-trim_months_from_end] if trim_months_from_end > 0 else result
# Parse CSV file downloaded from:
# https://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__vrm__kuol/statfin_kuol_pxt_12ah.px/
#
# Choices for obtaining CSV:
# Tiedot = Kuolleet
# Vuosi = Valitse kaikki
# -- Valitse luokitus -- = Kuukausi
# Tapahtumakuukausi = Valitse kaikki
#
# Click: Lataa taulukko > Lataa puolipiste-eroteltu csv-tiedosto (otsikollinen)
#
def parse_finland_deaths_by_month_csv(csv_file):
all_lines = list(csv_file.readlines())
heading_line = all_lines[2].strip()
heading_cells = heading_line.split(";")
assert heading_cells[0] == '"Vuosi"'
assert heading_cells[1] == '"Koko vuosi Kuolleet"'
assert heading_cells[2] == '"Tammikuu Kuolleet"'
assert heading_cells[-1] == '"Joulukuu Kuolleet"'
result = []
for line_idx, line in enumerate(all_lines[3:]):
cells = line.strip().split(";")
year = int(cells[0].strip('"'))
assert 1900 <= year <= 2100
deaths_total = int(cells[1])
output = {
"year": year,
"deaths_total": deaths_total,
}
deaths_sum = 0
for month in range(1, 13):
month_deaths = int(cells[2+month-1])
output[month] = month_deaths
deaths_sum += month_deaths
assert deaths_sum == deaths_total
result.append(output)
return result
# Parse CSV file downloaded from:
# https://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__vrm__vaerak/statfin_vaerak_pxt_11rb.px/table/tableViewLayout1/
#
# Choices for obtaining CSV:
# Tiedot = Väestö 31.12
# Vuosi = Valitse kaikki
# Sukupuoli = Valitse kaikki
#
# Click: Lataa taulukko > Lataa puolipiste-eroteltu csv-tiedosto (otsikollinen)
#
def parse_finland_population_by_month_csv(csv_file):
all_lines = list(csv_file.readlines())
heading_line = all_lines[2].strip()
heading_cells = heading_line.split(";")
assert heading_cells[0] == '"Vuosi"'
assert heading_cells[1] == '"Yhteensä Väestö 31.12."'
result = []
for line_idx, line in enumerate(all_lines[3:]):
cells = line.strip().split(";")
year = int(cells[0].strip('"'))
assert 1900 <= year <= 2100
population = int(cells[1])
assert 200000 <= population <= 10000000
result.append((year, population))
return result
def calculate_moving_average(arr, w, position="left"):
assert w >= 3
results = []
for i in range(len(arr)):
if position == "left":
lower_i = i-(w-1)
upper_i = i
elif position == "center":
lower_i = i-((w-w//2)-1)
upper_i = i+w//2
elif position == "right":
lower_i = i
upper_i = i+(w-1)
else:
raise ValueError("Unknown position: %s" % (position,))
assert lower_i <= upper_i
if lower_i < 0 or upper_i >= len(arr):
results.append(None)
continue
window = arr[lower_i:upper_i+1]
assert len(window) == w
if w % 2 == 0:
# even length window
result = (0.5 * window[0] + sum(window[1:-1]) + 0.5 * window[-1]) / (len(window) - 1)
else:
# odd length window
result = sum(window) / len(window)
results.append(result)
return numpy.array(results)
def calculate_variable_window_moving_average(arr, w):
results = []
for i in range(len(arr)):
lower_i = max(0, i-((w-w//2)-1))
upper_i = min(len(arr)-1, i+w//2)
window = arr[lower_i:upper_i+1]
result = sum(window) / len(window)
results.append(result)
return numpy.array(results)
def test_calculate_variable_window_moving_average():
assert repr(list(calculate_variable_window_moving_average([], 3))) == repr([])
source2 = [1.0]
result2 = list(calculate_variable_window_moving_average(source2, 3))
expected2 = [1.0]
assert repr(result2) == repr(expected2), \
"%s not equal to %s" % (repr(result2), repr(expected2))
assert repr(list(calculate_variable_window_moving_average([1.0, 3.0], 3))) == repr([2.0, 2.0])
source4 = [90.0, 40.0, 95.0, 119.0, 102.0, 118.0, 33.0, 100.0, 4.0, 46.0, 109.0, 34.0, 25.0, 125.0, 120.0]
result4 = list(calculate_variable_window_moving_average(numpy.array(source4), 5))
expected4 = [75.0, 86.0, 89.2, 94.8, 93.4, 94.4, 71.4, 60.2, 58.4, 58.6, 43.6, 67.8, 82.6, 76.0, 90.0]
assert repr(result4) == repr(expected4), \
"%s not equal to %s" % (repr(result4), repr(expected4))
test_calculate_variable_window_moving_average()
def map_datetime_to_x(d):
if isinstance(d, numpy.ndarray):
return numpy.array([(d-T0_DATE).days for d in d])
else:
return (d - T0_DATE).days
def map_datetime64_to_x(d):
return (d - T0_DATETIME64) / numpy.timedelta64(1, 'D')
def calculate_trend_extrapolation_slope(all_cause_mortality, years):
acm_baseline_x_list = []
acm_baseline_x_date_list = []
acm_baseline_y_list = []
start_date = BASELINE_CUTOFF_DATE - dateutil.relativedelta.relativedelta(years=years)
for item_date, item_deaths in all_cause_mortality:
if start_date <= item_date < BASELINE_CUTOFF_DATE:
x = (item_date - T0_DATE).days
acm_baseline_x_list.append(x)
acm_baseline_x_date_list.append(item_date)
acm_baseline_y_list.append(item_deaths)
acm_baseline_x = numpy.array(acm_baseline_x_list)
acm_baseline_x_date = numpy.array(acm_baseline_x_date_list)
acm_baseline_y = numpy.array(acm_baseline_y_list)
a, b = numpy.polyfit(acm_baseline_x, acm_baseline_y, 1)
return a
def calculate_acm_baseline_method1(all_cause_mortality, all_cause_mortality_estimate):
acm_raw_x_list = []
acm_raw_x_date_list = []
acm_raw_y_list = []
acm_baseline_x_list = []
acm_baseline_x_date_list = []
acm_baseline_y_list = []
for item_date, item_deaths in all_cause_mortality:
if item_date < BASELINE_START_DATE:
continue
x = (item_date - T0_DATE).days
acm_raw_x_list.append(x)
acm_raw_x_date_list.append(item_date)
acm_raw_y_list.append(item_deaths)
if item_date < BASELINE_CUTOFF_DATE:
acm_baseline_x_list.append(x)
acm_baseline_x_date_list.append(item_date)
acm_baseline_y_list.append(item_deaths)
acm_raw_x = numpy.array(acm_raw_x_list)
acm_raw_x_date = numpy.array(acm_raw_x_date_list)
acm_raw_y = numpy.array(acm_raw_y_list)
acm_baseline_x = numpy.array(acm_baseline_x_list)
acm_baseline_x_date = numpy.array(acm_baseline_x_date_list)
acm_baseline_y = numpy.array(acm_baseline_y_list)
acm_averaged_x = acm_raw_x
acm_averaged_x_date = acm_raw_x_date
acm_averaged_y = calculate_variable_window_moving_average(acm_raw_y, 7)
baseline_average_x_list = []
baseline_average_x_date_list = []
x_date = min(acm_raw_x_date) + BASELINE_INTERVAL / 2
while x_date < BASELINE_CUTOFF_DATE:
baseline_average_x_list.append((x_date - T0_DATE).days)
baseline_average_x_date_list.append(x_date)
x_date += BASELINE_INTERVAL
baseline_average_x = numpy.array(baseline_average_x_list)
baseline_average_x_date = numpy.array(baseline_average_x_date_list)
baseline_average_y_list = []
for baseline_x in baseline_average_x_date_list:
window_start_date = baseline_x - BASELINE_INTERVAL / 2
window_end_date = baseline_x + BASELINE_INTERVAL / 2
average_sum = 0
average_count = 0
for acm_date, acm_y in zip(acm_raw_x_date, acm_raw_y):
if acm_date >= window_start_date and acm_date < window_end_date:
average_sum += acm_y
average_count += 1
baseline_y = average_sum / average_count
baseline_average_y_list.append(baseline_y)
baseline_average_y = numpy.array(baseline_average_y_list)
if all_cause_mortality_estimate is not None:
acm_estimate_x_list = [baseline_average_x[-1]]
acm_estimate_x_date_list = [baseline_average_x_date[-1]]
acm_estimate_y_list = [baseline_average_y[-1]]
for x_date, year_mortality_estimate in all_cause_mortality_estimate:
x = (x_date - T0_DATE).days
acm_estimate_x_list.append(x)
acm_estimate_x_date_list.append(x_date)
acm_estimate_y_list.append(year_mortality_estimate/(datetime.date(x_date.year, 12, 31)-datetime.date(x_date.year, 1, 1)).days)
acm_estimate_x = numpy.array(acm_estimate_x_list)
acm_estimate_x_date = numpy.array(acm_estimate_x_date_list)
acm_estimate_y = numpy.array(acm_estimate_y_list)
else:
acm_estimate_x = None
acm_estimate_x_date = None
acm_estimate_y = None
if False:
# spline trend
spline_only_fn = scipy.interpolate.PchipInterpolator(baseline_average_x, baseline_average_y, axis=0, extrapolate=True)
if all_cause_mortality_estimate is not None:
def baseline_trend_fn(x):
y = spline_only_fn(x)
y[x > acm_estimate_x[0]]= acm_estimate_y[0] + (x[x>acm_estimate_x[0]] - acm_estimate_x[0]) * (acm_estimate_y[1] - acm_estimate_y[0]) / (acm_estimate_x[1] - acm_estimate_x[0])
return y
else:
baseline_trend_fn = spline_only_fn
else:
# linear trend
baseline_average_and_estimate_x = numpy.concatenate((baseline_average_x, acm_estimate_x[1:]))
baseline_average_and_estimate_x_date = numpy.concatenate((baseline_average_x_date, acm_estimate_x_date[1:]))
baseline_average_and_estimate_y = numpy.concatenate((baseline_average_y, acm_estimate_y[1:]))
baseline_trend_fn = scipy.interpolate.interp1d(baseline_average_and_estimate_x, baseline_average_and_estimate_y, axis=0, fill_value="extrapolate")
def days_to_rad(days):
return 1 / DAYS_IN_YEAR_EXACT * 2 * math.pi * days
def baseline_cosine_fn(x, t_offs, a):
baseline = baseline_trend_fn(x)
return baseline * (1 + a * numpy.cos(days_to_rad(x + t_offs)))
baseline_cosine_params, _ = scipy.optimize.curve_fit(baseline_cosine_fn, acm_baseline_x, acm_baseline_y, p0=[-51, 0])
print("Cosine time offset %.2f days (%.3f rad)" % (baseline_cosine_params[0], days_to_rad(baseline_cosine_params[0])))
print("Cosine amplitude factor: %.4f" % (baseline_cosine_params[1],))
def baseline_fn(x):
return baseline_cosine_fn(x, *baseline_cosine_params)
excess_mortality_x_list = []
excess_mortality_x_date_list = []
excess_mortality_y_list = []
excess_mortality_baseline_part_sum = 0
excess_mortality_baseline_part_count = 0
baseline_part_deaths_sum = 0
for item_date, item_deaths in all_cause_mortality:
x = (item_date - T0_DATE).days
baseline_deaths = baseline_fn(numpy.array([x]))[0]
excess_deaths = item_deaths - baseline_deaths
if item_date < BASELINE_CUTOFF_DATE:
excess_mortality_baseline_part_sum += excess_deaths
excess_mortality_baseline_part_count += 1
baseline_part_deaths_sum += item_deaths
excess_mortality_x_list.append(x)
excess_mortality_x_date_list.append(item_date)
excess_mortality_y_list.append(excess_deaths)
excess_mortality_x = numpy.array(excess_mortality_x_list)
excess_mortality_x_date = numpy.array(excess_mortality_x_date_list)
excess_mortality_y = numpy.array(excess_mortality_y_list)
if excess_mortality_baseline_part_count > 0:
excess_mortality_baseline_part_avg = excess_mortality_baseline_part_sum / excess_mortality_baseline_part_count
else:
excess_mortality_baseline_part_avg = 0
print("Sum of excess deaths: %.1f of %d total deaths" % (excess_mortality_baseline_part_sum, baseline_part_deaths_sum))
output_dataseries("data_output/excess_mortality.csv",
["excess_mortality_x", "excess_mortality_x_date", "excess_mortality_y"],
excess_mortality_x, excess_mortality_x_date, excess_mortality_y)
return (
(acm_raw_x, acm_raw_x_date, acm_raw_y),
(acm_averaged_x, acm_averaged_x_date, acm_averaged_y),
(baseline_average_x, baseline_average_x_date, baseline_average_y),
(acm_estimate_x, acm_estimate_x_date, acm_estimate_y),
(baseline_trend_fn, baseline_fn),
(excess_mortality_x, excess_mortality_x_date, excess_mortality_y)
)
def calculate_acm_baseline_method2(all_cause_mortality, all_cause_mortality_estimate):
acm_raw_x_list = []
acm_raw_x_date_list = []
acm_raw_y_list = []
acm_baseline_x_list = []
acm_baseline_x_date_list = []
acm_baseline_y_list = []
for item_date, item_deaths in all_cause_mortality:
x = (item_date - T0_DATE).days
acm_raw_x_list.append(x)
acm_raw_x_date_list.append(item_date)
acm_raw_y_list.append(item_deaths)
if BASELINE_START_DATE <= item_date < BASELINE_CUTOFF_DATE:
acm_baseline_x_list.append(x)
acm_baseline_x_date_list.append(item_date)
acm_baseline_y_list.append(item_deaths)
acm_raw_x = numpy.array(acm_raw_x_list)
acm_raw_x_date = numpy.array(acm_raw_x_date_list)
acm_raw_y = numpy.array(acm_raw_y_list)
acm_baseline_x = numpy.array(acm_baseline_x_list)
acm_baseline_x_date = numpy.array(acm_baseline_x_date_list)
acm_baseline_y = numpy.array(acm_baseline_y_list)
acm_averaged_x = acm_raw_x
acm_averaged_x_date = acm_raw_x_date
acm_averaged_y = calculate_variable_window_moving_average(acm_raw_y, 7)
baseline_point_x_list = []
baseline_point_x_date_list = []
min_date = min(acm_baseline_x_date)
max_date = max(acm_baseline_x_date)
for x_date in (min_date, max_date):
baseline_point_x_list.append((x_date - T0_DATE).days)
baseline_point_x_date_list.append(x_date)
#for year in range(min_date.year+1, max_date.year+10, 3):
# x_date = datetime.date(year, 1, 1) + datetime.timedelta(days=182)
# if min_date <= x_date <= max_date and x_date < BASELINE_CUTOFF_DATE:
# baseline_point_x_list.append((x_date - T0_DATE).days)
# baseline_point_x_date_list.append(x_date)
baseline_point_x = numpy.array(baseline_point_x_list)
baseline_point_x_date = numpy.array(baseline_point_x_date_list)
baseline_average_y_list = []
for baseline_x in baseline_point_x_date_list:
window_size = datetime.timedelta(days=365*3)
window_start_date = baseline_x - window_size / 2
window_end_date = baseline_x + window_size / 2
average_sum = 0
average_count = 0
for acm_date, acm_y in zip(acm_raw_x_date, acm_raw_y):
if acm_date >= window_start_date and acm_date < window_end_date:
average_sum += acm_y
average_count += 1
baseline_y = average_sum / average_count
baseline_average_y_list.append(baseline_y)
baseline_average_y = numpy.array(baseline_average_y_list)
if False:
print("Years\tTrend extrapolation slope")
for i in (5, 6, 7, 8, 9, 10, 11):
trend_extrapolation_slope = calculate_trend_extrapolation_slope(all_cause_mortality, years=i)
print("%d\t%.5f" % (i, trend_extrapolation_slope))
trend_extrapolation_slope = calculate_trend_extrapolation_slope(all_cause_mortality, years=10)
else:
trend_extrapolation_slope = None
print("Year\t3 year average weekly dead")
for x_date, deaths_average in zip(baseline_point_x_date, baseline_average_y):
print("%s\t%.1f" % (x_date.year, deaths_average))
if all_cause_mortality_estimate is not None:
print("Year\tEstimated average weekly dead")
acm_estimate_x_list = [baseline_point_x[-1]]
acm_estimate_x_date_list = [baseline_point_x_date[-1]]
acm_estimate_y_list = [baseline_average_y[-1]]
for x_date, estimated_weekly_mortality in all_cause_mortality_estimate:
x = (x_date - T0_DATE).days
acm_estimate_x_list.append(x)
acm_estimate_x_date_list.append(x_date)
print("%s\t%.1f" % (x_date.year, estimated_weekly_mortality))
acm_estimate_y_list.append(estimated_weekly_mortality)
acm_estimate_x = numpy.array(acm_estimate_x_list)
acm_estimate_x_date = numpy.array(acm_estimate_x_date_list)
acm_estimate_y = numpy.array(acm_estimate_y_list)
else:
acm_estimate_x = None
acm_estimate_x_date = None
acm_estimate_y = None
# linear interpolation between points found through curve fitting, where the point y-values are curve fitting variables
#
def get_linfit_fn(yvalues):
linfit_x = baseline_point_x
if acm_estimate_x is not None:
linfit_x = numpy.concatenate((linfit_x, acm_estimate_x[1:]))
linfit_y = numpy.array(yvalues)
if acm_estimate_x is not None:
linfit_y = numpy.concatenate((linfit_y, acm_estimate_y[1:]))
if trend_extrapolation_slope is not None:
delta_x = linfit_x[-1] - linfit_x[-2]
trend_extrapolation_x = linfit_x[-1] + (linfit_x[-1] - linfit_x[-2])
trend_extrapolation_y = linfit_y[-1] + delta_x * trend_extrapolation_slope
linfit_x = numpy.concatenate((linfit_x, numpy.array([trend_extrapolation_x])))
linfit_y = numpy.concatenate((linfit_y, numpy.array([trend_extrapolation_y])))
return scipy.interpolate.interp1d(linfit_x, linfit_y, axis=0, fill_value="extrapolate")
def days_to_rad(days):
return 1 / DAYS_IN_YEAR_EXACT * 2 * math.pi * days
def baseline_optimization_fn(x, t_offs, a, *yvalues):
assert len(yvalues) == len(baseline_point_x), "Invalid lengths: %s != %s" % (len(yvalues), len(baseline_point_x))
linfit_fn = get_linfit_fn(yvalues)
trend_value = linfit_fn(x)
return trend_value * (1 + a * numpy.cos(days_to_rad(x + t_offs)))
# Reason for this hack is that curve_fit inspects the optimization function and requires
# positional parameters, i.e. variable *args is not possible. This array allows for
# variable amount of piecewise linear points
fn_wrappers = [lambda x, t_offs, a, p0: baseline_optimization_fn(x, t_offs, a, p0),
lambda x, t_offs, a, p0, p1: baseline_optimization_fn(x, t_offs, a, p0, p1),
lambda x, t_offs, a, p0, p1, p2: baseline_optimization_fn(x, t_offs, a, p0, p1, p2),
lambda x, t_offs, a, p0, p1, p2, p3: baseline_optimization_fn(x, t_offs, a, p0, p1, p2, p3),
lambda x, t_offs, a, p0, p1, p2, p3, p4: baseline_optimization_fn(x, t_offs, a, p0, p1, p2, p3, p4),
lambda x, t_offs, a, p0, p1, p2, p3, p4, p5: baseline_optimization_fn(x, t_offs, a, p0, p1, p2, p3, p4, p5),
lambda x, t_offs, a, p0, p1, p2, p3, p4, p5, p6: baseline_optimization_fn(x, t_offs, a, p0, p1, p2, p3, p4, p5, p6),
lambda x, t_offs, a, p0, p1, p2, p3, p4, p5, p6, p7: baseline_optimization_fn(x, t_offs, a, p0, p1, p2, p3, p4, p5, p6, p7),
lambda x, t_offs, a, p0, p1, p2, p3, p4, p5, p6, p7, p8: baseline_optimization_fn(x, t_offs, a, p0, p1, p2, p3, p4, p5, p6, p7, p8),
lambda x, t_offs, a, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9: baseline_optimization_fn(x, t_offs, a, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9),