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
@@ -0,0 +1,283 @@
1
+ """ADRIOs for US Census Bureau American Community Survey Commuting Flows data."""
2
+
3
+ from pathlib import Path
4
+ from typing import Callable, Literal, NamedTuple
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from numpy.typing import NDArray
9
+ from typing_extensions import override
10
+
11
+ from epymorph.adrio.adrio import (
12
+ ADRIOCommunicationError,
13
+ ADRIOContextError,
14
+ FetchADRIO,
15
+ PipelineResult,
16
+ adrio_validate_pipe,
17
+ )
18
+ from epymorph.adrio.processing import DataPipeline, Fill, PivotAxis
19
+ from epymorph.adrio.validation import (
20
+ ResultFormat,
21
+ validate_dtype,
22
+ validate_numpy,
23
+ validate_shape,
24
+ validate_values_in_range,
25
+ )
26
+ from epymorph.cache import check_file_in_cache, load_or_fetch_url, module_cache_path
27
+ from epymorph.data_shape import Shapes
28
+ from epymorph.data_usage import AvailableDataEstimate, DataEstimate
29
+ from epymorph.geography.us_census import CountyScope, StateScope
30
+ from epymorph.simulation import Context
31
+
32
+ _COMMFLOWS_CACHE_PATH = module_cache_path(__name__)
33
+
34
+
35
+ class _Config(NamedTuple):
36
+ """Configuration for an ACS Comm Flows product."""
37
+
38
+ year: int
39
+ """The nominal year of the survey results."""
40
+ geo_year: int
41
+ """The Census vintage used in the data."""
42
+ url: str
43
+ """The URL for the source file."""
44
+ header: int
45
+ """How many header rows?"""
46
+ footer: int
47
+ """How many footer rows?"""
48
+ cols: list[str]
49
+ """Column names."""
50
+ estimate: int
51
+ """Estimated file size in bytes."""
52
+
53
+ @property
54
+ def cache_path(self) -> Path:
55
+ """The path to where the source data should be cached."""
56
+ return _COMMFLOWS_CACHE_PATH / f"{self.year}.xlsx"
57
+
58
+ @property
59
+ def cache_key(self) -> str:
60
+ """The cache key to use for this result."""
61
+ return f"commflows:{self.year}"
62
+
63
+
64
+ # fmt: off
65
+ _CONFIG = [
66
+ _Config(
67
+ year=2010,
68
+ geo_year=2010,
69
+ url="https://www2.census.gov/programs-surveys/demo/tables/metro-micro/2010/commuting-employment-2010/table1.xlsx",
70
+ header=4,
71
+ footer=3,
72
+ cols=[
73
+ "res_state_code", "res_county_code", "wrk_state_code", "wrk_county_code",
74
+ "workers", "moe", "res_state", "res_county", "wrk_state", "wrk_county",
75
+ ],
76
+ estimate=7_200_000,
77
+ ),
78
+ _Config(
79
+ year=2015,
80
+ geo_year=2015,
81
+ url="https://www2.census.gov/programs-surveys/demo/tables/metro-micro/2015/commuting-flows-2015/table1.xlsx",
82
+ header=6,
83
+ footer=2,
84
+ cols=[
85
+ "res_state_code", "res_county_code", "res_state", "res_county",
86
+ "wrk_state_code", "wrk_county_code", "wrk_state", "wrk_county",
87
+ "workers", "moe",
88
+ ],
89
+ estimate=6_700_000,
90
+ ),
91
+ _Config(
92
+ year=2020,
93
+ geo_year=2022,
94
+ # yes, the 2020 results use 2022 geography, which is when the Census officially
95
+ # switched to using planning regions instead of counties for Connecticut.
96
+ # The footer of this document says as much.
97
+ url="https://www2.census.gov/programs-surveys/demo/tables/metro-micro/2020/commuting-flows-2020/table1.xlsx",
98
+ header=7,
99
+ footer=4,
100
+ cols=[
101
+ "res_state_code", "res_county_code", "res_state", "res_county",
102
+ "wrk_state_code", "wrk_county_code", "wrk_state", "wrk_county",
103
+ "workers", "moe",
104
+ ],
105
+ estimate=5_800_000,
106
+ ),
107
+ ]
108
+ """All supported ACS Comm Flow products."""
109
+ # fmt: on
110
+
111
+
112
+ class Commuters(FetchADRIO[np.int64, np.int64]):
113
+ """
114
+ Loads data from the US Census Bureau's ACS Commuting Flows product.
115
+ This product uses answers to the American Community Survey over a five year period
116
+ to estimate the number of workers aggregated by where they live and where they work.
117
+ It is a useful estimate of regular commuting activity between locations.
118
+
119
+ The product aggregates to the US-County-equivalent granularity, so this ADRIO
120
+ can work with county or state scopes. Because the data are presented using
121
+ FIPS codes, we must be certain to use a compatible scope -- therefore the
122
+ data vintage loaded by this ADRIO is based on the geo scope year and not the
123
+ simulation time frame. Available data years are nominally 2010, 2015, and 2020,
124
+ however note that the 2020 data year was compiled using 2022 geography.
125
+
126
+ The result is an NxN matrix of integers, with residency location on the first axis
127
+ and work location on the second axis.
128
+
129
+ Parameters
130
+ ----------
131
+ fix_missing :
132
+ The method to use to fix missing values. Missing values are common in this dataset,
133
+ which simply omits pairs of locations for which there were no recorded workers.
134
+ Therefore the default is to fill with zero.
135
+
136
+ See Also
137
+ --------
138
+ The [ACS Commuting Flows documentation](https://www.census.gov/topics/employment/commuting/guidance/flows.html)
139
+ from the US Census.
140
+ """ # noqa: E501
141
+
142
+ _fix_missing: Fill[np.int64]
143
+ """The method to use to fix missing values."""
144
+
145
+ def __init__(
146
+ self,
147
+ *,
148
+ fix_missing: Fill[np.int64] | int | Callable[[], int] | Literal[False] = 0,
149
+ ):
150
+ try:
151
+ self._fix_missing = Fill.of_int64(fix_missing)
152
+ except ValueError:
153
+ raise ValueError("Invalid value for `fix_missing`")
154
+
155
+ @property
156
+ @override
157
+ def result_format(self) -> ResultFormat:
158
+ return ResultFormat(shape=Shapes.NxN, dtype=np.int64)
159
+
160
+ @override
161
+ def validate_result(self, context: Context, result: NDArray) -> None:
162
+ adrio_validate_pipe(
163
+ self,
164
+ context,
165
+ result,
166
+ validate_numpy(),
167
+ validate_shape(self.result_format.shape.to_tuple(context.dim)),
168
+ validate_dtype(self.result_format.dtype),
169
+ validate_values_in_range(0, None),
170
+ )
171
+
172
+ def _get_config(self, context: Context) -> tuple[_Config, StateScope | CountyScope]:
173
+ scope = context.scope
174
+ if not isinstance(scope, StateScope | CountyScope):
175
+ err = "US State or County geo scope required."
176
+ raise ADRIOContextError(self, context, err)
177
+
178
+ config = next((x for x in _CONFIG if x.geo_year == scope.year), None)
179
+ if config is None:
180
+ all_years = [str(x.geo_year) for x in _CONFIG]
181
+ err = (
182
+ "Commuters loads data according to your geo scope year "
183
+ "because it is sensitive to changes in geography. "
184
+ "Data is only available for these geo years: "
185
+ f"{','.join(all_years)}"
186
+ )
187
+ raise ADRIOContextError(self, context, err)
188
+
189
+ return config, scope
190
+
191
+ @override
192
+ def estimate_data(self) -> DataEstimate:
193
+ config, _ = self._get_config(self.context)
194
+ in_cache = check_file_in_cache(config.cache_path)
195
+ total_bytes = config.estimate
196
+ new_bytes = total_bytes if not in_cache else 0
197
+ return AvailableDataEstimate(
198
+ name=self.class_name,
199
+ cache_key=config.cache_key,
200
+ new_network_bytes=new_bytes,
201
+ new_cache_bytes=new_bytes,
202
+ total_cache_bytes=total_bytes,
203
+ max_bandwidth=None,
204
+ )
205
+
206
+ @override
207
+ def validate_context(self, context: Context) -> None:
208
+ self._get_config(context)
209
+
210
+ @override
211
+ def _fetch(self, context: Context) -> pd.DataFrame:
212
+ config, scope = self._get_config(context)
213
+
214
+ # Get and read data file.
215
+ try:
216
+ commuter_file = load_or_fetch_url(config.url, config.cache_path)
217
+ except Exception as e:
218
+ raise ADRIOCommunicationError(self, context) from e
219
+
220
+ data_df = pd.read_excel(
221
+ commuter_file,
222
+ header=config.header,
223
+ skipfooter=config.footer,
224
+ names=config.cols,
225
+ usecols=[
226
+ "res_state_code",
227
+ "res_county_code",
228
+ "wrk_state_code",
229
+ "wrk_county_code",
230
+ "workers",
231
+ ],
232
+ dtype={
233
+ "res_state_code": str,
234
+ "wrk_state_code": str,
235
+ "res_county_code": str,
236
+ "wrk_county_code": str,
237
+ "workers": np.int64,
238
+ },
239
+ )
240
+
241
+ # Filter out destinations which are not US states and fix two-digit state codes.
242
+ data_df = data_df.loc[data_df["wrk_state_code"].str.startswith("0", na=False)]
243
+ data_df = data_df.assign(wrk_state_code=data_df["wrk_state_code"].str.slice(1))
244
+
245
+ # Reformat to combine geoid columns according to result granularity.
246
+ if scope.granularity == "state":
247
+ geoid_src = data_df["res_state_code"]
248
+ geoid_dst = data_df["wrk_state_code"]
249
+ else:
250
+ geoid_src = data_df["res_state_code"] + data_df["res_county_code"]
251
+ geoid_dst = data_df["wrk_state_code"] + data_df["wrk_county_code"]
252
+ data_df = pd.DataFrame(
253
+ {
254
+ "geoid_src": geoid_src,
255
+ "geoid_dst": geoid_dst,
256
+ "value": data_df["workers"],
257
+ }
258
+ )
259
+
260
+ # Filter for the geographies in our scope.
261
+ src_in = data_df["geoid_src"].isin(context.scope.node_ids)
262
+ dst_in = data_df["geoid_dst"].isin(context.scope.node_ids)
263
+ data_df = data_df.loc[src_in & dst_in]
264
+
265
+ # Aggregate results if our result granularity requires it. Fix indexing.
266
+ if scope.granularity == "state":
267
+ data_df = data_df.groupby(["geoid_src", "geoid_dst"]).sum().reset_index()
268
+ else:
269
+ data_df = data_df.reset_index(drop=True)
270
+ return data_df
271
+
272
+ @override
273
+ def _process(self, context: Context, data_df: pd.DataFrame) -> PipelineResult:
274
+ pipeline = DataPipeline(
275
+ axes=(
276
+ PivotAxis("geoid_src", context.scope.node_ids),
277
+ PivotAxis("geoid_dst", context.scope.node_ids),
278
+ ),
279
+ ndims=2,
280
+ dtype=self.result_format.dtype.type,
281
+ rng=context,
282
+ ).finalize(self._fix_missing)
283
+ return pipeline(data_df)