home · contact · privacy
De-hardcode infections table path from enhance_table.py.
[berlin-corona-table] / enhance_table.py
1 #!//usr/bin/env python3
2
3 import sys
4 if len(sys.argv) != 2:
5     print('Expecting infections table file path as only argument.')
6     exit(1)
7 infections_table = sys.argv[1]
8
9 # District population numbers as per Wikipedia.
10 district_pops = {
11   'CW': 342332,
12   'FK': 289762,
13   'Li': 291452,
14   'MH': 268548,
15   'Mi': 384172,
16   'Ne': 329691,
17   'Pa': 407765,
18   'Re': 265225,
19   'Sp': 243977,
20   'SZ': 308697,
21   'TS': 351644,
22   'TK': 271153,
23   'sum': 3754418,
24 }
25
26 f = open(infections_table, 'r')
27 lines = f.readlines()
28 f.close()
29
30 # Parse first table file line for the names and order of districts.
31 db = {}
32 sorted_districts = []
33 for header in lines[0].split():
34     sorted_districts += [header]
35     db[header] = {}
36
37 # Seed DB with daily new infections data per district, per date.
38 sorted_dates = []
39 for line in lines[1:]:
40     fields = line.split()
41     date = fields[0]
42     sorted_dates += [date]
43     for i in range(len(sorted_districts)):
44         district = sorted_districts[i]
45         district_data = fields[i + 1]
46         db[district][date] = {'new_infections': int(district_data)}
47 sorted_dates.sort()
48
49 # In LaGeSo's data, the last "district" is actually the sum of all districts /
50 # the whole of Berlin.
51 #
52 # Fail on any day where the "sum" district's new infections are not the proper
53 # sum of the individual districts new infections.  Yes, sometimes Lageso sends
54 # data that is troubled in this way.  It will then have to be fixed manually in
55 # the table file, since we should have a human look at what mistake was
56 # probably made.
57 for date in sorted_dates:
58     sum_district = sorted_districts[-1]
59     day_sum = 0
60     for district in sorted_districts[:-1]:
61         day_sum += db[district][date]['new_infections']
62     if day_sum != db[sum_district][date]['new_infections']:
63         raise Exception('Questionable district infection sum in %s' % date)
64
65 # Enhance DB with data about weekly sums, averages, incidences per day.  Ignore
66 # days that have less than 6 predecessors (we can only know a weekly average if
67 # we have a whole week of data).
68 for i in range(len(sorted_dates)):
69     if i < 6:
70         continue
71     date = sorted_dates[i]
72     week_dates = []
73     for j in range(7):
74         week_dates += [sorted_dates[i - j]]
75     for district in sorted_districts:
76         district_pop = district_pops[district]
77         week_sum = 0
78         for week_date in week_dates:
79             week_sum += db[district][week_date]['new_infections']
80         db[district][date]['week_sum'] = week_sum
81         db[district][date]['week_average'] = week_sum / 7
82         db[district][date]['week_incidence'] = (week_sum / district_pop) * 100000
83
84 # Explain what this is.
85 intro = """Table of Berlin's Corona infection number development by districts.
86 Updated daily around 9pm.
87
88 Abbrevations/explanations:
89
90 CW: Charlottenburg-Wilmersdorf
91 FK: Friedrichshain-Kreuzberg
92 Li: Lichtenberg
93 MH: Marzahn-Hellersdorf
94 Mi: Mitte
95 Ne: Neukölln
96 Pa: Pankow
97 Re: Reinickendorf
98 Sp: Spandau
99 SZ: Steglitz-Zehlendorf
100 TS: Tempelhof-Schöneberg
101 TK: Treptow-Köpenick
102 sum: sum for all the districts
103 wsum: sum for last 7 days
104 wavg: per-day average of new infections for last 7 days
105 winc: incidence (x per 100k inhabitants) of new infections for last 7 days
106
107 Source code: https://plomlompom.com/repos/?p=berlin-corona-table
108 """
109 print(intro)
110
111 # Output table of enhanced daily infection data, newest on top, separated into
112 # 7-day units.
113 sorted_dates.reverse()
114 weekday_count = 0
115 for date in sorted_dates:
116
117     # Week table header.
118     if weekday_count == 0:
119         print(' '*11, '  '.join(sorted_districts[:-1]),
120               sorted_districts[-1], 'wsum', ' wavg', 'winc')
121         week_start_date = date
122
123     # Day data line.
124     new_infections = []
125     for district in sorted_districts:
126         new_infections += [db[district][date]['new_infections']]
127     week_sum = week_avg = week_inc = ''
128     sum_district = sorted_districts[-1]
129     sum_district_data = db[sum_district][date]
130     if 'week_sum' in sum_district_data:
131         week_sum = '%4s' % sum_district_data['week_sum']
132     if 'week_average' in sum_district_data:
133         week_avg = '%5.1f' % sum_district_data['week_average']
134     if 'week_incidence' in sum_district_data:
135         week_inc = '%4.1f' % sum_district_data['week_incidence']
136     print(date, ' '.join(['%3s' % infections for infections in new_infections]),
137           week_sum, week_avg, week_inc)
138
139     # Maintain 7-day cycle.
140     weekday_count += 1
141     if weekday_count != 7:
142         continue
143     weekday_count = 0
144
145     # After each 7 days, print summary for individual districts.
146     weekly_sums = []
147     weekly_avgs = []
148     weekly_incs = []
149     for district in sorted_districts[:-1]:
150         weekly_sums += [db[district][week_start_date]['week_sum']]
151         weekly_avgs += [db[district][week_start_date]['week_average']]
152         weekly_incs += [db[district][week_start_date]['week_incidence']]
153     print()
154     print('district stats for week from %s to %s:' % (date, week_start_date))
155     print(' '*7, '    '.join(sorted_districts[:-1]))
156     print('wsum', ' '.join(['%5.1f' % wsum for wsum in weekly_sums]))
157     print('wavg', ' '.join(['%5.1f' % wavg for wavg in weekly_avgs]))
158     print('winc', ' '.join(['%5.1f' % winc for winc in weekly_incs]))
159     print()