epymorph 1.0.0b0__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 (102) 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 +602 -0
  5. epymorph/adrio/adrio.py +215 -0
  6. epymorph/adrio/cdc.py +781 -0
  7. epymorph/adrio/commuting_flows.py +237 -0
  8. epymorph/adrio/csv.py +387 -0
  9. epymorph/adrio/humidity.py +84 -0
  10. epymorph/adrio/lodes.py +624 -0
  11. epymorph/adrio/numpy.py +119 -0
  12. epymorph/adrio/prism.py +543 -0
  13. epymorph/adrio/respiratory_cdc.py +489 -0
  14. epymorph/adrio/us_tiger.py +217 -0
  15. epymorph/attribute.py +301 -0
  16. epymorph/cache.py +494 -0
  17. epymorph/cli/__init__.py +0 -0
  18. epymorph/cli/cache.py +77 -0
  19. epymorph/cli/main.py +29 -0
  20. epymorph/compartment_model.py +1335 -0
  21. epymorph/data/__init__.py +1 -0
  22. epymorph/data/ipm/__init__.py +22 -0
  23. epymorph/data/ipm/no.py +14 -0
  24. epymorph/data/ipm/pei.py +40 -0
  25. epymorph/data/ipm/seirs.py +50 -0
  26. epymorph/data/ipm/sirh.py +55 -0
  27. epymorph/data/ipm/sirs.py +48 -0
  28. epymorph/data/ipm/sparsemod.py +96 -0
  29. epymorph/data/mm/__init__.py +22 -0
  30. epymorph/data/mm/centroids.py +76 -0
  31. epymorph/data/mm/flat.py +61 -0
  32. epymorph/data/mm/icecube.py +50 -0
  33. epymorph/data/mm/no.py +29 -0
  34. epymorph/data/mm/pei.py +105 -0
  35. epymorph/data/mm/sparsemod.py +73 -0
  36. epymorph/data/pei.py +424 -0
  37. epymorph/data_shape.py +475 -0
  38. epymorph/data_type.py +129 -0
  39. epymorph/data_usage.py +171 -0
  40. epymorph/database.py +1010 -0
  41. epymorph/error.py +183 -0
  42. epymorph/event.py +188 -0
  43. epymorph/geography/__init__.py +0 -0
  44. epymorph/geography/custom.py +61 -0
  45. epymorph/geography/scope.py +214 -0
  46. epymorph/geography/us_census.py +622 -0
  47. epymorph/geography/us_geography.py +278 -0
  48. epymorph/geography/us_tiger.py +755 -0
  49. epymorph/initializer.py +596 -0
  50. epymorph/kit.py +90 -0
  51. epymorph/log/__init__.py +0 -0
  52. epymorph/log/file.py +108 -0
  53. epymorph/log/messaging.py +129 -0
  54. epymorph/log/movement.py +151 -0
  55. epymorph/movement_model.py +274 -0
  56. epymorph/parameter_fitting/__init__.py +0 -0
  57. epymorph/parameter_fitting/distribution.py +68 -0
  58. epymorph/parameter_fitting/dynamics.py +19 -0
  59. epymorph/parameter_fitting/filter/__init__.py +0 -0
  60. epymorph/parameter_fitting/filter/base_filter.py +50 -0
  61. epymorph/parameter_fitting/filter/particle.py +32 -0
  62. epymorph/parameter_fitting/filter/particle_filter.py +296 -0
  63. epymorph/parameter_fitting/likelihood.py +54 -0
  64. epymorph/parameter_fitting/output.py +73 -0
  65. epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
  66. epymorph/parameter_fitting/perturbation.py +19 -0
  67. epymorph/parameter_fitting/utils/__init__.py +0 -0
  68. epymorph/parameter_fitting/utils/data_loader.py +111 -0
  69. epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
  70. epymorph/parameter_fitting/utils/observations.py +63 -0
  71. epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
  72. epymorph/parameter_fitting/utils/params_perturb.py +43 -0
  73. epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
  74. epymorph/parameter_fitting/utils/resampler.py +249 -0
  75. epymorph/parameter_fitting/utils/utils.py +101 -0
  76. epymorph/params.py +248 -0
  77. epymorph/py.typed +0 -0
  78. epymorph/rume.py +700 -0
  79. epymorph/simulation.py +706 -0
  80. epymorph/simulator/__init__.py +0 -0
  81. epymorph/simulator/basic/__init__.py +0 -0
  82. epymorph/simulator/basic/basic_simulator.py +145 -0
  83. epymorph/simulator/basic/ipm_exec.py +406 -0
  84. epymorph/simulator/basic/mm_exec.py +197 -0
  85. epymorph/simulator/basic/output.py +181 -0
  86. epymorph/simulator/world.py +83 -0
  87. epymorph/simulator/world_list.py +196 -0
  88. epymorph/strata.py +12 -0
  89. epymorph/sympy_shim.py +55 -0
  90. epymorph/time.py +649 -0
  91. epymorph/tools/__init__.py +0 -0
  92. epymorph/tools/data.py +218 -0
  93. epymorph/tools/ipm_diagram.py +165 -0
  94. epymorph/tools/out_map.py +426 -0
  95. epymorph/tools/out_plot.py +412 -0
  96. epymorph/tools/out_table.py +575 -0
  97. epymorph/util.py +825 -0
  98. epymorph-1.0.0b0.dist-info/METADATA +57 -0
  99. epymorph-1.0.0b0.dist-info/RECORD +102 -0
  100. epymorph-1.0.0b0.dist-info/WHEEL +5 -0
  101. epymorph-1.0.0b0.dist-info/entry_points.txt +2 -0
  102. epymorph-1.0.0b0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,489 @@
