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/acs5.py ADDED
@@ -0,0 +1,1378 @@
1
+ """ADRIOs for access US Census Bureau American Community Survey data."""
2
+
3
+ import os
4
+ import re
5
+ from abc import abstractmethod
6
+ from functools import cache, reduce
7
+ from itertools import groupby
8
+ from json import load as load_json
9
+ from typing import Callable, Iterable, Literal, NamedTuple, Sequence, TypeGuard, cast
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ import requests
14
+ from numpy.typing import NDArray
15
+ from typing_extensions import override
16
+
17
+ from epymorph.adrio.adrio import (
18
+ ADRIO,
19
+ ADRIOCommunicationError,
20
+ ADRIOContextError,
21
+ ADRIOProcessingError,
22
+ FetchADRIO,
23
+ InspectResult,
24
+ PipelineResult,
25
+ ResultT,
26
+ ValueT,
27
+ adrio_cache,
28
+ adrio_validate_pipe,
29
+ )
30
+ from epymorph.adrio.processing import (
31
+ DataPipeline,
32
+ DontFix,
33
+ Fill,
34
+ FillLikeFloat,
35
+ FillLikeInt,
36
+ Fix,
37
+ FixLikeFloat,
38
+ FixLikeInt,
39
+ PivotAxis,
40
+ )
41
+ from epymorph.adrio.validation import (
42
+ ResultFormat,
43
+ validate_dtype,
44
+ validate_numpy,
45
+ validate_shape,
46
+ validate_values_in_range,
47
+ )
48
+ from epymorph.attribute import AttributeDef
49
+ from epymorph.cache import load_or_fetch_url, module_cache_path
50
+ from epymorph.data_shape import Shapes
51
+ from epymorph.error import MissingContextError
52
+ from epymorph.geography.us_census import (
53
+ BlockGroupScope,
54
+ CensusScope,
55
+ CountyScope,
56
+ StateScope,
57
+ TractScope,
58
+ )
59
+ from epymorph.geography.us_geography import (
60
+ BLOCK_GROUP,
61
+ COUNTY,
62
+ TRACT,
63
+ CensusGranularity,
64
+ )
65
+ from epymorph.simulation import Context
66
+ from epymorph.util import filter_unique, filter_with_mask
67
+
68
+
69
+ def census_api_key() -> str | None:
70
+ """
71
+ Load the API key to use for census.gov,
72
+ as environment variable 'API_KEY__census.gov'.
73
+ If that's not found we fall back to 'CENSUS_API_KEY',
74
+ as a legacy form.
75
+
76
+ Returns
77
+ -------
78
+ :
79
+ The key, or `None` if it's not set.
80
+ """
81
+ key = os.environ.get("API_KEY__census.gov", default=None)
82
+ if key is None:
83
+ key = os.environ.get("CENSUS_API_KEY", default=None)
84
+ return key
85
+
86
+
87
+ # fmt:off
88
+ ACS5Year = Literal[2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023] # noqa: E501
89
+ """A supported ACS5 data year."""
90
+
91
+ ACS5_YEARS: Sequence[ACS5Year] = (2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023) # noqa: E501
92
+ """All supported ACS5 data years."""
93
+ # fmt: on
94
+
95
+ _ACS5_CACHE_PATH = module_cache_path(__name__)
96
+ """
97
+ For caching ACS5. At the moment, the only thing that is cached is variables metadata.
98
+ """
99
+
100
+
101
+ class ACS5Client:
102
+ """
103
+ Methods for interacting with the Census API for ACS5 data. Typical usage will not
104
+ need to use this class, but it's provided for advanced cases.
105
+ """
106
+
107
+ @staticmethod
108
+ def url(year: int) -> str:
109
+ """
110
+ Get the base request URL for a given ACS5 year.
111
+
112
+ Parameters
113
+ ----------
114
+ year :
115
+ The ACS5 data vintage year.
116
+
117
+ Returns
118
+ -------
119
+ :
120
+ The formatted base url.
121
+ """
122
+ return f"https://api.census.gov/data/{year}/acs/acs5"
123
+
124
+ @cache
125
+ @staticmethod
126
+ def get_vars(year: int) -> dict[str, dict]:
127
+ """
128
+ Load (and caches) ACS5 variable metadata. This metadata is published by the
129
+ Census alongside the data for each year.
130
+
131
+ Parameters
132
+ ----------
133
+ year :
134
+ The ACS5 data vintage year.
135
+
136
+ Returns
137
+ -------
138
+ :
139
+ A dictionary of metadata about available variables,
140
+ where the key is a variable name and values are
141
+ also dictionaries containing the metadata pertaining
142
+ to the variable.
143
+ """
144
+ try:
145
+ vars_url = f"{ACS5Client.url(year)}/variables.json"
146
+ cache_path = _ACS5_CACHE_PATH / f"variables-{year}.json"
147
+ file = load_or_fetch_url(vars_url, cache_path)
148
+ return load_json(file)["variables"]
149
+ except Exception as e:
150
+ err = "Unable to load ACS5 variables."
151
+ raise Exception(err) from e
152
+
153
+ @cache
154
+ @staticmethod
155
+ def get_group_vars(year: int, group: str) -> list[tuple[str, dict]]:
156
+ """
157
+ Retrieve the variables metadata for a specific group of variables.
158
+ This is equivalent to calling `get_vars` and then filtering to the
159
+ variables in the group.
160
+
161
+ Parameters
162
+ ----------
163
+ year :
164
+ The ACS5 data vintage year.
165
+ group :
166
+ The name of the group to fetch.
167
+
168
+ Returns
169
+ -------
170
+ :
171
+ Variable metadata for all variables in the group.
172
+ """
173
+ variables = sorted(
174
+ (
175
+ (name, attrs)
176
+ for name, attrs in ACS5Client.get_vars(year).items()
177
+ if attrs["group"] == group
178
+ ),
179
+ key=lambda x: x[0],
180
+ )
181
+ if len(variables) == 0:
182
+ raise ValueError(f"ACS5 variable group '{group}' not found in year {year}.")
183
+ return variables
184
+
185
+ @cache
186
+ @staticmethod
187
+ def get_group_var_names(year: int, group: str) -> list[str]:
188
+ """
189
+ Like `get_group_vars` but just returns the variable names in the group.
190
+
191
+ Parameters
192
+ ----------
193
+ year :
194
+ The ACS5 data vintage year.
195
+ group :
196
+ The name of the group to fetch.
197
+
198
+ Returns
199
+ -------
200
+ :
201
+ The names of all variables in the group.
202
+ """
203
+ return [var for var, _ in ACS5Client.get_group_vars(year, group)]
204
+
205
+ @staticmethod
206
+ def make_queries(scope: CensusScope) -> list[dict[str, str]]:
207
+ """
208
+ Create one or more Census API query predicates for the given scope.
209
+ These may involve the "for" and "in" request parameters.
210
+ Depending on your scope and the limitations of the API, multiple queries
211
+ may be required, especially when your scope represents a disjoint spatial
212
+ selection or one that otherwise can't be neatly expressed in a form like
213
+ "all counties within state X".
214
+
215
+ Parameters
216
+ ----------
217
+ scope :
218
+ The geo scope for which to make a query.
219
+
220
+ Returns
221
+ -------
222
+ :
223
+ The list of queries necessary to cover the scope. As defined by the Census
224
+ API, individual queries are in the form of key/value pairs of strings.
225
+ """
226
+
227
+ def to_list(group: Iterable[tuple[str, ...]]) -> str:
228
+ return ",".join(map(lambda x: x[-1], group))
229
+
230
+ match scope:
231
+ case StateScope(includes_granularity="state", includes=includes):
232
+ if scope.is_all_states():
233
+ return [{"for": "state:*"}]
234
+ else:
235
+ return [{"for": f"state:{','.join(includes)}"}]
236
+
237
+ case CountyScope(includes_granularity="state", includes=includes):
238
+ return [
239
+ {
240
+ "for": "county:*",
241
+ "in": f"state:{','.join(includes)}",
242
+ }
243
+ ]
244
+
245
+ case CountyScope(includes_granularity="county", includes=includes):
246
+ return [
247
+ {"for": f"county:{to_list(group)}", "in": f"state:{state}"}
248
+ for (state,), group in groupby(
249
+ map(COUNTY.decompose, includes),
250
+ key=lambda x: x[0:-1],
251
+ )
252
+ ]
253
+
254
+ case TractScope(includes_granularity="state", includes=includes):
255
+ return [
256
+ {
257
+ "for": "tract:*",
258
+ "in": f"state:{','.join(includes)} county:*",
259
+ }
260
+ ]
261
+
262
+ case TractScope(includes_granularity="county", includes=includes):
263
+ return [
264
+ {"for": "tract:*", "in": f"state:{state} county:{to_list(group)}"}
265
+ for (state,), group in groupby(
266
+ map(COUNTY.decompose, includes),
267
+ key=lambda x: x[0:-1],
268
+ )
269
+ ]
270
+
271
+ case TractScope(includes_granularity="tract", includes=includes):
272
+ return [
273
+ {
274
+ "for": f"tract:{to_list(group)}",
275
+ "in": f"state:{state} county:{county}",
276
+ }
277
+ for (state, county), group in groupby(
278
+ map(TRACT.decompose, includes),
279
+ key=lambda x: x[0:-1],
280
+ )
281
+ ]
282
+
283
+ case BlockGroupScope(includes_granularity="state", includes=includes):
284
+ # This wouldn't normally need to be multiple queries,
285
+ # but Census API won't let you fetch CBGs for multiple states.
286
+ return [
287
+ {"for": "block group:*", "in": f"state:{state} county:* tract:*"}
288
+ for state in includes
289
+ ]
290
+
291
+ case BlockGroupScope(includes_granularity="county", includes=includes):
292
+ return [
293
+ {
294
+ "for": "block group:*",
295
+ "in": f"state:{state} county:{to_list(group)} tract:*",
296
+ }
297
+ for (state,), group in groupby(
298
+ map(COUNTY.decompose, includes),
299
+ key=lambda x: x[0:-1],
300
+ )
301
+ ]
302
+
303
+ case BlockGroupScope(includes_granularity="tract", includes=includes):
304
+ return [
305
+ {
306
+ "for": "block group:*",
307
+ "in": f"state:{state} county:{county} tract:{to_list(group)}",
308
+ }
309
+ for (state, county), group in groupby(
310
+ map(TRACT.decompose, includes),
311
+ key=lambda x: x[0:-1],
312
+ )
313
+ ]
314
+
315
+ case BlockGroupScope(includes_granularity="block group", includes=includes):
316
+ return [
317
+ {
318
+ "for": f"block group:{to_list(group)}",
319
+ "in": f"state:{state} county:{county} tract:{tract}",
320
+ }
321
+ for (state, county, tract), group in groupby(
322
+ map(BLOCK_GROUP.decompose, includes),
323
+ key=lambda x: x[0:-1],
324
+ )
325
+ ]
326
+
327
+ case _:
328
+ err = "Unsupported geo scope."
329
+ raise Exception(err)
330
+
331
+ @staticmethod
332
+ def fetch(
333
+ scope: CensusScope,
334
+ variables: list[str],
335
+ value_dtype: type[np.generic],
336
+ report_progress: Callable[[float], None] | None = None,
337
+ ) -> pd.DataFrame:
338
+ """
339
+ Request `variables` from the Census API for the given `scope`.
340
+
341
+ Parameters
342
+ ----------
343
+ scope :
344
+ The geo scope to query.
345
+ variables :
346
+ The list of variables to query.
347
+ value_dtype :
348
+ The dtype of the result array.
349
+ report_progress :
350
+ A callback for reporting query progress; especially useful when the scope
351
+ necessitates multiple queries.
352
+
353
+ Returns
354
+ -------
355
+ :
356
+ A dataframe in "long" format, with columns: geoid, variable, and value.
357
+ Geoid and variable are strings and value will be converted to the given
358
+ dtype.
359
+ """
360
+ url = ACS5Client.url(scope.year)
361
+ params = {
362
+ "key": census_api_key(),
363
+ "get": ",".join(["GEO_ID", *variables]),
364
+ }
365
+ queries = ACS5Client.make_queries(scope)
366
+ processing_steps = len(queries) + 1
367
+ with requests.Session() as session:
368
+ results = []
369
+ for i, q in enumerate(queries):
370
+ response = session.get(
371
+ url,
372
+ params={**params, **q},
373
+ timeout=30,
374
+ )
375
+ response.raise_for_status() # Raise an error for bad status codes
376
+ [columns, *rows] = response.json()
377
+
378
+ # keep all estimate columns
379
+ estimate_var = re.compile(r".*?_\d\d\dE$")
380
+ column_sel = [i for i, x in enumerate(columns) if estimate_var.match(x)]
381
+
382
+ # convert to "long" DataFrame
383
+ result_df = pd.DataFrame.from_records(
384
+ [
385
+ # drop ucgid prefix from geoid, e.g., "0500000US"
386
+ (row[0][9:], columns[col], row[col])
387
+ for row in rows
388
+ for col in column_sel
389
+ ],
390
+ columns=["geoid", "variable", "value"],
391
+ index="geoid",
392
+ )
393
+ result_df["value"] = result_df["value"].astype(value_dtype)
394
+
395
+ results.append(result_df)
396
+ if report_progress:
397
+ report_progress((i + 1) / processing_steps)
398
+
399
+ return pd.concat(results).sort_index()
400
+
401
+
402
+ class _ACS5Mixin(ADRIO):
403
+ """Common ADRIO logic for ACS5 ADRIOs."""
404
+
405
+ @override
406
+ def validate_context(self, context: Context) -> None:
407
+ if census_api_key() is None:
408
+ err = (
409
+ "Census API key is required for accessing ACS5 data. "
410
+ "Please set the environment variable 'CENSUS_API_KEY'"
411
+ )
412
+ raise ADRIOContextError(self, context, err)
413
+ try:
414
+ scope = context.scope # scope is required
415
+ except MissingContextError as e:
416
+ raise ADRIOContextError(self, self.context, str(e))
417
+ if not isinstance(scope, CensusScope):
418
+ err = "US Census geo scope required."
419
+ raise ADRIOContextError(self, context, err)
420
+ if scope.year not in ACS5_YEARS:
421
+ err = f"{scope.year} is not a supported year for ACS5 data."
422
+ raise ADRIOContextError(self, context, err)
423
+ if isinstance(scope, BlockGroupScope) and scope.year <= 2012:
424
+ err = (
425
+ "Block group ACS5 data is not available via this API for 2012 or prior."
426
+ )
427
+ raise ADRIOContextError(self, context, err)
428
+
429
+
430
+ class _ACS5FetchMixin(_ACS5Mixin, FetchADRIO[ResultT, ValueT]):
431
+ """
432
+ Mixin implementing some of `FetchADRIO`'s API for ADRIOs which fetch
433
+ data from the ACS5 API. At a minimum, implementors will need to
434
+ provide an initializer to set Fix/Fill values, and override `result_format`,
435
+ `validate_result`, and `_variables` -- that is sufficient for simple cases.
436
+ """
437
+
438
+ # sentinel values: https://www.census.gov/data/developers/data-sets/acs-1year/notes-on-acs-estimate-and-annotation-values.html
439
+
440
+ _fix_insufficient_data: Fix[ValueT]
441
+ """
442
+ The method to use to replace values that could not be computed due to an
443
+ insufficient number of sample observation (-666666666 in the data).
444
+ """
445
+ _fix_missing: Fill[ValueT]
446
+ """The method to use to fix missing values."""
447
+
448
+ @property
449
+ @abstractmethod
450
+ def _variables(self) -> list[str]:
451
+ """The ACS variables to fetch for this ADRIO."""
452
+
453
+ @override
454
+ def _fetch(self, context: Context) -> pd.DataFrame:
455
+ scope = cast(CensusScope, self.context.scope)
456
+ try:
457
+ return ACS5Client.fetch(
458
+ scope=scope,
459
+ variables=self._variables,
460
+ value_dtype=self.result_format.dtype.type,
461
+ report_progress=self._report_progress,
462
+ )
463
+ except Exception as e:
464
+ raise ADRIOCommunicationError(self, context) from e
465
+
466
+ @override
467
+ def _process(
468
+ self,
469
+ context: Context,
470
+ data_df: pd.DataFrame,
471
+ ) -> PipelineResult[ResultT]:
472
+ scope = cast(CensusScope, self.context.scope)
473
+ vrbs = self._variables
474
+
475
+ # If we're loading a group variable, expand it.
476
+ if len(vrbs) == 1 and (m := re.match(r"^group\((.*?)\)$", vrbs[0])):
477
+ group_name = m.group(1)
478
+ vrbs = ACS5Client.get_group_var_names(scope.year, group_name)
479
+
480
+ value_dtype = self.result_format.dtype.type
481
+ pipeline = (
482
+ DataPipeline(
483
+ axes=(
484
+ PivotAxis("geoid", context.scope.node_ids),
485
+ PivotAxis("variable", vrbs),
486
+ ),
487
+ ndims=1 if len(vrbs) == 1 else 2,
488
+ dtype=value_dtype,
489
+ rng=context,
490
+ )
491
+ .strip_sentinel(
492
+ "insufficient_data",
493
+ value_dtype(-666666666),
494
+ self._fix_insufficient_data,
495
+ )
496
+ .finalize(self._fix_missing)
497
+ )
498
+ return pipeline(data_df)
499
+
500
+
501
+ @adrio_cache
502
+ class Population(_ACS5FetchMixin, FetchADRIO[np.int64, np.int64]):
503
+ """
504
+ Loads population data from the US Census ACS 5-Year Data (variable B01001_001E).
505
+ ACS5 data is compiled from surveys taken during a rolling five year period, and
506
+ as such are estimates.
507
+
508
+ Data is available using `CensusScope` geographies, from `StateScope` down to
509
+ `BlockGroupScope` (aggregates are computed by the Census Bureau). Data is loaded
510
+ according to the scope's year, from 2009 to 2023.
511
+
512
+ The result is an N-shaped array of integers.
513
+
514
+ Parameters
515
+ ----------
516
+ fix_insufficient_data :
517
+ The method to use to replace values that could not be computed due to an
518
+ insufficient number of sample observation (-666666666 in the data).
519
+ fix_missing :
520
+ The method to use to fix missing values.
521
+
522
+ See Also
523
+ --------
524
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
525
+ from the US Census.
526
+ """
527
+
528
+ def __init__(
529
+ self,
530
+ *,
531
+ fix_insufficient_data: FixLikeInt = False,
532
+ fix_missing: FillLikeInt = False,
533
+ ):
534
+ self._fix_insufficient_data = Fix.of_int64(fix_insufficient_data)
535
+ self._fix_missing = Fill.of_int64(fix_missing)
536
+
537
+ @property
538
+ @override
539
+ def result_format(self) -> ResultFormat:
540
+ return ResultFormat(shape=Shapes.N, dtype=np.int64)
541
+
542
+ @override
543
+ def validate_result(self, context: Context, result: NDArray) -> None:
544
+ adrio_validate_pipe(
545
+ self,
546
+ context,
547
+ result,
548
+ validate_numpy(),
549
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
550
+ validate_dtype(self.result_format.dtype),
551
+ validate_values_in_range(0, None),
552
+ )
553
+
554
+ @property
555
+ @override
556
+ def _variables(self) -> list[str]:
557
+ return ["B01001_001E"]
558
+
559
+
560
+ @adrio_cache
561
+ class PopulationByAgeTable(_ACS5FetchMixin, FetchADRIO[np.int64, np.int64]):
562
+ """
563
+ Loads a table of population categorized by Census-defined age brackets from the
564
+ US Census ACS 5-Year Data (group B01001). This table is most useful as the source
565
+ data for one or more `PopulationByAge` ADRIOs, which knows how to select, group,
566
+ and aggregate the data for simulations. ACS5 data is compiled from surveys taken
567
+ during a rolling five year period, and as such are estimates.
568
+
569
+ Data is available using `CensusScope` geographies, from `StateScope` down to
570
+ `BlockGroupScope` (aggregates are computed by the Census Bureau). Data is loaded
571
+ according to the scope's year, from 2009 to 2023.
572
+
573
+ The result is an NxA-shaped array of integers where A is the number of variables
574
+ included in the table. For example, in 2023 there are 49 variables: 23 age brackets
575
+ for male, 23 age brackets for female, the male all-ages total, the female all-ages
576
+ total, and a grand total.
577
+
578
+ Parameters
579
+ ----------
580
+ fix_insufficient_data :
581
+ The method to use to replace values that could not be computed due to an
582
+ insufficient number of sample observation (-666666666 in the data).
583
+ fix_missing :
584
+ The method to use to fix missing values.
585
+
586
+ See Also
587
+ --------
588
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
589
+ from the US Census, and [an example of this table for 2023](https://data.census.gov/table/ACSDT5Y2023.B01001).
590
+ """
591
+
592
+ def __init__(
593
+ self,
594
+ *,
595
+ fix_insufficient_data: FixLikeInt = False,
596
+ fix_missing: FillLikeInt = False,
597
+ ):
598
+ self._fix_insufficient_data = Fix.of_int64(fix_insufficient_data)
599
+ self._fix_missing = Fill.of_int64(fix_missing)
600
+
601
+ @property
602
+ @override
603
+ def result_format(self) -> ResultFormat:
604
+ return ResultFormat(shape=Shapes.NxA, dtype=np.int64)
605
+
606
+ @override
607
+ def validate_result(self, context: Context, result: NDArray) -> None:
608
+ scope = cast(CensusScope, self.scope)
609
+ variables = ACS5Client.get_group_var_names(scope.year, "B01001")
610
+ result_shape = (context.scope.nodes, len(variables))
611
+ adrio_validate_pipe(
612
+ self,
613
+ context,
614
+ result,
615
+ validate_numpy(),
616
+ validate_shape(result_shape),
617
+ validate_dtype(self.result_format.dtype),
618
+ validate_values_in_range(0, None),
619
+ )
620
+
621
+ @property
622
+ @override
623
+ def _variables(self) -> list[str]:
624
+ return ["group(B01001)"]
625
+
626
+
627
+ _exact_pattern = re.compile(r"^(\d+) years$")
628
+ _under_pattern = re.compile(r"^Under (\d+) years$")
629
+ _range_pattern = re.compile(r"^(\d+) (?:to|and) (\d+) years")
630
+ _over_pattern = re.compile(r"^(\d+) years and over")
631
+
632
+
633
+ class AgeRange(NamedTuple):
634
+ """
635
+ Models an age range for use with ACS age-categorized data.
636
+ Unlike Python integer ranges, the `end` of the this range is inclusive.
637
+ `end` can also be None which models the "and over" part of ranges
638
+ like "85 years and over".
639
+ """
640
+
641
+ start: int
642
+ """The youngest age included in the range."""
643
+ end: int | None
644
+ """The oldest age included in the range, or None to indicate an unbounded range."""
645
+
646
+ def contains(self, other: "AgeRange") -> bool:
647
+ """
648
+ Check if `other` range is fully contained in (or coincident with) this range.
649
+
650
+ Parameters
651
+ ----------
652
+ other :
653
+ The other age range to consider.
654
+
655
+ Returns
656
+ -------
657
+ :
658
+ True if the range is contained in this range.
659
+ """
660
+ if self.start > other.start:
661
+ return False
662
+ if self.end is None:
663
+ return True
664
+ if other.end is None:
665
+ return False
666
+ return self.end >= other.end
667
+
668
+ @staticmethod
669
+ def parse(label: str) -> "AgeRange | None":
670
+ """
671
+ Parse the age range of an ACS field label.
672
+
673
+ For example: `Estimate!!Total:!!Male:!!22 to 24 years`.
674
+
675
+ Parameters
676
+ ----------
677
+ label :
678
+ A census variable label.
679
+
680
+ Returns
681
+ -------
682
+ :
683
+ The `AgeRange` object if parsing is successful, `None` if not.
684
+ """
685
+ parts = label.split("!!")
686
+ if len(parts) != 4:
687
+ return None
688
+ bracket = parts[-1]
689
+ if (m := _exact_pattern.match(bracket)) is not None:
690
+ start = int(m.group(1))
691
+ end = start
692
+ elif (m := _under_pattern.match(bracket)) is not None:
693
+ start = 0
694
+ end = int(m.group(1)) - 1
695
+ elif (m := _range_pattern.match(bracket)) is not None:
696
+ start = int(m.group(1))
697
+ end = int(m.group(2))
698
+ elif (m := _over_pattern.match(bracket)) is not None:
699
+ start = int(m.group(1))
700
+ end = None
701
+ else:
702
+ raise ValueError(f"No match for {label}")
703
+ return AgeRange(start, end)
704
+
705
+
706
+ @adrio_cache
707
+ class PopulationByAge(_ACS5Mixin, ADRIO[np.int64, np.int64]):
708
+ """
709
+ Processes a population-by-age table to extract the population of a specified age
710
+ bracket, as limited by the age brackets defined by the US Census ACS 5-Year Data
711
+ (group B01001). This ADRIO does not fetch data on its own, but requires you to
712
+ provide another attribute named "population_by_age_table" for it to parse.
713
+ Most often, this will be provided by a `PopulationByAgeTable` instance.
714
+ This allows the table to be reused in case you need to calculate more than one
715
+ population bracket (as is common in a multi-strata model).
716
+
717
+ The result is an N-shaped array of integers.
718
+
719
+ Parameters
720
+ ----------
721
+ age_range_start :
722
+ The youngest age to include in the age bracket.
723
+ age_range_end :
724
+ The oldest age to include in the age bracket, or None to indicate an unbounded
725
+ range (include all ages greater than or equal to `age_range_start`).
726
+
727
+ Raises
728
+ ------
729
+ ValueError
730
+ If the given age range does not line up with those ranges which are available
731
+ in the source data. For instance, the Census defines an age bracket of 20-to-24
732
+ years. This makes it impossible for 21, 22, or 23 to be either the start or end
733
+ of an age range. You can view the available age ranges on
734
+ [data.census.gov](https://data.census.gov/table/ACSDT5Y2023.B01001).
735
+
736
+ See Also
737
+ --------
738
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
739
+ from the US Census, and [an example of this table for 2023](https://data.census.gov/table/ACSDT5Y2023.B01001).
740
+ """
741
+
742
+ # a nice feature would be for ADRIOs to suggest defaults for their requirements,
743
+ # so if someone doesn't provide a 'population_by_age_table' for us, we can add
744
+ # it to the requirements resolution automatically; have to make sure this is done
745
+ # so that it's re-usable by other matching suggestions
746
+ # (e.g., three different PopByAge)
747
+
748
+ POP_BY_AGE_TABLE = AttributeDef("population_by_age_table", int, Shapes.NxA)
749
+ """Defines the population-by-age-table requirement of this ADRIO."""
750
+
751
+ requirements = (POP_BY_AGE_TABLE,)
752
+
753
+ _age_range: AgeRange
754
+ """The age range to load with this ADRIO."""
755
+
756
+ def __init__(self, age_range_start: int, age_range_end: int | None):
757
+ self._age_range = AgeRange(age_range_start, age_range_end)
758
+
759
+ @property
760
+ @override
761
+ def result_format(self) -> ResultFormat:
762
+ return ResultFormat(shape=Shapes.N, dtype=np.int64)
763
+
764
+ @override
765
+ def validate_result(self, context: Context, result: NDArray) -> None:
766
+ adrio_validate_pipe(
767
+ self,
768
+ context,
769
+ result,
770
+ validate_numpy(),
771
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
772
+ validate_dtype(self.result_format.dtype),
773
+ validate_values_in_range(0, None),
774
+ )
775
+
776
+ @override
777
+ def inspect(self) -> InspectResult[np.int64, np.int64]:
778
+ self.validate_context(self.context)
779
+ scope = cast(CensusScope, self.scope)
780
+
781
+ # NOTE: we don't use the age_ranges() static method here because it's important
782
+ # for us to keep one value per column, even for columns which don't
783
+ # correspond to an age group (total, total male, total female).
784
+ age_ranges = [
785
+ AgeRange.parse(attrs["label"])
786
+ for var, attrs in ACS5Client.get_group_vars(scope.year, "B01001")
787
+ ]
788
+
789
+ adrio_range = self._age_range
790
+
791
+ def is_included(x: AgeRange | None) -> TypeGuard[AgeRange]:
792
+ return x is not None and adrio_range.contains(x)
793
+
794
+ included, col_mask = filter_with_mask(age_ranges, is_included)
795
+
796
+ # At least one var must have its start equal to the ADRIO range
797
+ if not any((x.start == adrio_range.start for x in included)):
798
+ raise ADRIOProcessingError(self, self.context, f"bad start {adrio_range}")
799
+ # At least one var must have its end equal to the ADRIO range
800
+ if not any((x.end == adrio_range.end for x in included)):
801
+ raise ADRIOProcessingError(self, self.context, f"bad end {adrio_range}")
802
+
803
+ source_np = self.data(PopulationByAge.POP_BY_AGE_TABLE)
804
+ result_np = source_np[:, col_mask].sum(axis=1)
805
+
806
+ self.validate_result(self.context, result_np)
807
+ return InspectResult(
808
+ adrio=self,
809
+ source=source_np,
810
+ result=result_np,
811
+ dtype=self.result_format.dtype.type,
812
+ shape=self.result_format.shape,
813
+ issues={},
814
+ )
815
+
816
+ @staticmethod
817
+ def age_ranges(year: int) -> Sequence[AgeRange]:
818
+ """
819
+ List the age ranges used by the ACS5 population by age table in definition
820
+ order for the given year. Note that this does not correspond one-to-one with the
821
+ values in the B01001 table -- this list omits "total" columns and duplicates.
822
+
823
+ Parameters
824
+ ----------
825
+ year :
826
+ A supported ACS5 year.
827
+
828
+ Returns
829
+ -------
830
+ :
831
+ The age ranges.
832
+ """
833
+ return filter_unique(
834
+ x
835
+ for x in (
836
+ AgeRange.parse(attrs["label"])
837
+ for _, attrs in ACS5Client.get_group_vars(year, "B01001")
838
+ )
839
+ if x is not None
840
+ )
841
+
842
+
843
+ # fmt: off
844
+ RaceCategory = Literal["White", "Black", "Native", "Asian", "Pacific Islander", "Other", "Multiple"] # noqa: E501
845
+ """A racial category defined by ACS5."""
846
+ # fmt: on
847
+
848
+
849
+ @adrio_cache
850
+ class PopulationByRace(_ACS5FetchMixin, FetchADRIO[np.int64, np.int64]):
851
+ """
852
+ Loads population by race from the US Census ACS 5-Year Data (group B02001).
853
+ ACS5 data is compiled from surveys taken during a rolling five year period, and
854
+ as such are estimates.
855
+
856
+ Data is available using `CensusScope` geographies, from `StateScope` down to
857
+ `BlockGroupScope` (aggregates are computed by the Census Bureau). Data is loaded
858
+ according to the scope's year, from 2009 to 2023.
859
+
860
+ The result is an N-shaped array of integers.
861
+
862
+ Parameters
863
+ ----------
864
+ race :
865
+ The Census-defined race category to load.
866
+ fix_insufficient_data :
867
+ The method to use to fix values for which there were insufficient data to report
868
+ (sentinel value: -666666666).
869
+ fix_missing :
870
+ The method to use to fix missing values.
871
+
872
+ See Also
873
+ --------
874
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
875
+ from the US Census.
876
+ """ # noqa: E501
877
+
878
+ _RACE_VARIABLES: dict[RaceCategory, str] = {
879
+ "White": "B02001_002E",
880
+ "Black": "B02001_003E",
881
+ "Native": "B02001_004E",
882
+ "Asian": "B02001_005E",
883
+ "Pacific Islander": "B02001_006E",
884
+ "Other": "B02001_007E",
885
+ "Multiple": "B02001_008E",
886
+ }
887
+
888
+ _race: RaceCategory
889
+ """The race category to load."""
890
+
891
+ def __init__(
892
+ self,
893
+ race: RaceCategory,
894
+ *,
895
+ fix_insufficient_data: FixLikeInt = False,
896
+ fix_missing: FillLikeInt = False,
897
+ ):
898
+ self._race = race
899
+ self._fix_insufficient_data = Fix.of_int64(fix_insufficient_data)
900
+ self._fix_missing = Fill.of_int64(fix_missing)
901
+
902
+ @property
903
+ @override
904
+ def result_format(self) -> ResultFormat:
905
+ return ResultFormat(shape=Shapes.N, dtype=np.int64)
906
+
907
+ @override
908
+ def validate_result(self, context: Context, result: NDArray) -> None:
909
+ adrio_validate_pipe(
910
+ self,
911
+ context,
912
+ result,
913
+ validate_numpy(),
914
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
915
+ validate_dtype(self.result_format.dtype),
916
+ validate_values_in_range(0, None),
917
+ )
918
+
919
+ @property
920
+ @override
921
+ def _variables(self) -> list[str]:
922
+ return [PopulationByRace._RACE_VARIABLES[self._race]]
923
+
924
+
925
+ @adrio_cache
926
+ class AverageHouseholdSize(_ACS5FetchMixin, FetchADRIO[np.float64, np.float64]):
927
+ """
928
+ Loads average household size data, based on the number of people living in a
929
+ household, from the US Census ACS 5-Year Data (variable B25010_001E).
930
+ ACS5 data is compiled from surveys taken during a rolling five year period, and
931
+ as such are estimates.
932
+
933
+ Data is available using `CensusScope` geographies, from `StateScope` down to
934
+ `BlockGroupScope` (aggregates are computed by the Census Bureau). Data is loaded
935
+ according to the scope's year, from 2009 to 2023.
936
+
937
+ The result is an N-shaped array of floats.
938
+
939
+ Parameters
940
+ ----------
941
+ fix_insufficient_data :
942
+ The method to use to fix values for which there were insufficient data to report
943
+ (sentinel value: -666666666).
944
+ fix_missing :
945
+ The method to use to fix missing values.
946
+
947
+ See Also
948
+ --------
949
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
950
+ from the US Census.
951
+ """ # noqa: E501
952
+
953
+ def __init__(
954
+ self,
955
+ *,
956
+ fix_insufficient_data: FixLikeFloat = False,
957
+ fix_missing: FillLikeFloat = False,
958
+ ):
959
+ self._fix_insufficient_data = Fix.of_float64(fix_insufficient_data)
960
+ self._fix_missing = Fill.of_float64(fix_missing)
961
+
962
+ @property
963
+ @override
964
+ def result_format(self) -> ResultFormat:
965
+ return ResultFormat(shape=Shapes.N, dtype=np.float64)
966
+
967
+ @override
968
+ def validate_result(self, context: Context, result: NDArray) -> None:
969
+ adrio_validate_pipe(
970
+ self,
971
+ context,
972
+ result,
973
+ validate_numpy(),
974
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
975
+ validate_dtype(self.result_format.dtype),
976
+ validate_values_in_range(0, None),
977
+ )
978
+
979
+ @property
980
+ @override
981
+ def _variables(self) -> list[str]:
982
+ return ["B25010_001E"]
983
+
984
+
985
+ @adrio_cache
986
+ class MedianAge(_ACS5FetchMixin, FetchADRIO[np.float64, np.float64]):
987
+ """
988
+ Loads median age data from the US Census ACS 5-Year Data (variable B01002_001E).
989
+ ACS5 data is compiled from surveys taken during a rolling five year period, and
990
+ as such are estimates.
991
+
992
+ Data is available using `CensusScope` geographies, from `StateScope` down to
993
+ `BlockGroupScope` (aggregates are computed by the Census Bureau). Data is loaded
994
+ according to the scope's year, from 2009 to 2023.
995
+
996
+ The result is an N-shaped array of floats.
997
+
998
+ Parameters
999
+ ----------
1000
+ fix_insufficient_data :
1001
+ The method to use to fix values for which there were insufficient data to report
1002
+ (sentinel value: -666666666).
1003
+ fix_missing :
1004
+ The method to use to fix missing values.
1005
+
1006
+ See Also
1007
+ --------
1008
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
1009
+ from the US Census.
1010
+ """ # noqa: E501
1011
+
1012
+ def __init__(
1013
+ self,
1014
+ *,
1015
+ fix_insufficient_data: FixLikeFloat = False,
1016
+ fix_missing: FillLikeFloat = False,
1017
+ ):
1018
+ self._fix_insufficient_data = Fix.of_float64(fix_insufficient_data)
1019
+ self._fix_missing = Fill.of_float64(fix_missing)
1020
+
1021
+ @property
1022
+ @override
1023
+ def result_format(self) -> ResultFormat:
1024
+ return ResultFormat(shape=Shapes.N, dtype=np.float64)
1025
+
1026
+ @override
1027
+ def validate_result(self, context: Context, result: NDArray) -> None:
1028
+ adrio_validate_pipe(
1029
+ self,
1030
+ context,
1031
+ result,
1032
+ validate_numpy(),
1033
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
1034
+ validate_dtype(self.result_format.dtype),
1035
+ validate_values_in_range(0, None),
1036
+ )
1037
+
1038
+ @property
1039
+ @override
1040
+ def _variables(self) -> list[str]:
1041
+ return ["B01002_001E"]
1042
+
1043
+
1044
+ @adrio_cache
1045
+ class MedianIncome(_ACS5FetchMixin, FetchADRIO[np.int64, np.int64]):
1046
+ """
1047
+ Loads median income data in whole dollars from the US Census ACS 5-Year Data
1048
+ (variable B19013_001E), which is adjusted for inflation to the year of the data.
1049
+ ACS5 data is compiled from surveys taken during a rolling five year period, and
1050
+ as such are estimates.
1051
+
1052
+ Data is available using `CensusScope` geographies, from `StateScope` down to
1053
+ `BlockGroupScope` (aggregates are computed by the Census Bureau). Data is loaded
1054
+ according to the scope's year, from 2009 to 2023.
1055
+
1056
+ The result is an N-shaped array of integers.
1057
+
1058
+ Parameters
1059
+ ----------
1060
+ fix_insufficient_data :
1061
+ The method to use to fix values for which there were insufficient data to report
1062
+ (sentinel value: -666666666).
1063
+ fix_missing :
1064
+ The method to use to fix missing values.
1065
+
1066
+ See Also
1067
+ --------
1068
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
1069
+ from the US Census.
1070
+ """ # noqa: E501
1071
+
1072
+ def __init__(
1073
+ self,
1074
+ *,
1075
+ fix_insufficient_data: FixLikeInt = False,
1076
+ fix_missing: FillLikeInt = False,
1077
+ ):
1078
+ self._fix_insufficient_data = Fix.of_int64(fix_insufficient_data)
1079
+ self._fix_missing = Fill.of_int64(fix_missing)
1080
+
1081
+ @property
1082
+ @override
1083
+ def result_format(self) -> ResultFormat:
1084
+ return ResultFormat(shape=Shapes.N, dtype=np.int64)
1085
+
1086
+ @override
1087
+ def validate_result(self, context: Context, result: NDArray) -> None:
1088
+ adrio_validate_pipe(
1089
+ self,
1090
+ context,
1091
+ result,
1092
+ validate_numpy(),
1093
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
1094
+ validate_dtype(self.result_format.dtype),
1095
+ validate_values_in_range(0, None),
1096
+ )
1097
+
1098
+ @property
1099
+ @override
1100
+ def _variables(self) -> list[str]:
1101
+ return ["B19013_001E"]
1102
+
1103
+
1104
+ @adrio_cache
1105
+ class GiniIndex(_ACS5FetchMixin, FetchADRIO[np.float64, np.float64]):
1106
+ """
1107
+ Loads Gini Index data from the US Census ACS 5-Year Data (variable B19083_001E).
1108
+ This is a measure of income inequality on a scale from 0 (perfect equality)
1109
+ to 1 (perfect inequality).
1110
+ ACS5 data is compiled from surveys taken during a rolling five year period, and
1111
+ as such are estimates.
1112
+
1113
+ Data is available using `CensusScope` geographies, from `StateScope` down to
1114
+ `BlockGroupScope` (aggregates are computed by the Census Bureau). Data is loaded
1115
+ according to the scope's year, from 2009 to 2023.
1116
+
1117
+ The result is an N-shaped array of floats.
1118
+
1119
+ Parameters
1120
+ ----------
1121
+ fix_insufficient_data :
1122
+ The method to use to fix values for which there were insufficient data to report
1123
+ (sentinel value: -666666666).
1124
+ fix_missing :
1125
+ The method to use to fix missing values.
1126
+
1127
+ See Also
1128
+ --------
1129
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
1130
+ from the US Census, and [general info on the Gini index](https://en.wikipedia.org/wiki/Gini_coefficient).
1131
+ """ # noqa: E501
1132
+
1133
+ # NOTE: the Gini index is named after its inventor, Corrado Gini, so this is the
1134
+ # correct capitalization
1135
+
1136
+ def __init__(
1137
+ self,
1138
+ *,
1139
+ fix_insufficient_data: FixLikeFloat = False,
1140
+ fix_missing: FillLikeFloat = False,
1141
+ ):
1142
+ self._fix_insufficient_data = Fix.of_float64(fix_insufficient_data)
1143
+ self._fix_missing = Fill.of_float64(fix_missing)
1144
+
1145
+ @property
1146
+ @override
1147
+ def result_format(self) -> ResultFormat:
1148
+ return ResultFormat(shape=Shapes.N, dtype=np.float64)
1149
+
1150
+ @override
1151
+ def validate_result(self, context: Context, result: NDArray) -> None:
1152
+ adrio_validate_pipe(
1153
+ self,
1154
+ context,
1155
+ result,
1156
+ validate_numpy(),
1157
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
1158
+ validate_dtype(self.result_format.dtype),
1159
+ validate_values_in_range(0, 1.0),
1160
+ )
1161
+
1162
+ @property
1163
+ @override
1164
+ def _variables(self) -> list[str]:
1165
+ return ["B19083_001E"]
1166
+
1167
+ @override
1168
+ def validate_context(self, context: Context) -> None:
1169
+ super(_ACS5Mixin, self).validate_context(context)
1170
+ if isinstance(context.scope, BlockGroupScope):
1171
+ err = "Gini index is not available for block group scope."
1172
+ raise ADRIOContextError(self, context, err)
1173
+
1174
+
1175
+ @adrio_cache
1176
+ class DissimilarityIndex(_ACS5Mixin, ADRIO[np.float64, np.float64]):
1177
+ """
1178
+ Calculates the Dissimilarity Index using US Census ACS 5-Year Data (group B02001).
1179
+ The dissimilarity index is a measure of segregation comparing two races.
1180
+ Typically one compares a majority to a minority race and so the names of parameters
1181
+ reflect this, but this relationship between races involved isn't strictly necessary.
1182
+ The numerical result can be interpreted as the percentage of "minority" individuals
1183
+ that would have to move in order for the geographic distribution of individuals
1184
+ within subdivisions of a location to match the distribution of individuals in the
1185
+ location as a whole.
1186
+ ACS5 data is compiled from surveys taken during a rolling five year period, and
1187
+ as such are estimates.
1188
+
1189
+ Data is available using `CensusScope` geographies, from `StateScope` down to
1190
+ `TractScope`. Data is loaded according to the scope's year, from 2009 to 2023.
1191
+ This ADRIO does not support `BlockGroupScope` because we the calculation of the index
1192
+ requires loading data at a finer granularity than the target granularity, and
1193
+ there is no ACS5 data below block groups.
1194
+
1195
+ The result is an N-shaped array of floats.
1196
+
1197
+ Parameters
1198
+ ----------
1199
+ majority_pop :
1200
+ The race category representing the majority population for the amount of
1201
+ segregation.
1202
+ minority_pop :
1203
+ The race category representing the minority population within the
1204
+ segregation analysis.
1205
+ fix_insufficient_population :
1206
+ The method to use to fix values for which there were insufficient data to report
1207
+ (sentinel value: -666666666).
1208
+ The replacement is performed on the underlying population by race data.
1209
+ fix_missing_population :
1210
+ The method to use to fix missing values. The replacement is performed on the
1211
+ underlying population by race data.
1212
+ fix_not_computable :
1213
+ The method to use to fix values for which we cannot compute a value because population
1214
+ numbers cannot be loaded for one or more of the populations involved.
1215
+
1216
+ See Also
1217
+ --------
1218
+ The [ACS 5-Year documentation](https://www.census.gov/data/developers/data-sets/acs-5year.html)
1219
+ from the US Census, and
1220
+ [general information about the dissimilarity index](https://en.wikipedia.org/wiki/Index_of_dissimilarity).
1221
+ """ # noqa: E501
1222
+
1223
+ _majority_pop: RaceCategory
1224
+ """The race category of the majority population of interest"""
1225
+ _minority_pop: RaceCategory
1226
+ """The race category of the minority population of interest"""
1227
+ _fix_insufficient_population: Fix[np.int64]
1228
+ """
1229
+ The method to use to replace population values that could not be computed due to an
1230
+ insufficient number of sample observation (-666666666 in the data).
1231
+ """
1232
+ _fix_missing_population: Fill[np.int64]
1233
+ """The method to use to fix missing population values."""
1234
+ _fix_minority_total_zero: Fix[np.float64]
1235
+ """
1236
+ The method to use to replace dissimilarity index values when the minority population
1237
+ is zero (which would cause a divide-by-zero error).
1238
+ """
1239
+
1240
+ def __init__(
1241
+ self,
1242
+ majority_pop: RaceCategory,
1243
+ minority_pop: RaceCategory,
1244
+ *,
1245
+ fix_insufficient_population: FixLikeInt = False,
1246
+ fix_missing_population: FillLikeInt = False,
1247
+ fix_not_computable: FixLikeFloat = False,
1248
+ ):
1249
+ self._majority_pop = majority_pop
1250
+ self._minority_pop = minority_pop
1251
+ self._fix_insufficient_population = Fix.of_int64(fix_insufficient_population)
1252
+ self._fix_missing_population = Fill.of_int64(fix_missing_population)
1253
+ self._fix_not_computable = Fix.of_float64(fix_not_computable)
1254
+
1255
+ @override
1256
+ def validate_context(self, context: Context) -> None:
1257
+ super(_ACS5Mixin, self).validate_context(context)
1258
+ if isinstance(context.scope, BlockGroupScope):
1259
+ err = (
1260
+ "Dissimilarity index is not available for block group scope. "
1261
+ "We need to be able to load population data for the "
1262
+ "Census geography granularity one step finer than the target "
1263
+ "granularity, and block group data is already the finest available."
1264
+ )
1265
+ raise ADRIOContextError(self, context, err)
1266
+
1267
+ @property
1268
+ @override
1269
+ def result_format(self) -> ResultFormat:
1270
+ return ResultFormat(shape=Shapes.N, dtype=np.float64)
1271
+
1272
+ @override
1273
+ def validate_result(self, context: Context, result: NDArray) -> None:
1274
+ adrio_validate_pipe(
1275
+ self,
1276
+ context,
1277
+ result,
1278
+ validate_numpy(),
1279
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
1280
+ validate_dtype(self.result_format.dtype),
1281
+ validate_values_in_range(0, 1.0),
1282
+ )
1283
+
1284
+ @override
1285
+ def inspect(self) -> InspectResult[np.float64, np.float64]:
1286
+ self.validate_context(self.context)
1287
+
1288
+ majority_race = PopulationByRace(
1289
+ race=self._majority_pop,
1290
+ fix_insufficient_data=self._fix_insufficient_population,
1291
+ fix_missing=self._fix_missing_population,
1292
+ )
1293
+ minority_race = PopulationByRace(
1294
+ race=self._minority_pop,
1295
+ fix_insufficient_data=self._fix_insufficient_population,
1296
+ fix_missing=self._fix_missing_population,
1297
+ )
1298
+
1299
+ # Load populations at the coarse-granularity scope (coarse nodes)
1300
+ high_scope = cast(CensusScope, self.scope)
1301
+ high_majority = self.defer(majority_race)
1302
+ high_minority = self.defer(minority_race)
1303
+
1304
+ # Load populations at the fine-granularity scope (fine nodes)
1305
+ low_scope = high_scope.lower_granularity()
1306
+ low_majority = self.defer(majority_race, scope=low_scope)
1307
+ low_minority = self.defer(minority_race, scope=low_scope)
1308
+
1309
+ # Which fine nodes belong to which coarse nodes?
1310
+ as_high = np.vectorize(CensusGranularity.of(high_scope.granularity).truncate)
1311
+ nodes_high = high_scope.node_ids
1312
+ nodes_low = as_high(low_scope.node_ids)
1313
+
1314
+ # disaggregate coarse node population to get the total to use for each fine node
1315
+ high_low_index_map = np.searchsorted(nodes_high, nodes_low)
1316
+ maj_total = high_majority[high_low_index_map]
1317
+ min_total = high_minority[high_low_index_map]
1318
+
1319
+ # If coarse population is unavailable or zero, we can't compute DI
1320
+ issues: list[tuple[str, NDArray[np.bool_]]] = []
1321
+ if np.ma.is_masked(maj_total):
1322
+ issues.append(("majority_total_unavailable", np.ma.getmask(maj_total)))
1323
+ if np.ma.is_masked(min_total):
1324
+ issues.append(("minority_total_unavailable", np.ma.getmask(min_total)))
1325
+ if np.any(maj_zeros := (maj_total == 0)):
1326
+ issues.append(("majority_total_zero", maj_zeros))
1327
+ if np.any(min_zeros := (min_total == 0)):
1328
+ issues.append(("minority_total_zero", min_zeros))
1329
+
1330
+ # Compute scores for fine nodes (excluding where masked values are involved)
1331
+ low_mask = reduce(np.logical_or, [m for _, m in issues], np.ma.nomask)
1332
+ unmasked = ~low_mask
1333
+ subscore_np = np.zeros(shape=low_scope.nodes, dtype=np.float64)
1334
+ a = low_minority[unmasked] / min_total[unmasked]
1335
+ b = low_majority[unmasked] / maj_total[unmasked]
1336
+ subscore_np[unmasked] = np.abs(a - b)
1337
+
1338
+ # Aggregate fine scores to coarse scores
1339
+ result_np = 0.5 * np.bincount(high_low_index_map, weights=subscore_np)
1340
+
1341
+ # Aggregate fine masks to coarse masks
1342
+ def aggregate_mask(mask):
1343
+ return np.bincount(high_low_index_map, weights=mask).astype(np.bool_)
1344
+
1345
+ if np.any(low_mask):
1346
+ issues = [(issue_name, aggregate_mask(m)) for issue_name, m in issues]
1347
+ result_np = np.ma.masked_array(result_np, aggregate_mask(low_mask))
1348
+
1349
+ # If there are incomputable values and a fix, apply it;
1350
+ # if successful, consider all underlying issues addressed.
1351
+ has_fix = not isinstance(self._fix_not_computable, DontFix)
1352
+ if np.ma.is_masked(result_np) and has_fix:
1353
+ sentinel = np.float64(-999999)
1354
+ sentinel_result = np.ma.getdata(result_np).copy()
1355
+ sentinel_result[np.ma.getmask(result_np)] = sentinel
1356
+ fixed_result = self._fix_not_computable(
1357
+ rng=self.context,
1358
+ replace=sentinel,
1359
+ columns=("value",),
1360
+ data_df=pd.DataFrame({"value": sentinel_result}),
1361
+ )["value"].to_numpy()
1362
+ unfixed = fixed_result == sentinel
1363
+ if unfixed.any():
1364
+ issues = [("not_computable", unfixed)]
1365
+ result_np = np.ma.masked_array(fixed_result, unfixed)
1366
+ else:
1367
+ issues = []
1368
+ result_np = fixed_result
1369
+
1370
+ self.validate_result(self.context, result_np)
1371
+ return InspectResult(
1372
+ adrio=self,
1373
+ source=np.column_stack((low_majority, low_minority, maj_total, min_total)),
1374
+ result=result_np,
1375
+ dtype=self.result_format.dtype.type,
1376
+ shape=self.result_format.shape,
1377
+ issues={k: v for k, v in issues},
1378
+ )