epymorph 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. epymorph/__init__.py +7 -0
  2. epymorph/__main__.py +16 -0
  3. epymorph/adrio/__init__.py +0 -0
  4. epymorph/adrio/acs5.py +1378 -0
  5. epymorph/adrio/adrio.py +953 -0
  6. epymorph/adrio/cdc.py +1826 -0
  7. epymorph/adrio/commuting_flows.py +283 -0
  8. epymorph/adrio/csv.py +499 -0
  9. epymorph/adrio/humidity.py +206 -0
  10. epymorph/adrio/lodes.py +509 -0
  11. epymorph/adrio/numpy.py +160 -0
  12. epymorph/adrio/prism.py +345 -0
  13. epymorph/adrio/processing.py +1221 -0
  14. epymorph/adrio/soda.py +602 -0
  15. epymorph/adrio/us_tiger.py +289 -0
  16. epymorph/adrio/validation.py +382 -0
  17. epymorph/attribute.py +614 -0
  18. epymorph/cache.py +680 -0
  19. epymorph/cli/__init__.py +0 -0
  20. epymorph/cli/cache.py +78 -0
  21. epymorph/cli/main.py +29 -0
  22. epymorph/compartment_model.py +1873 -0
  23. epymorph/data/__init__.py +1 -0
  24. epymorph/data/ipm/__init__.py +22 -0
  25. epymorph/data/ipm/no.py +14 -0
  26. epymorph/data/ipm/pei.py +40 -0
  27. epymorph/data/ipm/seirs.py +50 -0
  28. epymorph/data/ipm/sirh.py +55 -0
  29. epymorph/data/ipm/sirs.py +48 -0
  30. epymorph/data/ipm/sparsemod.py +96 -0
  31. epymorph/data/mm/__init__.py +22 -0
  32. epymorph/data/mm/centroids.py +76 -0
  33. epymorph/data/mm/flat.py +61 -0
  34. epymorph/data/mm/icecube.py +50 -0
  35. epymorph/data/mm/no.py +29 -0
  36. epymorph/data/mm/pei.py +105 -0
  37. epymorph/data/mm/sparsemod.py +73 -0
  38. epymorph/data/pei.py +424 -0
  39. epymorph/data_shape.py +593 -0
  40. epymorph/data_type.py +185 -0
  41. epymorph/data_usage.py +258 -0
  42. epymorph/database.py +1301 -0
  43. epymorph/error.py +195 -0
  44. epymorph/event.py +196 -0
  45. epymorph/geography/__init__.py +0 -0
  46. epymorph/geography/custom.py +93 -0
  47. epymorph/geography/scope.py +457 -0
  48. epymorph/geography/us_census.py +1056 -0
  49. epymorph/geography/us_geography.py +502 -0
  50. epymorph/geography/us_tiger.py +1083 -0
  51. epymorph/initializer.py +786 -0
  52. epymorph/kit.py +107 -0
  53. epymorph/log/__init__.py +0 -0
  54. epymorph/log/file.py +128 -0
  55. epymorph/log/messaging.py +139 -0
  56. epymorph/log/movement.py +228 -0
  57. epymorph/movement_model.py +347 -0
  58. epymorph/parameter_fitting/__init__.py +0 -0
  59. epymorph/parameter_fitting/distribution.py +68 -0
  60. epymorph/parameter_fitting/dynamics.py +19 -0
  61. epymorph/parameter_fitting/filter/__init__.py +0 -0
  62. epymorph/parameter_fitting/filter/base_filter.py +50 -0
  63. epymorph/parameter_fitting/filter/particle.py +32 -0
  64. epymorph/parameter_fitting/filter/particle_filter.py +296 -0
  65. epymorph/parameter_fitting/likelihood.py +54 -0
  66. epymorph/parameter_fitting/output.py +73 -0
  67. epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
  68. epymorph/parameter_fitting/perturbation.py +19 -0
  69. epymorph/parameter_fitting/utils/__init__.py +0 -0
  70. epymorph/parameter_fitting/utils/data_loader.py +97 -0
  71. epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
  72. epymorph/parameter_fitting/utils/observations.py +63 -0
  73. epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
  74. epymorph/parameter_fitting/utils/params_perturb.py +43 -0
  75. epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
  76. epymorph/parameter_fitting/utils/resampler.py +258 -0
  77. epymorph/parameter_fitting/utils/utils.py +101 -0
  78. epymorph/params.py +438 -0
  79. epymorph/py.typed +0 -0
  80. epymorph/rume.py +871 -0
  81. epymorph/simulation.py +991 -0
  82. epymorph/simulator/__init__.py +0 -0
  83. epymorph/simulator/basic/__init__.py +0 -0
  84. epymorph/simulator/basic/basic_simulator.py +171 -0
  85. epymorph/simulator/basic/ipm_exec.py +437 -0
  86. epymorph/simulator/basic/mm_exec.py +244 -0
  87. epymorph/simulator/basic/output.py +213 -0
  88. epymorph/simulator/world.py +149 -0
  89. epymorph/simulator/world_list.py +274 -0
  90. epymorph/strata.py +24 -0
  91. epymorph/sympy_shim.py +57 -0
  92. epymorph/time.py +1197 -0
  93. epymorph/tools/__init__.py +0 -0
  94. epymorph/tools/data.py +297 -0
  95. epymorph/tools/ipm_diagram.py +208 -0
  96. epymorph/tools/out_map.py +551 -0
  97. epymorph/tools/out_plot.py +423 -0
  98. epymorph/tools/out_table.py +582 -0
  99. epymorph/util.py +1036 -0
  100. epymorph-1.0.0.dist-info/METADATA +57 -0
  101. epymorph-1.0.0.dist-info/RECORD +104 -0
  102. epymorph-1.0.0.dist-info/WHEEL +5 -0
  103. epymorph-1.0.0.dist-info/entry_points.txt +2 -0
  104. epymorph-1.0.0.dist-info/top_level.txt +1 -0
