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,1083 @@
1
+ """
2
+ Functions for fetching information from TIGER files for common US Census geographic
3
+ delineations. This is designed to return information for a common selection of the
4
+ United States and territories, and handles quirks and differences between the supported
5
+ census years.
6
+ """
7
+
8
+ import re
9
+ from abc import ABC
10
+ from dataclasses import asdict, dataclass
11
+ from functools import cached_property
12
+ from io import BytesIO
13
+ from pathlib import Path
14
+ from typing import (
15
+ Callable,
16
+ Literal,
17
+ Mapping,
18
+ NamedTuple,
19
+ Sequence,
20
+ TypeGuard,
21
+ TypeVar,
22
+ overload,
23
+ )
24
+
25
+ import numpy as np
26
+ from geopandas import GeoDataFrame
27
+ from geopandas import read_file as gp_read_file
28
+ from pandas import DataFrame
29
+ from pandas import concat as pd_concat
30
+ from typing_extensions import override
31
+
32
+ from epymorph.adrio.adrio import ProgressCallback
33
+ from epymorph.cache import (
34
+ CacheMissError,
35
+ check_file_in_cache,
36
+ load_bundle_from_cache,
37
+ load_or_fetch_url,
38
+ module_cache_path,
39
+ save_bundle_to_cache,
40
+ )
41
+ from epymorph.error import GeographyError
42
+ from epymorph.geography.us_geography import STATE, CensusGranularityName
43
+ from epymorph.util import cache_transparent, normalize_list, normalize_str, zip_list
44
+
45
+ # A fair question is why did we implement our own TIGER files loader instead of using
46
+ # pygris? The short answer is for efficiently and to correct inconsistencies that matter
47
+ # for our use-case. For one, pygris always loads geography but we only want the
48
+ # geography sometimes. By loading it ourselves, we can tell Geopandas to skip it,
49
+ # which is a lot faster. Second, asking pygris for counties in 2020 returns all
50
+ # territories, while 2010 and 2000 do not.
51
+ # This *is* consistent with the TIGER files themselves, but not ideal for us.
52
+ # (You can compare the following two files to see for yourself:)
53
+ # https://www2.census.gov/geo/tiger/TIGER2020/COUNTY/tl_2020_us_county.zip
54
+ # https://www2.census.gov/geo/tiger/TIGER2010/COUNTY/2010/tl_2010_us_county10.zip
55
+ # Lastly, pygris has a bug which is patched but not available in a release version
56
+ # at this time:
57
+ # https://github.com/walkerke/pygris/commit/9ad16208b5b1e67909ff2dfdea26333ddd4a2e17
58
+
59
+ # NOTE on which states/territories are included in our results --
60
+ # We have chosen to filter results to include only the 50 states, District of Columbia,
61
+ # and Puerto Rico. This is not the entire set of data provided by TIGER files, but does
62
+ # align with the data that ACS5 provides. Since that is our primary data source at the
63
+ # moment, we felt that this was an acceptable simplification. Either we make the two
64
+ # sets match (as we've done here, by removing 4 territories) OR we have a special
65
+ # "all states for the ACS5" scope. We chose this solution as the less-bad option,
66
+ # but this may be revised in future. Below there are some commented-code remnants which
67
+ # demonstrate what it takes to support the additional territories, in case we ever want
68
+ # to reverse this choice.
69
+
70
+ # NOTE: TIGER files express areas in meters-squared.
71
+
72
+ # fmt: off
73
+ TigerYear = Literal[2000, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023] # noqa
74
+ """A supported TIGER file year. (2000 and 2009-2023)"""
75
+
76
+ TIGER_YEARS: Sequence[TigerYear] = (2000, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023) #noqa
77
+ """All supported TIGER file years. (2000 and 2009-2023)"""
78
+
79
+ _SUPPORTED_STATES = [
80
+ "01", "02", "04", "05", "06", "08", "09", "10", "11", "12",
81
+ "13", "15", "16", "17", "18", "19", "20", "21", "22", "23",
82
+ "24", "25", "26", "27", "28", "29", "30", "31", "32", "33",
83
+ "34", "35", "36", "37", "38", "39", "40", "41", "42", "44",
84
+ "45", "46", "47", "48", "49", "50", "51", "53", "54", "55",
85
+ "56", "72",
86
+ ]
87
+ """
88
+ The FIPS IDs of states which are included in our set of supported states.
89
+ Not needed if we didn't have to filter out 4 territories. (60, 66, 69, 78)
90
+ """
91
+ # fmt: on
92
+
93
+ _TIGER_URL = "https://www2.census.gov/geo/tiger"
94
+
95
+ _TIGER_CACHE_PATH = module_cache_path(__name__)
96
+
97
+ _CACHE_VERSION = 1
98
+
99
+ _SUPPORTED_STATE_FILES = ["us"]
100
+ """
101
+ The IDs of TIGER files that are included in our set of supported states.
102
+ In some TIGER years, data for the 4 territories were given in separate files.
103
+ """
104
+
105
+
106
+ def is_tiger_year(year: int) -> TypeGuard[TigerYear]:
107
+ """
108
+ Check that a year is a supported TIGER year, as a type guard.
109
+
110
+ Parameters
111
+ ----------
112
+ year :
113
+ The year to check.
114
+
115
+ Returns
116
+ -------
117
+ :
118
+ True (as a type guard) if the year is in the set of supported TIGER years.
119
+ """
120
+ return year in TIGER_YEARS
121
+
122
+
123
+ def _url_to_cache_path(url: str) -> Path:
124
+ """Given the URL of a TIGER file, return the cache path we should use for it."""
125
+ return _TIGER_CACHE_PATH / Path(url).name
126
+
127
+
128
+ class _DataConfig(NamedTuple):
129
+ """
130
+ Encodes configuration details needed to access a particular granularity and year
131
+ of TIGER files.
132
+ """
133
+
134
+ granularity: CensusGranularityName
135
+ """The granularity these details are for."""
136
+ urls: list[str]
137
+ """URLs for all of the required data files."""
138
+ columns: list[tuple[str, str]]
139
+ """Map each column's name in the source file to its final name in the result."""
140
+ estimated_file_size: int
141
+ """The approximate size of individual TIGER files at this granularity."""
142
+
143
+
144
+ @overload
145
+ def _load_tiger_data(
146
+ config: _DataConfig,
147
+ *,
148
+ ignore_geometry: Literal[True],
149
+ progress: ProgressCallback | None = None,
150
+ ) -> DataFrame: ...
151
+
152
+
153
+ @overload
154
+ def _load_tiger_data(
155
+ config: _DataConfig,
156
+ *,
157
+ ignore_geometry: Literal[False],
158
+ progress: ProgressCallback | None = None,
159
+ ) -> GeoDataFrame: ...
160
+
161
+
162
+ def _load_tiger_data(
163
+ config: _DataConfig,
164
+ *,
165
+ ignore_geometry: bool,
166
+ progress: ProgressCallback | None = None,
167
+ ) -> DataFrame | GeoDataFrame:
168
+ """
169
+ Load TIGER files either from disk cache or the network.
170
+ The result is processed and returned as one large DataFrame.
171
+ """
172
+ _, urls, columns, _ = config
173
+ processing_steps = len(urls) + 1 # add one to account for the post-processing
174
+ try:
175
+ # Fetch the contents of each file and read them as a DataFrame.
176
+ dfs = list[DataFrame]()
177
+ for i, u in enumerate(urls):
178
+ u_df = gp_read_file(
179
+ load_or_fetch_url(u, _url_to_cache_path(u)),
180
+ engine="fiona",
181
+ ignore_geometry=ignore_geometry,
182
+ include_fields=[c for c, _ in columns],
183
+ )
184
+ dfs.append(u_df)
185
+ if progress is not None:
186
+ progress((i + 1) / processing_steps, None)
187
+
188
+ # Concat the DataFrames, fix column names, and data quality checks.
189
+ combined_df = (
190
+ pd_concat(dfs, ignore_index=True)
191
+ .rename(columns=dict(columns))
192
+ .drop_duplicates()
193
+ )
194
+ # Drop records that aren't in our supported set of states.
195
+ selection = combined_df["GEOID"].apply(STATE.truncate).isin(_SUPPORTED_STATES)
196
+ selected_df = combined_df[selection]
197
+ return selected_df if ignore_geometry else GeoDataFrame(selected_df)
198
+ except Exception as e:
199
+ msg = "Unable to retrieve TIGER files for US Census geography."
200
+ raise GeographyError(msg) from e
201
+
202
+
203
+ @dataclass(frozen=True)
204
+ class GranularitySummary(ABC):
205
+ """
206
+ Contains information about the geography at the given level of
207
+ granularity for a specific Census year. The information available may differ
208
+ between the implementations for different granularities, but at a minimum
209
+ each provides the full list of GEOIDs in that granularity.
210
+
211
+ Concrete child classes exist for the various Census granularity levels.
212
+
213
+ Parameters
214
+ ----------
215
+ geoid :
216
+ The GEOIDs (sometimes called FIPS codes) of all nodes in this granularity.
217
+ """
218
+
219
+ geoid: list[str]
220
+ """The GEOIDs (sometimes called FIPS codes) of all nodes in this granularity."""
221
+
222
+ def interpret(self, identifiers: Sequence[str]) -> list[str]:
223
+ """
224
+ Permissively interprets the given set of identifiers as describing nodes,
225
+ and converts them to a sorted list of GEOIDs.
226
+
227
+ Parameters
228
+ ----------
229
+ identifiers :
230
+ A list of identifiers. Which kind of identifiers are allowed depends
231
+ on the granularity.
232
+
233
+ Returns
234
+ -------
235
+ :
236
+ The list of GEOIDs in canonical sort order.
237
+
238
+ Raises
239
+ ------
240
+ GeographyError
241
+ If the identifiers cannot be interpreted.
242
+ """
243
+ # The base case is that the identifiers are literal GEOIDs.
244
+ return self._to_geoid(identifiers, self.geoid, "FIPS code")
245
+
246
+ def _to_geoid(
247
+ self,
248
+ identifiers: Sequence[str],
249
+ source: list[str],
250
+ description: str,
251
+ ) -> list[str]:
252
+ results = list[str]()
253
+ for x in identifiers:
254
+ try:
255
+ i = source.index(normalize_str(x))
256
+ results.append(self.geoid[i])
257
+ except ValueError:
258
+ err = f"{x} is not a valid {description}."
259
+ raise GeographyError(err) from None
260
+ results.sort()
261
+ return results
262
+
263
+
264
+ _SummaryT = TypeVar("_SummaryT", bound=GranularitySummary)
265
+
266
+
267
+ def _load_summary_from_cache(
268
+ relpath: str,
269
+ on_miss: Callable[[], _SummaryT], # load ModelT from another source
270
+ on_hit: Callable[..., _SummaryT], # load ModelT from cache (constructor)
271
+ ) -> _SummaryT:
272
+ # NOTE: this would be more natural as a decorator,
273
+ # but Pylance seems to have problems tracking the return type properly
274
+ # with that implementation
275
+ path = _TIGER_CACHE_PATH.joinpath(relpath)
276
+ try:
277
+ content = load_bundle_from_cache(path, _CACHE_VERSION)
278
+ with np.load(content["data.npz"]) as data_npz:
279
+ return on_hit(**{k: v.tolist() for k, v in data_npz.items()})
280
+ except CacheMissError:
281
+ data = on_miss()
282
+ data_bytes = BytesIO()
283
+ # NOTE: Python doesn't include a type for dataclass instances;
284
+ # you can import DataclassInstance from _typeshed, but that seems
285
+ # to break test discovery. Oh well; just ignore this one.
286
+ model_dict = asdict(data) # type: ignore
287
+ np.savez_compressed(data_bytes, **model_dict)
288
+ save_bundle_to_cache(path, _CACHE_VERSION, {"data.npz": data_bytes})
289
+ return data
290
+
291
+
292
+ ##########
293
+ # STATES #
294
+ ##########
295
+
296
+
297
+ def _get_states_config(year: int) -> _DataConfig:
298
+ """Produce the args for _get_info or _get_geo (states)."""
299
+ if not is_tiger_year(year):
300
+ raise GeographyError(f"Unsupported year: {year}")
301
+ match year:
302
+ case year if year in range(2011, 2024):
303
+ cols = ["GEOID", "NAME", "STUSPS", "ALAND", "INTPTLAT", "INTPTLON"]
304
+ urls = [f"{_TIGER_URL}/TIGER{year}/STATE/tl_{year}_us_state.zip"]
305
+ case 2010:
306
+ cols = [
307
+ "GEOID10",
308
+ "NAME10",
309
+ "STUSPS10",
310
+ "ALAND10",
311
+ "INTPTLAT10",
312
+ "INTPTLON10",
313
+ ]
314
+ urls = [
315
+ f"{_TIGER_URL}/TIGER2010/STATE/2010/tl_2010_{xx}_state10.zip"
316
+ for xx in _SUPPORTED_STATE_FILES
317
+ ]
318
+ case 2009:
319
+ cols = [
320
+ "STATEFP00",
321
+ "NAME00",
322
+ "STUSPS00",
323
+ "ALAND00",
324
+ "INTPTLAT00",
325
+ "INTPTLON00",
326
+ ]
327
+ urls = [f"{_TIGER_URL}/TIGER2009/tl_2009_us_state00.zip"]
328
+ case 2000:
329
+ cols = [
330
+ "STATEFP00",
331
+ "NAME00",
332
+ "STUSPS00",
333
+ "ALAND00",
334
+ "INTPTLAT00",
335
+ "INTPTLON00",
336
+ ]
337
+ urls = [
338
+ f"{_TIGER_URL}/TIGER2010/STATE/2000/tl_2010_{xx}_state00.zip"
339
+ for xx in _SUPPORTED_STATE_FILES
340
+ ]
341
+ case _:
342
+ raise GeographyError(f"Unsupported year: {year}")
343
+ columns = zip_list(
344
+ cols, ["GEOID", "NAME", "STUSPS", "ALAND", "INTPTLAT", "INTPTLON"]
345
+ )
346
+ # each states file is approx 9MB
347
+ return _DataConfig("state", urls, columns, estimated_file_size=9_000_000)
348
+
349
+
350
+ def get_states_geo(
351
+ year: int,
352
+ progress: ProgressCallback | None = None,
353
+ ) -> GeoDataFrame:
354
+ """
355
+ Get all supported US states and territories for the given census year, with
356
+ geography.
357
+
358
+ Parameters
359
+ ----------
360
+ year :
361
+ The geography year.
362
+ progress :
363
+ A optional callback for reporting the progress of downloading TIGER files.
364
+
365
+ Returns
366
+ -------
367
+ :
368
+ The TIGER file info with geography.
369
+ """
370
+ config = _get_states_config(year)
371
+ return _load_tiger_data(config, ignore_geometry=False, progress=progress)
372
+
373
+
374
+ def get_states_info(
375
+ year: int,
376
+ progress: ProgressCallback | None = None,
377
+ ) -> DataFrame:
378
+ """
379
+ Get all US states and territories for the given census year, without geography.
380
+
381
+ Parameters
382
+ ----------
383
+ year :
384
+ The geography year.
385
+ progress :
386
+ A optional callback for reporting the progress of downloading TIGER files.
387
+
388
+ Returns
389
+ -------
390
+ :
391
+ The TIGER file info without geography.
392
+ """
393
+ config = _get_states_config(year)
394
+ return _load_tiger_data(config, ignore_geometry=True, progress=progress)
395
+
396
+
397
+ @dataclass(frozen=True)
398
+ class StatesSummary(GranularitySummary):
399
+ """
400
+ Information about US states (and state equivalents). Typically you will use
401
+ `get_states` to obtain an instance of this class for a particular year.
402
+
403
+ Parameters
404
+ ----------
405
+ geoid :
406
+ The GEOIDs (aka FIPS codes) of all states.
407
+ name :
408
+ The typical names for the states.
409
+ code :
410
+ The US postal codes for the states.
411
+ """
412
+
413
+ geoid: list[str]
414
+ """The GEOIDs (aka FIPS codes) of all states."""
415
+ name: list[str]
416
+ """The typical names for the states."""
417
+ code: list[str]
418
+ """The US postal codes for the states."""
419
+
420
+ @cached_property
421
+ def state_code_to_fips(self) -> Mapping[str, str]:
422
+ """Mapping from state postal code to FIPS code."""
423
+ return dict(zip(self.code, self.geoid, strict=True))
424
+
425
+ @cached_property
426
+ def state_fips_to_code(self) -> Mapping[str, str]:
427
+ """Mapping from state FIPS code to postal code."""
428
+ return dict(zip(self.geoid, self.code, strict=True))
429
+
430
+ @cached_property
431
+ def state_fips_to_name(self) -> Mapping[str, str]:
432
+ """Mapping from state FIPS code to full name."""
433
+ return dict(zip(self.geoid, self.name, strict=True))
434
+
435
+ @override
436
+ def interpret(self, identifiers: Sequence[str]) -> list[str]:
437
+ """
438
+ Permissively interprets the given set of identifiers as describing nodes,
439
+ and converts them to a sorted list of GEOIDs.
440
+
441
+ Parameters
442
+ ----------
443
+ identifiers :
444
+ A list of identifiers. Identifiers can be given in any of the acceptable
445
+ forms, but all of the identifiers must use the same form. Forms are:
446
+ GEOID/FIPS code, full name, or postal code.
447
+
448
+ Returns
449
+ -------
450
+ :
451
+ The list of GEOIDs in canonical sort order.
452
+
453
+ Raises
454
+ ------
455
+ GeographyError
456
+ If invalid identifiers are given.
457
+ """
458
+ first_val = identifiers[0]
459
+ if re.fullmatch(r"\d{2}", first_val) is not None:
460
+ return super().interpret(identifiers)
461
+ elif re.fullmatch(r"[A-Z]{2}", first_val, flags=re.IGNORECASE) is not None:
462
+ return self._to_geoid(identifiers, normalize_list(self.code), "postal code")
463
+ else:
464
+ return self._to_geoid(identifiers, normalize_list(self.name), "state name")
465
+
466
+
467
+ @cache_transparent
468
+ def get_states(year: int) -> StatesSummary:
469
+ """
470
+ Load US States information (assumed to be invariant for all supported years).
471
+
472
+ Parameters
473
+ ----------
474
+ year :
475
+ The geography year.
476
+
477
+ Returns
478
+ -------
479
+ :
480
+ The summary.
481
+ """
482
+ if not is_tiger_year(year):
483
+ raise GeographyError(f"Unsupported year: {year}")
484
+
485
+ def _get_us_states() -> StatesSummary:
486
+ states_df = get_states_info(year).sort_values("GEOID")
487
+ return StatesSummary(
488
+ geoid=states_df["GEOID"].to_list(),
489
+ name=states_df["NAME"].to_list(),
490
+ code=states_df["STUSPS"].to_list(),
491
+ )
492
+
493
+ return _load_summary_from_cache("us_states_all.tgz", _get_us_states, StatesSummary)
494
+
495
+
496
+ ############
497
+ # COUNTIES #
498
+ ############
499
+
500
+
501
+ def _get_counties_config(year: int) -> _DataConfig:
502
+ """Produce the args for _get_info or _get_geo (counties)."""
503
+ if not is_tiger_year(year):
504
+ raise GeographyError(f"Unsupported year: {year}")
505
+ match year:
506
+ case year if year in range(2011, 2024):
507
+ cols = ["GEOID", "NAME", "ALAND", "INTPTLAT", "INTPTLON"]
508
+ urls = [f"{_TIGER_URL}/TIGER{year}/COUNTY/tl_{year}_us_county.zip"]
509
+ case 2010:
510
+ cols = ["GEOID10", "NAME10", "ALAND10", "INTPTLAT10", "INTPTLON10"]
511
+ urls = [
512
+ f"{_TIGER_URL}/TIGER2010/COUNTY/2010/tl_2010_{xx}_county10.zip"
513
+ for xx in _SUPPORTED_STATE_FILES
514
+ ]
515
+ case 2009:
516
+ cols = [
517
+ "CNTYIDFP00",
518
+ "NAME00",
519
+ "ALAND00",
520
+ "INTPTLAT00",
521
+ "INTPTLON00",
522
+ ]
523
+ urls = [f"{_TIGER_URL}/TIGER2009/tl_2009_us_county00.zip"]
524
+ case 2000:
525
+ cols = ["CNTYIDFP00", "NAME00", "ALAND00", "INTPTLAT00", "INTPTLON00"]
526
+ urls = [
527
+ f"{_TIGER_URL}/TIGER2010/COUNTY/2000/tl_2010_{xx}_county00.zip"
528
+ for xx in _SUPPORTED_STATE_FILES
529
+ ]
530
+ case _:
531
+ raise GeographyError(f"Unsupported year: {year}")
532
+ columns = zip_list(cols, ["GEOID", "NAME", "ALAND", "INTPTLAT", "INTPTLON"])
533
+ # each county file is approx 75MB
534
+ return _DataConfig("county", urls, columns, 75_000_000)
535
+
536
+
537
+ def get_counties_geo(
538
+ year: int,
539
+ progress: ProgressCallback | None = None,
540
+ ) -> GeoDataFrame:
541
+ """
542
+ Get all supported US counties and county-equivalents for the given census year,
543
+ with geography.
544
+
545
+ Parameters
546
+ ----------
547
+ year :
548
+ The geography year.
549
+ progress :
550
+ A optional callback for reporting the progress of downloading TIGER files.
551
+
552
+ Returns
553
+ -------
554
+ :
555
+ The TIGER file info with geography.
556
+ """
557
+ config = _get_counties_config(year)
558
+ return _load_tiger_data(config, ignore_geometry=False, progress=progress)
559
+
560
+
561
+ def get_counties_info(
562
+ year: int,
563
+ progress: ProgressCallback | None = None,
564
+ ) -> DataFrame:
565
+ """
566
+ Get all US counties and county-equivalents for the given census year,
567
+ without geography.
568
+
569
+ Parameters
570
+ ----------
571
+ year :
572
+ The geography year.
573
+ progress :
574
+ A optional callback for reporting the progress of downloading TIGER files.
575
+
576
+ Returns
577
+ -------
578
+ :
579
+ The TIGER file info without geography.
580
+ """
581
+ config = _get_counties_config(year)
582
+ return _load_tiger_data(config, ignore_geometry=True, progress=progress)
583
+
584
+
585
+ @dataclass(frozen=True)
586
+ class CountiesSummary(GranularitySummary):
587
+ """
588
+ Information about US counties (and county equivalents.) Typically you will use
589
+ `get_counties` to obtain an instance of this class for a particular year.
590
+
591
+ Parameters
592
+ ----------
593
+ geoid :
594
+ The GEOIDs (aka FIPS codes) of all counties.
595
+ name :
596
+ The typical names of the counties (does not include state).
597
+ """
598
+
599
+ geoid: list[str]
600
+ """The GEOIDs (aka FIPS codes) of all counties."""
601
+ name: list[str]
602
+ """
603
+ The typical names of the counties (does not include state).
604
+ Note: county names are not unique across the whole US.
605
+ """
606
+ name_with_state: list[str]
607
+ """The typical names including county and state, e.g., `Coconino, AZ`"""
608
+
609
+ @cached_property
610
+ def county_fips_to_name(self) -> Mapping[str, str]:
611
+ """Mapping from county FIPS code to name with state."""
612
+ return dict(zip(self.geoid, self.name_with_state, strict=True))
613
+
614
+ @override
615
+ def interpret(self, identifiers: Sequence[str]) -> list[str]:
616
+ """
617
+ Permissively interprets the given set of identifiers as describing nodes,
618
+ and converts them to a sorted list of GEOIDs.
619
+
620
+ Parameters
621
+ ----------
622
+ identifiers :
623
+ A list of identifiers. Identifiers can be given in any of the acceptable
624
+ forms, but all of the identifiers must use the same form. Forms are:
625
+ GEOID/FIPS code, or the name of the county and its state postal code
626
+ separated by a comma, e.g., `Coconino, AZ`.
627
+
628
+ Returns
629
+ -------
630
+ :
631
+ The list of GEOIDs in canonical sort order.
632
+
633
+ Raises
634
+ ------
635
+ GeographyError
636
+ If invalid identifiers are given.
637
+ """
638
+ first_val = identifiers[0]
639
+ if re.fullmatch(r"\d{5}", first_val) is not None:
640
+ return super().interpret(identifiers)
641
+ else:
642
+ return self._to_geoid(
643
+ identifiers,
644
+ normalize_list(self.name_with_state),
645
+ "county name",
646
+ )
647
+
648
+
649
+ @cache_transparent
650
+ def get_counties(year: int) -> CountiesSummary:
651
+ """
652
+ Load US Counties information for the given year.
653
+
654
+ Parameters
655
+ ----------
656
+ year :
657
+ The geography year.
658
+
659
+ Returns
660
+ -------
661
+ :
662
+ The summary.
663
+ """
664
+ if not is_tiger_year(year):
665
+ raise GeographyError(f"Unsupported year: {year}")
666
+
667
+ def _get_us_counties() -> CountiesSummary:
668
+ counties_df = get_counties_info(year, None).sort_values("GEOID")
669
+ code_map = get_states(year).state_fips_to_code
670
+ counties_df["POSTAL_CODE"] = (
671
+ counties_df["GEOID"].str.slice(0, 2).apply(lambda x: code_map[x])
672
+ )
673
+ counties_df["NAME_WITH_STATE"] = (
674
+ counties_df["NAME"] + ", " + counties_df["POSTAL_CODE"]
675
+ )
676
+ return CountiesSummary(
677
+ geoid=counties_df["GEOID"].to_list(),
678
+ name=counties_df["NAME"].to_list(),
679
+ name_with_state=counties_df["NAME_WITH_STATE"].to_list(),
680
+ )
681
+
682
+ return _load_summary_from_cache(
683
+ f"us_counties_{year}.tgz", _get_us_counties, CountiesSummary
684
+ )
685
+
686
+
687
+ ##########
688
+ # TRACTS #
689
+ ##########
690
+
691
+
692
+ def _get_tracts_config(
693
+ year: int,
694
+ state_ids: Sequence[str] | None = None,
695
+ ) -> _DataConfig:
696
+ """Produce the args for _get_info or _get_geo (tracts)."""
697
+ if not is_tiger_year(year):
698
+ raise GeographyError(f"Unsupported year: {year}")
699
+ states = get_states_info(year)
700
+ if state_ids is not None:
701
+ states = states[states["GEOID"].isin(state_ids)]
702
+
703
+ match year:
704
+ case year if year in range(2011, 2024):
705
+ cols = ["GEOID", "ALAND", "INTPTLAT", "INTPTLON"]
706
+ urls = [
707
+ f"{_TIGER_URL}/TIGER{year}/TRACT/tl_{year}_{xx}_tract.zip"
708
+ for xx in states["GEOID"]
709
+ ]
710
+ case 2010:
711
+ cols = ["GEOID10", "ALAND10", "INTPTLAT10", "INTPTLON10"]
712
+ urls = [
713
+ f"{_TIGER_URL}/TIGER2010/TRACT/2010/tl_2010_{xx}_tract10.zip"
714
+ for xx in states["GEOID"]
715
+ ]
716
+ case 2009:
717
+
718
+ def state_folder(fips, name):
719
+ return f"{fips}_{name.upper().replace(' ', '_')}"
720
+
721
+ cols = ["CTIDFP00", "ALAND00", "INTPTLAT00", "INTPTLON00"]
722
+ urls = [
723
+ f"{_TIGER_URL}/TIGER2009/{state_folder(xx, name)}/tl_2009_{xx}_tract00.zip" # noqa: E501
724
+ for xx, name in zip(states["GEOID"], states["NAME"])
725
+ ]
726
+ case 2000:
727
+ cols = ["CTIDFP00", "ALAND00", "INTPTLAT00", "INTPTLON00"]
728
+ urls = [
729
+ f"{_TIGER_URL}/TIGER2010/TRACT/2000/tl_2010_{xx}_tract00.zip"
730
+ for xx in states["GEOID"]
731
+ ]
732
+ case _:
733
+ raise GeographyError(f"Unsupported year: {year}")
734
+ columns = zip_list(cols, ["GEOID", "ALAND", "INTPTLAT", "INTPTLON"])
735
+ # each tracts file is approx 7MB
736
+ return _DataConfig("tract", urls, columns, 7_000_000)
737
+
738
+
739
+ def get_tracts_geo(
740
+ year: int,
741
+ state_id: Sequence[str] | None = None,
742
+ progress: ProgressCallback | None = None,
743
+ ) -> GeoDataFrame:
744
+ """
745
+ Get all supported US census tracts for the given census year, with geography.
746
+
747
+ Parameters
748
+ ----------
749
+ year :
750
+ The geography year.
751
+ state_id :
752
+ If provided, return only the tracts in the given list of states (by GEOID).
753
+ progress :
754
+ A optional callback for reporting the progress of downloading TIGER files.
755
+
756
+ Returns
757
+ -------
758
+ :
759
+ The TIGER file info with geography.
760
+ """
761
+ config = _get_tracts_config(year, state_id)
762
+ return _load_tiger_data(config, ignore_geometry=False, progress=progress)
763
+
764
+
765
+ def get_tracts_info(
766
+ year: int,
767
+ state_id: Sequence[str] | None = None,
768
+ progress: ProgressCallback | None = None,
769
+ ) -> DataFrame:
770
+ """
771
+ Get all US census tracts for the given census year, without geography.
772
+
773
+ Parameters
774
+ ----------
775
+ year :
776
+ The geography year.
777
+ state_id :
778
+ If provided, return only the tracts in the given list of states (by GEOID).
779
+ progress :
780
+ A optional callback for reporting the progress of downloading TIGER files.
781
+
782
+ Returns
783
+ -------
784
+ :
785
+ The TIGER file info without geography.
786
+ """
787
+ config = _get_tracts_config(year, state_id)
788
+ return _load_tiger_data(config, ignore_geometry=True, progress=progress)
789
+
790
+
791
+ @dataclass(frozen=True)
792
+ class TractsSummary(GranularitySummary):
793
+ """
794
+ Information about US Census tracts. Typically you will use
795
+ `get_tracts` to obtain an instance of this class for a particular year.
796
+
797
+ Parameters
798
+ ----------
799
+ geoid :
800
+ The GEOIDs (aka FIPS codes) of all tracts.
801
+ """
802
+
803
+ geoid: list[str]
804
+ """The GEOIDs (aka FIPS codes) of all tracts."""
805
+
806
+
807
+ @cache_transparent
808
+ def get_tracts(year: int) -> TractsSummary:
809
+ """
810
+ Load US Census Tracts information for the given year.
811
+
812
+ Parameters
813
+ ----------
814
+ year :
815
+ The geography year.
816
+
817
+ Returns
818
+ -------
819
+ :
820
+ The summary.
821
+ """
822
+ if not is_tiger_year(year):
823
+ raise GeographyError(f"Unsupported year: {year}")
824
+
825
+ def _get_us_tracts() -> TractsSummary:
826
+ tracts_df = get_tracts_info(year).sort_values("GEOID")
827
+ return TractsSummary(
828
+ geoid=tracts_df["GEOID"].to_list(),
829
+ )
830
+
831
+ return _load_summary_from_cache(
832
+ f"us_tracts_{year}.tgz", _get_us_tracts, TractsSummary
833
+ )
834
+
835
+
836
+ ################
837
+ # BLOCK GROUPS #
838
+ ################
839
+
840
+
841
+ def _get_block_groups_config(
842
+ year: int,
843
+ state_ids: Sequence[str] | None = None,
844
+ ) -> _DataConfig:
845
+ """Produce the args for _get_info or _get_geo (block groups)."""
846
+ if not is_tiger_year(year):
847
+ raise GeographyError(f"Unsupported year: {year}")
848
+ states = get_states_info(year)
849
+ if state_ids is not None:
850
+ states = states[states["GEOID"].isin(state_ids)]
851
+
852
+ match year:
853
+ case year if year in range(2011, 2024):
854
+ cols = ["GEOID", "ALAND", "INTPTLAT", "INTPTLON"]
855
+ urls = [
856
+ f"{_TIGER_URL}/TIGER{year}/BG/tl_{year}_{xx}_bg.zip"
857
+ for xx in states["GEOID"]
858
+ ]
859
+ case 2010:
860
+ cols = ["GEOID10", "ALAND10", "INTPTLAT10", "INTPTLON10"]
861
+ urls = [
862
+ f"{_TIGER_URL}/TIGER2010/BG/2010/tl_2010_{xx}_bg10.zip"
863
+ for xx in states["GEOID"]
864
+ ]
865
+ case 2009:
866
+
867
+ def state_folder(fips, name):
868
+ return f"{fips}_{name.upper().replace(' ', '_')}"
869
+
870
+ cols = ["BKGPIDFP00", "ALAND00", "INTPTLAT00", "INTPTLON00"]
871
+ urls = [
872
+ f"{_TIGER_URL}/TIGER2009/{state_folder(xx, name)}/tl_2009_{xx}_bg00.zip"
873
+ for xx, name in zip(states["GEOID"], states["NAME"])
874
+ ]
875
+ case 2000:
876
+ cols = ["BKGPIDFP00", "ALAND00", "INTPTLAT00", "INTPTLON00"]
877
+ urls = [
878
+ f"{_TIGER_URL}/TIGER2010/BG/2000/tl_2010_{xx}_bg00.zip"
879
+ for xx in states["GEOID"]
880
+ ]
881
+ case _:
882
+ raise GeographyError(f"Unsupported year: {year}")
883
+ columns = zip_list(cols, ["GEOID", "ALAND", "INTPTLAT", "INTPTLON"])
884
+ # each block groups file is approx 1.25MB
885
+ return _DataConfig("block group", urls, columns, 1_250_000)
886
+
887
+
888
+ def get_block_groups_geo(
889
+ year: int,
890
+ state_id: Sequence[str] | None = None,
891
+ progress: ProgressCallback | None = None,
892
+ ) -> GeoDataFrame:
893
+ """
894
+ Get all supported US census block groups for the given census year, with geography.
895
+
896
+ Parameters
897
+ ----------
898
+ year :
899
+ The geography year.
900
+ state_id :
901
+ If provided, return only the block groups in the given list of states
902
+ (by GEOID).
903
+ progress :
904
+ A optional callback for reporting the progress of downloading TIGER files.
905
+
906
+ Returns
907
+ -------
908
+ :
909
+ The TIGER file info with geography.
910
+ """
911
+ config = _get_block_groups_config(year, state_id)
912
+ return _load_tiger_data(config, ignore_geometry=False, progress=progress)
913
+
914
+
915
+ def get_block_groups_info(
916
+ year: int,
917
+ state_id: Sequence[str] | None = None,
918
+ progress: ProgressCallback | None = None,
919
+ ) -> DataFrame:
920
+ """
921
+ Get all US census block groups for the given census year, without geography.
922
+
923
+ Parameters
924
+ ----------
925
+ year :
926
+ The geography year.
927
+ state_id :
928
+ If provided, return only the block groups in the given list of states
929
+ (by GEOID).
930
+ progress :
931
+ A optional callback for reporting the progress of downloading TIGER files.
932
+
933
+ Returns
934
+ -------
935
+ :
936
+ The TIGER file info without geography.
937
+ """
938
+ config = _get_block_groups_config(year, state_id)
939
+ return _load_tiger_data(config, ignore_geometry=True, progress=progress)
940
+
941
+
942
+ @dataclass(frozen=True)
943
+ class BlockGroupsSummary(GranularitySummary):
944
+ """
945
+ Information about US Census block groups. Typically you will use
946
+ `get_block_groups` to obtain an instance of this class for a particular year.
947
+
948
+ Parameters
949
+ ----------
950
+ geoid :
951
+ The GEOIDs (aka FIPS codes) of all block groups.
952
+ """
953
+
954
+ geoid: list[str]
955
+ """The GEOIDs (aka FIPS codes) of all block groups."""
956
+
957
+
958
+ @cache_transparent
959
+ def get_block_groups(year: int) -> BlockGroupsSummary:
960
+ """
961
+ Load US Census Block Group information for the given year.
962
+
963
+ Parameters
964
+ ----------
965
+ year :
966
+ The geography year.
967
+
968
+ Returns
969
+ -------
970
+ :
971
+ The summary.
972
+ """
973
+ if not is_tiger_year(year):
974
+ raise GeographyError(f"Unsupported year: {year}")
975
+
976
+ def _get_us_cbgs() -> BlockGroupsSummary:
977
+ cbgs_df = get_block_groups_info(year).sort_values("GEOID")
978
+ return BlockGroupsSummary(
979
+ geoid=cbgs_df["GEOID"].to_list(),
980
+ )
981
+
982
+ return _load_summary_from_cache(
983
+ f"us_block_groups_{year}.tgz",
984
+ _get_us_cbgs,
985
+ BlockGroupsSummary,
986
+ )
987
+
988
+
989
+ ################
990
+ # GENERAL UTIL #
991
+ ################
992
+
993
+
994
+ def get_summary_of(granularity: CensusGranularityName, year: int) -> GranularitySummary:
995
+ """
996
+ Retrieve a `GranularitySummary` for the given granularity and year.
997
+
998
+ Parameters
999
+ ----------
1000
+ granularity :
1001
+ The granularity.
1002
+ year :
1003
+ The geography year.
1004
+
1005
+ Returns
1006
+ -------
1007
+ :
1008
+ The summary.
1009
+
1010
+ Raises
1011
+ ------
1012
+ GeographyError
1013
+ If no summary can be retrieved.
1014
+ """
1015
+ match granularity:
1016
+ case "state":
1017
+ return get_states(year)
1018
+ case "county":
1019
+ return get_counties(year)
1020
+ case "tract":
1021
+ return get_tracts(year)
1022
+ case "block group":
1023
+ return get_block_groups(year)
1024
+ case _:
1025
+ err = f"Unsupported granularity: {granularity}"
1026
+ raise GeographyError(err)
1027
+
1028
+
1029
+ class CacheEstimate(NamedTuple):
1030
+ """Estimates related to data needed to fulfill TIGER requests."""
1031
+
1032
+ total_cache_size: int
1033
+ """An estimate of the size of the files that we need to have cached to fulfill
1034
+ a request."""
1035
+ missing_cache_size: int
1036
+ """An estimate of the size of the files that are not currently cached that we
1037
+ would need to fulfill a request. Zero if we have all of the files already."""
1038
+
1039
+
1040
+ def check_cache(
1041
+ granularity: CensusGranularityName,
1042
+ year: int,
1043
+ *,
1044
+ state_ids: Sequence[str] | None = None,
1045
+ ) -> CacheEstimate:
1046
+ """
1047
+ Check the status of the cache for a specified TIGER granularity and year.
1048
+
1049
+ Parameters
1050
+ ----------
1051
+ granularity :
1052
+ The Census granularity.
1053
+ year :
1054
+ The geography year.
1055
+ state_ids :
1056
+ If specified, only consider places in this set of states.
1057
+ Must be in state GEOID (FIPS code) format.
1058
+
1059
+ Returns
1060
+ -------
1061
+ :
1062
+ The estimate of the total size of the cached files for the given granularity
1063
+ and year, as well as how much is not currently cached.
1064
+ """
1065
+ match granularity:
1066
+ case "state":
1067
+ config = _get_states_config(year)
1068
+ case "county":
1069
+ config = _get_counties_config(year)
1070
+ case "tract":
1071
+ config = _get_tracts_config(year, state_ids)
1072
+ case "block group":
1073
+ config = _get_block_groups_config(year, state_ids)
1074
+ case _:
1075
+ err = f"Unsupported granularity: {granularity}"
1076
+ raise GeographyError(err)
1077
+
1078
+ cache_files = [_url_to_cache_path(u) for u in config.urls]
1079
+ missing_files = sum(1 for f in cache_files if not check_file_in_cache(f))
1080
+ return CacheEstimate(
1081
+ total_cache_size=len(cache_files) * config.estimated_file_size,
1082
+ missing_cache_size=missing_files * config.estimated_file_size,
1083
+ )