1
+ from datetime import date
2
+ from typing import Literal
3
+ from warnings import warn
4
+
5
+ import numpy as np
6
+ from numpy.typing import NDArray
7
+ from typing_extensions import override
8
+
9
+ from epymorph.adrio.adrio import ADRIO, ProgressCallback, adrio_cache
10
+ from epymorph.adrio.cdc import DataSource, _api_query, _validate_scope
11
+ from epymorph.error import DataResourceError
12
+ from epymorph.geography.us_census import CensusScope
13
+ from epymorph.geography.us_tiger import get_states
14
+ from epymorph.time import TimeFrame
15
+
16
+ DiseaseType = Literal["Covid", "Influenza", "RSV"]
17
+
18
+ _DISEASE_VARIABLES: dict[DiseaseType, str] = {
19
+ "Covid": "c19",
20
+ "Influenza": "flu",
21
+ "RSV": "rsv",
22
+ }
23
+
24
+
25
+ def _fetch_respiratory(
26
+ attrib_name: str,
27
+ scope: CensusScope,
28
+ time_frame: TimeFrame,
29
+ progress: ProgressCallback,
30
+ ) -> NDArray[np.float64]:
31
+ """
32
+ Fetches data from CDC dataset reporting weekly hospital data and metrics from rsv
33
+ and other respiratory illnesses during manditory and voluntary
34
+ reporting periods.
35
+ Available from 8/8/2020 to present at state granularity.
36
+ https://data.cdc.gov/Public-Health-Surveillance/Weekly-Hospital-Respiratory-Data-HRD-Metrics-by-Ju/mpgq-jmmr/about_data
37
+ """
38
+
39
+ source = DataSource(
40
+ url_base="https://data.cdc.gov/resource/mpgq-jmmr.csv?",
41
+ date_col="weekendingdate",
42
+ fips_col="jurisdiction",
43
+ data_col=attrib_name,
44
+ granularity="state",
45
+ replace_sentinel=None,
46
+ map_geo_ids=get_states(scope.year).state_fips_to_code,
47
+ )
48
+
49
+ return _api_query(source, scope, time_frame, progress)
50
+
51
+
52
+ class _RespiratoryADRIO(ADRIO[np.float64]):
53
+ _override_time_frame: TimeFrame | None
54
+ """The time period the data encompasses."""
55
+
56
+ disease_name: DiseaseType
57
+
58
+ def __init__(
59
+ self,
60
+ disease_name: DiseaseType,
61
+ voluntary_reporting=True,
62
+ time_frame: TimeFrame | None = None,
63
+ ):
64
+ self.disease_name = disease_name
65
+ self._override_time_frame = time_frame
66
+ self.voluntary_reporting = voluntary_reporting
67
+
68
+ @property
69
+ def data_time_frame(self) -> TimeFrame:
70
+ """The time frame for which to fetch data."""
71
+ return self._override_time_frame or self.time_frame
72
+
73
+ def _validate_dates_(self):
74
+ dataset_start = date(2020, 8, 8)
75
+ first_mandate_end = date(2024, 4, 30)
76
+ second_mandate_start = date(2024, 11, 1)
77
+ no_mandate_range = TimeFrame.rangex(first_mandate_end, second_mandate_start)
78
+
79
+ covid_flu_voluntary_msg = (
80
+ "The dates you entered take place during a voluntary reporting "
81
+ "period.\nEnter dates between August 8th, 2020 through April"
82
+ " 30th, 2024 or from November 1st, 2024 to the present day for data "
83
+ "captured during a mandatory reporting period."
84
+ )
85
+ rsv_voluntary_msg = (
86
+ "All data and metrics reported before November 1st, 2024 for RSV"
87
+ " were reported voluntarily.\nEnter a date on or after"
88
+ " 11/01/2024 for data captured during a mandatory reporting period."
89
+ )
90
+
91
+ # check if the dates are before August 8th, 2020
92
+ if self.data_time_frame.start_date < dataset_start:
93
+ raise DataResourceError(
94
+ "The Weekly Hospital Respiratory dataset provides metrics starting"
95
+ " August 8th, 2020.\nPlease enter a time frame starting on or after "
96
+ "08/08/2020."
97
+ )
98
+
99
+ # check for the voluntary reporting period for Covid and Influenza
100
+ voluntary_covid_flu = (
101
+ self.disease_name != "RSV"
102
+ and self.data_time_frame.is_subset(no_mandate_range)
103
+ )
104
+ # check for the voluntary reporting period for RSV
105
+ voluntary_rsv = (
106
+ self.disease_name == "RSV"
107
+ and self.data_time_frame.start_date < second_mandate_start
108
+ )
109
+
110
+ # warn or raise the error
111
+ if voluntary_covid_flu or voluntary_rsv:
112
+ msg = covid_flu_voluntary_msg if voluntary_covid_flu else rsv_voluntary_msg
113
+ if not self.voluntary_reporting:
114
+ raise DataResourceError(msg)
115
+ warn(msg)
116
+
117
+ return self.data_time_frame
118
+
119
+
120
+ class DiseaseHospitalizations(_RespiratoryADRIO):
121
+ """
122
+ Creates a TxN matrix of tuples, containing a date and a float representing the
123
+ number of patients hospitalized with a confirmed disease for that week. May be
124
+ specified for the total number of patients, the number of adult patients, or the
125
+ number of pediatric patients.
126
+ """
127
+
128
+ AmountType = Literal["Total", "Adult", "Pediatric"]
129
+
130
+ amount_variables: dict[AmountType, str] = {
131
+ "Total": "total",
132
+ "Adult": "adult",
133
+ "Pediatric": "ped",
134
+ }
135
+
136
+ amount_type: AmountType
137
+
138
+ def __init__(
139
+ self,
140
+ disease_name: DiseaseType,
141
+ amount_type: AmountType = "Total",
142
+ voluntary_reporting=True,
143
+ time_frame: TimeFrame | None = None,
144
+ ):
145
+ """
146
+ Creates an ADRIO of the confirmed hospitalizations for a disease.
147
+
148
+ Parameters
149
+ ----------
150
+ disease_name: DiseaseType
151
+ The name of the disease that is desired to be fetched for (options: 'RSV',
152
+ 'Influenza', 'Covid').
153
+ amount_type : AmountType
154
+ The category of hospitalized patient sums to fetch for.
155
+ - `'Total'`: Displays the total amount of patients that have been
156
+ hospitalized with a disease (default).
157
+ - `'Adult'`: Displays the number of adults, starting from age 18 and beyond,
158
+ who have been hospitalized with a disease.
159
+ - `'Pediatric'`: Displays the number of pediatric patients, from ages 0 to
160
+ 17, who have been hospitalized with a disease.
161
+ voluntary_reporting: bool, optional
162
+ The flag that indicates whether the user would like the ADRIO to warn or
163
+ error when the timeframe is within a voluntary reporting period.
164
+ If True, all available data is returned with a warning about the
165
+ timeframe. (default)
166
+ If False, the ADRIO will error and will not return any requested data.
167
+ time_frame : TimeFrame, optional
168
+ The range of dates to fetch hospital metric data for.
169
+ Default: the simulation time frame.
170
+ """
171
+ super().__init__(disease_name, voluntary_reporting, time_frame)
172
+ self.amount_type = amount_type
173
+
174
+ @override
175
+ def evaluate_adrio(self) -> NDArray[np.float64]:
176
+ time_frame = self._validate_dates_()
177
+ scope = _validate_scope(self.scope)
178
+ amount_var = self.amount_variables[self.amount_type]
179
+ disease_var = _DISEASE_VARIABLES[self.disease_name]
180
+ if amount_var == "total":
181
+ hosp_var = f"totalconf{disease_var}hosppats"
182
+ else:
183
+ hosp_var = f"numconf{disease_var}hosppats{amount_var}"
184
+ return _fetch_respiratory(
185
+ hosp_var,
186
+ scope,
187
+ time_frame,
188
+ self.progress,
189
+ )
190
+
191
+
192
+ class DiseaseAdmissions(_RespiratoryADRIO):
193
+ """
194
+ Creates a TxN matrix of tuples, containing a date and a float representing the
195
+ number of new admissions for a confirmed disease for that week. May be
196
+ specified for the total number of patients, the total number of adult patients, the
197
+ total number of pediatric patients, or any of the specified age ranges.
198
+ """
199
+
200
+ AmountType = Literal[
201
+ "0 to 4",
202
+ "5 to 17",
203
+ "18 to 49",
204
+ "50 to 64",
205
+ "65 to 74",
206
+ "75 and above",
207
+ "Unknown",
208
+ "Adult",
209
+ "Pediatric",
210
+ "Total",
211
+ ]
212
+
213
+ amount_variables: dict[AmountType, str] = {
214
+ "0 to 4": "0to4",
215
+ "5 to 17": "5to17",
216
+ "18 to 49": "18to49",
217
+ "50 to 64": "50to64",
218
+ "65 to 74": "65to74",
219
+ "75 and above": "75plus",
220
+ "Unknown": "unk",
221
+ "Adult": "adult",
222
+ "Pediatric": "ped",
223
+ "Total": "total",
224
+ }
225
+
226
+ amount_type: AmountType
227
+
228
+ def __init__(
229
+ self,
230
+ disease_name: DiseaseType,
231
+ amount_type: AmountType = "Total",
232
+ voluntary_reporting=True,
233
+ time_frame: TimeFrame | None = None,
234
+ ):
235
+ """
236
+ Creates an ADRIO of the confirmed admissions for a confirmed disease.
237
+
238
+ Parameters
239
+ ----------
240
+ disease_name: DiseaseType
241
+ The name of the disease that is desired to be fetched for (options: 'RSV',
242
+ 'Influenza', 'Covid').
243
+ amount_type : AmountType
244
+ The category of the disease of hospitalized patient sums to fetch for.
245
+ The parameters for 'Total', 'Adult', and 'Pediatric' start from
246
+ November 25th, 2023 to present. For any numerical age range parameter,
247
+ the starting date is October 12th, 2024.
248
+ - `'Total'`: Displays the total amount of patient admissions with the
249
+ confirmed disease (default).
250
+ - `'Adult'`: Displays the number of adult patient admissions, starting from
251
+ age 18 and beyond, confirmed with the disease.
252
+ - `'Pediatric'`: Displays the number of pediatric patient admissions, from
253
+ ages 0 to 17, confirmed with the disease.
254
+ - `'0 to 4'`: Displays the number of patient admissions, ages 0 to 4, with
255
+ the confirmed disease.
256
+ - `'5 to 17'`: Displays the number of patient admissions, ages 5 to 17, with
257
+ the confirmed disease.
258
+ - `'18 to 49'`: Displays the number of patient admissions, ages 18 to 49,
259
+ with the confirmed disease.
260
+ - `'50 to 64'`: Displays the number of patient admissions, ages 50 to 64,
261
+ with the confirmed disease.
262
+ - `'65 to 74'`: Displays the number of patient admissions, ages 65 to 74,
263
+ with the confirmed disease.
264
+ - `'75 and above'`: Displays the number of patient admissions, from ages 75
265
+ and beyond, with the confirmed disease.
266
+ - `'Unknown'`: Displays the number of patient admissions with an unkown age
267
+ voluntary_reporting: bool, optional
268
+ The flag that indicates whether the user would like the ADRIO to warn or
269
+ error when the timeframe is within a voluntary reporting period.
270
+ If True, all available data is returned with a warning about the
271
+ timeframe. (default)
272
+ If False, the ADRIO will error and will not return any requested data.
273
+ time_frame : TimeFrame, optional
274
+ The range of dates to fetch hospital metric data for.
275
+ Default: the simulation time frame.
276
+ """
277
+ super().__init__(disease_name, voluntary_reporting, time_frame)
278
+ self.amount_type = amount_type
279
+
280
+ def evaluate_adrio(self) -> NDArray[np.float64]:
281
+ """
282
+ Allow admissions classes to set up their queries.
283
+ """
284
+ time_frame = self._validate_dates_()
285
+ scope = _validate_scope(self.scope)
286
+ amount_var = self.amount_variables[self.amount_type]
287
+ disease_var = _DISEASE_VARIABLES[self.disease_name]
288
+ age_type_var = ""
289
+ if amount_var == "total":
290
+ adm_var = f"totalconf{disease_var}newadm"
291
+ elif amount_var in ["adult", "ped"]:
292
+ adm_var = f"totalconf{disease_var}newadm{amount_var}"
293
+ else:
294
+ if amount_var in ["0to4", "5to17"]:
295
+ age_type_var = "ped"
296
+ elif amount_var == "unk":
297
+ age_type_var = ""
298
+ else:
299
+ age_type_var = "adult"
300
+ adm_var = f"numconf{self.disease_name}newadm{age_type_var}{amount_var}"
301
+ return _fetch_respiratory(
302
+ adm_var,
303
+ scope,
304
+ time_frame,
305
+ self.progress,
306
+ )
307
+
308
+
309
+ @adrio_cache
310
+ class AdmissionsPer100k(_RespiratoryADRIO):
311
+ """
312
+ Creates a TxN matrix of tuples, containing a date and a float representing the
313
+ number of new admissions for a confirmed disease for that week per
314
+ 100k population. May be specified for the total number of patients, the total number
315
+ of adult patients, the total number of pediatric patients, or any of the specified
316
+ age ranges.
317
+ """
318
+
319
+ AmountType = Literal[
320
+ "0 to 4",
321
+ "5 to 17",
322
+ "18 to 49",
323
+ "50 to 64",
324
+ "65 to 74",
325
+ "75 and above",
326
+ "Adult",
327
+ "Pediatric",
328
+ "Total",
329
+ ]
330
+
331
+ amount_variables: dict[AmountType, str] = {
332
+ "0 to 4": "0to4",
333
+ "5 to 17": "5to17",
334
+ "18 to 49": "18to49",
335
+ "50 to 64": "50to64",
336
+ "65 to 74": "65to74",
337
+ "75 and above": "75plus",
338
+ "Adult": "adult",
339
+ "Pediatric": "ped",
340
+ "Total": "total",
341
+ }
342
+
343
+ amount_type: AmountType
344
+
345
+ def __init__(
346
+ self,
347
+ disease_name: DiseaseType,
348
+ amount_type: AmountType = "Total",
349
+ voluntary_reporting=True,
350
+ time_frame: TimeFrame | None = None,
351
+ ):
352
+ """
353
+ Creates an ADRIO of the admissions for a confirmed disease per 100k
354
+ population.
355
+
356
+ Parameters
357
+ ----------
358
+ disease_name: DiseaseType
359
+ The name of the disease that is desired to be fetched for (options: 'RSV',
360
+ 'Influenza', 'Covid').
361
+ amount_type : AmountType
362
+ The category of hospitalized patient sums to fetch for.
363
+ - `'Total'`: Displays the total amount of patient admissions with
364
+ the confirmed disease (default).
365
+ - `'Adult'`: Displays the number of adult patient admissions, starting from
366
+ age 18 and beyond, confirmed with the confirmed disease.
367
+ - `'Pediatric'`: Displays the number of pediatric patient admissions, from
368
+ ages 0 to 17, confirmed with the confirmed disease.
369
+ - `'0 to 4'`: Displays the number of patient admissions, ages 0 to 4, with
370
+ the confirmed disease.
371
+ - `'5 to 17'`: Displays the number of patient admissions, ages 5 to 17, with
372
+ the confirmed disease.
373
+ - `'18 to 49'`: Displays the number of patient admissions, ages 18 to 49,
374
+ with the confirmed disease.
375
+ - `'50 to 64'`: Displays the number of patient admissions, ages 50 to 64,
376
+ with the confirmed disease.
377
+ - `'65 to 74'`: Displays the number of patient admissions, ages 65 to 74,
378
+ with the confirmed disease.
379
+ - `'75 and above'`: Displays the number of patient admissions, from ages 75
380
+ and beyond, with the confirmed disease.
381
+ voluntary_reporting: bool, optional
382
+ The flag that indicates whether the user would like the ADRIO to warn or
383
+ error when the timeframe is within a voluntary reporting period.
384
+ If True, all available data is returned with a warning about the
385
+ timeframe. (default)
386
+ If False, the ADRIO will error and will not return any requested data.
387
+ time_frame : TimeFrame, optional
388
+ The range of dates to fetch hospital metric data for.
389
+ Default: the simulation time frame.
390
+ """
391
+ super().__init__(disease_name, voluntary_reporting, time_frame)
392
+ self.amount_type = amount_type
393
+
394
+ @override
395
+ def evaluate_adrio(self) -> NDArray[np.float64]:
396
+ time_frame = self._validate_dates_()
397
+ scope = _validate_scope(self.scope)
398
+ amount_var = self.amount_variables[self.amount_type]
399
+ disease_var = _DISEASE_VARIABLES[self.disease_name]
400
+ age_type_var = ""
401
+ if amount_var == "total":
402
+ adm_var = f"totalconf{disease_var}newadmper100k"
403
+ elif amount_var in ["adult", "ped"]:
404
+ adm_var = f"totalconf{disease_var}newadm{amount_var}per100k"
405
+ else:
406
+ if amount_var in ["0to4", "5to17"]:
407
+ age_type_var = "ped"
408
+ else:
409
+ age_type_var = "adult"
410
+ adm_var = f"numconf{disease_var}newadm{age_type_var}{amount_var}per100k"
411
+ return _fetch_respiratory(
412
+ adm_var,
413
+ scope,
414
+ time_frame,
415
+ self.progress,
416
+ )
417
+
418
+
419
+ @adrio_cache
420
+ class HospitalizationsICU(_RespiratoryADRIO):
421
+ """
422
+ Creates a TxN matrix of tuples, containing a date and a float representing the
423
+ number of ICU patients hospitalized with a confirmed disease for that week. May be
424
+ specified for the total number of patients, the number of adult patients, or the
425
+ number of pediatric patients.
426
+ """
427
+
428
+ AmountType = Literal["Total", "Adult", "Pediatric"]
429
+
430
+ amount_variables: dict[AmountType, str] = {
431
+ "Total": "total",
432
+ "Adult": "adult",
433
+ "Pediatric": "ped",
434
+ }
435
+
436
+ amount_type: AmountType
437
+
438
+ def __init__(
439
+ self,
440
+ disease_name: DiseaseType,
441
+ amount_type: AmountType = "Total",
442
+ voluntary_reporting=True,
443
+ time_frame: TimeFrame | None = None,
444
+ ):
445
+ """
446
+ Creates an ADRIO of the confirmed hospitalizations for a confirmed disease.
447
+
448
+ Parameters
449
+ ----------
450
+ disease_name: DiseaseType
451
+ The name of the disease that is desired to be fetched for (options: 'RSV',
452
+ 'Influenza', 'Covid').
453
+ amount_type : AmountType
454
+ The category of hospitalized patient sums to fetch for.
455
+ - `'Total'`: Displays the total amount of patients that have been
456
+ hospitalized with a confirmed disease (default).
457
+ - `'Adult'`: Displays the number of adults, starting from age 18 and beyond,
458
+ who have been hospitalized with a confirmed disease.
459
+ - `'Pediatric'`: Displays the number of pediatric patients, from ages 0 to
460
+ 17, who have been hospitalized with a confirmed disease.
461
+ voluntary_reporting: bool, optional
462
+ The flag that indicates whether the user would like the ADRIO to warn or
463
+ error when the timeframe is within a voluntary reporting period.
464
+ If True, all available data is returned with a warning about the
465
+ timeframe. (default)
466
+ If False, the ADRIO will error and will not return any requested data.
467
+ time_frame : TimeFrame, optional
468
+ The range of dates to fetch hospital metric data for.
469
+ Default: the simulation time frame.
470
+ """
471
+ super().__init__(disease_name, voluntary_reporting, time_frame)
472
+ self.amount_type = amount_type
473
+
474
+ @override
475
+ def evaluate_adrio(self) -> NDArray[np.float64]:
476
+ time_frame = self._validate_dates_()
477
+ scope = _validate_scope(self.scope)
478
+ amount_var = self.amount_variables[self.amount_type]
479
+ disease_var = _DISEASE_VARIABLES[self.disease_name]
480
+ if amount_var == "total":
481
+ hosp_var = f"totalconf{disease_var}icupats"
482
+ else:
483
+ hosp_var = f"numconf{disease_var}icupats{amount_var}"
484
+ return _fetch_respiratory(
485
+ hosp_var,
486
+ scope,
487
+ time_frame,
488
+ self.progress,
489
+ )
@@ -0,0 +1,217 @@
1
+ """ADRIOs that access the US Census TIGER geography files."""
2
+
3
+ from abc import ABC
4
+ from typing import TypeVar
5
+
6
+ import numpy as np
7
+ from geopandas import GeoDataFrame
8
+ from pandas import DataFrame, to_numeric
9
+ from typing_extensions import override
10
+
11
+ from epymorph.adrio.adrio import ADRIO, ProgressCallback, adrio_cache
12
+ from epymorph.data_type import CentroidDType, StructDType
13
+ from epymorph.data_usage import AvailableDataEstimate, DataEstimate
14
+ from epymorph.error import DataResourceError
15
+ from epymorph.geography.scope import GeoScope
16
+ from epymorph.geography.us_census import CensusScope
17
+ from epymorph.geography.us_geography import STATE
18
+ from epymorph.geography.us_tiger import (
19
+ TigerYear,
20
+ check_cache_block_groups,
21
+ check_cache_counties,
22
+ check_cache_states,
23
+ check_cache_tracts,
24
+ get_block_groups_geo,
25
+ get_block_groups_info,
26
+ get_counties_geo,
27
+ get_counties_info,
28
+ get_states_geo,
29
+ get_states_info,
30
+ get_tracts_geo,
31
+ get_tracts_info,
32
+ is_tiger_year,
33
+ )
34
+
35
+
36
+ def _validate_scope(scope: GeoScope) -> CensusScope:
37
+ if not isinstance(scope, CensusScope):
38
+ raise DataResourceError("Census scope is required for us_tiger attributes.")
39
+ return scope
40
+
41
+
42
+ def _validate_year(scope: CensusScope) -> TigerYear:
43
+ year = scope.year
44
+ if not is_tiger_year(year):
45
+ raise DataResourceError(
46
+ f"{year} is not a supported year for us_tiger attributes."
47
+ )
48
+ return year
49
+
50
+
51
+ def _get_geo(scope: CensusScope, progress: ProgressCallback) -> GeoDataFrame:
52
+ year = _validate_year(scope)
53
+ match scope.granularity:
54
+ case "state":
55
+ gdf = get_states_geo(year, progress)
56
+ case "county":
57
+ gdf = get_counties_geo(year, progress)
58
+ case "tract":
59
+ gdf = get_tracts_geo(
60
+ year,
61
+ list({STATE.extract(x) for x in scope.node_ids}),
62
+ progress,
63
+ )
64
+ case "block group":
65
+ gdf = get_block_groups_geo(
66
+ year,
67
+ list({STATE.extract(x) for x in scope.node_ids}),
68
+ progress,
69
+ )
70
+ case x:
71
+ raise DataResourceError(
72
+ f"{x} is not a supported granularity for us_tiger attributes."
73
+ )
74
+ geoid_df = DataFrame({"GEOID": scope.node_ids})
75
+ return GeoDataFrame(geoid_df.merge(gdf, on="GEOID", how="left", sort=True))
76
+
77
+
78
+ def _get_info(scope: CensusScope, progress: ProgressCallback) -> DataFrame:
79
+ year = _validate_year(scope)
80
+ match scope.granularity:
81
+ case "state":
82
+ gdf = get_states_info(year, progress)
83
+ case "county":
84
+ gdf = get_counties_info(year, progress)
85
+ case "tract":
86
+ gdf = get_tracts_info(
87
+ year,
88
+ list({STATE.extract(x) for x in scope.node_ids}),
89
+ progress,
90
+ )
91
+ case "block group":
92
+ gdf = get_block_groups_info(
93
+ year,
94
+ list({STATE.extract(x) for x in scope.node_ids}),
95
+ progress,
96
+ )
97
+ case x:
98
+ raise DataResourceError(
99
+ f"{x} is not a supported granularity for us_tiger attributes."
100
+ )
101
+ geoid_df = DataFrame({"GEOID": scope.node_ids})
102
+ return geoid_df.merge(gdf, on="GEOID", how="left", sort=True)
103
+
104
+
105
+ T_co = TypeVar("T_co", bound=np.generic)
106
+
107
+
108
+ class _USTigerAdrio(ADRIO[T_co], ABC):
109
+ """Abstract class for shared functionality in US Tiger ADRIOs."""
110
+
111
+ def estimate_data(self) -> DataEstimate:
112
+ scope = _validate_scope(self.scope)
113
+ year = _validate_year(scope)
114
+ match scope.granularity:
115
+ case "state":
116
+ est = check_cache_states(year)
117
+ case "county":
118
+ est = check_cache_counties(year)
119
+ case "tract":
120
+ states = list(STATE.truncate_unique(scope.node_ids))
121
+ est = check_cache_tracts(year, states)
122
+ case "block group":
123
+ states = list(STATE.truncate_unique(scope.node_ids))
124
+ est = check_cache_block_groups(year, states)
125
+ case x:
126
+ raise DataResourceError(
127
+ f"{x} is not a supported granularity for us_tiger attributes."
128
+ )
129
+ key = f"us_tiger:{scope.granularity}:{year}"
130
+ return AvailableDataEstimate(
131
+ name=self.class_name,
132
+ cache_key=key,
133
+ new_network_bytes=est.missing_cache_size,
134
+ new_cache_bytes=est.missing_cache_size,
135
+ total_cache_bytes=est.total_cache_size,
136
+ max_bandwidth=None,
137
+ )
138
+
139
+
140
+ @adrio_cache
141
+ class GeometricCentroid(_USTigerAdrio[StructDType]):
142
+ """The centroid of the geographic polygons."""
143
+
144
+ @override
145
+ def evaluate_adrio(self):
146
+ scope = _validate_scope(self.scope)
147
+ return (
148
+ _get_geo(scope, self.progress)["geometry"]
149
+ .apply(lambda x: x.centroid.coords[0]) # type: ignore
150
+ .to_numpy(dtype=CentroidDType)
151
+ )
152
+
153
+
154
+ @adrio_cache
155
+ class InternalPoint(_USTigerAdrio[StructDType]):
156
+ """
157
+ The internal point provided by TIGER data. These points are selected by
158
+ Census workers so as to be guaranteed to be within the geographic polygons,
159
+ while geometric centroids have no such guarantee.
160
+ """
161
+
162
+ @override
163
+ def evaluate_adrio(self):
164
+ scope = _validate_scope(self.scope)
165
+ info_df = _get_info(scope, self.progress)
166
+ centroids = zip(
167
+ to_numeric(info_df["INTPTLON"]),
168
+ to_numeric(info_df["INTPTLAT"]),
169
+ )
170
+ return np.array(list(centroids), dtype=CentroidDType)
171
+
172
+
173
+ @adrio_cache
174
+ class Name(_USTigerAdrio[np.str_]):
175
+ """For states and counties, the proper name of the location; otherwise its GEOID."""
176
+
177
+ @override
178
+ def evaluate_adrio(self):
179
+ scope = _validate_scope(self.scope)
180
+ if scope.granularity in ("state", "county"):
181
+ info_df = _get_info(scope, self.progress)
182
+ return info_df["NAME"].to_numpy(dtype=np.str_)
183
+ else:
184
+ # There aren't good names for Tracts or CBGs, just use GEOID
185
+ return scope.node_ids
186
+
187
+
188
+ @adrio_cache
189
+ class PostalCode(_USTigerAdrio[np.str_]):
190
+ """
191
+ For states only, the postal code abbreviation for the state
192
+ ("AZ" for Arizona, and so on).
193
+ """
194
+
195
+ @override
196
+ def evaluate_adrio(self):
197
+ scope = _validate_scope(self.scope)
198
+ if scope.granularity != "state":
199
+ raise DataResourceError(
200
+ "PostalCode is only available at state granularity."
201
+ )
202
+ info_df = _get_info(scope, self.progress)
203
+ return info_df["STUSPS"].to_numpy(dtype=np.str_)
204
+
205
+
206
+ @adrio_cache
207
+ class LandAreaM2(_USTigerAdrio[np.float64]):
208
+ """
209
+ The land area of the geo node in meters-squared. This is the 'ALAND' attribute
210
+ from the TIGER data files.
211
+ """
212
+
213
+ @override
214
+ def evaluate_adrio(self):
215
+ scope = _validate_scope(self.scope)
216
+ info_df = _get_info(scope, self.progress)
217
+ return info_df["ALAND"].to_numpy(dtype=np.float64)