epymorph/adrio/cdc.py ADDED
@@ -0,0 +1,1826 @@
1
+ """ADRIOs for access US Centers for Disease Control data."""
2
+
3
+ import dataclasses
4
+ import os
5
+ from abc import abstractmethod
6
+ from datetime import date, timedelta
7
+ from typing import Callable, Literal, TypeVar, cast
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from numpy.typing import NDArray
12
+ from typing_extensions import override
13
+
14
+ import epymorph.adrio.soda as q
15
+ from epymorph.adrio.adrio import (
16
+ ADRIOCommunicationError,
17
+ ADRIOContextError,
18
+ FetchADRIO,
19
+ PipelineResult,
20
+ adrio_cache,
21
+ adrio_validate_pipe,
22
+ validate_time_frame,
23
+ )
24
+ from epymorph.adrio.processing import (
25
+ DataPipeline,
26
+ DateValueType,
27
+ Fill,
28
+ FillLikeFloat,
29
+ FillLikeInt,
30
+ Fix,
31
+ FixLikeInt,
32
+ PivotAxis,
33
+ )
34
+ from epymorph.adrio.validation import (
35
+ ResultFormat,
36
+ on_date_values,
37
+ validate_dtype,
38
+ validate_numpy,
39
+ validate_shape,
40
+ validate_values_in_range,
41
+ )
42
+ from epymorph.data_shape import Shapes
43
+ from epymorph.error import GeographyError
44
+ from epymorph.geography.scope import GeoScope
45
+ from epymorph.geography.us_census import CensusScope, CountyScope, StateScope
46
+ from epymorph.geography.us_geography import STATE
47
+ from epymorph.geography.us_tiger import get_states
48
+ from epymorph.simulation import Context
49
+ from epymorph.time import DateRange, iso8601
50
+ from epymorph.util import date_value_dtype
51
+
52
+
53
+ def healthdata_api_key() -> str | None:
54
+ """
55
+ Load the Socrata API key to use for healthdata.gov,
56
+ as environment variable 'API_KEY__healthdata.gov'.
57
+
58
+ Returns
59
+ -------
60
+ :
61
+ The key or `None` if it is not set.
62
+ """
63
+ return os.environ.get("API_KEY__healthdata.gov", default=None)
64
+
65
+
66
+ def data_cdc_api_key() -> str | None:
67
+ """
68
+ Load the Socrata API key to use for data.cdc.gov,
69
+ as environment variable 'API_KEY__data.cdc.gov'.
70
+
71
+ Returns
72
+ -------
73
+ :
74
+ The key or `None` if it is not set.
75
+ """
76
+ return os.environ.get("API_KEY__data.cdc.gov", default=None)
77
+
78
+
79
+ def _truncate_county_to_scope_fn(scope: GeoScope) -> Callable[[str], str] | None:
80
+ if isinstance(scope, StateScope):
81
+ return STATE.truncate
82
+ if isinstance(scope, CountyScope):
83
+ return None
84
+ err = f"Unsupported scope: {scope}."
85
+ raise GeographyError(err)
86
+
87
+
88
+ ############################
89
+ # HEALTHDATA.GOV anag-cw7u #
90
+ ############################
91
+
92
+
93
+ class _HealthdataAnagCw7uMixin(FetchADRIO[DateValueType, np.int64]):
94
+ """
95
+ A mixin implementing some of `FetchADRIO`'s API for ADRIOs which fetch
96
+ data from healthdata.gov dataset anag-cw7u: a.k.a.
97
+ "COVID-19 Reported Patient Impact and Hospital Capacity by Facility".
98
+
99
+ https://healthdata.gov/Hospital/COVID-19-Reported-Patient-Impact-and-Hospital-Capa/anag-cw7u/about_data
100
+ """
101
+
102
+ _RESOURCE = q.SocrataResource(domain="healthdata.gov", id="anag-cw7u")
103
+ """The Socrata API endpoint."""
104
+
105
+ _TIME_RANGE = DateRange(iso8601("2019-12-29"), iso8601("2024-04-21"), step=7)
106
+ """The time range over which values are available."""
107
+
108
+ _REDACTED_VALUE = np.int64(-999999)
109
+ """The value of redacted reports: between 1 and 3 cases."""
110
+
111
+ @property
112
+ @override
113
+ def result_format(self) -> ResultFormat:
114
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.int64))
115
+
116
+ @override
117
+ def validate_context(self, context: Context):
118
+ if not isinstance(context.scope, StateScope | CountyScope):
119
+ err = "US State or County geo scope required."
120
+ raise ADRIOContextError(self, context, err)
121
+ if context.scope.year != 2019:
122
+ err = "This data supports 2019 Census geography only."
123
+ raise ADRIOContextError(self, context, err)
124
+ validate_time_frame(self, context, self._TIME_RANGE)
125
+
126
+ @override
127
+ def validate_result(self, context: Context, result: NDArray) -> None:
128
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame)
129
+ result_shape = (len(time_series), context.scope.nodes)
130
+ adrio_validate_pipe(
131
+ self,
132
+ context,
133
+ result,
134
+ validate_numpy(),
135
+ validate_shape(result_shape),
136
+ validate_dtype(self.result_format.dtype),
137
+ on_date_values(validate_values_in_range(0, None)),
138
+ )
139
+
140
+
141
+ @adrio_cache
142
+ class COVIDFacilityHospitalization(
143
+ _HealthdataAnagCw7uMixin, FetchADRIO[DateValueType, np.int64]
144
+ ):
145
+ """
146
+ Loads COVID hospitalization data from HealthData.gov's
147
+ "COVID-19 Reported Patient Impact and Hospital Capacity by Facility"
148
+ dataset. The data were reported by healthcare facilities on a weekly basis,
149
+ starting 2019-12-29 and ending 2024-04-21, although the data is not complete
150
+ over this entire range, nor over the entire United States.
151
+
152
+ This ADRIO supports geo scopes at US State and County granularities in 2019.
153
+ The data loaded will be matched to the simulation time frame. The result is a 2D
154
+ matrix where the first axis represents reporting weeks during the time frame and the
155
+ second axis is geo scope nodes. Values are tuples of date and the integer number of
156
+ reported hospitalizations. The data contain sentinel values (-999999) which
157
+ represent values redacted for the sake of protecting patient privacy -- there
158
+ were between 1 and 3 cases reported by the facility on that date.
159
+
160
+ NOTE: this data source has a number of issues representing Alaska geography.
161
+ It uses borough 02280 which isn't in the Census geography until 2020, and
162
+ simultaneously uses pre-1980 Alaska geography (02080, 02120, 02210, and 02260).
163
+ This makes these data inaccessible via this ADRIO. If Alaska data is important for
164
+ your use-case, we recommend processing the data another way.
165
+
166
+ Parameters
167
+ ----------
168
+ age_group :
169
+ Which age group to fetch data for.
170
+ fix_redacted :
171
+ The method to use to replace redacted values (-999999 in the data).
172
+ fix_missing :
173
+ The method to use to fix missing values.
174
+
175
+ See Also
176
+ --------
177
+ [The dataset documentation](https://healthdata.gov/Hospital/COVID-19-Reported-Patient-Impact-and-Hospital-Capa/anag-cw7u/about_data).
178
+ """ # noqa: E501
179
+
180
+ _ADULTS = "total_adult_patients_hospitalized_confirmed_covid_7_day_sum"
181
+ _PEDS = "total_pediatric_patients_hospitalized_confirmed_covid_7_day_sum"
182
+
183
+ _age_group: Literal["adult", "pediatric", "both"]
184
+ _fix_redacted: Fix[np.int64]
185
+ _fix_missing: Fill[np.int64]
186
+
187
+ def __init__(
188
+ self,
189
+ *,
190
+ age_group: Literal["adult", "pediatric", "both"] = "both",
191
+ fix_redacted: FixLikeInt = False,
192
+ fix_missing: FillLikeInt = False,
193
+ ):
194
+ if age_group not in ("adult", "pediatric", "both"):
195
+ raise ValueError(f"Unsupported `age_group`: {age_group}")
196
+ self._age_group = age_group
197
+ try:
198
+ self._fix_redacted = Fix.of_int64(fix_redacted)
199
+ except ValueError:
200
+ raise ValueError("Invalid value for `fix_redacted`")
201
+ try:
202
+ self._fix_missing = Fill.of_int64(fix_missing)
203
+ except ValueError:
204
+ raise ValueError("Invalid value for `fix_missing`")
205
+
206
+ @override
207
+ def _fetch(self, context: Context) -> pd.DataFrame:
208
+ match self._age_group:
209
+ case "adult":
210
+ values = [q.Select(self._ADULTS, "int", as_name="value")]
211
+ not_nulls = [q.NotNull(self._ADULTS)]
212
+ case "pediatric":
213
+ values = [q.Select(self._PEDS, "int", as_name="value")]
214
+ not_nulls = [q.NotNull(self._PEDS)]
215
+ case "both":
216
+ values = [
217
+ q.Select(self._ADULTS, "nullable_int", as_name="value_adult"),
218
+ q.Select(self._PEDS, "nullable_int", as_name="value_ped"),
219
+ ]
220
+ not_nulls = []
221
+ case x:
222
+ raise ValueError(f"Unsupported `age_group`: {x}")
223
+
224
+ query = q.Query(
225
+ select=(
226
+ q.Select("collection_week", "date", as_name="date"),
227
+ q.Select("fips_code", "str", as_name="geoid"),
228
+ *values,
229
+ ),
230
+ where=q.And(
231
+ q.DateBetween(
232
+ "collection_week",
233
+ context.time_frame.start_date,
234
+ context.time_frame.end_date,
235
+ ),
236
+ q.In("fips_code", context.scope.node_ids),
237
+ *not_nulls,
238
+ ),
239
+ order_by=(
240
+ q.Ascending("collection_week"),
241
+ q.Ascending("fips_code"),
242
+ q.Ascending(":id"),
243
+ ),
244
+ )
245
+ try:
246
+ return q.query_csv(
247
+ resource=self._RESOURCE,
248
+ query=query,
249
+ api_token=healthdata_api_key(),
250
+ )
251
+ except Exception as e:
252
+ raise ADRIOCommunicationError(self, context) from e
253
+
254
+ @override
255
+ def _process(
256
+ self,
257
+ context: Context,
258
+ data_df: pd.DataFrame,
259
+ ) -> PipelineResult[DateValueType]:
260
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame).to_numpy()
261
+ pipeline = (
262
+ DataPipeline(
263
+ axes=(
264
+ PivotAxis("date", time_series),
265
+ PivotAxis("geoid", context.scope.node_ids),
266
+ ),
267
+ ndims=2,
268
+ dtype=self.result_format.dtype["value"].type,
269
+ rng=context,
270
+ )
271
+ .strip_sentinel("redacted", self._REDACTED_VALUE, self._fix_redacted)
272
+ .finalize(self._fix_missing)
273
+ )
274
+
275
+ if self._age_group == "both":
276
+ # Age group is both adult and pediatric, so
277
+ # process the two columns separately and sum.
278
+ adult_df = (
279
+ data_df[["date", "geoid", "value_adult"]]
280
+ .rename(columns={"value_adult": "value"})
281
+ .dropna(subset="value")
282
+ )
283
+ adult_df["value"] = adult_df["value"].astype(np.int64)
284
+ adult_result = pipeline(adult_df)
285
+
286
+ ped_df = (
287
+ data_df[["date", "geoid", "value_ped"]]
288
+ .rename(columns={"value_ped": "value"})
289
+ .dropna(subset="value")
290
+ )
291
+ ped_df["value"] = ped_df["value"].astype(np.int64)
292
+ ped_result = pipeline(ped_df)
293
+
294
+ result = PipelineResult.sum(
295
+ adult_result,
296
+ ped_result,
297
+ left_prefix="adult_",
298
+ right_prefix="pediatric_",
299
+ )
300
+ else:
301
+ # Age group is just adult or pediatric, so process as normal
302
+ result = pipeline(data_df)
303
+ return result.to_date_value(time_series)
304
+
305
+
306
+ @adrio_cache
307
+ class InfluenzaFacilityHospitalization(
308
+ _HealthdataAnagCw7uMixin, FetchADRIO[DateValueType, np.int64]
309
+ ):
310
+ """
311
+ Loads influenza hospitalization data from HealthData.gov's
312
+ "COVID-19 Reported Patient Impact and Hospital Capacity by Facility"
313
+ dataset. The data were reported by healthcare facilities on a weekly basis,
314
+ starting 2019-12-29 and ending 2024-04-21, although the data is not complete
315
+ over this entire range, nor over the entire United States.
316
+
317
+ This ADRIO supports geo scopes at US State and County granularities in 2019.
318
+ The data loaded will be matched to the simulation time frame. The result is a 2D matrix
319
+ where the first axis represents reporting weeks during the time frame and the
320
+ second axis is geo scope nodes. Values are tuples of date and the integer number of
321
+ reported hospitalizations. The data contain sentinel values (-999999) which
322
+ represent values redacted for the sake of protecting patient privacy -- there
323
+ were between 1 and 3 cases reported by the facility on that date.
324
+
325
+ NOTE: the data source has a number of issues representing Alaska geography.
326
+ It uses borough 02280 which isn't in the Census geography until 2020, and
327
+ simultaneously uses pre-1980 Alaska geography (02080, 02120, 02210, and 02260).
328
+ This makes these data inaccessible via this ADRIO. If Alaska data is important for
329
+ your use-case, we recommend processing the data another way.
330
+
331
+ Parameters
332
+ ----------
333
+ fix_redacted :
334
+ The method to use to replace redacted values (-999999 in the data).
335
+ fix_missing :
336
+ The method to use to fix missing values.
337
+
338
+ See Also
339
+ --------
340
+ [The dataset documentation](https://healthdata.gov/Hospital/COVID-19-Reported-Patient-Impact-and-Hospital-Capa/anag-cw7u/about_data).
341
+ """ # noqa: E501
342
+
343
+ _fix_redacted: Fix[np.int64]
344
+ _fix_missing: Fill[np.int64]
345
+
346
+ def __init__(
347
+ self,
348
+ *,
349
+ fix_redacted: FixLikeInt = False,
350
+ fix_missing: FillLikeInt = False,
351
+ ):
352
+ try:
353
+ self._fix_redacted = Fix.of_int64(fix_redacted)
354
+ except ValueError:
355
+ raise ValueError("Invalid value for `fix_redacted`")
356
+ try:
357
+ self._fix_missing = Fill.of_int64(fix_missing)
358
+ except ValueError:
359
+ raise ValueError("Invalid value for `fix_missing`")
360
+
361
+ @override
362
+ def _fetch(self, context: Context) -> pd.DataFrame:
363
+ query = q.Query(
364
+ select=(
365
+ q.Select("collection_week", "date", as_name="date"),
366
+ q.Select("fips_code", "str", as_name="geoid"),
367
+ q.Select(
368
+ "total_patients_hospitalized_confirmed_influenza_7_day_sum",
369
+ dtype="int",
370
+ as_name="value",
371
+ ),
372
+ ),
373
+ where=q.And(
374
+ q.DateBetween(
375
+ "collection_week",
376
+ context.time_frame.start_date,
377
+ context.time_frame.end_date,
378
+ ),
379
+ q.In("fips_code", context.scope.node_ids),
380
+ ),
381
+ order_by=(
382
+ q.Ascending("collection_week"),
383
+ q.Ascending("fips_code"),
384
+ q.Ascending(":id"),
385
+ ),
386
+ )
387
+ try:
388
+ return q.query_csv(
389
+ resource=self._RESOURCE,
390
+ query=query,
391
+ api_token=healthdata_api_key(),
392
+ )
393
+ except Exception as e:
394
+ raise ADRIOCommunicationError(self, context) from e
395
+
396
+ @override
397
+ def _process(
398
+ self,
399
+ context: Context,
400
+ data_df: pd.DataFrame,
401
+ ) -> PipelineResult[DateValueType]:
402
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame).to_numpy()
403
+ pipeline = (
404
+ DataPipeline(
405
+ axes=(
406
+ PivotAxis("date", time_series),
407
+ PivotAxis("geoid", context.scope.node_ids),
408
+ ),
409
+ ndims=2,
410
+ dtype=self.result_format.dtype["value"].type,
411
+ rng=context,
412
+ )
413
+ .strip_sentinel(
414
+ "redacted",
415
+ self._REDACTED_VALUE,
416
+ self._fix_redacted,
417
+ )
418
+ .finalize(self._fix_missing)
419
+ )
420
+ return pipeline(data_df).to_date_value(time_series)
421
+
422
+
423
+ ##########################
424
+ # DATA.CDC.GOV 3nnm-4jni #
425
+ ##########################
426
+
427
+
428
+ @adrio_cache
429
+ class COVIDCountyCases(FetchADRIO[DateValueType, np.int64]):
430
+ """
431
+ Loads COVID case data from data.cdc.gov's dataset named
432
+ "United States COVID-19 Community Levels by County".
433
+
434
+ The data were reported starting 2022-02-24 and ending 2023-05-11, and aggregated
435
+ by CDC to the US County level.
436
+
437
+ This ADRIO supports geo scopes at US State and County granularity (2015 through 2019
438
+ allowed). The data loaded will be matched to the simulation time frame. The result
439
+ is a 2D matrix where the first axis represents reporting weeks during the time frame
440
+ and the second axis is geo scope nodes. Values are tuples of date and the integer
441
+ number of cases, calculated by multiplying the per-100k rates by the county
442
+ population and rounding (via banker's rounding).
443
+
444
+ Parameters
445
+ ----------
446
+ fix_missing :
447
+ The method to use to fix missing values.
448
+
449
+ See Also
450
+ --------
451
+ [The dataset documentation](https://data.cdc.gov/Public-Health-Surveillance/United-States-COVID-19-Community-Levels-by-County/3nnm-4jni/about_data).
452
+ """ # noqa: E501
453
+
454
+ _RESOURCE = q.SocrataResource(domain="data.cdc.gov", id="3nnm-4jni")
455
+ """The Socrata API endpoint."""
456
+
457
+ _TIME_RANGE = DateRange(iso8601("2022-02-24"), iso8601("2023-05-11"), step=7)
458
+ """The time range over which values are available."""
459
+
460
+ _fix_missing: Fill[np.int64]
461
+
462
+ def __init__(
463
+ self,
464
+ *,
465
+ fix_missing: Fill[np.int64] | int | Callable[[], int] | Literal[False] = False,
466
+ ):
467
+ try:
468
+ self._fix_missing = Fill.of_int64(fix_missing)
469
+ except ValueError:
470
+ raise ValueError("Invalid value for `fix_missing`")
471
+
472
+ @property
473
+ @override
474
+ def result_format(self) -> ResultFormat:
475
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.int64))
476
+
477
+ @override
478
+ def validate_context(self, context: Context):
479
+ if not isinstance(context.scope, StateScope | CountyScope):
480
+ err = "US State or County geo scope required."
481
+ raise ADRIOContextError(self, context, err)
482
+ if context.scope.year < 2015 or context.scope.year > 2019:
483
+ err = "This data supports Census geography from 2015 through 2019 only."
484
+ raise ADRIOContextError(self, context, err)
485
+ validate_time_frame(self, context, self._TIME_RANGE)
486
+
487
+ @override
488
+ def _fetch(self, context: Context) -> pd.DataFrame:
489
+ counties = cast(CensusScope, context.scope).as_granularity("county")
490
+
491
+ # API URL can get too big if we're querying for a large number of counties.
492
+ # And doing a very large "in" statement is not ideal anyway.
493
+ # So after 1000 counties, just get all geography and we'll filter locally.
494
+ if counties.nodes < 1000:
495
+ geo_clause = [q.In("county_fips", counties.node_ids)]
496
+ result_filter = None
497
+ else:
498
+ geo_clause = []
499
+ result_filter = lambda df: df[df["geoid"].isin(counties.node_ids)] # noqa: E731
500
+
501
+ query = q.Query(
502
+ select=(
503
+ q.Select("date_updated", "date", as_name="date"),
504
+ q.Select("county_fips", "str", as_name="geoid"),
505
+ q.SelectExpression(
506
+ "`covid_cases_per_100k` * (`county_population` / 100000)",
507
+ "float",
508
+ as_name="value",
509
+ ),
510
+ ),
511
+ where=q.And(
512
+ q.DateBetween(
513
+ "date_updated",
514
+ context.time_frame.start_date,
515
+ context.time_frame.end_date,
516
+ ),
517
+ *geo_clause,
518
+ ),
519
+ order_by=(
520
+ q.Ascending("date_updated"),
521
+ q.Ascending("county_fips"),
522
+ q.Ascending(":id"),
523
+ ),
524
+ )
525
+ try:
526
+ return q.query_csv(
527
+ resource=self._RESOURCE,
528
+ query=query,
529
+ api_token=data_cdc_api_key(),
530
+ result_filter=result_filter,
531
+ )
532
+ except Exception as e:
533
+ raise ADRIOCommunicationError(self, context) from e
534
+
535
+ @override
536
+ def _process(
537
+ self,
538
+ context: Context,
539
+ data_df: pd.DataFrame,
540
+ ) -> PipelineResult[DateValueType]:
541
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame).to_numpy()
542
+ pipeline = (
543
+ DataPipeline(
544
+ axes=(
545
+ PivotAxis("date", time_series),
546
+ PivotAxis("geoid", context.scope.node_ids),
547
+ ),
548
+ ndims=2,
549
+ dtype=self.result_format.dtype["value"].type,
550
+ rng=context,
551
+ )
552
+ .map_column(
553
+ "geoid",
554
+ map_fn=_truncate_county_to_scope_fn(context.scope),
555
+ )
556
+ .map_series("value", map_fn=lambda xs: xs.round())
557
+ .finalize(self._fix_missing)
558
+ )
559
+ return pipeline(data_df).to_date_value(time_series)
560
+
561
+ @override
562
+ def validate_result(self, context: Context, result: NDArray) -> None:
563
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame)
564
+ result_shape = (len(time_series), context.scope.nodes)
565
+ adrio_validate_pipe(
566
+ self,
567
+ context,
568
+ result,
569
+ validate_numpy(),
570
+ validate_shape(result_shape),
571
+ validate_dtype(self.result_format.dtype),
572
+ on_date_values(validate_values_in_range(0, None)),
573
+ )
574
+
575
+
576
+ ##########################
577
+ # DATA.CDC.GOV aemt-mg7g #
578
+ ##########################
579
+
580
+
581
+ class _DataCDCAemtMg7gMixin(FetchADRIO[DateValueType, np.int64]):
582
+ """
583
+ An mixin implemeting some of `FetchADRIO`'s API for ADRIOs which fetch
584
+ data from cdc.gov dataset aemt-mg7g: a.k.a.
585
+ "Weekly United States Hospitalization Metrics by Jurisdiction, During Mandatory
586
+ Reporting Period from August 1, 2020 to April 30, 2024, and for Data Reported
587
+ Voluntarily Beginning May 1, 2024, National Healthcare Safety Network
588
+ (NHSN) - ARCHIVED".
589
+
590
+ https://data.cdc.gov/Public-Health-Surveillance/Weekly-United-States-Hospitalization-Metrics-by-Ju/aemt-mg7g/about_data
591
+ """
592
+
593
+ _RESOURCE = q.SocrataResource(domain="data.cdc.gov", id="aemt-mg7g")
594
+ """The Socrata API endpoint."""
595
+
596
+ _TIME_RANGE = DateRange(iso8601("2020-08-08"), iso8601("2024-10-26"), step=7)
597
+ """The time range over which values are available."""
598
+
599
+ _VOLUNTARY_TIME_RANGE = DateRange(
600
+ iso8601("2024-05-04"), iso8601("2024-10-26"), step=7
601
+ )
602
+ """The time range over which values were reported voluntarily."""
603
+
604
+ _column: str
605
+ """The name of the data source column to fetch for this ADRIO."""
606
+ _fix_missing: Fill[np.int64]
607
+ """The method to use to fix missing values."""
608
+ _allow_voluntary: bool
609
+ """Whether or not to accept voluntary data."""
610
+
611
+ @property
612
+ @override
613
+ def result_format(self) -> ResultFormat:
614
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.int64))
615
+
616
+ @override
617
+ def validate_context(self, context: Context):
618
+ if not isinstance(context.scope, StateScope):
619
+ err = "US State geo scope required."
620
+ raise ADRIOContextError(self, context, err)
621
+ # No year restriction since state-equivalents are the same
622
+ # for the entire supported time range.
623
+ validate_time_frame(self, context, self._TIME_RANGE)
624
+
625
+ @override
626
+ def _fetch(self, context: Context) -> pd.DataFrame:
627
+ scope = cast(StateScope, self.context.scope)
628
+ state_info = get_states(scope.year)
629
+ to_postal = state_info.state_fips_to_code
630
+ to_fips = state_info.state_code_to_fips
631
+
632
+ query = q.Query(
633
+ select=(
634
+ q.Select("week_end_date", "date", as_name="date"),
635
+ q.Select("jurisdiction", "str", as_name="geoid"),
636
+ q.Select(self._column, "int", as_name="value"),
637
+ ),
638
+ where=q.And(
639
+ q.DateBetween(
640
+ "week_end_date",
641
+ context.time_frame.start_date,
642
+ context.time_frame.end_date,
643
+ ),
644
+ q.In("jurisdiction", [to_postal[x] for x in scope.node_ids]),
645
+ q.NotNull(self._column),
646
+ ),
647
+ order_by=(
648
+ q.Ascending("week_end_date"),
649
+ q.Ascending("jurisdiction"),
650
+ q.Ascending(":id"),
651
+ ),
652
+ )
653
+ try:
654
+ result_df = q.query_csv(
655
+ resource=self._RESOURCE,
656
+ query=query,
657
+ api_token=data_cdc_api_key(),
658
+ )
659
+ result_df["geoid"] = result_df["geoid"].apply(lambda x: to_fips[x])
660
+ return result_df
661
+ except Exception as e:
662
+ raise ADRIOCommunicationError(self, context) from e
663
+
664
+ @override
665
+ def _process(
666
+ self,
667
+ context: Context,
668
+ data_df: pd.DataFrame,
669
+ ) -> PipelineResult[DateValueType]:
670
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame).to_numpy()
671
+ pipeline = DataPipeline(
672
+ axes=(
673
+ PivotAxis("date", time_series),
674
+ PivotAxis("geoid", context.scope.node_ids),
675
+ ),
676
+ ndims=2,
677
+ dtype=self.result_format.dtype["value"].type,
678
+ rng=context,
679
+ ).finalize(self._fix_missing)
680
+ result = pipeline(data_df)
681
+
682
+ # If we don't allow voluntary reported data and if the time series overlaps
683
+ # the voluntary period, add a data issue with the voluntary dates masked.
684
+ vtr = self._VOLUNTARY_TIME_RANGE
685
+ if (
686
+ not self._allow_voluntary
687
+ and (voluntary := vtr.overlap(context.time_frame)) is not None
688
+ ):
689
+ mask = np.isin(time_series, voluntary.to_numpy(), assume_unique=True)
690
+ mask = np.broadcast_to(
691
+ mask[:, np.newaxis],
692
+ shape=(len(time_series), context.scope.nodes),
693
+ )
694
+ result = dataclasses.replace(
695
+ result,
696
+ issues={**result.issues, "voluntary": mask},
697
+ )
698
+
699
+ return result.to_date_value(time_series)
700
+
701
+ @override
702
+ def validate_result(self, context: Context, result: NDArray) -> None:
703
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame)
704
+ result_shape = (len(time_series), context.scope.nodes)
705
+ adrio_validate_pipe(
706
+ self,
707
+ context,
708
+ result,
709
+ validate_numpy(),
710
+ validate_shape(result_shape),
711
+ validate_dtype(self.result_format.dtype),
712
+ on_date_values(validate_values_in_range(0, None)),
713
+ )
714
+
715
+
716
+ @adrio_cache
717
+ class COVIDStateHospitalization(
718
+ _DataCDCAemtMg7gMixin, FetchADRIO[DateValueType, np.int64]
719
+ ):
720
+ """
721
+ Loads COVID hospitalization data from data.cdc.gov's dataset named
722
+ "Weekly United States Hospitalization Metrics by Jurisdiction, During Mandatory
723
+ Reporting Period from August 1, 2020 to April 30, 2024, and for Data Reported
724
+ Voluntarily Beginning May 1, 2024, National Healthcare Safety Network
725
+ (NHSN) - ARCHIVED".
726
+
727
+ The data were reported by healthcare facilities on a weekly basis to CDC's
728
+ National Healthcare Safety Network with reporting dates starting 2020-08-08
729
+ and ending 2024-10-26. The data were aggregated by CDC to the US State level.
730
+ While reporting was initially federally required, beginning May 2024
731
+ reporting became entirely voluntary and as such may include fewer responses.
732
+
733
+ This ADRIO supports geo scopes at US State granularity. The data
734
+ loaded will be matched to the simulation time frame. The result is a 2D matrix
735
+ where the first axis represents reporting weeks during the time frame and the
736
+ second axis is geo scope nodes. Values are tuples of date and the integer number of
737
+ reported hospitalizations.
738
+
739
+ Parameters
740
+ ----------
741
+ fix_missing :
742
+ The method to use to fix missing values.
743
+ allow_voluntary :
744
+ Whether or not to accept voluntary data. If False and if the simulation time
745
+ frame overlaps the voluntary period, such data will be masked.
746
+ Set this to False if you want to be sure you are only using data during the
747
+ required reporting period.
748
+
749
+ See Also
750
+ --------
751
+ [The dataset documentation](https://data.cdc.gov/Public-Health-Surveillance/Weekly-United-States-Hospitalization-Metrics-by-Ju/aemt-mg7g/about_data).
752
+ """ # noqa: E501
753
+
754
+ _column = "total_admissions_all_covid_confirmed"
755
+
756
+ def __init__(
757
+ self,
758
+ *,
759
+ fix_missing: FillLikeInt = False,
760
+ allow_voluntary: bool = True,
761
+ ):
762
+ try:
763
+ self._fix_missing = Fill.of_int64(fix_missing)
764
+ except ValueError:
765
+ raise ValueError("Invalid value for `fix_missing`")
766
+ self._allow_voluntary = allow_voluntary
767
+
768
+
769
+ @adrio_cache
770
+ class InfluenzaStateHospitalization(
771
+ _DataCDCAemtMg7gMixin, FetchADRIO[DateValueType, np.int64]
772
+ ):
773
+ """
774
+ Loads influenza hospitalization data from data.cdc.gov's dataset named
775
+ "Weekly United States Hospitalization Metrics by Jurisdiction, During Mandatory
776
+ Reporting Period from August 1, 2020 to April 30, 2024, and for Data Reported
777
+ Voluntarily Beginning May 1, 2024, National Healthcare Safety Network
778
+ (NHSN) - ARCHIVED".
779
+
780
+ The data were reported by healthcare facilities on a weekly basis to CDC's
781
+ National Healthcare Safety Network with reporting dates starting 2020-08-08
782
+ and ending 2024-10-26. The data were aggregated by CDC to the US State level.
783
+ While reporting was initially federally required, beginning May 2024
784
+ reporting became entirely voluntary and as such may include fewer responses.
785
+
786
+ This ADRIO supports geo scopes at US State granularity. The data
787
+ loaded will be matched to the simulation time frame. The result is a 2D matrix
788
+ where the first axis represents reporting weeks during the time frame and the
789
+ second axis is geo scope nodes. Values are tuples of date and the integer number of
790
+ reported hospitalizations.
791
+
792
+ Parameters
793
+ ----------
794
+ fix_missing :
795
+ The method to use to fix missing values.
796
+ allow_voluntary :
797
+ Whether or not to accept voluntary data. If False and if the simulation time
798
+ frame overlaps the voluntary period, such data will be masked.
799
+ Set this to False if you want to be sure you are only using data during the
800
+ required reporting period.
801
+
802
+ See Also
803
+ --------
804
+ [The dataset documentation](https://data.cdc.gov/Public-Health-Surveillance/Weekly-United-States-Hospitalization-Metrics-by-Ju/aemt-mg7g/about_data).
805
+ """ # noqa: E501
806
+
807
+ _column = "total_admissions_all_influenza_confirmed"
808
+
809
+ def __init__(
810
+ self,
811
+ *,
812
+ fix_missing: FillLikeInt = False,
813
+ allow_voluntary: bool = True,
814
+ ):
815
+ try:
816
+ self._fix_missing = Fill.of_int64(fix_missing)
817
+ except ValueError:
818
+ raise ValueError("Invalid value for `fix_missing`")
819
+ self._allow_voluntary = allow_voluntary
820
+
821
+
822
+ ##########################
823
+ # DATA.CDC.GOV 8xkx-amqh #
824
+ ##########################
825
+
826
+
827
+ @adrio_cache
828
+ class COVIDVaccination(FetchADRIO[DateValueType, np.int64]):
829
+ """
830
+ Loads COVID hospitalization data from data.cdc.gov's dataset named
831
+ "COVID-19 Vaccinations in the United States,County".
832
+
833
+ The data cover a time period starting 2020-12-13 and ending 2023-05-10.
834
+ Up through 2022-06-16, data were reported on a daily cadence, and after
835
+ that switched to a weekly cadence.
836
+
837
+ This ADRIO supports geo scopes at US State and County granularity (2015 through 2019
838
+ allowed). The data appears to have been compiled using 2019 Census delineations, so
839
+ for best results, use a geo scope for that year. The data loaded will be matched
840
+ to the simulation time frame. The result is a 2D matrix where the first axis
841
+ represents reporting dates during the time frame and the second axis is geo scope
842
+ nodes. Values are tuples of date and the integer number of people who have had the
843
+ requested vaccine dosage.
844
+
845
+ Parameters
846
+ ----------
847
+ vaccine_status :
848
+ The dataset breaks down vaccination status by how many doses individuals have
849
+ received. Use this to specify which status you're interested in.
850
+ "at least one dose" includes people who have received at least one COVID vaccine
851
+ dose; "full series" includes people who have received at least either
852
+ two doses of a two-dose vaccine or one dose of a one-dose vaccine;
853
+ "full series and booster" includes people who have received the full series
854
+ and at least one booster dose.
855
+ fix_missing :
856
+ The method to use to fix missing values.
857
+
858
+ See Also
859
+ --------
860
+ [The dataset documentation](https://data.cdc.gov/Vaccinations/COVID-19-Vaccinations-in-the-United-States-County/8xkx-amqh/about_data).
861
+ """ # noqa: E501
862
+
863
+ _RESOURCE = q.SocrataResource(domain="data.cdc.gov", id="8xkx-amqh")
864
+ """The Socrata API endpoint."""
865
+
866
+ _TIME_RANGE = DateRange(iso8601("2020-12-13"), iso8601("2023-05-10"), step=1)
867
+ """The time range over which values are available."""
868
+ _DAILY_TIME_RANGE = DateRange(iso8601("2020-12-13"), iso8601("2022-06-16"), step=1)
869
+ """The time range during which data were reported daily."""
870
+ _WEEKLY_TIME_RANGE = DateRange(iso8601("2022-06-22"), iso8601("2023-05-10"), step=7)
871
+ """The time range during which data were reported weekly."""
872
+
873
+ _vaccine_status: Literal[
874
+ "at least one dose", "full series", "full series and booster"
875
+ ]
876
+ """The datapoint to fetch for this ADRIO."""
877
+ _fix_missing: Fill[np.int64]
878
+ """The method to use to fix missing values."""
879
+
880
+ def __init__(
881
+ self,
882
+ vaccine_status: Literal[
883
+ "at least one dose", "full series", "full series and booster"
884
+ ],
885
+ *,
886
+ fix_missing: Fill[np.int64] | int | Callable[[], int] | Literal[False] = False,
887
+ ):
888
+ if vaccine_status not in (
889
+ "at least one dose",
890
+ "full series",
891
+ "full series and booster",
892
+ ):
893
+ raise ValueError(f"Invalid value for `vaccine_status`: {vaccine_status}")
894
+ self._vaccine_status = vaccine_status
895
+ try:
896
+ self._fix_missing = Fill.of_int64(fix_missing)
897
+ except ValueError:
898
+ raise ValueError("Invalid value for `fix_missing`")
899
+
900
+ @property
901
+ @override
902
+ def result_format(self) -> ResultFormat:
903
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.int64))
904
+
905
+ @override
906
+ def validate_context(self, context: Context):
907
+ if not isinstance(context.scope, StateScope | CountyScope):
908
+ err = "US State or County geo scope required."
909
+ raise ADRIOContextError(self, context, err)
910
+ if context.scope.year < 2015 or context.scope.year > 2019:
911
+ err = "This data supports Census geography from 2015 through 2019 only."
912
+ raise ADRIOContextError(self, context, err)
913
+ validate_time_frame(self, context, self._TIME_RANGE)
914
+
915
+ def _calculate_time_series(self) -> NDArray[np.datetime64]:
916
+ time_frame = self.context.time_frame
917
+ daily = self._DAILY_TIME_RANGE.overlap(time_frame)
918
+ weekly = self._WEEKLY_TIME_RANGE.overlap(time_frame)
919
+ match (daily, weekly):
920
+ case None, None:
921
+ # this should be caught during validate_context(), but just in case...
922
+ err = "The supplied time frame does not include any available dates."
923
+ raise ADRIOContextError(self, self.context, err)
924
+ case d, None:
925
+ return d.to_numpy()
926
+ case None, w:
927
+ return w.to_numpy()
928
+ case d, w:
929
+ return np.concatenate((d.to_numpy(), w.to_numpy()))
930
+
931
+ @override
932
+ def _fetch(self, context: Context) -> pd.DataFrame:
933
+ # There are three cases to handle:
934
+ # - StateScope
935
+ # - CountyScope with # nodes <= 1000
936
+ # - CountyScope with # nodes > 1000
937
+ # In this case API URL can get too big, so just get all geography
938
+ # and we'll filter locally.
939
+ if isinstance(context.scope, StateScope):
940
+ to_postal = get_states(context.scope.year).state_fips_to_code
941
+ postal_codes = [to_postal[x] for x in context.scope.node_ids]
942
+ geo_clause = [q.In("Recip_State", postal_codes)]
943
+ result_filter = None
944
+ elif isinstance(context.scope, CountyScope) and context.scope.nodes < 1000:
945
+ geo_clause = [q.In("fips", context.scope.node_ids)]
946
+ result_filter = None
947
+ elif isinstance(context.scope, CountyScope):
948
+ geo_clause = []
949
+ result_filter = lambda df: df[df["geoid"].isin(context.scope.node_ids)] # noqa: E731
950
+ else:
951
+ err = "US State or County geo scope required."
952
+ raise ADRIOContextError(self, context, err)
953
+
954
+ match self._vaccine_status:
955
+ case "at least one dose":
956
+ column = "administered_dose1_recip"
957
+ case "full series":
958
+ column = "series_complete_yes"
959
+ case "full series and booster":
960
+ column = "booster_doses"
961
+
962
+ query = q.Query(
963
+ select=(
964
+ q.Select("date", "date", as_name="date"),
965
+ q.Select("fips", "str", as_name="geoid"),
966
+ q.Select(column, "nullable_int", as_name="value"),
967
+ ),
968
+ where=q.And(
969
+ q.DateBetween(
970
+ "date",
971
+ context.time_frame.start_date,
972
+ context.time_frame.end_date,
973
+ ),
974
+ *geo_clause,
975
+ q.NotNull(column),
976
+ ),
977
+ order_by=(
978
+ q.Ascending("date"),
979
+ q.Ascending("fips"),
980
+ q.Ascending(":id"),
981
+ ),
982
+ )
983
+ try:
984
+ return q.query_csv(
985
+ resource=self._RESOURCE,
986
+ query=query,
987
+ api_token=data_cdc_api_key(),
988
+ result_filter=result_filter,
989
+ )
990
+ except Exception as e:
991
+ raise ADRIOCommunicationError(self, context) from e
992
+
993
+ @override
994
+ def _process(
995
+ self,
996
+ context: Context,
997
+ data_df: pd.DataFrame,
998
+ ) -> PipelineResult[DateValueType]:
999
+ time_series = self._calculate_time_series()
1000
+ pipeline = (
1001
+ DataPipeline(
1002
+ axes=(
1003
+ PivotAxis("date", time_series),
1004
+ PivotAxis("geoid", context.scope.node_ids),
1005
+ ),
1006
+ ndims=2,
1007
+ dtype=self.result_format.dtype["value"].type,
1008
+ rng=context,
1009
+ )
1010
+ .map_column(
1011
+ "geoid",
1012
+ map_fn=_truncate_county_to_scope_fn(context.scope),
1013
+ )
1014
+ .finalize(self._fix_missing)
1015
+ )
1016
+ return pipeline(data_df).to_date_value(time_series)
1017
+
1018
+ @override
1019
+ def validate_result(self, context: Context, result: NDArray) -> None:
1020
+ time_series = self._calculate_time_series()
1021
+ result_shape = (len(time_series), context.scope.nodes)
1022
+ adrio_validate_pipe(
1023
+ self,
1024
+ context,
1025
+ result,
1026
+ validate_numpy(),
1027
+ validate_shape(result_shape),
1028
+ validate_dtype(self.result_format.dtype),
1029
+ on_date_values(validate_values_in_range(0, None)),
1030
+ )
1031
+
1032
+
1033
+ ##########################
1034
+ # DATA.CDC.GOV ite7-j2w7 #
1035
+ ##########################
1036
+
1037
+
1038
+ @adrio_cache
1039
+ class CountyDeaths(FetchADRIO[DateValueType, np.int64]):
1040
+ """
1041
+ Loads COVID and total deaths data from data.cdc.gov's dataset named
1042
+ "AH COVID-19 Death Counts by County and Week, 2020-present".
1043
+
1044
+ The data were reported starting 2020-01-04 and ending 2023-04-01, and aggregated
1045
+ by CDC to the US County level.
1046
+
1047
+ This ADRIO supports geo scopes at US State and County granularity (2014 through 2019
1048
+ allowed). The data loaded will be matched to the simulation time frame. The result
1049
+ is a 2D matrix where the first axis represents reporting weeks during the time frame
1050
+ and the second axis is geo scope nodes. Values are tuples of date and the integer
1051
+ number of deaths.
1052
+
1053
+ NOTE: this data source uses non-standard geography for two county-equivalents.
1054
+ In Alaska, 02270 was the Wade Hampton Census Area prior to 2015 and thereafter
1055
+ renamed Kusilvak Census Area with code 02158. And in South Dakota, 46113 was
1056
+ Shannon County prior to 2015 and thereafter renamed Oglala Lakota County
1057
+ with code 46102. These data are inaccessible via this ADRIO unless you use
1058
+ 2014 geography.
1059
+
1060
+ Parameters
1061
+ ----------
1062
+ cause_of_death :
1063
+ The cause of death.
1064
+ fix_redacted :
1065
+ The method to use to fix redacted values.
1066
+ fix_missing :
1067
+ The method to use to fix missing values.
1068
+
1069
+ See Also
1070
+ --------
1071
+ [The dataset documentation](https://data.cdc.gov/NCHS/AH-COVID-19-Death-Counts-by-County-and-Week-2020-p/ite7-j2w7/about_data).
1072
+ """ # noqa: E501
1073
+
1074
+ _RESOURCE = q.SocrataResource(domain="data.cdc.gov", id="ite7-j2w7")
1075
+ """The Socrata API endpoint."""
1076
+
1077
+ _TIME_RANGE = DateRange(iso8601("2020-01-04"), iso8601("2023-04-01"), step=7)
1078
+ """The time range over which values are available."""
1079
+
1080
+ _cause_of_death: Literal["all", "COVID-19"]
1081
+ """The cause of death."""
1082
+ _fix_redacted: Fix[np.int64]
1083
+ """The method to use to replace redacted values (N/A in the data)."""
1084
+ _fix_missing: Fill[np.int64]
1085
+ """The method to use to fix missing values."""
1086
+
1087
+ def __init__(
1088
+ self,
1089
+ cause_of_death: Literal["all", "COVID-19"],
1090
+ *,
1091
+ fix_redacted: Fix[np.int64] | int | Callable[[], int] | Literal[False] = False,
1092
+ fix_missing: Fill[np.int64] | int | Callable[[], int] | Literal[False] = False,
1093
+ ):
1094
+ if cause_of_death not in ("all", "COVID-19"):
1095
+ err = f"Unsupported cause of death: {cause_of_death}"
1096
+ raise ValueError(err)
1097
+ self._cause_of_death = cause_of_death
1098
+ try:
1099
+ self._fix_redacted = Fix.of_int64(fix_redacted)
1100
+ except ValueError:
1101
+ raise ValueError("Invalid value for `fix_redacted`")
1102
+ try:
1103
+ self._fix_missing = Fill.of_int64(fix_missing)
1104
+ except ValueError:
1105
+ raise ValueError("Invalid value for `fix_missing`")
1106
+
1107
+ @property
1108
+ @override
1109
+ def result_format(self) -> ResultFormat:
1110
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.int64))
1111
+
1112
+ @override
1113
+ def validate_context(self, context: Context):
1114
+ if not isinstance(context.scope, StateScope | CountyScope):
1115
+ err = "US State or County geo scope required."
1116
+ raise ADRIOContextError(self, context, err)
1117
+ if context.scope.year < 2014 or context.scope.year > 2019:
1118
+ err = "This data supports Census geography from 2014 through 2019 only."
1119
+ raise ADRIOContextError(self, context, err)
1120
+ validate_time_frame(self, context, self._TIME_RANGE)
1121
+
1122
+ @override
1123
+ def _fetch(self, context: Context) -> pd.DataFrame:
1124
+ # Data represents county-level FIPS codes as numbers,
1125
+ # so we strip leading zeros when querying and
1126
+ # left-pad with zero to get back to five characters in the result.
1127
+ counties = cast(CensusScope, context.scope).as_granularity("county")
1128
+
1129
+ if counties.nodes < 1000:
1130
+ geo_clause = [q.In("fips_code", counties.node_ids)]
1131
+
1132
+ def result_filter(df):
1133
+ df["geoid"] = df["geoid"].str.rjust(5, "0")
1134
+ return df
1135
+ else:
1136
+ geo_clause = []
1137
+
1138
+ def result_filter(df):
1139
+ df["geoid"] = df["geoid"].str.rjust(5, "0")
1140
+ return df[df["geoid"].isin(counties.node_ids)]
1141
+
1142
+ match self._cause_of_death:
1143
+ case "all":
1144
+ value_column = "total_deaths"
1145
+ case "COVID-19":
1146
+ value_column = "covid_19_deaths"
1147
+
1148
+ query = q.Query(
1149
+ select=(
1150
+ q.Select("week_ending_date", "date", as_name="date"),
1151
+ q.Select("fips_code", "str", as_name="geoid"),
1152
+ q.SelectExpression(
1153
+ value_column,
1154
+ "nullable_int",
1155
+ as_name="value",
1156
+ ),
1157
+ ),
1158
+ where=q.And(
1159
+ q.DateBetween(
1160
+ "week_ending_date",
1161
+ context.time_frame.start_date,
1162
+ context.time_frame.end_date,
1163
+ ),
1164
+ *geo_clause,
1165
+ ),
1166
+ order_by=(
1167
+ q.Ascending("week_ending_date"),
1168
+ q.Ascending("fips_code"),
1169
+ q.Ascending(":id"),
1170
+ ),
1171
+ )
1172
+ try:
1173
+ return q.query_csv(
1174
+ resource=self._RESOURCE,
1175
+ query=query,
1176
+ api_token=data_cdc_api_key(),
1177
+ result_filter=result_filter,
1178
+ )
1179
+ except Exception as e:
1180
+ raise ADRIOCommunicationError(self, context) from e
1181
+
1182
+ @override
1183
+ def _process(
1184
+ self,
1185
+ context: Context,
1186
+ data_df: pd.DataFrame,
1187
+ ) -> PipelineResult[DateValueType]:
1188
+ value_dtype = self.result_format.dtype["value"].type
1189
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame).to_numpy()
1190
+ pipeline = (
1191
+ DataPipeline(
1192
+ axes=(
1193
+ PivotAxis("date", time_series),
1194
+ PivotAxis("geoid", context.scope.node_ids),
1195
+ ),
1196
+ ndims=2,
1197
+ dtype=value_dtype,
1198
+ rng=context,
1199
+ )
1200
+ .map_column(
1201
+ "geoid",
1202
+ map_fn=_truncate_county_to_scope_fn(context.scope),
1203
+ )
1204
+ # insert our own sentinel value: nulls in these data mean "redacted"
1205
+ # but we can't have null values for the finalize step
1206
+ .strip_na_as_sentinel(
1207
+ "value",
1208
+ sentinel_name="redacted",
1209
+ sentinel_value=value_dtype(-999999),
1210
+ fix=self._fix_redacted,
1211
+ )
1212
+ .finalize(self._fix_missing)
1213
+ )
1214
+ return pipeline(data_df).to_date_value(time_series)
1215
+
1216
+ @override
1217
+ def validate_result(self, context: Context, result: NDArray) -> None:
1218
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame)
1219
+ result_shape = (len(time_series), context.scope.nodes)
1220
+ adrio_validate_pipe(
1221
+ self,
1222
+ context,
1223
+ result,
1224
+ validate_numpy(),
1225
+ validate_shape(result_shape),
1226
+ validate_dtype(self.result_format.dtype),
1227
+ on_date_values(validate_values_in_range(0, None)),
1228
+ )
1229
+
1230
+
1231
+ ##########################
1232
+ # DATA.CDC.GOV r8kw-7aab #
1233
+ ##########################
1234
+
1235
+
1236
+ @adrio_cache
1237
+ class StateDeaths(FetchADRIO[DateValueType, np.int64]):
1238
+ """
1239
+ Loads deaths data (COVID-19, influenza, pneumonia, and total) from data.cdc.gov's dataset named
1240
+ "Provisional COVID-19 Death Counts by Week Ending Date and State".
1241
+
1242
+ The data were reported starting 2020-01-04 and aggregated by CDC to the US State level.
1243
+
1244
+ This ADRIO supports geo scopes at US State granularity. The data
1245
+ loaded will be matched to the simulation time frame. The result is a 2D matrix
1246
+ where the first axis represents reporting weeks during the time frame and the
1247
+ second axis is geo scope nodes. Values are tuples of date and the integer number of
1248
+ deaths.
1249
+
1250
+ Parameters
1251
+ ----------
1252
+ cause_of_death :
1253
+ The cause of death.
1254
+ fix_redacted :
1255
+ The method to use to fix redacted values.
1256
+ fix_missing :
1257
+ The method to use to fix missing values.
1258
+
1259
+ See Also
1260
+ --------
1261
+ [The dataset documentation](https://data.cdc.gov/NCHS/Provisional-COVID-19-Death-Counts-by-Week-Ending-D/r8kw-7aab/about_data).
1262
+ """ # noqa: E501
1263
+
1264
+ _RESOURCE = q.SocrataResource(domain="data.cdc.gov", id="r8kw-7aab")
1265
+ """The Socrata API endpoint."""
1266
+
1267
+ @staticmethod
1268
+ def _time_range() -> DateRange:
1269
+ """Compute the time range over which values are available."""
1270
+ # There's about a one week lag in the data.
1271
+ # On a Thursday they seem to post data up to the previous Saturday,
1272
+ # so this config handles that.
1273
+ return DateRange.until_date(
1274
+ iso8601("2020-01-04"),
1275
+ date.today() - timedelta(days=7),
1276
+ step=7,
1277
+ )
1278
+
1279
+ _cause_of_death: Literal["all", "COVID-19", "influenza", "pneumonia"]
1280
+ """The cause of death."""
1281
+ _fix_redacted: Fix[np.int64]
1282
+ """The method to use to replace redacted values (N/A in the data)."""
1283
+ _fix_missing: Fill[np.int64]
1284
+ """The method to use to fix missing values."""
1285
+
1286
+ def __init__(
1287
+ self,
1288
+ cause_of_death: Literal["all", "COVID-19", "influenza", "pneumonia"],
1289
+ *,
1290
+ fix_redacted: Fix[np.int64] | int | Callable[[], int] | Literal[False] = False,
1291
+ fix_missing: Fill[np.int64] | int | Callable[[], int] | Literal[False] = False,
1292
+ ):
1293
+ if cause_of_death not in ("all", "COVID-19", "influenza", "pneumonia"):
1294
+ err = f"Unsupported cause of death: {cause_of_death}"
1295
+ raise ValueError(err)
1296
+ self._cause_of_death = cause_of_death
1297
+ try:
1298
+ self._fix_redacted = Fix.of_int64(fix_redacted)
1299
+ except ValueError:
1300
+ raise ValueError("Invalid value for `fix_redacted`")
1301
+ try:
1302
+ self._fix_missing = Fill.of_int64(fix_missing)
1303
+ except ValueError:
1304
+ raise ValueError("Invalid value for `fix_missing`")
1305
+
1306
+ @property
1307
+ @override
1308
+ def result_format(self) -> ResultFormat:
1309
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.int64))
1310
+
1311
+ @override
1312
+ def validate_context(self, context: Context):
1313
+ if not isinstance(context.scope, StateScope):
1314
+ err = "US State geo scope required."
1315
+ raise ADRIOContextError(self, context, err)
1316
+ # No year restriction since state-equivalents are the same
1317
+ # for the entire supported time range.
1318
+ validate_time_frame(self, context, self._time_range())
1319
+
1320
+ @override
1321
+ def _fetch(self, context: Context) -> pd.DataFrame:
1322
+ # Data contains state names, so create mappings to and from.
1323
+ scope = cast(StateScope, context.scope)
1324
+ to_state = get_states(year=scope.year).state_fips_to_name
1325
+ to_fips = {to_state[x]: x for x in scope.node_ids}
1326
+ states = to_fips.keys()
1327
+
1328
+ match self._cause_of_death:
1329
+ case "all":
1330
+ value_column = "total_deaths"
1331
+ case "COVID-19":
1332
+ value_column = "covid_19_deaths"
1333
+ case "influenza":
1334
+ value_column = "influenza_deaths"
1335
+ case "pneumonia":
1336
+ value_column = "pneumonia_deaths"
1337
+
1338
+ query = q.Query(
1339
+ select=(
1340
+ q.Select("week_ending_date", "date", as_name="date"),
1341
+ q.Select("state", "str", as_name="geoid"),
1342
+ q.SelectExpression(
1343
+ value_column,
1344
+ "nullable_int",
1345
+ as_name="value",
1346
+ ),
1347
+ ),
1348
+ where=q.And(
1349
+ q.Equals("group", "By Week"),
1350
+ q.DateBetween(
1351
+ "week_ending_date",
1352
+ context.time_frame.start_date,
1353
+ context.time_frame.end_date,
1354
+ ),
1355
+ q.In("state", states),
1356
+ ),
1357
+ order_by=(
1358
+ q.Ascending("week_ending_date"),
1359
+ q.Ascending("state"),
1360
+ q.Ascending(":id"),
1361
+ ),
1362
+ )
1363
+ try:
1364
+ result_df = q.query_csv(
1365
+ resource=self._RESOURCE,
1366
+ query=query,
1367
+ api_token=data_cdc_api_key(),
1368
+ )
1369
+ geoid = result_df["geoid"].apply(lambda x: to_fips[x])
1370
+ return result_df.assign(geoid=geoid)
1371
+ except Exception as e:
1372
+ raise ADRIOCommunicationError(self, context) from e
1373
+
1374
+ @override
1375
+ def _process(
1376
+ self,
1377
+ context: Context,
1378
+ data_df: pd.DataFrame,
1379
+ ) -> PipelineResult[DateValueType]:
1380
+ value_dtype = self.result_format.dtype["value"].type
1381
+ time_series = self._time_range().overlap_or_raise(context.time_frame).to_numpy()
1382
+ pipeline = (
1383
+ DataPipeline(
1384
+ axes=(
1385
+ PivotAxis("date", time_series),
1386
+ PivotAxis("geoid", context.scope.node_ids),
1387
+ ),
1388
+ ndims=2,
1389
+ dtype=value_dtype,
1390
+ rng=context,
1391
+ )
1392
+ # insert our own sentinel value: nulls in these data mean "redacted"
1393
+ # but we can't have null values for the finalize step
1394
+ .strip_na_as_sentinel(
1395
+ "value",
1396
+ sentinel_name="redacted",
1397
+ sentinel_value=value_dtype(-999999),
1398
+ fix=self._fix_redacted,
1399
+ )
1400
+ .finalize(self._fix_missing)
1401
+ )
1402
+ return pipeline(data_df).to_date_value(time_series)
1403
+
1404
+ @override
1405
+ def validate_result(self, context: Context, result: NDArray) -> None:
1406
+ time_series = self._time_range().overlap_or_raise(context.time_frame)
1407
+ result_shape = (len(time_series), context.scope.nodes)
1408
+ adrio_validate_pipe(
1409
+ self,
1410
+ context,
1411
+ result,
1412
+ validate_numpy(),
1413
+ validate_shape(result_shape),
1414
+ validate_dtype(self.result_format.dtype),
1415
+ on_date_values(validate_values_in_range(0, None)),
1416
+ )
1417
+
1418
+
1419
+ ##########################
1420
+ # DATA.CDC.GOV mpgq-jmmr #
1421
+ ##########################
1422
+
1423
+ ResultT = TypeVar("ResultT", bound=np.generic)
1424
+
1425
+
1426
+ class _DataCDCMpgqJmmrMixin(FetchADRIO[DateValueType, ResultT]):
1427
+ """
1428
+ An mixin implemeting some of `FetchADRIO`'s API for ADRIOs which fetch
1429
+ data from cdc.gov dataset mpgq-jmmr: a.k.a.
1430
+ "Weekly Hospital Respiratory Data (HRD) Metrics by Jurisdiction,
1431
+ National Healthcare Safety Network (NHSN) (Preliminary)".
1432
+
1433
+ https://data.cdc.gov/Public-Health-Surveillance/Weekly-Hospital-Respiratory-Data-HRD-Metrics-by-Ju/mpgq-jmmr/about_data
1434
+ """
1435
+
1436
+ _RESOURCE = q.SocrataResource(domain="data.cdc.gov", id="mpgq-jmmr")
1437
+ """The Socrata API endpoint."""
1438
+
1439
+ _TIME_RANGE = DateRange.until_date(
1440
+ start_date=iso8601("2024-11-02"),
1441
+ max_end_date=date.today() - timedelta(days=1),
1442
+ step=7,
1443
+ )
1444
+ """The time range over which values are available."""
1445
+
1446
+ _fix_missing: Fill[ResultT]
1447
+ """The method to use to fix missing values."""
1448
+
1449
+ @property
1450
+ @abstractmethod
1451
+ def _column_name(self) -> str:
1452
+ """The column to fetch from the data source."""
1453
+
1454
+ @override
1455
+ def validate_context(self, context: Context):
1456
+ if not isinstance(context.scope, StateScope):
1457
+ err = "US State geo scope required."
1458
+ raise ADRIOContextError(self, context, err)
1459
+ # No geo year restriction since state-equivalents are the same
1460
+ # for the entire supported time range.
1461
+ validate_time_frame(self, context, self._TIME_RANGE)
1462
+
1463
+ @override
1464
+ def _fetch(self, context: Context) -> pd.DataFrame:
1465
+ scope = cast(StateScope, self.context.scope)
1466
+ state_info = get_states(scope.year)
1467
+ to_postal = state_info.state_fips_to_code
1468
+ to_fips = state_info.state_code_to_fips
1469
+
1470
+ val_dtype = self.result_format.dtype["value"]
1471
+ col_type = "float" if val_dtype == np.float64 else "int"
1472
+
1473
+ query = q.Query(
1474
+ select=(
1475
+ q.Select("weekendingdate", "date", as_name="date"),
1476
+ q.Select("jurisdiction", "str", as_name="geoid"),
1477
+ q.Select(self._column_name, col_type, as_name="value"),
1478
+ ),
1479
+ where=q.And(
1480
+ q.DateBetween(
1481
+ "weekendingdate",
1482
+ context.time_frame.start_date,
1483
+ context.time_frame.end_date,
1484
+ ),
1485
+ q.In("jurisdiction", [to_postal[x] for x in scope.node_ids]),
1486
+ q.NotNull(self._column_name),
1487
+ ),
1488
+ order_by=(
1489
+ q.Ascending("weekendingdate"),
1490
+ q.Ascending("jurisdiction"),
1491
+ q.Ascending(":id"),
1492
+ ),
1493
+ )
1494
+ try:
1495
+ result_df = q.query_csv(
1496
+ resource=self._RESOURCE,
1497
+ query=query,
1498
+ api_token=data_cdc_api_key(),
1499
+ )
1500
+ result_df["geoid"] = result_df["geoid"].apply(lambda x: to_fips[x])
1501
+ return result_df
1502
+ except Exception as e:
1503
+ raise ADRIOCommunicationError(self, context) from e
1504
+
1505
+ @override
1506
+ def _process(
1507
+ self,
1508
+ context: Context,
1509
+ data_df: pd.DataFrame,
1510
+ ) -> PipelineResult[DateValueType]:
1511
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame).to_numpy()
1512
+ pipeline = DataPipeline(
1513
+ axes=(
1514
+ PivotAxis("date", time_series),
1515
+ PivotAxis("geoid", context.scope.node_ids),
1516
+ ),
1517
+ ndims=2,
1518
+ dtype=self.result_format.dtype["value"].type,
1519
+ rng=context,
1520
+ ).finalize(self._fix_missing)
1521
+ result = pipeline(data_df)
1522
+ return result.to_date_value(time_series)
1523
+
1524
+ @override
1525
+ def validate_result(self, context: Context, result: NDArray) -> None:
1526
+ time_series = self._TIME_RANGE.overlap_or_raise(context.time_frame)
1527
+ result_shape = (len(time_series), context.scope.nodes)
1528
+ adrio_validate_pipe(
1529
+ self,
1530
+ context,
1531
+ result,
1532
+ validate_numpy(),
1533
+ validate_shape(result_shape),
1534
+ validate_dtype(self.result_format.dtype),
1535
+ on_date_values(validate_values_in_range(0, None)),
1536
+ )
1537
+
1538
+
1539
+ @adrio_cache
1540
+ class CurrentStateHospitalization(
1541
+ _DataCDCMpgqJmmrMixin[np.int64], FetchADRIO[DateValueType, np.int64]
1542
+ ):
1543
+ """
1544
+ Loads disease-specific hospitalization data from data.cdc.gov's dataset named
1545
+ "Weekly Hospital Respiratory Data (HRD) Metrics by Jurisdiction,
1546
+ National Healthcare Safety Network (NHSN) (Preliminary)".
1547
+
1548
+ The data are currently being reported by healthcare facilities on a weekly basis to
1549
+ CDC's National Healthcare Safety Network. This ADRIO loads recent data from the
1550
+ source, starting 2024-11-02 and onward. (Data exist before this date but with some
1551
+ caveats; see `COVIDStateHospitalization` and `InfluenzaStateHospitalization` for
1552
+ ADRIOs which support earlier, archived data.) The data were aggregated by CDC to
1553
+ the US State level.
1554
+
1555
+ This ADRIO supports geo scopes at US State granularity. The data
1556
+ loaded will be matched to the simulation time frame. The result is a 2D matrix
1557
+ where the first axis represents reporting weeks during the time frame and the
1558
+ second axis is geo scope nodes. Dates represent the MMWR week ending date of the
1559
+ data collection week. Values are tuples of date and the integer number of reported
1560
+ hospitalizations.
1561
+
1562
+ Parameters
1563
+ ----------
1564
+ fix_missing :
1565
+ The method to use to fix missing values.
1566
+
1567
+ See Also
1568
+ --------
1569
+ [The dataset documentation](https://data.cdc.gov/Public-Health-Surveillance/Weekly-Hospital-Respiratory-Data-HRD-Metrics-by-Ju/mpgq-jmmr/about_data).
1570
+ [epymorph.adrio.cdc.COVIDStateHospitalization][] and
1571
+ [epymorph.adrio.cdc.InfluenzaStateHospitalization][] for data prior to 2024-11-01.
1572
+ """ # noqa: E501
1573
+
1574
+ Disease = Literal["Covid", "Influenza", "RSV"]
1575
+ """A disease category available in this data."""
1576
+ AgeGroup = Literal["Total", "Adult", "Pediatric"]
1577
+ """An age category available in this data."""
1578
+
1579
+ _DISEASE_VALUES = {
1580
+ "Covid": "c19",
1581
+ "Influenza": "flu",
1582
+ "RSV": "rsv",
1583
+ }
1584
+
1585
+ # column name format is primarily dependent on the chosen age group,
1586
+ # and then we insert the disease identifier
1587
+ _AGE_GROUP_VALUES = {
1588
+ "Total": "totalconf{}hosppats",
1589
+ "Adult": "numconf{}hosppatsadult",
1590
+ "Pediatric": "numconf{}hosppatsped",
1591
+ }
1592
+
1593
+ _disease: Disease
1594
+ """The disease to load."""
1595
+ _age_group: AgeGroup
1596
+ """The age group to load."""
1597
+
1598
+ def __init__(
1599
+ self,
1600
+ *,
1601
+ disease: Disease,
1602
+ age_group: AgeGroup = "Total",
1603
+ fix_missing: FillLikeInt = False,
1604
+ ):
1605
+ if disease not in self._DISEASE_VALUES:
1606
+ err = f"Not a supported disease type: {disease}"
1607
+ raise ValueError(err)
1608
+ if age_group not in self._AGE_GROUP_VALUES:
1609
+ err = f"Not a supported age group type: {age_group}"
1610
+ raise ValueError(err)
1611
+ self._disease = disease
1612
+ self._age_group = age_group
1613
+ try:
1614
+ self._fix_missing = Fill.of_int64(fix_missing)
1615
+ except ValueError:
1616
+ raise ValueError("Invalid value for `fix_missing`")
1617
+
1618
+ @property
1619
+ @override
1620
+ def _column_name(self) -> str:
1621
+ disease = self._DISEASE_VALUES[self._disease]
1622
+ column_template = self._AGE_GROUP_VALUES[self._age_group]
1623
+ return column_template.format(disease)
1624
+
1625
+ @property
1626
+ @override
1627
+ def result_format(self) -> ResultFormat:
1628
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.int64))
1629
+
1630
+
1631
+ @adrio_cache
1632
+ class CurrentStateHospitalizationICU(
1633
+ _DataCDCMpgqJmmrMixin[np.float64], FetchADRIO[DateValueType, np.float64]
1634
+ ):
1635
+ """
1636
+ Loads disease-specific ICU hospitalization data from data.cdc.gov's dataset named
1637
+ "Weekly Hospital Respiratory Data (HRD) Metrics by Jurisdiction,
1638
+ National Healthcare Safety Network (NHSN) (Preliminary)".
1639
+
1640
+ The data are currently being reported by healthcare facilities on a weekly basis to
1641
+ CDC's National Healthcare Safety Network. This ADRIO loads recent data from the
1642
+ source, starting 2024-11-02 and onward. The data were aggregated by CDC to
1643
+ the US State level.
1644
+
1645
+ This ADRIO supports geo scopes at US State granularity. The data
1646
+ loaded will be matched to the simulation time frame. The result is a 2D matrix
1647
+ where the first axis represents reporting weeks during the time frame and the
1648
+ second axis is geo scope nodes. Dates represent the MMWR week ending date of the
1649
+ data collection week. Values are tuples of date and the integer number of reported
1650
+ ICU hospitalizations.
1651
+
1652
+ Parameters
1653
+ ----------
1654
+ fix_missing :
1655
+ The method to use to fix missing values.
1656
+
1657
+ See Also
1658
+ --------
1659
+ [The dataset documentation](https://data.cdc.gov/Public-Health-Surveillance/Weekly-Hospital-Respiratory-Data-HRD-Metrics-by-Ju/mpgq-jmmr/about_data).
1660
+ """ # noqa: E501
1661
+
1662
+ Disease = Literal["Covid", "Influenza", "RSV"]
1663
+ """A disease category available in this data."""
1664
+ AgeGroup = Literal["Total", "Adult", "Pediatric"]
1665
+ """An age category available in this data."""
1666
+
1667
+ _DISEASE_VALUES = {
1668
+ "Covid": "c19",
1669
+ "Influenza": "flu",
1670
+ "RSV": "rsv",
1671
+ }
1672
+
1673
+ # column name format is primarily dependent on the chosen age group,
1674
+ # and then we insert the disease identifier
1675
+ _AGE_GROUP_VALUES = {
1676
+ "Total": "totalconf{}icupats",
1677
+ "Adult": "numconf{}icupatsadult",
1678
+ "Pediatric": "numconf{}icupatsped",
1679
+ }
1680
+
1681
+ _disease: Disease
1682
+ """The disease to load."""
1683
+ _age_group: AgeGroup
1684
+ """The age group to load."""
1685
+
1686
+ def __init__(
1687
+ self,
1688
+ *,
1689
+ disease: Disease,
1690
+ age_group: AgeGroup = "Total",
1691
+ fix_missing: FillLikeFloat = False,
1692
+ ):
1693
+ if disease not in self._DISEASE_VALUES:
1694
+ err = f"Not a supported disease type: {disease}"
1695
+ raise ValueError(err)
1696
+ if age_group not in self._AGE_GROUP_VALUES:
1697
+ err = f"Not a supported age group type: {age_group}"
1698
+ raise ValueError(err)
1699
+ self._disease = disease
1700
+ self._age_group = age_group
1701
+ try:
1702
+ self._fix_missing = Fill.of_float64(fix_missing)
1703
+ except ValueError:
1704
+ raise ValueError("Invalid value for `fix_missing`")
1705
+
1706
+ @property
1707
+ @override
1708
+ def _column_name(self) -> str:
1709
+ disease = self._DISEASE_VALUES[self._disease]
1710
+ column_template = self._AGE_GROUP_VALUES[self._age_group]
1711
+ return column_template.format(disease)
1712
+
1713
+ @property
1714
+ @override
1715
+ def result_format(self) -> ResultFormat:
1716
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.float64))
1717
+
1718
+
1719
+ @adrio_cache
1720
+ class CurrentStateAdmissions(
1721
+ _DataCDCMpgqJmmrMixin[np.int64], FetchADRIO[DateValueType, np.int64]
1722
+ ):
1723
+ """
1724
+ Loads disease-specific hospital admissions data from data.cdc.gov's dataset named
1725
+ "Weekly Hospital Respiratory Data (HRD) Metrics by Jurisdiction,
1726
+ National Healthcare Safety Network (NHSN) (Preliminary)".
1727
+
1728
+ The data are currently being reported by healthcare facilities on a weekly basis to
1729
+ CDC's National Healthcare Safety Network. This ADRIO loads recent data from the
1730
+ source, starting 2024-11-02 and onward. (Data exist before this date but with some
1731
+ caveats; see `COVIDStateHospitalization` and `InfluenzaStateHospitalization` for
1732
+ ADRIOs which support earlier, archived data.) The data were aggregated by CDC to
1733
+ the US State level.
1734
+
1735
+ This ADRIO supports geo scopes at US State granularity. The data
1736
+ loaded will be matched to the simulation time frame. The result is a 2D matrix
1737
+ where the first axis represents reporting weeks during the time frame and the
1738
+ second axis is geo scope nodes. Dates represent the MMWR week ending date of the
1739
+ data collection week. Values are tuples of date and the integer number of reported
1740
+ hospital admissions.
1741
+
1742
+ Parameters
1743
+ ----------
1744
+ fix_missing :
1745
+ The method to use to fix missing values.
1746
+
1747
+ See Also
1748
+ --------
1749
+ [The dataset documentation](https://data.cdc.gov/Public-Health-Surveillance/Weekly-Hospital-Respiratory-Data-HRD-Metrics-by-Ju/mpgq-jmmr/about_data).
1750
+ [epymorph.adrio.cdc.COVIDStateHospitalization][] and
1751
+ [epymorph.adrio.cdc.InfluenzaStateHospitalization][] for data prior to 2024-11-01.
1752
+ """ # noqa: E501
1753
+
1754
+ Disease = Literal["Covid", "Influenza", "RSV"]
1755
+ """A disease category available in this data."""
1756
+ AgeGroup = Literal[
1757
+ "0 to 4",
1758
+ "5 to 17",
1759
+ "18 to 49",
1760
+ "50 to 64",
1761
+ "65 to 74",
1762
+ "75 and above",
1763
+ "Unknown",
1764
+ "Adult",
1765
+ "Pediatric",
1766
+ "Total",
1767
+ ]
1768
+ """An age category available in this data."""
1769
+
1770
+ _DISEASE_VALUES = {
1771
+ "Covid": "c19",
1772
+ "Influenza": "flu",
1773
+ "RSV": "rsv",
1774
+ }
1775
+
1776
+ # column name format is primarily dependent on the chosen age group,
1777
+ # and then we insert the disease identifier
1778
+ _AGE_GROUP_VALUES = {
1779
+ "0 to 4": "numconf{}newadmped0to4",
1780
+ "5 to 17": "numconf{}newadmped5to17",
1781
+ "18 to 49": "numconf{}newadmadult18to49",
1782
+ "50 to 64": "numconf{}newadmadult50to64",
1783
+ "65 to 74": "numconf{}newadmadult65to74",
1784
+ "75 and above": "numconf{}newadmadult75plus",
1785
+ "Unknown": "numconf{}newadmunk",
1786
+ "Adult": "totalconf{}newadmadult",
1787
+ "Pediatric": "totalconf{}newadmped",
1788
+ "Total": "totalconf{}newadm",
1789
+ }
1790
+
1791
+ _disease: Disease
1792
+ """The disease to load."""
1793
+ _age_group: AgeGroup
1794
+ """The age group to load."""
1795
+
1796
+ def __init__(
1797
+ self,
1798
+ *,
1799
+ disease: Disease,
1800
+ age_group: AgeGroup = "Total",
1801
+ fix_missing: FillLikeInt = False,
1802
+ ):
1803
+ if disease not in self._DISEASE_VALUES:
1804
+ err = f"Not a supported disease type: {disease}"
1805
+ raise ValueError(err)
1806
+ if age_group not in self._AGE_GROUP_VALUES:
1807
+ err = f"Not a supported age group type: {age_group}"
1808
+ raise ValueError(err)
1809
+ self._disease = disease
1810
+ self._age_group = age_group
1811
+ try:
1812
+ self._fix_missing = Fill.of_int64(fix_missing)
1813
+ except ValueError:
1814
+ raise ValueError("Invalid value for `fix_missing`")
1815
+
1816
+ @property
1817
+ @override
1818
+ def _column_name(self) -> str:
1819
+ disease = self._DISEASE_VALUES[self._disease]
1820
+ column_template = self._AGE_GROUP_VALUES[self._age_group]
1821
+ return column_template.format(disease)
1822
+
1823
+ @property
1824
+ @override
1825
+ def result_format(self) -> ResultFormat:
1826
+ return ResultFormat(shape=Shapes.AxN, dtype=date_value_dtype(np.int64))