-
Notifications
You must be signed in to change notification settings - Fork 10
/
plot-de-districts-map.py
executable file
·511 lines (474 loc) · 18.3 KB
/
plot-de-districts-map.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
#!/usr/bin/env python3.10
# by Dr. Torben Menke https://entorb.net
# https://github.com/entorb/COVID-19-Coronavirus-German-Regions
"""
Generates animated maps for Germany using Covid-19 data and Divi hospital data
Based on
https://raw.githubusercontent.com/ythlev/covid-19/master/run.py
by Chang Chia-huan
"""
import glob
import os
import re
import subprocess # noqa: S404
import sys
import helper
# TODO: replace threshold magic based on all data by simple logic based on last value for cases and manually set threshold for other sets
unit = 1000000
def run_imagemagick_convert(
l_imagemagick_parameters: list,
wait_for_finish: bool = True,
):
"""
wait_for_finish = False: the calling function needs to handle the returned process
"""
# prepend 'convert'
l_imagemagick_parameters.insert(0, "convert")
if os.name == "posix":
# print ('posix/Unix/Linux')
pass
elif os.name == "nt":
# print ('Windows')
# prepend 'magick
l_imagemagick_parameters.insert(0, "magick")
else:
print("unknown os")
sys.exit(1) # throws exception, use quit() to close silently
process = subprocess.Popen( # noqa: S603
l_imagemagick_parameters,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
if wait_for_finish:
stdout, stderr = process.communicate()
if stdout != "":
print(f"Out: {stdout}")
if stderr != "":
print(f"ERROR: {stderr}")
return process
# from https://htmlcolorcodes.com/
# alternative: https://www.w3schools.com/colors/colors_picker.asp
d_color_scales = {
"template": [
"#aed6f1",
"#85c1e9",
"#5dade2",
"#3498db",
"#2e86c1",
"#2874a6",
"#21618c",
"#1b4f72",
],
"blue": [
"#d6eaf8",
"#85c1e9",
"#5dade2",
"#3498db",
"#2e86c1",
"#2874a6",
"#21618c",
"#1b4f72",
],
"red": [
"#e6b0aa",
"#d98880",
"#cd6155",
"#c0392b",
"#a93226",
"#922b21",
"#7b241c",
"#641e16",
],
"purple": [
"#d2b4de",
"#bb8fce",
"#a569bd",
"#8e44ad",
"#7d3c98",
"#6c3483",
"#5b2c6f",
"#4a235a",
],
"green": [
"#a9dfbf",
"#7dcea0",
"#52be80",
"#27ae60",
"#229954",
"#1e8449",
"#196f3d",
"#145a32",
],
}
d_all_date_data = {}
l_month = []
count = 0
f = "data-json/de-districts/de-district_timeseries-02000.json"
if not os.path.exists(f):
raise Exception(f"file missing: {f}")
l = glob.glob("data-json/de-districts/de-district_timeseries-*.json")
assert len(l) > 400
for f in l:
count += 1
my_match = re.search(r"^.*de-district_timeseries\-(\d+)\.json$", f)
assert my_match
lk_id = int(my_match.group(1))
l = helper.read_json_file(f)
for d in l:
date = d["Date"]
thisMonth = date[0:7]
# skip old data points
if thisMonth in ("2020-01", "2020-02"):
continue
# add to list of months for later creations of 1 gif per month
if count == 1 and thisMonth not in l_month:
l_month.append(thisMonth)
if d["Date"] not in d_all_date_data:
d_all_date_data[d["Date"]] = {}
# del d['Timestamp'], d['Date'], d['Days_Past'], d['Days_Since_2nd_Death']
d_all_date_data[date][lk_id] = d
del f, d, l, count, my_match
# check if last date has as many values as the 2nd last, of not drop it
dates = sorted(d_all_date_data.keys())
if len(d_all_date_data[dates[-1]]) != len(d_all_date_data[dates[-2]]):
print("WARNING: last date is incomplete, so removing it")
del d_all_date_data[dates[-1]]
del dates
# property_to_plot = 'Deaths_Last_Week_Per_Million'
l_subprocesses = []
d_latest_svg_file = {} # store the last generated file per property
# for property_to_plot in ('Cases_Per_Million',):
for property_to_plot in (
"Cases_Last_Week_Per_100000",
"Cases_Per_Million",
"Deaths_Per_Million",
"DIVI_Intensivstationen_Covid_Prozent",
):
print(f"=== start {property_to_plot}")
meta = {}
# set color and manual setting of color scale
if property_to_plot == "Cases_Per_Million":
meta["colour"] = d_color_scales["red"]
threshold = [1, 10, 100, 1000, 10000, 50000, 100000]
elif property_to_plot == "Deaths_Per_Million":
meta["colour"] = d_color_scales["green"]
threshold = [100, 200, 500, 1000, 2000, 5000, 10000]
elif property_to_plot == "Cases_Last_Week_Per_100000":
meta["colour"] = d_color_scales["blue"]
threshold = [1, 10, 35, 50, 100, 200, 500]
elif property_to_plot == "DIVI_Intensivstationen_Covid_Prozent":
meta["colour"] = d_color_scales["purple"]
threshold = [1, 10, 20, 30, 40, 50, 75]
elif property_to_plot == "DIVI_Intensivstationen_Betten_belegt_Prozent":
# not in use
meta["colour"] = d_color_scales["purple"]
threshold = [30, 40, 50, 60, 70, 80, 90]
else:
raise Exception(f"unknown property_to_plot '{property_to_plot}'")
# read template and generate image per day
with open(
"maps/template_de-districts.svg",
newline="",
encoding="utf-8",
) as file_in:
# plot loop for each date
# date_str = '2020-04-24'
# l_districts = d_all_date_data[date_str]
print("generating SVGs")
for date_str, l_districts in d_all_date_data.items():
# skip date if for this month I already have a month .gif
thisMonth = date_str[0:7]
if os.path.isfile(
f"maps/out/de-districts/{property_to_plot}-{thisMonth}.gif",
):
continue
file_in.seek(0, 0) # reset file pointer
main = {}
at_least_one_value_found = False
for lk_id, d in l_districts.items():
area = lk_id
if property_to_plot in d and d[property_to_plot] is not None:
pcapita = d[property_to_plot]
at_least_one_value_found = True
else:
pcapita = -1
main[area] = {"pcapita": pcapita}
# do not create an svg if not areas with data for property_to_plot are available
if not at_least_one_value_found:
continue
outfile = f"maps/out/de-districts/{property_to_plot}-{date_str}.svg"
# overwritting per date, until it holds the latest file
d_latest_svg_file[property_to_plot] = outfile
# skip svg generation if I have not cleaned up, for faster gif generation debugging
if os.path.isfile(outfile):
continue
with open(outfile, mode="w", newline="", encoding="utf-8") as file_out:
# decide on the digits for the legend
if (property_to_plot == "DIVI_Intensivstationen_Covid_Prozent") or (
property_to_plot == "DIVI_Intensivstationen_Betten_belegt_Prozent"
):
num = "{:.0f}%"
# elif threshold[7-1] >= 10000:
# num = "{:.0f}"
# elif threshold[1] >= 10:
# num = "{:.0f}"
else:
num = "{:.0f}"
for row in file_in:
written = False
# 1. check if the row contains any of the known area codes (lk_id)
for area in main:
if row.find('id="{}"'.format(area)) > -1:
# paint white if we have no value
if main[area]["pcapita"] == -1:
file_out.write(
row.replace(
'id="{}"'.format(area),
'style="fill:{}"'.format("#ffffff"),
),
)
# else paint it in the correct color
else:
i = 0
while i <= 7 - 1:
if main[area]["pcapita"] > threshold[i]:
i += 1
else:
break
file_out.write(
row.replace(
'id="{}"'.format(area),
'style="fill:{}"'.format(meta["colour"][i]),
),
)
written = True
break
if written is False:
# 2. check if row contains Date placeholder
if row.find(">!!!Date!!!") > -1:
file_out.write(row.replace("!!!Date!!!", date_str))
# 3. check if row contains Label placeholder
elif row.find(">!!!Level") > -1:
for i in range(7 + 1):
if row.find("!!!Level{}".format(i)) > -1:
if i == 0:
file_out.write(
row.replace(
"!!!Level{}".format(i),
"≤ "
+ num.format(threshold[i]).replace(
"_",
" ",
),
),
)
else:
file_out.write(
row.replace(
"!!!Level{}".format(i),
"> "
+ num.format(threshold[i - 1]).replace(
"_",
" ",
),
),
)
# 4. check if row contains legend color box
elif row.find('<path fill="#') > -1:
s = row
for i in range(7 + 1):
s = s.replace(
d_color_scales["template"][i],
meta["colour"][i],
)
file_out.write(s)
# 5. check if row contains Title
elif row.find("!!!TITLE!!!") > -1:
if property_to_plot == "Cases_Last_Week_Per_100000":
file_out.write(
row.replace(
"!!!TITLE!!!",
"Neu-Infizierte 7 Tage pro 100000 EW",
),
)
elif property_to_plot == "Cases_Per_Million":
file_out.write(
row.replace(
"!!!TITLE!!!",
"Infizierte pro Millionen EW.",
),
)
elif property_to_plot == "Deaths_Per_Million":
file_out.write(
row.replace(
"!!!TITLE!!!",
"Tote pro Millionen EW.",
),
)
elif (
property_to_plot
== "DIVI_Intensivstationen_Covid_Prozent"
):
file_out.write(
row.replace(
"!!!TITLE!!!",
"Intensivstationen: COVID-19 Patienten",
),
)
elif (
property_to_plot
== "DIVI_Intensivstationen_Betten_belegt_Prozent"
):
file_out.write(
row.replace(
"!!!TITLE!!!",
"Intensivstationen: Betten belegt",
),
)
else:
file_out.write(
row.replace(
"!!!TITLE!!!",
property_to_plot.replace("_", " "),
),
)
else:
file_out.write(row)
# break
# break
l_subprocesses = []
print("svg -> month-gif")
for month in l_month:
if f"{property_to_plot}-{month}" in [
"DIVI_Intensivstationen_Betten_belegt_Prozent-2020-03",
"DIVI_Intensivstationen_Covid_Prozent-2020-03",
]:
# we do not have DIVI data for 03/2020
continue
l = glob.glob(f"maps/out/de-districts/{property_to_plot}-{month}*.svg")
if len(l) == 0:
continue
# convert -size 480x maps/out/de-districts/Cases_Last_Week_Per_100000-2020-03*.svg -resize 480x -coalesce -fuzz 2% +dither -layers Optimize maps/out/de-districts/Cases_Last_Week_Per_100000-2020-03.gif
l_imagemagick_parameters = [
"-size",
"480x",
f"maps/out/de-districts/{property_to_plot}-{month}*.svg",
"-resize",
"480x",
"-coalesce",
"-fuzz",
"2%",
"+dither",
"-layers",
"Optimize",
f"maps/out/de-districts/{property_to_plot}-{month}.gif",
]
# parallel processing ran into mem limits, fixed by editing the /etc/ImageMagick-6/policy.xml file
process = run_imagemagick_convert(
l_imagemagick_parameters,
wait_for_finish=False,
)
l_subprocesses.append(process)
# single processing
# process = run_imagemagick_convert(
# l_imagemagick_parameters, wait_for_finish=True)
# wait for subprocesses to finish
for process in l_subprocesses:
stdout, stderr = process.communicate()
if stdout != "":
print(f"Out: {stdout}")
if stderr != "":
print(f"ERROR: {stderr}")
# generate a static image for the latest date
l_imagemagick_parameters = [
f"{d_latest_svg_file[property_to_plot]}",
"-resize",
"480x",
"-coalesce",
"-fuzz",
"2%",
"+dither",
"-layers",
"Optimize",
f"maps/de-districts-{property_to_plot}-latest.gif",
]
run_imagemagick_convert(l_imagemagick_parameters)
# cleanup the svg to reduce space on file system
for f in glob.glob("maps/out/de-districts/*.svg"):
os.remove(f)
pass
outfile = f"maps/de-districts-{property_to_plot}.gif"
print("join monthly gifs")
l_imagemagick_parameters = [
f"maps/out/de-districts/{property_to_plot}-*.gif",
"-coalesce",
"-fuzz",
"2%",
"+dither",
"-layers",
"Optimize",
outfile,
]
run_imagemagick_convert(l_imagemagick_parameters)
# delete gif of last month, as this is not be complete and thus shall not be commited
l = sorted(glob.glob(f"maps/out/de-districts/{property_to_plot}-*.gif"))
os.remove(l.pop())
# set delay of 0.25s for all frames
l_imagemagick_parameters = [outfile, "-delay", "250x1000", outfile]
run_imagemagick_convert(l_imagemagick_parameters)
# clone last frame and set longer delay time of 2s
l_imagemagick_parameters = [
outfile,
"(",
"-clone",
"-1",
"-set",
"delay",
"2000x1000",
")",
outfile,
]
run_imagemagick_convert(l_imagemagick_parameters)
print(f"converting {property_to_plot}.gif -> .mp4")
# from https://unix.stackexchange.com/questions/40638/how-to-do-i-convert-an-animated-gif-to-an-mp4-or-mv4-on-the-command-line
# fmpeg -i animated.gif -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" video.mp4
command = [
"ffmpeg",
"-y",
"-loglevel",
"warning",
"-i",
outfile,
"-movflags",
"faststart",
"-pix_fmt",
"yuv420p",
"-vf",
"scale=trunc(iw/2)*2:trunc(ih/2)*2",
f"maps/de-districts-{property_to_plot}.mp4",
]
process = subprocess.Popen( # noqa: S603
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
# wait_for_finish
stdout, stderr = process.communicate()
if stdout != "":
print(f"Out: {stdout}")
if stderr != "":
print(f"ERROR: {stderr}")
# # create copies with shorter and longer delay
# # this does not work: all have the same speed :-(
# delay_variants = (100, 250, 500)
# for delay in delay_variants:
# outfileDelay = f'maps/de-districts-{property_to_plot}-{delay}.gif'
# run_imagemagick_convert([
# outfile, '-delay', f'{delay}x1000', outfileDelay
# ])
# run_imagemagick_convert([
# outfileDelay, '(', '-clone', '-1', '-set', 'delay', '2000x1000', ')', outfileDelay
# ])
print("End of script reached")