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.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +602 -0
- epymorph/adrio/adrio.py +215 -0
- epymorph/adrio/cdc.py +781 -0
- epymorph/adrio/commuting_flows.py +237 -0
- epymorph/adrio/csv.py +387 -0
- epymorph/adrio/humidity.py +84 -0
- epymorph/adrio/lodes.py +624 -0
- epymorph/adrio/numpy.py +119 -0
- epymorph/adrio/prism.py +543 -0
- epymorph/adrio/respiratory_cdc.py +489 -0
- epymorph/adrio/us_tiger.py +217 -0
- epymorph/attribute.py +301 -0
- epymorph/cache.py +494 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +77 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1335 -0
- epymorph/data/__init__.py +1 -0
- epymorph/data/ipm/__init__.py +22 -0
- epymorph/data/ipm/no.py +14 -0
- epymorph/data/ipm/pei.py +40 -0
- epymorph/data/ipm/seirs.py +50 -0
- epymorph/data/ipm/sirh.py +55 -0
- epymorph/data/ipm/sirs.py +48 -0
- epymorph/data/ipm/sparsemod.py +96 -0
- epymorph/data/mm/__init__.py +22 -0
- epymorph/data/mm/centroids.py +76 -0
- epymorph/data/mm/flat.py +61 -0
- epymorph/data/mm/icecube.py +50 -0
- epymorph/data/mm/no.py +29 -0
- epymorph/data/mm/pei.py +105 -0
- epymorph/data/mm/sparsemod.py +73 -0
- epymorph/data/pei.py +424 -0
- epymorph/data_shape.py +475 -0
- epymorph/data_type.py +129 -0
- epymorph/data_usage.py +171 -0
- epymorph/database.py +1010 -0
- epymorph/error.py +183 -0
- epymorph/event.py +188 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +61 -0
- epymorph/geography/scope.py +214 -0
- epymorph/geography/us_census.py +622 -0
- epymorph/geography/us_geography.py +278 -0
- epymorph/geography/us_tiger.py +755 -0
- epymorph/initializer.py +596 -0
- epymorph/kit.py +90 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +108 -0
- epymorph/log/messaging.py +129 -0
- epymorph/log/movement.py +151 -0
- epymorph/movement_model.py +274 -0
- epymorph/parameter_fitting/__init__.py +0 -0
- epymorph/parameter_fitting/distribution.py +68 -0
- epymorph/parameter_fitting/dynamics.py +19 -0
- epymorph/parameter_fitting/filter/__init__.py +0 -0
- epymorph/parameter_fitting/filter/base_filter.py +50 -0
- epymorph/parameter_fitting/filter/particle.py +32 -0
- epymorph/parameter_fitting/filter/particle_filter.py +296 -0
- epymorph/parameter_fitting/likelihood.py +54 -0
- epymorph/parameter_fitting/output.py +73 -0
- epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
- epymorph/parameter_fitting/perturbation.py +19 -0
- epymorph/parameter_fitting/utils/__init__.py +0 -0
- epymorph/parameter_fitting/utils/data_loader.py +111 -0
- epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
- epymorph/parameter_fitting/utils/observations.py +63 -0
- epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
- epymorph/parameter_fitting/utils/params_perturb.py +43 -0
- epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
- epymorph/parameter_fitting/utils/resampler.py +249 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +248 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +700 -0
- epymorph/simulation.py +706 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +145 -0
- epymorph/simulator/basic/ipm_exec.py +406 -0
- epymorph/simulator/basic/mm_exec.py +197 -0
- epymorph/simulator/basic/output.py +181 -0
- epymorph/simulator/world.py +83 -0
- epymorph/simulator/world_list.py +196 -0
- epymorph/strata.py +12 -0
- epymorph/sympy_shim.py +55 -0
- epymorph/time.py +649 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +218 -0
- epymorph/tools/ipm_diagram.py +165 -0
- epymorph/tools/out_map.py +426 -0
- epymorph/tools/out_plot.py +412 -0
- epymorph/tools/out_table.py +575 -0
- epymorph/util.py +825 -0
- epymorph-1.0.0b0.dist-info/METADATA +57 -0
- epymorph-1.0.0b0.dist-info/RECORD +102 -0
- epymorph-1.0.0b0.dist-info/WHEEL +5 -0
- epymorph-1.0.0b0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0b0.dist-info/top_level.txt +1 -0
epymorph/__init__.py
ADDED
epymorph/__main__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""The main entrypoint for epymorph: a CLI with a number of subcommands."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from epymorph.cli.main import define_argparser
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main() -> None:
|
|
9
|
+
"""The main entrypoint for epymorph."""
|
|
10
|
+
args = define_argparser().parse_args()
|
|
11
|
+
exit_code = args.handler(args)
|
|
12
|
+
sys.exit(exit_code)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
if __name__ == "__main__":
|
|
16
|
+
main()
|
|
File without changes
|
epymorph/adrio/acs5.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
"""ADRIOs that access the US Census ACS 5-year data."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from functools import cache
|
|
6
|
+
from json import load as load_json
|
|
7
|
+
from os import environ
|
|
8
|
+
from typing import Literal, NamedTuple, Sequence, TypeGuard
|
|
9
|
+
from warnings import warn
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pandas as pd
|
|
13
|
+
from census import Census, CensusException
|
|
14
|
+
from numpy.typing import NDArray
|
|
15
|
+
from pandas import DataFrame
|
|
16
|
+
from typing_extensions import override
|
|
17
|
+
|
|
18
|
+
from epymorph.adrio.adrio import ADRIO, ProgressCallback, adrio_cache
|
|
19
|
+
from epymorph.attribute import AttributeDef
|
|
20
|
+
from epymorph.cache import load_or_fetch_url, module_cache_path
|
|
21
|
+
from epymorph.data_shape import Shapes
|
|
22
|
+
from epymorph.error import DataResourceError
|
|
23
|
+
from epymorph.geography.scope import GeoScope
|
|
24
|
+
from epymorph.geography.us_census import (
|
|
25
|
+
BlockGroupScope,
|
|
26
|
+
CensusScope,
|
|
27
|
+
CountyScope,
|
|
28
|
+
StateScope,
|
|
29
|
+
TractScope,
|
|
30
|
+
)
|
|
31
|
+
from epymorph.geography.us_geography import (
|
|
32
|
+
BLOCK_GROUP,
|
|
33
|
+
COUNTY,
|
|
34
|
+
STATE,
|
|
35
|
+
TRACT,
|
|
36
|
+
CensusGranularity,
|
|
37
|
+
)
|
|
38
|
+
from epymorph.util import filter_with_mask
|
|
39
|
+
|
|
40
|
+
_ACS5_CACHE_PATH = module_cache_path(__name__)
|
|
41
|
+
|
|
42
|
+
ACS5Year = Literal[
|
|
43
|
+
2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022
|
|
44
|
+
]
|
|
45
|
+
"""A supported ACS5 data year."""
|
|
46
|
+
|
|
47
|
+
ACS5_YEARS: Sequence[ACS5Year] = (
|
|
48
|
+
2009,
|
|
49
|
+
2010,
|
|
50
|
+
2011,
|
|
51
|
+
2012,
|
|
52
|
+
2013,
|
|
53
|
+
2014,
|
|
54
|
+
2015,
|
|
55
|
+
2016,
|
|
56
|
+
2017,
|
|
57
|
+
2018,
|
|
58
|
+
2019,
|
|
59
|
+
2020,
|
|
60
|
+
2021,
|
|
61
|
+
2022,
|
|
62
|
+
)
|
|
63
|
+
"""All supported ACS5 data years."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@cache
|
|
67
|
+
def _get_api() -> Census:
|
|
68
|
+
api_key = environ.get("CENSUS_API_KEY")
|
|
69
|
+
if api_key is None:
|
|
70
|
+
msg = (
|
|
71
|
+
"Census API key not found. "
|
|
72
|
+
"Please ensure you have set the environment variable 'CENSUS_API_KEY'"
|
|
73
|
+
)
|
|
74
|
+
raise DataResourceError(msg)
|
|
75
|
+
return Census(api_key)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@cache
|
|
79
|
+
def _get_vars(year: int) -> dict[str, dict]:
|
|
80
|
+
try:
|
|
81
|
+
vars_url = f"https://api.census.gov/data/{year}/acs/acs5/variables.json"
|
|
82
|
+
cache_path = _ACS5_CACHE_PATH / f"variables-{year}.json"
|
|
83
|
+
file = load_or_fetch_url(vars_url, cache_path)
|
|
84
|
+
return load_json(file)["variables"]
|
|
85
|
+
except Exception as e:
|
|
86
|
+
raise DataResourceError("Unable to load ACS5 variables.") from e
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@cache
|
|
90
|
+
def _get_group_vars(year: int, group: str) -> list[tuple[str, dict]]:
|
|
91
|
+
return sorted(
|
|
92
|
+
(
|
|
93
|
+
(name, attrs)
|
|
94
|
+
for name, attrs in _get_vars(year).items()
|
|
95
|
+
if attrs["group"] == group
|
|
96
|
+
),
|
|
97
|
+
key=lambda x: x[0],
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _validate_scope(scope: GeoScope) -> CensusScope:
|
|
102
|
+
if not isinstance(scope, CensusScope):
|
|
103
|
+
raise DataResourceError("Census scope is required for acs5 attributes.")
|
|
104
|
+
if not is_acs5_year(scope.year):
|
|
105
|
+
raise DataResourceError(
|
|
106
|
+
f"{scope.year} is not a supported year for acs5 attributes."
|
|
107
|
+
)
|
|
108
|
+
return scope
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def is_acs5_year(year: int) -> TypeGuard[ACS5Year]:
|
|
112
|
+
"""A type-guard function to ensure a year is a supported ACS5 year."""
|
|
113
|
+
return year in ACS5_YEARS
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _make_acs5_queries(scope: CensusScope) -> list[dict[str, str]]:
|
|
117
|
+
"""Creates census API queries that cover the given scope."""
|
|
118
|
+
match scope:
|
|
119
|
+
case StateScope(includes_granularity="state", includes=includes):
|
|
120
|
+
if scope.is_all_states():
|
|
121
|
+
return [{"for": "state:*"}]
|
|
122
|
+
else:
|
|
123
|
+
return [{"for": f"state:{','.join(includes)}"}]
|
|
124
|
+
|
|
125
|
+
case CountyScope(includes_granularity="state", includes=includes):
|
|
126
|
+
return [
|
|
127
|
+
{
|
|
128
|
+
"for": "county:*",
|
|
129
|
+
"in": f"state:{','.join(includes)}",
|
|
130
|
+
}
|
|
131
|
+
]
|
|
132
|
+
|
|
133
|
+
case CountyScope(includes_granularity="county", includes=includes):
|
|
134
|
+
counties_by_state: dict[str, list[str]] = defaultdict(list)
|
|
135
|
+
for state, county in map(COUNTY.decompose, includes):
|
|
136
|
+
counties_by_state[state].append(county)
|
|
137
|
+
return [
|
|
138
|
+
{"for": f"county:{','.join(cs)}", "in": f"state:{s}"}
|
|
139
|
+
for s, cs in counties_by_state.items()
|
|
140
|
+
]
|
|
141
|
+
|
|
142
|
+
case TractScope(includes_granularity="state", includes=includes):
|
|
143
|
+
return [
|
|
144
|
+
{
|
|
145
|
+
"for": "tract:*",
|
|
146
|
+
"in": f"state:{','.join(includes)} county:*",
|
|
147
|
+
}
|
|
148
|
+
]
|
|
149
|
+
|
|
150
|
+
case TractScope(includes_granularity="county", includes=includes):
|
|
151
|
+
counties_by_state: dict[str, list[str]] = defaultdict(list)
|
|
152
|
+
for state, county in map(COUNTY.decompose, includes):
|
|
153
|
+
counties_by_state[state].append(county)
|
|
154
|
+
return [
|
|
155
|
+
{"for": "tract:*", "in": f"state:{s} county:{','.join(cs)}"}
|
|
156
|
+
for s, cs in counties_by_state.items()
|
|
157
|
+
]
|
|
158
|
+
|
|
159
|
+
case TractScope(includes_granularity="tract", includes=includes):
|
|
160
|
+
tracts_by_county: dict[str, list[str]] = defaultdict(list)
|
|
161
|
+
|
|
162
|
+
for state, county, tract in map(TRACT.decompose, includes):
|
|
163
|
+
tracts_by_county[state + county].append(tract)
|
|
164
|
+
|
|
165
|
+
return [
|
|
166
|
+
{
|
|
167
|
+
"for": f"tract:{','.join(tracts_by_county[state + county])}",
|
|
168
|
+
"in": f"state:{state} county:{county}",
|
|
169
|
+
}
|
|
170
|
+
for state, county in [
|
|
171
|
+
COUNTY.decompose(c) for c in tracts_by_county.keys()
|
|
172
|
+
]
|
|
173
|
+
]
|
|
174
|
+
|
|
175
|
+
case BlockGroupScope(includes_granularity="state", includes=includes):
|
|
176
|
+
# This wouldn't normally need to be multiple queries,
|
|
177
|
+
# but Census API won't let you fetch CBGs for multiple states.
|
|
178
|
+
states = {STATE.extract(x) for x in includes}
|
|
179
|
+
return [
|
|
180
|
+
{"for": "block group:*", "in": f"state:{s} county:* tract:*"}
|
|
181
|
+
for s in states
|
|
182
|
+
]
|
|
183
|
+
|
|
184
|
+
case BlockGroupScope(includes_granularity="county", includes=includes):
|
|
185
|
+
counties_by_state: dict[str, list[str]] = defaultdict(list)
|
|
186
|
+
for state, county in map(COUNTY.decompose, includes):
|
|
187
|
+
counties_by_state[state].append(county)
|
|
188
|
+
return [
|
|
189
|
+
{
|
|
190
|
+
"for": "block group:*",
|
|
191
|
+
"in": f"state:{s} county:{','.join(cs)} tract:*",
|
|
192
|
+
}
|
|
193
|
+
for s, cs in counties_by_state.items()
|
|
194
|
+
]
|
|
195
|
+
|
|
196
|
+
case BlockGroupScope(includes_granularity="tract", includes=includes):
|
|
197
|
+
tracts_by_county: dict[str, list[str]] = defaultdict(list)
|
|
198
|
+
|
|
199
|
+
for state, county, tract in map(TRACT.decompose, includes):
|
|
200
|
+
tracts_by_county[state + county].append(tract)
|
|
201
|
+
|
|
202
|
+
return [
|
|
203
|
+
{
|
|
204
|
+
"for": "block group:*",
|
|
205
|
+
"in": (
|
|
206
|
+
f"state:{state} county:{county} "
|
|
207
|
+
f"tract:{','.join(tracts_by_county[state + county])}"
|
|
208
|
+
),
|
|
209
|
+
}
|
|
210
|
+
for state, county in [
|
|
211
|
+
COUNTY.decompose(c) for c in tracts_by_county.keys()
|
|
212
|
+
]
|
|
213
|
+
]
|
|
214
|
+
|
|
215
|
+
case BlockGroupScope(includes_granularity="block group", includes=includes):
|
|
216
|
+
block_groups_by_tract: dict[str, list[str]] = defaultdict(list)
|
|
217
|
+
|
|
218
|
+
for state, county, tract, block_group in map(
|
|
219
|
+
BLOCK_GROUP.decompose, includes
|
|
220
|
+
):
|
|
221
|
+
block_groups_by_tract[state + county + tract].append(block_group)
|
|
222
|
+
|
|
223
|
+
return [
|
|
224
|
+
{
|
|
225
|
+
"for": f"block group:{'.'.join(block_groups_by_tract[state + county + tract])}", # noqa: E501
|
|
226
|
+
"in": f"state:{state} county:{county} tract:{tract}",
|
|
227
|
+
}
|
|
228
|
+
for state, county, tract in [
|
|
229
|
+
TRACT.decompose(t) for t in block_groups_by_tract.keys()
|
|
230
|
+
]
|
|
231
|
+
]
|
|
232
|
+
|
|
233
|
+
case _:
|
|
234
|
+
raise DataResourceError("Unsupported query.")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _fetch_acs5(
|
|
238
|
+
variables: list[str], scope: CensusScope, progress: ProgressCallback
|
|
239
|
+
) -> DataFrame:
|
|
240
|
+
census = _get_api()
|
|
241
|
+
queries = _make_acs5_queries(scope)
|
|
242
|
+
|
|
243
|
+
# fetch all queries and combine results
|
|
244
|
+
try:
|
|
245
|
+
acs_data = list[DataFrame]()
|
|
246
|
+
processing_steps = len(queries) + 1
|
|
247
|
+
for i, query in enumerate(queries):
|
|
248
|
+
acs_data.append(
|
|
249
|
+
pd.DataFrame.from_records(
|
|
250
|
+
census.acs5.get(variables, geo=query, year=scope.year)
|
|
251
|
+
)
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
progress((i + 1) / processing_steps, None)
|
|
255
|
+
|
|
256
|
+
acs_df = pd.concat(acs_data)
|
|
257
|
+
|
|
258
|
+
except CensusException as e:
|
|
259
|
+
err = "Unable to load data from the US Census API at this time."
|
|
260
|
+
raise DataResourceError(err) from e
|
|
261
|
+
if acs_df.empty:
|
|
262
|
+
msg = (
|
|
263
|
+
"ACS5 query returned empty. "
|
|
264
|
+
"Ensure all geographies included in your scope are supported and try again."
|
|
265
|
+
)
|
|
266
|
+
raise DataResourceError(msg)
|
|
267
|
+
|
|
268
|
+
# concatenate geoid components to create 'geoid' column
|
|
269
|
+
columns: list[str] = {
|
|
270
|
+
"state": ["state"],
|
|
271
|
+
"county": ["state", "county"],
|
|
272
|
+
"tract": ["state", "county", "tract"],
|
|
273
|
+
"block group": ["state", "county", "tract", "block group"],
|
|
274
|
+
}[scope.granularity]
|
|
275
|
+
acs_df["geoid"] = acs_df[columns].apply("".join, axis=1)
|
|
276
|
+
|
|
277
|
+
# check and sort results for 1:1 match with scope
|
|
278
|
+
try:
|
|
279
|
+
geoid_df = pd.DataFrame({"geoid": scope.node_ids})
|
|
280
|
+
return geoid_df.merge(acs_df, on="geoid", how="left", validate="1:1")
|
|
281
|
+
except pd.errors.MergeError:
|
|
282
|
+
msg = "Fetched data was not an exact match for the scope's geographies."
|
|
283
|
+
raise DataResourceError(msg) from None
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@adrio_cache
|
|
287
|
+
class Population(ADRIO[np.int64]):
|
|
288
|
+
"""
|
|
289
|
+
Retrieves an N-shaped array of integers representing the total population of each
|
|
290
|
+
geographic node. Data is retrieved from Census table variable B01001_001 using ACS5
|
|
291
|
+
5-year estimates.
|
|
292
|
+
"""
|
|
293
|
+
|
|
294
|
+
@override
|
|
295
|
+
def evaluate_adrio(self) -> NDArray[np.int64]:
|
|
296
|
+
scope = _validate_scope(self.scope)
|
|
297
|
+
acs_df = _fetch_acs5(["B01001_001E"], scope, self.progress)
|
|
298
|
+
return acs_df["B01001_001E"].to_numpy(dtype=np.int64)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@adrio_cache
|
|
302
|
+
class PopulationByAgeTable(ADRIO[np.int64]):
|
|
303
|
+
"""
|
|
304
|
+
Creates a table of population data for each geographic node split into various age
|
|
305
|
+
categories. Data is retrieved from Census table B01001 using ACS5 5-year estimates.
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
@override
|
|
309
|
+
def evaluate_adrio(self) -> NDArray[np.int64]:
|
|
310
|
+
scope = _validate_scope(self.scope)
|
|
311
|
+
# NOTE: asking acs5 explicitly for the [B01001_001E, ...] vars
|
|
312
|
+
# seems to be about twice as fast as asking for group(B01001)
|
|
313
|
+
age_vars = [var for var, _ in _get_group_vars(scope.year, "B01001")]
|
|
314
|
+
age_vars.sort()
|
|
315
|
+
acs_df = _fetch_acs5(age_vars, scope, self.progress)
|
|
316
|
+
return acs_df[age_vars].to_numpy(dtype=np.int64)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
_exact_pattern = re.compile(r"^(\d+) years$")
|
|
320
|
+
_under_pattern = re.compile(r"^Under (\d+) years$")
|
|
321
|
+
_range_pattern = re.compile(r"^(\d+) (?:to|and) (\d+) years")
|
|
322
|
+
_over_pattern = re.compile(r"^(\d+) years and over")
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
class AgeRange(NamedTuple):
|
|
326
|
+
"""
|
|
327
|
+
Models an age range for use with ACS age-categorized data.
|
|
328
|
+
Unlike Python integer ranges, the `end` of the this range is inclusive.
|
|
329
|
+
`end` can also be None which models the "and over" part of ranges
|
|
330
|
+
like "85 years and over".
|
|
331
|
+
"""
|
|
332
|
+
|
|
333
|
+
start: int
|
|
334
|
+
end: int | None
|
|
335
|
+
|
|
336
|
+
def contains(self, other: "AgeRange") -> bool:
|
|
337
|
+
"""Is the `other` range fully contained in (or coincident with) this range?"""
|
|
338
|
+
if self.start > other.start:
|
|
339
|
+
return False
|
|
340
|
+
if self.end is None:
|
|
341
|
+
return True
|
|
342
|
+
if other.end is None:
|
|
343
|
+
return False
|
|
344
|
+
return self.end >= other.end
|
|
345
|
+
|
|
346
|
+
@staticmethod
|
|
347
|
+
def parse(label: str) -> "AgeRange | None":
|
|
348
|
+
"""
|
|
349
|
+
Parse the age range of an ACS field label;
|
|
350
|
+
e.g.: `Estimate!!Total:!!Male:!!22 to 24 years`
|
|
351
|
+
"""
|
|
352
|
+
parts = label.split("!!")
|
|
353
|
+
if len(parts) != 4:
|
|
354
|
+
return None
|
|
355
|
+
bracket = parts[-1]
|
|
356
|
+
if (m := _exact_pattern.match(bracket)) is not None:
|
|
357
|
+
start = int(m.group(1))
|
|
358
|
+
end = start
|
|
359
|
+
elif (m := _under_pattern.match(bracket)) is not None:
|
|
360
|
+
start = 0
|
|
361
|
+
end = int(m.group(1))
|
|
362
|
+
elif (m := _range_pattern.match(bracket)) is not None:
|
|
363
|
+
start = int(m.group(1))
|
|
364
|
+
end = int(m.group(2))
|
|
365
|
+
elif (m := _over_pattern.match(bracket)) is not None:
|
|
366
|
+
start = int(m.group(1))
|
|
367
|
+
end = None
|
|
368
|
+
else:
|
|
369
|
+
raise DataResourceError(f"No match for {label}")
|
|
370
|
+
return AgeRange(start, end)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
@adrio_cache
|
|
374
|
+
class PopulationByAge(ADRIO[np.int64]):
|
|
375
|
+
"""
|
|
376
|
+
Retrieves an N-shaped array of integers representing the total population
|
|
377
|
+
within a specified age range for each geographic node. Data is retrieved from
|
|
378
|
+
a population by age table constructed from Census table B01001.
|
|
379
|
+
"""
|
|
380
|
+
|
|
381
|
+
POP_BY_AGE_TABLE = AttributeDef("population_by_age_table", int, Shapes.NxA)
|
|
382
|
+
|
|
383
|
+
requirements = [POP_BY_AGE_TABLE]
|
|
384
|
+
"""The population by age table is required for retrieving the population totals by
|
|
385
|
+
age range."""
|
|
386
|
+
|
|
387
|
+
_age_range: AgeRange
|
|
388
|
+
|
|
389
|
+
def __init__(self, age_range_start: int, age_range_end: int | None):
|
|
390
|
+
"""
|
|
391
|
+
Initializes the population by age array with a starting age and an end age to
|
|
392
|
+
define the total age range.
|
|
393
|
+
|
|
394
|
+
Parameters
|
|
395
|
+
----------
|
|
396
|
+
age_range_start : int
|
|
397
|
+
The starting age for the age range to retrieve from the population table.
|
|
398
|
+
age_range_end : int | None
|
|
399
|
+
The inclusive ending age for the age range to retrieve from the population
|
|
400
|
+
table. If None, the range includes all ages at and above age_range_start.
|
|
401
|
+
"""
|
|
402
|
+
self._age_range = AgeRange(age_range_start, age_range_end)
|
|
403
|
+
|
|
404
|
+
@override
|
|
405
|
+
def evaluate_adrio(self) -> NDArray[np.int64]:
|
|
406
|
+
scope = _validate_scope(self.scope)
|
|
407
|
+
|
|
408
|
+
age_ranges = [
|
|
409
|
+
AgeRange.parse(attrs["label"])
|
|
410
|
+
for var, attrs in _get_group_vars(scope.year, "B01001")
|
|
411
|
+
]
|
|
412
|
+
|
|
413
|
+
adrio_range = self._age_range
|
|
414
|
+
|
|
415
|
+
def is_included(x: AgeRange | None) -> TypeGuard[AgeRange]:
|
|
416
|
+
return x is not None and adrio_range.contains(x)
|
|
417
|
+
|
|
418
|
+
included, col_mask = filter_with_mask(age_ranges, is_included)
|
|
419
|
+
|
|
420
|
+
# At least one var must have its start equal to the ADRIO range
|
|
421
|
+
if not any((x.start == adrio_range.start for x in included)):
|
|
422
|
+
raise DataResourceError(f"bad start {adrio_range}")
|
|
423
|
+
# At least one var must have its end equal to the ADRIO range
|
|
424
|
+
if not any((x.end == adrio_range.end for x in included)):
|
|
425
|
+
raise DataResourceError(f"bad end {adrio_range}")
|
|
426
|
+
|
|
427
|
+
table = self.data(self.POP_BY_AGE_TABLE)
|
|
428
|
+
return table[:, col_mask].sum(axis=1)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
@adrio_cache
|
|
432
|
+
class AverageHouseholdSize(ADRIO[np.float64]):
|
|
433
|
+
"""
|
|
434
|
+
Retrieves an N-shaped array of floats representing the average number of people
|
|
435
|
+
living in each household for every geographic node.
|
|
436
|
+
Data is retrieved from Census table variable B25010_001 using ACS5 5-year estimates.
|
|
437
|
+
"""
|
|
438
|
+
|
|
439
|
+
@override
|
|
440
|
+
def evaluate_adrio(self) -> NDArray[np.float64]:
|
|
441
|
+
scope = _validate_scope(self.scope)
|
|
442
|
+
acs_df = _fetch_acs5(["B25010_001E"], scope, self.progress)
|
|
443
|
+
return acs_df["B25010_001E"].to_numpy(dtype=np.float64)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
@adrio_cache
|
|
447
|
+
class DissimilarityIndex(ADRIO[np.float64]):
|
|
448
|
+
"""
|
|
449
|
+
Calculates an N-shaped array of floats representing the amount of racial segregation
|
|
450
|
+
between a specified racial majority and minority groups on a scale of
|
|
451
|
+
0 (complete integration) to 1 (complete segregation). Data is calculated using
|
|
452
|
+
population data from Census table B02001 using ACS5 5-year estimates.
|
|
453
|
+
"""
|
|
454
|
+
|
|
455
|
+
RaceCategory = Literal[
|
|
456
|
+
"White", "Black", "Native", "Asian", "Pacific Islander", "Other"
|
|
457
|
+
]
|
|
458
|
+
|
|
459
|
+
race_variables: dict[RaceCategory, str] = {
|
|
460
|
+
"White": "B02001_002E",
|
|
461
|
+
"Black": "B02001_003E",
|
|
462
|
+
"Native": "B02001_004E",
|
|
463
|
+
"Asian": "B02001_005E",
|
|
464
|
+
"Pacific Islander": "B02001_006E",
|
|
465
|
+
"Other": "B02001_007E",
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
majority_pop: RaceCategory
|
|
469
|
+
minority_pop: RaceCategory
|
|
470
|
+
|
|
471
|
+
def __init__(self, majority_pop: RaceCategory, minority_pop: RaceCategory):
|
|
472
|
+
"""
|
|
473
|
+
Initializes the fetching for the array of segregation with a majority and
|
|
474
|
+
minority population.
|
|
475
|
+
|
|
476
|
+
Parameters
|
|
477
|
+
----------
|
|
478
|
+
majority_pop : RaceCategory
|
|
479
|
+
The race category representing the majority population for the amount of
|
|
480
|
+
segregation (options:, 'White', 'Black', 'Native', 'Asian',
|
|
481
|
+
'Pacific Islander', 'Other').
|
|
482
|
+
|
|
483
|
+
minority_pop : RaceCategory
|
|
484
|
+
The race category representing the minority population within the
|
|
485
|
+
segregation analysis (options:, 'White', 'Black', 'Native', 'Asian',
|
|
486
|
+
'Pacific Islander', 'Other').
|
|
487
|
+
"""
|
|
488
|
+
self.majority_pop = majority_pop
|
|
489
|
+
"""The race category of the majority population"""
|
|
490
|
+
self.minority_pop = minority_pop
|
|
491
|
+
"""The race category of the minority population of interest"""
|
|
492
|
+
|
|
493
|
+
@override
|
|
494
|
+
def evaluate_adrio(self) -> NDArray[np.float64]:
|
|
495
|
+
high_scope = _validate_scope(self.scope)
|
|
496
|
+
if isinstance(high_scope, BlockGroupScope):
|
|
497
|
+
msg = "Dissimilarity index cannot be retreived for block group scope."
|
|
498
|
+
raise DataResourceError(msg)
|
|
499
|
+
low_scope = high_scope.lower_granularity()
|
|
500
|
+
|
|
501
|
+
majority_var = self.race_variables[self.majority_pop]
|
|
502
|
+
minority_var = self.race_variables[self.minority_pop]
|
|
503
|
+
|
|
504
|
+
# Fetch the data for the upper scope.
|
|
505
|
+
high_df = _fetch_acs5(
|
|
506
|
+
[majority_var, minority_var], high_scope, self.progress
|
|
507
|
+
).rename(columns={majority_var: "high_majority", minority_var: "high_minority"})
|
|
508
|
+
# Fetch the data for the lower scope.
|
|
509
|
+
low_df = _fetch_acs5(
|
|
510
|
+
[majority_var, minority_var], low_scope, self.progress
|
|
511
|
+
).rename(columns={majority_var: "low_majority", minority_var: "low_minority"})
|
|
512
|
+
# Create a merge key by truncating the lower scope's GEOID.
|
|
513
|
+
gran = CensusGranularity.of(high_scope.granularity)
|
|
514
|
+
low_df["geoid"] = low_df["geoid"].apply(gran.truncate)
|
|
515
|
+
|
|
516
|
+
# Merge and compute score.
|
|
517
|
+
result_df = high_df.merge(low_df, on="geoid")
|
|
518
|
+
result_df["score"] = abs(
|
|
519
|
+
result_df["low_minority"] / result_df["high_minority"]
|
|
520
|
+
- result_df["low_majority"] / result_df["high_majority"]
|
|
521
|
+
)
|
|
522
|
+
result_df = result_df.groupby("geoid").sum()
|
|
523
|
+
result_df["score"] *= 0.5
|
|
524
|
+
result_df["score"] = result_df["score"].replace(0.0, 0.5)
|
|
525
|
+
result_df = result_df.reset_index()
|
|
526
|
+
return result_df["score"].to_numpy(dtype=np.float64)
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
@adrio_cache
|
|
530
|
+
class GINIIndex(ADRIO[np.float64]):
|
|
531
|
+
"""
|
|
532
|
+
Retrieves an N-shaped array of floats representing the amount of income inequality
|
|
533
|
+
on a scale of 0 (perfect equality) to 1 (perfect inequality) for each
|
|
534
|
+
geographic node. Data is retrieved from Census table variable B19083_001 using
|
|
535
|
+
ACS 5-year estimates.
|
|
536
|
+
"""
|
|
537
|
+
|
|
538
|
+
@override
|
|
539
|
+
def evaluate_adrio(self) -> NDArray[np.float64]:
|
|
540
|
+
scope = _validate_scope(self.scope)
|
|
541
|
+
|
|
542
|
+
# if granularity is block groups, use the data of the parent tract
|
|
543
|
+
if isinstance(scope, BlockGroupScope):
|
|
544
|
+
warn(
|
|
545
|
+
"Gini Index cannot be retrieved for block group level, "
|
|
546
|
+
"fetching tract level data instead."
|
|
547
|
+
)
|
|
548
|
+
tracts = scope.raise_granularity()
|
|
549
|
+
tract_df = _fetch_acs5(["B19083_001E"], tracts, self.progress)
|
|
550
|
+
as_tract = np.vectorize(TRACT.truncate)
|
|
551
|
+
cbg_df = pd.DataFrame(
|
|
552
|
+
{
|
|
553
|
+
"geoid": scope.node_ids,
|
|
554
|
+
"tract_geoid": as_tract(scope.node_ids),
|
|
555
|
+
}
|
|
556
|
+
)
|
|
557
|
+
result_df = cbg_df.merge(
|
|
558
|
+
tract_df,
|
|
559
|
+
left_on="tract_geoid",
|
|
560
|
+
right_on="geoid",
|
|
561
|
+
suffixes=(None, "_y"),
|
|
562
|
+
)
|
|
563
|
+
else:
|
|
564
|
+
result_df = _fetch_acs5(["B19083_001E"], scope, self.progress)
|
|
565
|
+
|
|
566
|
+
return (
|
|
567
|
+
result_df["B19083_001E"]
|
|
568
|
+
.astype(np.float64)
|
|
569
|
+
.fillna(0.5)
|
|
570
|
+
.replace(-666666666, 0.5)
|
|
571
|
+
.to_numpy(dtype=np.float64)
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
@adrio_cache
|
|
576
|
+
class MedianAge(ADRIO[np.float64]):
|
|
577
|
+
"""
|
|
578
|
+
Retrieves an N-shaped array of floats representing the median age in
|
|
579
|
+
each geographic node. Data is retrieved from Census table variable
|
|
580
|
+
B01002_001 using ACS 5-year estimates.
|
|
581
|
+
"""
|
|
582
|
+
|
|
583
|
+
@override
|
|
584
|
+
def evaluate_adrio(self) -> NDArray[np.float64]:
|
|
585
|
+
scope = _validate_scope(self.scope)
|
|
586
|
+
acs_df = _fetch_acs5(["B01002_001E"], scope, self.progress)
|
|
587
|
+
return acs_df["B01002_001E"].to_numpy(dtype=np.float64)
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
@adrio_cache
|
|
591
|
+
class MedianIncome(ADRIO[np.float64]):
|
|
592
|
+
"""
|
|
593
|
+
Retrieves an N-shaped array of floats representing the median yearly income in
|
|
594
|
+
each geographic node. Data is retrieved from Census table variable B19013_001
|
|
595
|
+
using ACS 5-year estimates.
|
|
596
|
+
"""
|
|
597
|
+
|
|
598
|
+
@override
|
|
599
|
+
def evaluate_adrio(self) -> NDArray[np.float64]:
|
|
600
|
+
scope = _validate_scope(self.scope)
|
|
601
|
+
acs_df = _fetch_acs5(["B19013_001E"], scope, self.progress)
|
|
602
|
+
return acs_df["B19013_001E"].to_numpy(dtype=np.float64)
|