-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtest_update_sensor.py
273 lines (245 loc) · 9.32 KB
/
test_update_sensor.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
# standard
from copy import deepcopy
import os
from os.path import join, exists
import pytest
from tempfile import TemporaryDirectory
# third party
import pandas as pd
import numpy as np
from boto3 import Session
from moto import mock_s3
import pytest
# third party
from delphi_utils import read_params
# first party
from delphi_changehc.config import Config, Constants
from delphi_changehc.constants import *
from delphi_changehc.update_sensor import write_to_csv, add_prefix, CHCSensorUpdator
from delphi_changehc.load_data import *
from delphi_changehc.run import run_module
CONFIG = Config()
CONSTANTS = Constants()
PARAMS = read_params()
COVID_FILEPATH = PARAMS["input_covid_file"]
DENOM_FILEPATH = PARAMS["input_denom_file"]
DROP_DATE = pd.to_datetime(PARAMS["drop_date"])
OUTPATH="test_data/"
class TestCHCSensorUpdator:
geo = "county"
parallel = False
weekday = False
se = False
prefix = "foo"
small_test_data = pd.DataFrame({
"num": [0, 100, 200, 300, 400, 500, 600, 100, 200, 300, 400, 500, 600],
"fips": [1.0] * 7 + [2.0] * 6,
"den": [1000] * 7 + [2000] * 6,
"date": [pd.Timestamp(f'03-{i}-2020') for i in range(1, 14)]}).set_index(["fips","date"])
def test_shift_dates(self):
su_inst = CHCSensorUpdator(
"02-01-2020",
"06-01-2020",
"06-12-2020",
self.geo,
self.parallel,
self.weekday,
self.se
)
## Test init
assert su_inst.startdate.month == 2
assert su_inst.enddate.month == 6
assert su_inst.dropdate.day == 12
## Test shift
su_inst.shift_dates()
assert su_inst.sensor_dates[0] == su_inst.startdate
assert su_inst.sensor_dates[-1] == su_inst.enddate - pd.Timedelta(days=1)
def test_geo_reindex(self):
su_inst = CHCSensorUpdator(
"02-01-2020",
"06-01-2020",
"06-12-2020",
'county',
self.parallel,
self.weekday,
self.se
)
su_inst.shift_dates()
data_frame = su_inst.geo_reindex(self.small_test_data.reset_index())
assert data_frame.shape[0] == 2*len(su_inst.fit_dates)
assert (data_frame.sum() == (4200,19000)).all()
def test_update_sensor(self):
for geo in ["state","hrr"]:
td = TemporaryDirectory()
su_inst = CHCSensorUpdator(
"02-01-2020",
"06-01-2020",
"06-12-2020",
geo,
self.parallel,
self.weekday,
self.se
)
with mock_s3():
# Create the fake bucket we will be using
params = read_params()
aws_credentials = params["aws_credentials"]
s3_client = Session(**aws_credentials).client("s3")
s3_client.create_bucket(Bucket=params["bucket_name"])
su_inst.update_sensor(
DENOM_FILEPATH,
COVID_FILEPATH,
td.name,
PARAMS["static_file_dir"]
)
assert len(os.listdir(td.name)) == len(su_inst.sensor_dates), f"failed {geo} update sensor test"
td.cleanup()
class TestWriteToCsv:
def test_write_to_csv_results(self):
res0 = {
"rates": {
"a": [0.1, 0.5, 1.5],
"b": [1, 2, 3]
},
"se": {
"a": [0.1, 1, 1.1],
"b": [0.5, np.nan, 0.5]
},
"dates": [
pd.to_datetime("2020-05-01"),
pd.to_datetime("2020-05-02"),
pd.to_datetime("2020-05-04")
],
"include": {
"a": [True, True, True],
"b": [True, False, True]
},
"geo_ids": ["a", "b"],
"geo_level": "geography",
}
td = TemporaryDirectory()
write_to_csv(res0, False, "name_of_signal", td.name)
# check outputs
expected_name = "20200502_geography_name_of_signal.csv"
assert exists(join(td.name, expected_name))
output_data = pd.read_csv(join(td.name, expected_name))
assert (
output_data.columns == ["geo_id", "val", "se", "direction", "sample_size"]
).all()
assert (output_data.geo_id == ["a", "b"]).all()
assert np.array_equal(output_data.val.values, np.array([0.1, 1]))
# for privacy we do not usually report SEs
assert np.isnan(output_data.se.values).all()
assert np.isnan(output_data.direction.values).all()
assert np.isnan(output_data.sample_size.values).all()
expected_name = "20200503_geography_name_of_signal.csv"
assert exists(join(td.name, expected_name))
output_data = pd.read_csv(join(td.name, expected_name))
assert (
output_data.columns == ["geo_id", "val", "se", "direction", "sample_size"]
).all()
assert (output_data.geo_id == ["a"]).all()
assert np.array_equal(output_data.val.values, np.array([0.5]))
assert np.isnan(output_data.se.values).all()
assert np.isnan(output_data.direction.values).all()
assert np.isnan(output_data.sample_size.values).all()
expected_name = "20200505_geography_name_of_signal.csv"
assert exists(join(td.name, expected_name))
output_data = pd.read_csv(join(td.name, expected_name))
assert (
output_data.columns == ["geo_id", "val", "se", "direction", "sample_size"]
).all()
assert (output_data.geo_id == ["a", "b"]).all()
assert np.array_equal(output_data.val.values, np.array([1.5, 3]))
assert np.isnan(output_data.se.values).all()
assert np.isnan(output_data.direction.values).all()
assert np.isnan(output_data.sample_size.values).all()
td.cleanup()
def test_write_to_csv_with_se_results(self):
res0 = {
"rates": {
"a": [0.1, 0.5, 1.5],
"b": [1, 2, 3]
},
"se": {
"a": [0.1, 1, 1.1],
"b": [0.5, np.nan, 0.5]
},
"dates": [
pd.to_datetime("2020-05-01"),
pd.to_datetime("2020-05-02"),
pd.to_datetime("2020-05-04")
],
"include": {
"a": [True, True, True],
"b": [True, False, True]
},
"geo_ids": ["a", "b"],
"geo_level": "geography",
}
td = TemporaryDirectory()
write_to_csv(res0, True, "name_of_signal", td.name)
# check outputs
expected_name = "20200502_geography_name_of_signal.csv"
assert exists(join(td.name, expected_name))
output_data = pd.read_csv(join(td.name, expected_name))
assert (
output_data.columns == ["geo_id", "val", "se", "direction", "sample_size"]
).all()
assert (output_data.geo_id == ["a", "b"]).all()
assert np.array_equal(output_data.val.values, np.array([0.1, 1]))
assert np.array_equal(output_data.se.values, np.array([0.1, 0.5]))
assert np.isnan(output_data.direction.values).all()
assert np.isnan(output_data.sample_size.values).all()
td.cleanup()
def test_write_to_csv_wrong_results(self):
res0 = {
"rates": {
"a": [0.1, 0.5, 1.5],
"b": [1, 2, 3]
},
"se": {
"a": [0.1, 1, 1.1],
"b": [0.5, 0.5, 0.5]
},
"dates": [
pd.to_datetime("2020-05-01"),
pd.to_datetime("2020-05-02"),
pd.to_datetime("2020-05-04")
],
"include": {
"a": [True, True, True],
"b": [True, False, True]
},
"geo_ids": ["a", "b"],
"geo_level": "geography",
}
td = TemporaryDirectory()
# nan value for included loc-date
res1 = deepcopy(res0)
res1["rates"]["a"][1] = np.nan
with pytest.raises(AssertionError):
write_to_csv(res1, False, "name_of_signal", td.name)
# nan se for included loc-date
res2 = deepcopy(res0)
res2["se"]["a"][1] = np.nan
with pytest.raises(AssertionError):
write_to_csv(res2, False, "name_of_signal", td.name)
# large se value
res3 = deepcopy(res0)
res3["se"]["a"][0] = 10
with pytest.raises(AssertionError):
write_to_csv(res3, False, "name_of_signal", td.name)
td.cleanup()
def test_handle_wip_signal(self):
# Test wip_signal = True (all signals should receive prefix)
signal_names = add_prefix(SIGNALS, True)
assert all(s.startswith("wip_") for s in signal_names)
# Test wip_signal = list (only listed signals should receive prefix)
signal_names = add_prefix(SIGNALS, [SIGNALS[0]])
assert signal_names[0].startswith("wip_")
assert all(not s.startswith("wip_") for s in signal_names[1:])
# Test wip_signal = False (only unpublished signals should receive prefix)
signal_names = add_prefix(["xyzzy", SIGNALS[0]], False)
assert signal_names[0].startswith("wip_")
assert all(not s.startswith("wip_") for s in signal_names[1:])