-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathparameters.py
472 lines (408 loc) · 12 KB
/
parameters.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
"""Parameters.
Changes affecting results or their presentation should also update
constants.py `change_date``.
"""
from __future__ import annotations
import i18n
from argparse import ArgumentParser
from collections import namedtuple
from datetime import date, datetime
from logging import INFO, basicConfig, getLogger
from sys import stdout
from typing import Dict, List
from ..constants import (
CHANGE_DATE,
VERSION,
)
from .validators import (
Date,
GteOne,
OptionalDate,
OptionalValue,
OptionalStrictlyPositive,
Positive,
Rate,
StrictlyPositive,
ValDisposition,
)
basicConfig(
level=INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
stream=stdout,
)
logger = getLogger(__name__)
# Parameters for each disposition (hospitalized, icu, ventilated)
# The rate of disposition within the population of infected
# The average number days a patient has such disposition
# Hospitalized:
# 2.5 percent of the infected population are hospitalized: hospitalized.rate is 0.025
# Average hospital length of stay is 7 days: hospitalized.days = 7
# ICU:
# 0.75 percent of the infected population are in the ICU: icu.rate is 0.0075
# Average number of days in an ICU is 9 days: icu.days = 9
# Ventilated:
# 0.5 percent of the infected population are on a ventilator: ventilated.rate is 0.005
# Average number of days on a ventilator: ventilated.days = 10
# Be sure to multiply by 100 when using the parameter as a default to a percent widget!
_Disposition = namedtuple("_Disposition", ("days", "rate"))
class Disposition(_Disposition):
@classmethod
def create(cls, *, days: int, rate: float):
"""Mandate key word arguments."""
GteOne(key="days", value=days)
Rate(key="rate", value=rate)
return cls(days, rate)
class Regions:
"""Arbitrary regions to sum population."""
def __init__(self, **kwargs):
population = 0
for key, value in kwargs.items():
setattr(self, key, value)
population += value
self.population = population
def cast_date(string):
return datetime.strptime(string, '%Y-%m-%d').date()
def declarative_validator(cast):
"""Validator."""
def validate(string):
"""Validate."""
if string == '' and cast != str:
return None
return cast(string)
return validate
def validator(arg, cast, min_value, max_value, required=True):
"""Validator."""
def validate(string):
"""Validate."""
if string == '' and cast != str:
if required:
raise ValueError(f'{arg} is required.')
return None
value = cast(string)
if min_value is not None and value < min_value:
raise ValueError(f'{arg} must be greater than {min_value}.')
if max_value is not None and value > max_value:
raise ValueError(f'{arg} must be less than {max_value}.')
return value
return validate
# TODO make validators cast and report properties for args
VALIDATORS = {
"current_hospitalized": Positive,
"current_date": OptionalDate,
"date_first_hospitalized": OptionalDate,
"doubling_time": OptionalStrictlyPositive,
"infectious_days": StrictlyPositive,
"mitigation_date": OptionalDate,
"market_share": Rate,
"max_y_axis": OptionalStrictlyPositive,
"n_days": StrictlyPositive,
"population": OptionalStrictlyPositive,
"recovered": Positive,
"region": OptionalValue,
"relative_contact_rate": Rate,
"ventilated": ValDisposition,
"hospitalized": ValDisposition,
"icu": ValDisposition,
"use_log_scale": OptionalValue
}
HELP = {
"current_hospitalized": "Currently hospitalized COVID-19 patients (>= 0)",
"current_date": "Date on which the projection should be based (default is today)",
"date_first_hospitalized": "Date the first patient was hospitalized",
"doubling_time": "Doubling time before social distancing (days)",
"hospitalized_days": "Average hospital length of stay (in days)",
"hospitalized_rate": "Hospitalized Rate: 0.00001 - 1.0",
"icu_days": "Average days in ICU",
"icu_rate": "ICU rate: 0.0 - 1.0",
"infectious_days": "Infectious days",
"mitigation_date": "Date on which social distancing measures too effect",
"market_share": "Hospital market share (0.00001 - 1.0)",
"max_y_axis": "Max y-axis",
"n_days": "Number of days to project >= 1 and less than 30",
"parameters": "Parameters file",
"population": "Regional population >= 1",
"recovered": "Number of patients already recovered (not yet implemented)",
"region": "No help available",
"relative_contact_rate": "Social distancing reduction rate: 0.0 - 1.0",
"ventilated_days": "Average days on ventilator",
"ventilated_rate": "Ventilated Rate: 0.0 - 1.0",
"use_log_scale": "Flag to use logarithmic scale on charts instead of linear scale."
}
ARGS = (
(
"parameters",
str,
None, # Min value
None, # Max value
False, # Whether it is required or optional.
),
(
"current_hospitalized",
int,
0,
None,
True,
),
(
"current_date",
cast_date,
None,
None,
False,
),
(
"date_first_hospitalized",
cast_date,
None,
None,
False,
),
(
"doubling_time",
float,
0.0,
None,
True,
),
(
"hospitalized_days",
int,
1,
None,
True,
),
(
"hospitalized_rate",
float,
0.00001,
1.0,
True,
),
(
"icu_days",
int,
1,
None,
True,
),
(
"icu_rate",
float,
0.0,
1.0,
True,
),
(
"market_share",
float,
0.00001,
1.0,
True,
),
(
"infectious_days",
int,
0.0,
None,
True,
),
(
"mitigation_date",
cast_date,
None,
None,
False,
),
(
"max_y_axis",
int,
0,
None,
True,
),
(
"n-days",
int,
1,
30,
True,
),
(
"recovered",
int,
0,
None,
True,
),
(
"relative-contact-rate",
float,
0.0,
1.0,
True,
),
(
"population",
int,
1,
None,
True,
),
(
"ventilated_days",
int,
1,
None,
True,
),
(
"ventilated_rate",
float,
0.0,
1.0,
True,
),
(
"use_log_scale",
bool,
None,
None,
False
)
)
def to_cli(name):
return "--" + name.replace('_', '-')
class Parameters:
"""
Object containing all of the parameters that can be adjusted by the user, either from the command line or using
the side bar of the web app.
"""
@classmethod
def parser(cls):
parser = ArgumentParser(
description=f"penn_chime: {VERSION} {CHANGE_DATE}")
for name, cast, min_value, max_value, required in ARGS:
arg = to_cli(name)
if cast == bool:
# This argument is a command-line flag and does not need validation.
parser.add_argument(
arg,
action='store_true',
help=HELP.get(name),
)
else:
# Use a custom validator for any arguments that take in values.
parser.add_argument(
arg,
type=validator(arg, cast, min_value, max_value, required),
help=HELP.get(name),
)
return parser
@classmethod
def create(
cls,
env: Dict[str, str],
argv: List[str],
) -> Parameters:
parser = cls.parser()
a = parser.parse_args(argv)
if a.parameters is None:
a.parameters = env.get("PARAMETERS")
if a.parameters is not None:
logger.info('Using file: %s', a.parameters)
with open(a.parameters, 'r') as fin:
parser.parse_args(fin.read().split(), a)
del a.parameters
Positive(key='hospitalized_days', value=a.hospitalized_days)
Positive(key='icu_days', value=a.icu_days)
Positive(key='ventilated_days', value=a.ventilated_days)
Rate(key='hospitalized_rate', value=a.hospitalized_rate)
Rate(key='icu_rate', value=a.icu_rate)
Rate(key='ventilated_rate', value=a.ventilated_rate)
# ICU % Total infections = Hosp %(total infections) * ICU (% total hosp)
# Vent % Total infections = ICU % Total infections * Vent (% critical care)
icu_of_total_inf = a.hospitalized_rate * a.icu_rate
vent_of_total_inf = icu_of_total_inf * a.ventilated_rate
hospitalized = Disposition.create(
days=a.hospitalized_days,
rate=a.hospitalized_rate,
)
icu = Disposition.create(
days=a.icu_days,
rate=icu_of_total_inf,
)
ventilated = Disposition.create(
days=a.ventilated_days,
rate=vent_of_total_inf,
)
del a.hospitalized_days
del a.hospitalized_rate
del a.icu_days
del a.icu_rate
del a.ventilated_days
del a.ventilated_rate
return cls(
hospitalized=hospitalized,
icu=icu,
ventilated=ventilated,
**vars(a),
)
def __init__(self, **kwargs):
today = date.today()
# mypy needs properties
self.current_date = None
self.current_hospitalized = None
self.date_first_hospitalized = None
self.doubling_time = None
self.hospitalized = None
self.icu = None
self.infectious_days = None
self.market_share = None
self.max_y_axis = None
self.mitigation_date = None
self.n_days = None
self.population = None
self.region = None
self.relative_contact_rate = None
self.recovered = None
self.ventilated = None
self.use_log_scale = False
passed_and_default_parameters = {}
for key, value in kwargs.items():
if key not in VALIDATORS:
raise ValueError(f"Unexpected parameter {key}")
passed_and_default_parameters[key] = value
for key, value in passed_and_default_parameters.items():
validator = VALIDATORS[key]
try:
validator(key=key, value=value)
except TypeError as ve:
raise ValueError(
f"For parameter '{key}', with value '{value}', validation returned error \"{ve}\"")
setattr(self, key, value)
if self.region is None and self.population is None:
raise AssertionError('population or regions must be provided.')
if self.current_date is None:
self.current_date = today
if self.mitigation_date is None:
self.mitigation_date = today
Date(key='current_date', value=self.current_date)
Date(key='mitigation_date', value=self.mitigation_date)
self.labels = {
"admits_hospitalized": i18n.t("admits_hospitalized"),
"admits_icu": i18n.t("admits_icu"),
"admits_ventilated": i18n.t("admits_ventilated"),
"census_hospitalized": i18n.t("census_hospitalized"),
"census_icu": i18n.t("census_icu"),
"census_ventilated": i18n.t("census_ventilated"),
"day": i18n.t("day"),
"date": i18n.t("date"),
"susceptible" :i18n.t("susceptible"),
"infected": i18n.t("infected"),
"recovered": i18n.t("recovered")
}
self.dispositions = {
"hospitalized": self.hospitalized,
"icu": self.icu,
"ventilated": self.ventilated,
}