/
jhu-to-influx.py
executable file
·206 lines (170 loc) · 5.08 KB
/
jhu-to-influx.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
#!/usr/bin/env python3
import asyncio
import csv
import collections
import dataclasses
import functools
import operator
import pathlib
import typing
from datetime import datetime, timedelta, date
import numpy as np
import common
import influxdb
MEASUREMENT_GEOGRAPHICS = "jhu_data_v1_geo"
KIND_CASE = 0
KIND_DEATH = 1
KIND_RECOVERED = 2
class JHUSample(typing.NamedTuple):
country: str
kind: int
cases: int
def parse_date(s: str) -> date:
month, day, year = s.split("/")
return date(2000 + int(year), int(month), int(day))
def load_jhu_data(
f,
kind,
dest,
):
rows = iter(csv.reader(f))
header = next(rows)
date_offset = 4
dates = [
parse_date(s) for s in header[date_offset:]
]
for row in csv.reader(f):
_, country, _, _, *data = row
for date, value_s in zip(dates, data):
value = int(value_s)
dest.setdefault(date, []).append(
JHUSample(
country,
kind,
value,
)
)
print(f"\x1b[Jproc: {country}", end="\r")
def load_counters(
samples: typing.Mapping[datetime, typing.Collection[JHUSample]],
) -> common.Counters:
min_day = min(samples.keys())
max_day = max(samples.keys())
def keyfunc(s):
return ((s.country,),)
keys = common.build_axis_keys(
(s for date_samples in samples.values() for s in date_samples),
1, keyfunc,
)
key_indices = [
{
k: i
for i, k in enumerate(ks)
}
for ks in keys
]
ndays = (max_day - min_day).days + 1
counters = np.zeros(
(ndays,) + tuple(len(ks) for ks in keys) + (3,),
dtype=np.float32,
)
for i, date in enumerate(common.daterange(min_day, max_day)):
date_samples = samples.get(date, [])
for sample in date_samples:
sample_keys = keyfunc(sample)
indices = tuple(key_indices[i][k]
for i, k in enumerate(sample_keys))
counters[(i,) + indices + (sample.kind,)] += sample.cases
print(f"proc: {date}", end="\r")
return common.Counters(
first_date=min_day,
keys=keys,
key_indices=key_indices,
count_axis=len(keys) + 1,
data=counters,
)
def generate_population_samples(
population_info,
measurement: str,
first_date: datetime,
ndays: int):
templates = []
for country, population in population_info.items():
templates.append(influxdb.InfluxDBSample(
measurement=measurement,
tags=(
("country", country),
),
fields=(
("population", population),
),
timestamp=None,
ns_part=0,
))
for i in range(ndays+1):
date = first_date + timedelta(days=i)
timestamp = datetime(date.year, date.month, date.day)
yield from (
template._replace(timestamp=timestamp)
for template in templates
)
def load_jhu_population_data(f) -> typing.Mapping[str, int]:
result = collections.Counter()
for row in csv.DictReader(f):
if not row["Lat"]:
continue
population_s = row["Population"]
# using addition here because we strip out provinces etc.
result[row["Country_Region"]] += int(population_s or "0")
return result
def main():
import sys
mapping = [
(KIND_CASE, "cases.csv"),
(KIND_DEATH, "deaths.csv"),
(KIND_RECOVERED, "recovered.csv"),
]
print("loading ...")
data = {}
for kind, filename in mapping:
with (pathlib.Path(sys.argv[1]) / filename).open("r") as f:
load_jhu_data(f, kind, data)
print("\x1b[J", end="")
print("loading population data ...")
with (pathlib.Path(sys.argv[1]) / "lut.csv").open("r") as f:
population = load_jhu_population_data(f)
print("preparing ...")
counters = load_counters(data)
print("crunching the numbers ...")
print(" deriving data")
out = common.derive_data(counters.data, is_cumsum=True)
expected_samples = \
len(population) * out.shape[0] + \
functools.reduce(operator.mul, out.shape[:-1])
print("sending ...")
asyncio.run(common.push(
common.generate_counter_samples(
dataclasses.replace(
counters,
data=out,
keys=counters.keys,
),
MEASUREMENT_GEOGRAPHICS,
[("country",)],
["ccases", "cdeaths", "crecovered",
"d1cases", "d1deaths", "d1recovered",
"d7cases", "d7deaths", "d7recovered",
"d7cases_s7", "d7deaths_s7", "d7recovered_s7"],
),
generate_population_samples(
population,
MEASUREMENT_GEOGRAPHICS,
counters.first_date,
out.data.shape[0],
),
expected_samples=expected_samples,
))
import os
os._exit(0)
if __name__ == "__main__":
main()