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.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +1378 -0
- epymorph/adrio/adrio.py +953 -0
- epymorph/adrio/cdc.py +1826 -0
- epymorph/adrio/commuting_flows.py +283 -0
- epymorph/adrio/csv.py +499 -0
- epymorph/adrio/humidity.py +206 -0
- epymorph/adrio/lodes.py +509 -0
- epymorph/adrio/numpy.py +160 -0
- epymorph/adrio/prism.py +345 -0
- epymorph/adrio/processing.py +1221 -0
- epymorph/adrio/soda.py +602 -0
- epymorph/adrio/us_tiger.py +289 -0
- epymorph/adrio/validation.py +382 -0
- epymorph/attribute.py +614 -0
- epymorph/cache.py +680 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +78 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1873 -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 +593 -0
- epymorph/data_type.py +185 -0
- epymorph/data_usage.py +258 -0
- epymorph/database.py +1301 -0
- epymorph/error.py +195 -0
- epymorph/event.py +196 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +93 -0
- epymorph/geography/scope.py +457 -0
- epymorph/geography/us_census.py +1056 -0
- epymorph/geography/us_geography.py +502 -0
- epymorph/geography/us_tiger.py +1083 -0
- epymorph/initializer.py +786 -0
- epymorph/kit.py +107 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +128 -0
- epymorph/log/messaging.py +139 -0
- epymorph/log/movement.py +228 -0
- epymorph/movement_model.py +347 -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 +97 -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 +258 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +438 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +871 -0
- epymorph/simulation.py +991 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +171 -0
- epymorph/simulator/basic/ipm_exec.py +437 -0
- epymorph/simulator/basic/mm_exec.py +244 -0
- epymorph/simulator/basic/output.py +213 -0
- epymorph/simulator/world.py +149 -0
- epymorph/simulator/world_list.py +274 -0
- epymorph/strata.py +24 -0
- epymorph/sympy_shim.py +57 -0
- epymorph/time.py +1197 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +297 -0
- epymorph/tools/ipm_diagram.py +208 -0
- epymorph/tools/out_map.py +551 -0
- epymorph/tools/out_plot.py +423 -0
- epymorph/tools/out_table.py +582 -0
- epymorph/util.py +1036 -0
- epymorph-1.0.0.dist-info/METADATA +57 -0
- epymorph-1.0.0.dist-info/RECORD +104 -0
- epymorph-1.0.0.dist-info/WHEEL +5 -0
- epymorph-1.0.0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0.dist-info/top_level.txt +1 -0
epymorph/adrio/lodes.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
"""ADRIOs that access the US Census LODES files for commuting data."""
|
|
2
|
+
|
|
3
|
+
from abc import abstractmethod
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Literal, NamedTuple, cast
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from typing_extensions import override
|
|
10
|
+
|
|
11
|
+
from epymorph.adrio.adrio import (
|
|
12
|
+
ADRIO,
|
|
13
|
+
ADRIOCommunicationError,
|
|
14
|
+
ADRIOContextError,
|
|
15
|
+
InspectResult,
|
|
16
|
+
adrio_cache,
|
|
17
|
+
)
|
|
18
|
+
from epymorph.adrio.validation import ResultFormat
|
|
19
|
+
from epymorph.cache import check_file_in_cache, load_or_fetch_url, module_cache_path
|
|
20
|
+
from epymorph.data_shape import Shapes
|
|
21
|
+
from epymorph.data_usage import AvailableDataEstimate, DataEstimate
|
|
22
|
+
from epymorph.error import MissingContextError
|
|
23
|
+
from epymorph.geography.us_census import CensusScope
|
|
24
|
+
from epymorph.geography.us_geography import STATE, CensusGranularity
|
|
25
|
+
from epymorph.geography.us_tiger import get_states
|
|
26
|
+
from epymorph.simulation import Context
|
|
27
|
+
|
|
28
|
+
_LODES_CACHE_PATH = module_cache_path(__name__)
|
|
29
|
+
|
|
30
|
+
JobType = Literal[
|
|
31
|
+
"All Jobs",
|
|
32
|
+
"Primary Jobs",
|
|
33
|
+
"All Private Jobs",
|
|
34
|
+
"Private Primary Jobs",
|
|
35
|
+
"All Federal Jobs",
|
|
36
|
+
"Federal Primary Jobs",
|
|
37
|
+
]
|
|
38
|
+
"""A job type that LODES provides subtotals for."""
|
|
39
|
+
|
|
40
|
+
AgeRange = Literal["29 and Under", "30_54", "55 and Over"]
|
|
41
|
+
"""Age ranges that LODES provides subtotals for."""
|
|
42
|
+
|
|
43
|
+
EarningRange = Literal["$1250 and Under", "$1251_$3333", "$3333 and Over"]
|
|
44
|
+
"""Earning ranges that LODES provides subtotals for."""
|
|
45
|
+
|
|
46
|
+
Industry = Literal["Goods Producing", "Trade Transport Utility", "Other"]
|
|
47
|
+
"""Job industries that LODES provides subtotals for."""
|
|
48
|
+
|
|
49
|
+
_JobCode = Literal["JT00", "JT01", "JT02", "JT03", "JT04", "JT05"]
|
|
50
|
+
_FileType = Literal["main", "aux"]
|
|
51
|
+
|
|
52
|
+
# fmt: off
|
|
53
|
+
_STATE_FILE_ESTIMATES = {
|
|
54
|
+
"ak": 970_000, "al": 8_300_000, "ar": 4_400_000, "az": 11_500_000,
|
|
55
|
+
"ca": 72_300_000, "co": 10_600_000, "ct": 6_500_000, "dc": 719_000,
|
|
56
|
+
"de": 1_400_000, "fl": 36_700_000, "ga": 17_900_000, "hi": 1_900_000,
|
|
57
|
+
"ia": 6_200_000, "id": 2_700_000, "il": 26_000_000, "in": 12_800_000,
|
|
58
|
+
"ks": 5_200_000, "ky": 7_200_000, "la": 8_100_000, "ma": 8_200_000,
|
|
59
|
+
"md": 9_900_000, "me": 2_400_000, "mi": 18_820_000, "mn": 11_300_000,
|
|
60
|
+
"mo": 11_300_000, "ms": 4_400_000, "mt": 1_800_000, "nc": 18_200_000,
|
|
61
|
+
"nd": 1_400_000, "ne": 3_800_000, "nh": 2_300_000, "nj": 16_400_000,
|
|
62
|
+
"nm": 3_100_000, "nv": 4_700_000, "ny": 35_200_000, "oh": 23_500_000,
|
|
63
|
+
"ok": 6_700_000, "or": 7_300_000, "pa": 25_100_000, "ri": 1_900_000,
|
|
64
|
+
"sc": 8_100_000, "sd": 1_500_000, "tn": 11_400_000, "tx": 50_300_000,
|
|
65
|
+
"ut": 5_400_000, "va": 14_600_000, "vt": 1_080_000, "wa": 12_500_000,
|
|
66
|
+
"wi": 11_700_000, "wv": 2_600_000, "wy": 972_000,
|
|
67
|
+
}
|
|
68
|
+
"""File estimates for JT00-JT03 main files"""
|
|
69
|
+
# fmt: on
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _file_size(state: str, file: _FileType, job: _JobCode) -> int:
|
|
73
|
+
"""Estimate the file size in bytes of a LODES file."""
|
|
74
|
+
match (file, job):
|
|
75
|
+
case ("main", "JT04" | "JT05"):
|
|
76
|
+
return 86_200 # 86.2KB
|
|
77
|
+
case ("main", _):
|
|
78
|
+
return _STATE_FILE_ESTIMATES[state]
|
|
79
|
+
case ("aux", "JT04" | "JT05"):
|
|
80
|
+
return 18_700 # 18.7KB
|
|
81
|
+
case ("aux", _):
|
|
82
|
+
return 723_000 # 723KB
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _LodesFile(NamedTuple):
|
|
86
|
+
state: str
|
|
87
|
+
file: _FileType
|
|
88
|
+
url: str
|
|
89
|
+
cache_path: Path
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _lodes_files(scope: CensusScope, year: int, job: _JobCode) -> list[_LodesFile]:
|
|
93
|
+
"""Compute the complete list of LODES files needed."""
|
|
94
|
+
version = "LODES8" # we only support LODES v8 currently
|
|
95
|
+
|
|
96
|
+
def file_for(state, file_type):
|
|
97
|
+
url = f"https://lehd.ces.census.gov/data/lodes/{version}/{state}/od/{state}_od_{file_type}_{job}_{year}.csv.gz"
|
|
98
|
+
cache_path = _LODES_CACHE_PATH / Path(url).name
|
|
99
|
+
return _LodesFile(state, file_type, url, cache_path)
|
|
100
|
+
|
|
101
|
+
# files are state-based
|
|
102
|
+
states = list(STATE.truncate_unique(scope.node_ids))
|
|
103
|
+
state_fips_to_code = get_states(scope.year).state_fips_to_code
|
|
104
|
+
state_codes = [state_fips_to_code[x].lower() for x in states]
|
|
105
|
+
|
|
106
|
+
# if there's more than one state, we will need to load both main and aux files
|
|
107
|
+
file_types: list[_FileType] = ["main", "aux"] if len(states) > 1 else ["main"]
|
|
108
|
+
|
|
109
|
+
return [file_for(s, f) for s in state_codes for f in file_types]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class _LodesADRIOMixin(ADRIO[np.int64, np.int64]):
|
|
113
|
+
"""Shared functionality for LODES ADRIOs."""
|
|
114
|
+
|
|
115
|
+
_override_year: int | None
|
|
116
|
+
"""Selected data year."""
|
|
117
|
+
_job_type: JobType
|
|
118
|
+
"""Selected job type."""
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def _job_code(self) -> _JobCode:
|
|
122
|
+
"""The job code corresponding to the selected job type."""
|
|
123
|
+
match self._job_type:
|
|
124
|
+
case "All Jobs":
|
|
125
|
+
return "JT00"
|
|
126
|
+
case "Primary Jobs":
|
|
127
|
+
return "JT01"
|
|
128
|
+
case "All Private Jobs":
|
|
129
|
+
return "JT02"
|
|
130
|
+
case "Private Primary Jobs":
|
|
131
|
+
return "JT03"
|
|
132
|
+
case "All Federal Jobs":
|
|
133
|
+
return "JT04"
|
|
134
|
+
case "Federal Primary Jobs":
|
|
135
|
+
return "JT05"
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
@abstractmethod
|
|
139
|
+
def _worker_type(self) -> str:
|
|
140
|
+
"""The worker type code identifying the data column to use from LODES files."""
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def data_year(self) -> int:
|
|
144
|
+
"""
|
|
145
|
+
The data year to fetch. If this ADRIO was constructed with the `year` argument,
|
|
146
|
+
that is used. Otherwise default to the year in which the simulation time frame
|
|
147
|
+
starts.
|
|
148
|
+
"""
|
|
149
|
+
if self._override_year is not None:
|
|
150
|
+
return self._override_year
|
|
151
|
+
return self.time_frame.start_date.year
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
@override
|
|
155
|
+
def result_format(self) -> ResultFormat:
|
|
156
|
+
return ResultFormat(dtype=np.int64, shape=Shapes.NxN)
|
|
157
|
+
|
|
158
|
+
@override
|
|
159
|
+
def validate_context(self, context: Context) -> None:
|
|
160
|
+
try:
|
|
161
|
+
scope = self.scope
|
|
162
|
+
except MissingContextError:
|
|
163
|
+
err = "Census scope is required for LODES attributes."
|
|
164
|
+
raise ADRIOContextError(self, context, err)
|
|
165
|
+
if not isinstance(scope, CensusScope):
|
|
166
|
+
err = "Census scope is required for LODES attributes."
|
|
167
|
+
raise ADRIOContextError(self, context, err)
|
|
168
|
+
if scope.year != 2020:
|
|
169
|
+
err = "Invalid scope year; LODES requires 2020 Census geography."
|
|
170
|
+
raise ADRIOContextError(self, context, err)
|
|
171
|
+
|
|
172
|
+
year = self.data_year
|
|
173
|
+
if year not in range(2002, 2022):
|
|
174
|
+
err = "Invalid year. LODES data is only available for 2002-2021"
|
|
175
|
+
raise ValueError(err)
|
|
176
|
+
|
|
177
|
+
# LODES year and state exceptions
|
|
178
|
+
# exceptions can be found in this document for LODES8.1: https://lehd.ces.census.gov/data/lodes/LODES8/LODESTechDoc8.1.pdf
|
|
179
|
+
states = list(STATE.truncate_unique(scope.node_ids))
|
|
180
|
+
invalid_conditions = [
|
|
181
|
+
(
|
|
182
|
+
(year in range(2002, 2010)) and self._job_code in ("JT04", "JT05"),
|
|
183
|
+
"Federal job commuters data is not available between 2002 and 2009.",
|
|
184
|
+
),
|
|
185
|
+
(
|
|
186
|
+
("05" in states) and (year == 2002 or year in range(2019, 2022)),
|
|
187
|
+
"Invalid year for state, no commuters can be found "
|
|
188
|
+
"for Arkansas in 2002 or between 2019-2021",
|
|
189
|
+
),
|
|
190
|
+
(
|
|
191
|
+
("04" in states) and (year in (2002, 2003)),
|
|
192
|
+
"Invalid year for state, no commuters can be found "
|
|
193
|
+
"for Arizona in 2002 or 2003",
|
|
194
|
+
),
|
|
195
|
+
(
|
|
196
|
+
("11" in states) and (year in range(2002, 2010)),
|
|
197
|
+
"Invalid year for state, no commuters can be found "
|
|
198
|
+
"for DC in 2002 or between 2002-2009",
|
|
199
|
+
),
|
|
200
|
+
(
|
|
201
|
+
("25" in states) and (year in range(2002, 2011)),
|
|
202
|
+
"Invalid year for state, no commuters can be found "
|
|
203
|
+
"for Massachusetts between 2002-2010",
|
|
204
|
+
),
|
|
205
|
+
(
|
|
206
|
+
("28" in states)
|
|
207
|
+
and (year in range(2002, 2004) or year in range(2019, 2022)),
|
|
208
|
+
"Invalid year for state, no commuters can be found "
|
|
209
|
+
"for Mississippi in 2002, 2003, or between 2019-2021",
|
|
210
|
+
),
|
|
211
|
+
(
|
|
212
|
+
("33" in states) and year == 2002,
|
|
213
|
+
"Invalid year for state, no commuters can be found "
|
|
214
|
+
"for New Hampshire in 2002",
|
|
215
|
+
),
|
|
216
|
+
(
|
|
217
|
+
("02" in states) and year in range(2017, 2022),
|
|
218
|
+
"Invalid year for state, no commuters can be found "
|
|
219
|
+
"for Alaska in between 2017-2021",
|
|
220
|
+
),
|
|
221
|
+
]
|
|
222
|
+
for condition, err in invalid_conditions:
|
|
223
|
+
if condition:
|
|
224
|
+
raise ADRIOContextError(self, context, err)
|
|
225
|
+
|
|
226
|
+
@override
|
|
227
|
+
def estimate_data(self) -> DataEstimate:
|
|
228
|
+
scope = cast(CensusScope, self.scope)
|
|
229
|
+
job_code = self._job_code
|
|
230
|
+
year = self.data_year
|
|
231
|
+
|
|
232
|
+
# for each file, a tuple: (size estimate, already cached?)
|
|
233
|
+
files = [
|
|
234
|
+
(_file_size(state, file, job_code), check_file_in_cache(cache_path))
|
|
235
|
+
for state, file, _, cache_path in _lodes_files(scope, year, job_code)
|
|
236
|
+
]
|
|
237
|
+
|
|
238
|
+
total = sum(size for size, _ in files)
|
|
239
|
+
missing = sum(size for size, in_cache in files if not in_cache)
|
|
240
|
+
|
|
241
|
+
return AvailableDataEstimate(
|
|
242
|
+
name=self.class_name,
|
|
243
|
+
cache_key=f"lodes:{year}:{job_code}",
|
|
244
|
+
new_network_bytes=missing,
|
|
245
|
+
new_cache_bytes=missing,
|
|
246
|
+
total_cache_bytes=total,
|
|
247
|
+
max_bandwidth=None,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
@override
|
|
251
|
+
def inspect(self) -> InspectResult[np.int64, np.int64]:
|
|
252
|
+
self.validate_context(self.context)
|
|
253
|
+
scope = cast(CensusScope, self.scope)
|
|
254
|
+
node_ids: tuple[str, ...] = tuple(scope.node_ids)
|
|
255
|
+
|
|
256
|
+
worker_type = self._worker_type
|
|
257
|
+
|
|
258
|
+
# load the data from each LODES file
|
|
259
|
+
data_frames = []
|
|
260
|
+
files = _lodes_files(scope, self.data_year, self._job_code)
|
|
261
|
+
processing_steps = len(files) + 1
|
|
262
|
+
for i, file in enumerate(files):
|
|
263
|
+
try:
|
|
264
|
+
file_df = pd.read_csv(
|
|
265
|
+
load_or_fetch_url(file.url, file.cache_path),
|
|
266
|
+
compression="gzip",
|
|
267
|
+
dtype={"w_geocode": str, "h_geocode": str, worker_type: int},
|
|
268
|
+
usecols=["w_geocode", "h_geocode", worker_type],
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
# filter to locations that we're interested in
|
|
272
|
+
file_df = file_df[
|
|
273
|
+
file_df["h_geocode"].str.startswith(node_ids)
|
|
274
|
+
& file_df["w_geocode"].str.startswith(node_ids)
|
|
275
|
+
]
|
|
276
|
+
data_frames.append(file_df)
|
|
277
|
+
|
|
278
|
+
self._report_progress((i + 1) / processing_steps)
|
|
279
|
+
except Exception as e:
|
|
280
|
+
err = "Unable to fetch LODES data."
|
|
281
|
+
raise ADRIOCommunicationError(self, self.context, err) from e
|
|
282
|
+
|
|
283
|
+
# Combine LODES data, group by the nodes in our scope, and pivot/sum
|
|
284
|
+
full_df = pd.concat(data_frames)
|
|
285
|
+
|
|
286
|
+
geoid_len = CensusGranularity.of(scope.granularity).length
|
|
287
|
+
|
|
288
|
+
result_np = (
|
|
289
|
+
full_df.assign(
|
|
290
|
+
w_geocode=full_df["w_geocode"].str[:geoid_len],
|
|
291
|
+
h_geocode=full_df["h_geocode"].str[:geoid_len],
|
|
292
|
+
)
|
|
293
|
+
.pivot_table(
|
|
294
|
+
index="h_geocode",
|
|
295
|
+
columns="w_geocode",
|
|
296
|
+
values=worker_type,
|
|
297
|
+
aggfunc="sum",
|
|
298
|
+
fill_value=0,
|
|
299
|
+
sort=True,
|
|
300
|
+
)
|
|
301
|
+
.reindex(
|
|
302
|
+
index=scope.node_ids,
|
|
303
|
+
columns=scope.node_ids,
|
|
304
|
+
fill_value=0,
|
|
305
|
+
)
|
|
306
|
+
.to_numpy(dtype=np.int64)
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
self.validate_result(self.context, result_np)
|
|
310
|
+
return InspectResult(
|
|
311
|
+
adrio=self,
|
|
312
|
+
source=full_df,
|
|
313
|
+
result=result_np,
|
|
314
|
+
dtype=self.result_format.dtype.type,
|
|
315
|
+
shape=self.result_format.shape,
|
|
316
|
+
issues={},
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
@adrio_cache
|
|
321
|
+
class Commuters(_LodesADRIOMixin, ADRIO[np.int64, np.int64]):
|
|
322
|
+
"""
|
|
323
|
+
Loads data from the US Census Bureau's Longitudinal Employer-Household Dynamics
|
|
324
|
+
Origin-Destination Employment Statistics (LODES) data product, version 8.
|
|
325
|
+
LODES provides counts of individuals living in one location and working in another,
|
|
326
|
+
and various subtotals are available.
|
|
327
|
+
|
|
328
|
+
The product aggregates to 2020 census blocks, so this ADRIO can work with scopes
|
|
329
|
+
from state-granularity down to block-group-granularity. The geography year must be
|
|
330
|
+
2020, however the data itself is computed yearly from 2002 through 2022.
|
|
331
|
+
|
|
332
|
+
The result is an NxN matrix of integers, with residency location on the first axis
|
|
333
|
+
and work location on the second axis.
|
|
334
|
+
|
|
335
|
+
Parameters
|
|
336
|
+
----------
|
|
337
|
+
year :
|
|
338
|
+
The year for the commuting data.
|
|
339
|
+
Defaults to the year in which the simulation time frame starts.
|
|
340
|
+
job_type :
|
|
341
|
+
The job category used to filter commuters.
|
|
342
|
+
"""
|
|
343
|
+
|
|
344
|
+
def __init__(self, *, year: int | None = None, job_type: JobType = "All Jobs"):
|
|
345
|
+
self._override_year = year
|
|
346
|
+
self._job_type = job_type
|
|
347
|
+
|
|
348
|
+
@property
|
|
349
|
+
@override
|
|
350
|
+
def _worker_type(self) -> str:
|
|
351
|
+
return "S000"
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
@adrio_cache
|
|
355
|
+
class CommutersByAge(_LodesADRIOMixin, ADRIO[np.int64, np.int64]):
|
|
356
|
+
"""
|
|
357
|
+
Loads data from the US Census Bureau's Longitudinal Employer-Household Dynamics
|
|
358
|
+
Origin-Destination Employment Statistics (LODES) data product, version 8.
|
|
359
|
+
LODES provides counts of individuals living in one location and working in another,
|
|
360
|
+
and various subtotals are available.
|
|
361
|
+
|
|
362
|
+
The product aggregates to 2020 census blocks, so this ADRIO can work with scopes
|
|
363
|
+
from state-granularity down to block-group-granularity. The geography year must be
|
|
364
|
+
2020, however the data itself is computed yearly from 2002 through 2022.
|
|
365
|
+
|
|
366
|
+
This ADRIO filters by age groups of the workers.
|
|
367
|
+
The result is an NxN matrix of integers, with residency location on the first axis
|
|
368
|
+
and work location on the second axis.
|
|
369
|
+
|
|
370
|
+
Parameters
|
|
371
|
+
----------
|
|
372
|
+
age_range :
|
|
373
|
+
The age range used to filter commuters.
|
|
374
|
+
year :
|
|
375
|
+
The year for the commuting data.
|
|
376
|
+
Defaults to the year in which the simulation time frame starts.
|
|
377
|
+
job_type :
|
|
378
|
+
The job category used to filter commuters.
|
|
379
|
+
"""
|
|
380
|
+
|
|
381
|
+
_age_range: AgeRange
|
|
382
|
+
|
|
383
|
+
def __init__(
|
|
384
|
+
self,
|
|
385
|
+
age_range: AgeRange,
|
|
386
|
+
*,
|
|
387
|
+
year: int | None = None,
|
|
388
|
+
job_type: JobType = "All Jobs",
|
|
389
|
+
):
|
|
390
|
+
self._override_year = year
|
|
391
|
+
self._job_type = job_type
|
|
392
|
+
self._age_range = age_range
|
|
393
|
+
|
|
394
|
+
@property
|
|
395
|
+
@override
|
|
396
|
+
def _worker_type(self) -> str:
|
|
397
|
+
match self._age_range:
|
|
398
|
+
case "29 and Under":
|
|
399
|
+
return "SA01"
|
|
400
|
+
case "30_54":
|
|
401
|
+
return "SA02"
|
|
402
|
+
case "55 and Over":
|
|
403
|
+
return "SA03"
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
@adrio_cache
|
|
407
|
+
class CommutersByEarnings(_LodesADRIOMixin, ADRIO[np.int64, np.int64]):
|
|
408
|
+
"""
|
|
409
|
+
Loads data from the US Census Bureau's Longitudinal Employer-Household Dynamics
|
|
410
|
+
Origin-Destination Employment Statistics (LODES) data product, version 8.
|
|
411
|
+
LODES provides counts of individuals living in one location and working in another,
|
|
412
|
+
and various subtotals are available.
|
|
413
|
+
|
|
414
|
+
The product aggregates to 2020 census blocks, so this ADRIO can work with scopes
|
|
415
|
+
from state-granularity down to block-group-granularity. The geography year must be
|
|
416
|
+
2020, however the data itself is computed yearly from 2002 through 2022.
|
|
417
|
+
|
|
418
|
+
This ADRIO filters by the monthly earning bracket of the workers.
|
|
419
|
+
The result is an NxN matrix of integers, with residency location on the first axis
|
|
420
|
+
and work location on the second axis.
|
|
421
|
+
|
|
422
|
+
Parameters
|
|
423
|
+
----------
|
|
424
|
+
earning_range :
|
|
425
|
+
The monthly earnings range used to filter commuters.
|
|
426
|
+
year :
|
|
427
|
+
The year for the commuting data.
|
|
428
|
+
Defaults to the year in which the simulation time frame starts.
|
|
429
|
+
job_type :
|
|
430
|
+
The job category used to filter commuters.
|
|
431
|
+
"""
|
|
432
|
+
|
|
433
|
+
_earning_range: EarningRange
|
|
434
|
+
"""The monthly earnings range used to filter commuters."""
|
|
435
|
+
|
|
436
|
+
def __init__(
|
|
437
|
+
self,
|
|
438
|
+
earning_range: EarningRange,
|
|
439
|
+
*,
|
|
440
|
+
year: int | None = None,
|
|
441
|
+
job_type: JobType = "All Jobs",
|
|
442
|
+
):
|
|
443
|
+
self._override_year = year
|
|
444
|
+
self._job_type = job_type
|
|
445
|
+
self._earning_range = earning_range
|
|
446
|
+
|
|
447
|
+
@property
|
|
448
|
+
@override
|
|
449
|
+
def _worker_type(self) -> str:
|
|
450
|
+
match self._earning_range:
|
|
451
|
+
case "$1250 and Under":
|
|
452
|
+
return "SE01"
|
|
453
|
+
case "$1251_$3333":
|
|
454
|
+
return "SE02"
|
|
455
|
+
case "$3333 and Over":
|
|
456
|
+
return "SE03"
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
@adrio_cache
|
|
460
|
+
class CommutersByIndustry(_LodesADRIOMixin, ADRIO[np.int64, np.int64]):
|
|
461
|
+
"""
|
|
462
|
+
Loads data from the US Census Bureau's Longitudinal Employer-Household Dynamics
|
|
463
|
+
Origin-Destination Employment Statistics (LODES) data product, version 8.
|
|
464
|
+
LODES provides counts of individuals living in one location and working in another,
|
|
465
|
+
and various subtotals are available.
|
|
466
|
+
|
|
467
|
+
The product aggregates to 2020 census blocks, so this ADRIO can work with scopes
|
|
468
|
+
from state-granularity down to block-group-granularity. The geography year must be
|
|
469
|
+
2020, however the data itself is computed yearly from 2002 through 2022.
|
|
470
|
+
|
|
471
|
+
This ADRIO filters by the job industry of the workers.
|
|
472
|
+
The result is an NxN matrix of integers, with residency location on the first axis
|
|
473
|
+
and work location on the second axis.
|
|
474
|
+
|
|
475
|
+
Parameters
|
|
476
|
+
----------
|
|
477
|
+
industry :
|
|
478
|
+
The industry used to filter commuters.
|
|
479
|
+
year :
|
|
480
|
+
The year for the commuting data.
|
|
481
|
+
Defaults to the year in which the simulation time frame starts.
|
|
482
|
+
job_type :
|
|
483
|
+
The job category used to filter commuters.
|
|
484
|
+
"""
|
|
485
|
+
|
|
486
|
+
_industry: Industry
|
|
487
|
+
"""The industry used to filter commuters."""
|
|
488
|
+
|
|
489
|
+
def __init__(
|
|
490
|
+
self,
|
|
491
|
+
industry: Industry,
|
|
492
|
+
*,
|
|
493
|
+
year: int | None = None,
|
|
494
|
+
job_type: JobType = "All Jobs",
|
|
495
|
+
):
|
|
496
|
+
self._override_year = year
|
|
497
|
+
self._job_type = job_type
|
|
498
|
+
self._industry = industry
|
|
499
|
+
|
|
500
|
+
@property
|
|
501
|
+
@override
|
|
502
|
+
def _worker_type(self) -> str:
|
|
503
|
+
match self._industry:
|
|
504
|
+
case "Goods Producing":
|
|
505
|
+
return "SI01"
|
|
506
|
+
case "Trade Transport Utility":
|
|
507
|
+
return "SI02"
|
|
508
|
+
case "Other":
|
|
509
|
+
return "SI03"
|
epymorph/adrio/numpy.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""ADRIO for loading data from a compressed numpy data file (.npy or .npz)."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numpy.lib.npyio import NpzFile
|
|
7
|
+
from numpy.typing import NDArray
|
|
8
|
+
from typing_extensions import override
|
|
9
|
+
|
|
10
|
+
from epymorph.adrio.adrio import (
|
|
11
|
+
ADRIO,
|
|
12
|
+
ADRIOContextError,
|
|
13
|
+
ADRIOProcessingError,
|
|
14
|
+
InspectResult,
|
|
15
|
+
adrio_validate_pipe,
|
|
16
|
+
)
|
|
17
|
+
from epymorph.adrio.validation import (
|
|
18
|
+
ResultFormat,
|
|
19
|
+
validate_dtype,
|
|
20
|
+
validate_numpy,
|
|
21
|
+
validate_shape_unchecked_arbitrary,
|
|
22
|
+
)
|
|
23
|
+
from epymorph.data_shape import DataShape
|
|
24
|
+
from epymorph.error import MissingContextError
|
|
25
|
+
from epymorph.simulation import Context, validate_context_for_shape
|
|
26
|
+
|
|
27
|
+
SliceOrEllipsis = slice | type(Ellipsis)
|
|
28
|
+
"""Type alias: either a `slice` object or an ellipsis (`...`)."""
|
|
29
|
+
|
|
30
|
+
ArraySlice = SliceOrEllipsis | tuple[SliceOrEllipsis, ...]
|
|
31
|
+
"""
|
|
32
|
+
Type alias for a numpy array slice.
|
|
33
|
+
|
|
34
|
+
See Also
|
|
35
|
+
--------
|
|
36
|
+
It's very convenient to use numpy's `IndexExpression` helpers like [numpy.s\\_][]
|
|
37
|
+
to create one of these.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class NumpyFile(ADRIO[np.generic, np.generic]):
|
|
42
|
+
"""
|
|
43
|
+
Retrieves an array of data from a .npy or .npz file.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
file_path :
|
|
48
|
+
The path to a .npy or .npz file to load.
|
|
49
|
+
shape :
|
|
50
|
+
The expected shape of the array. "Arbitrary" axes lengths will not be
|
|
51
|
+
checked.
|
|
52
|
+
dtype :
|
|
53
|
+
The expected dtype of the array.
|
|
54
|
+
array_name :
|
|
55
|
+
If and only if loading an .npz file, the name of the array to load.
|
|
56
|
+
For .npy files, this must be `None`.
|
|
57
|
+
array_slice :
|
|
58
|
+
The optional array slice to apply to the loaded array. numpy provides a
|
|
59
|
+
helper called `np.s_` which is a convenient way to construct these.
|
|
60
|
+
If `None`, the entire array is returned.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
_file_path: Path
|
|
64
|
+
"""The path to a .npy or .npz file to load."""
|
|
65
|
+
_shape: DataShape
|
|
66
|
+
"""The expected shape of the array."""
|
|
67
|
+
_dtype: np.dtype
|
|
68
|
+
"""The expected dtype of the array."""
|
|
69
|
+
_array_name: str | None
|
|
70
|
+
"""The name of the array to load from an npz file."""
|
|
71
|
+
_array_slice: ArraySlice | None
|
|
72
|
+
"""The optional array slice to apply to the loaded array."""
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
*,
|
|
77
|
+
file_path: str | Path,
|
|
78
|
+
shape: DataShape,
|
|
79
|
+
dtype: np.dtype | type[np.generic],
|
|
80
|
+
array_name: str | None = None,
|
|
81
|
+
array_slice: ArraySlice | None = None,
|
|
82
|
+
) -> None:
|
|
83
|
+
file_path = file_path if isinstance(file_path, Path) else Path(file_path)
|
|
84
|
+
match file_path.suffix:
|
|
85
|
+
case ".npy":
|
|
86
|
+
if array_name is not None:
|
|
87
|
+
err = "To load an .npy file, do not specify an `array_name`."
|
|
88
|
+
raise ValueError(err)
|
|
89
|
+
case ".npz":
|
|
90
|
+
if array_name is None:
|
|
91
|
+
err = "To load an .npz file, specify the `array_name` to load."
|
|
92
|
+
raise ValueError(err)
|
|
93
|
+
case _:
|
|
94
|
+
err = "This ADRIO supports .npz or .npy files only."
|
|
95
|
+
raise ValueError(err)
|
|
96
|
+
|
|
97
|
+
self._file_path = file_path
|
|
98
|
+
self._shape = shape
|
|
99
|
+
self._dtype = dtype if isinstance(dtype, np.dtype) else np.dtype(dtype)
|
|
100
|
+
self._array_slice = array_slice
|
|
101
|
+
self._array_name = array_name
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
@override
|
|
105
|
+
def result_format(self) -> ResultFormat:
|
|
106
|
+
return ResultFormat(shape=self._shape, dtype=self._dtype)
|
|
107
|
+
|
|
108
|
+
@override
|
|
109
|
+
def validate_context(self, context: Context) -> None:
|
|
110
|
+
try:
|
|
111
|
+
validate_context_for_shape(context, self._shape)
|
|
112
|
+
except MissingContextError as e:
|
|
113
|
+
raise ADRIOContextError(self, self.context, str(e))
|
|
114
|
+
|
|
115
|
+
@override
|
|
116
|
+
def inspect(self) -> InspectResult[np.generic, np.generic]:
|
|
117
|
+
self.validate_context(self.context)
|
|
118
|
+
try:
|
|
119
|
+
data = np.load(self._file_path)
|
|
120
|
+
if isinstance(data, NpzFile):
|
|
121
|
+
if self._array_name is None:
|
|
122
|
+
err = "To load an .npz file, specify the `array_name` to load."
|
|
123
|
+
raise ADRIOProcessingError(self, self.context, err)
|
|
124
|
+
result = data[self._array_name]
|
|
125
|
+
data.close()
|
|
126
|
+
elif isinstance(data, np.ndarray):
|
|
127
|
+
result = data
|
|
128
|
+
else:
|
|
129
|
+
err = "File did not contain data as expected."
|
|
130
|
+
raise ADRIOProcessingError(self, self.context, err)
|
|
131
|
+
|
|
132
|
+
if self._array_slice is not None:
|
|
133
|
+
result = result[self._array_slice]
|
|
134
|
+
except (OSError, ValueError) as e:
|
|
135
|
+
err = "Error loading file."
|
|
136
|
+
raise ADRIOProcessingError(self, self.context, err) from e
|
|
137
|
+
except IndexError as e:
|
|
138
|
+
err = "Specified array slice is invalid for the shape of this data."
|
|
139
|
+
raise ADRIOProcessingError(self, self.context, err) from e
|
|
140
|
+
|
|
141
|
+
self.validate_result(self.context, result)
|
|
142
|
+
return InspectResult(
|
|
143
|
+
adrio=self,
|
|
144
|
+
source=result,
|
|
145
|
+
result=result,
|
|
146
|
+
dtype=self._dtype.type,
|
|
147
|
+
shape=self._shape,
|
|
148
|
+
issues={},
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
@override
|
|
152
|
+
def validate_result(self, context: Context, result: NDArray[np.generic]) -> None:
|
|
153
|
+
adrio_validate_pipe(
|
|
154
|
+
self,
|
|
155
|
+
context,
|
|
156
|
+
result,
|
|
157
|
+
validate_numpy(),
|
|
158
|
+
validate_shape_unchecked_arbitrary(self._shape.to_tuple(context.dim)),
|
|
159
|
+
validate_dtype(self._dtype),
|
|
160
|
+
)
|