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,1056 @@
1
+ """
2
+ Geo scope instances that utilize US Census delineations.
3
+ Generally, each `CensusScope` describes the granularity of the nodes
4
+ in scope, plus some containing boundary at the same level of granularity
5
+ or higher in which all nodes in that boundary are considered in scope.
6
+ For instance, "give me all of the counties in Nebraska and South Dakota".
7
+ """
8
+
9
+ from abc import ABC, abstractmethod
10
+ from dataclasses import dataclass, field
11
+ from functools import cached_property
12
+ from typing import Literal, Mapping, Never, Self, Sequence, TypeVar, cast
13
+
14
+ import numpy as np
15
+ from geopandas import GeoDataFrame
16
+ from numpy.typing import NDArray
17
+ from pandas import DataFrame
18
+ from typing_extensions import override
19
+
20
+ import epymorph.geography.us_tiger as tiger
21
+ from epymorph.error import GeographyError
22
+ from epymorph.geography.custom import CustomScope
23
+ from epymorph.geography.scope import (
24
+ GeoGroup,
25
+ GeoGrouping,
26
+ GeoScope,
27
+ GeoSelection,
28
+ GeoSelector,
29
+ GeoStrategy,
30
+ strategy_to_scope,
31
+ )
32
+ from epymorph.geography.us_geography import (
33
+ COUNTY,
34
+ STATE,
35
+ TRACT,
36
+ CensusGranularity,
37
+ CensusGranularityName,
38
+ )
39
+ from epymorph.util import filter_unique, mask
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class CensusScope(ABC, GeoScope):
44
+ """Base class for geo scopes using US Census delineations."""
45
+
46
+ year: int
47
+ """
48
+ The Census delineation year. Census Bureau can (and does) define
49
+ new delineations annually, especially at the smaller granularities. Hence, you must
50
+ know the year in order to absolutely identify a set of delineations.
51
+ """
52
+
53
+ granularity: CensusGranularityName
54
+ """Which granularity are the nodes in this scope?"""
55
+ includes_granularity: CensusGranularityName
56
+ """Which granularity defines the bounds of this scope?"""
57
+ includes: tuple[str, ...]
58
+ """Which nodes (of `includes_granularity`) are in scope?"""
59
+
60
+ _node_ids: NDArray[np.str_] = field(init=False, compare=False, hash=False)
61
+
62
+ def __post_init__(self):
63
+ # NOTE: functionality depends on `includes` being sorted and unique.
64
+ # Messing this up would be quite bad and hard to debug so I think it's
65
+ # worth the overhead to verify it.
66
+ xs = self.includes
67
+ if not all(xs[i] < xs[i + 1] for i in range(len(xs) - 1)):
68
+ raise ValueError("CensusScope.includes is not a sorted and unique list.")
69
+ node_ids = self._compute_node_ids()
70
+ object.__setattr__(self, "_node_ids", node_ids)
71
+
72
+ @property
73
+ @override
74
+ def node_ids(self) -> NDArray[np.str_]:
75
+ return self._node_ids
76
+
77
+ def _compute_node_ids(self) -> NDArray[np.str_]:
78
+ """Compute the GEOIDs for the nodes in scope."""
79
+ if self.granularity == self.includes_granularity:
80
+ return np.array(self.includes, dtype=np.str_)
81
+
82
+ # return the nodes within a larger granularity
83
+ g = CensusGranularity.of(self.includes_granularity)
84
+ return np.array(
85
+ [
86
+ x
87
+ for x in tiger.get_summary_of(self.granularity, self.year).geoid
88
+ if g.truncate(x) in self.includes
89
+ ],
90
+ dtype=np.str_,
91
+ )
92
+
93
+ @abstractmethod
94
+ def raise_granularity(self) -> "CensusScope":
95
+ """
96
+ Convert this scope to one that is one level higher in granularity.
97
+
98
+ Returns
99
+ -------
100
+ :
101
+ A scope with granularity one level higher than this.
102
+ This may have the effect of widening the scope; for example,
103
+ raising a `TractScope` which is filtered to a set of tracts will
104
+ result in a `CountyScope` containing the counties that contained our
105
+ tracts.
106
+
107
+ Raises
108
+ ------
109
+ GeographyError
110
+ If the granularity cannot be raised.
111
+ """
112
+
113
+ @abstractmethod
114
+ def lower_granularity(self) -> "CensusScope":
115
+ """
116
+ Convert this scope to one that is one level lower in granularity.
117
+
118
+ Returns
119
+ -------
120
+ :
121
+ A scope with granularity one level lower than this.
122
+
123
+ Raises
124
+ ------
125
+ GeographyError
126
+ If the granularity cannot be lowered.
127
+ """
128
+
129
+ def as_granularity(self, granularity: CensusGranularityName) -> "CensusScope":
130
+ """
131
+ Convert this scope to the named granularity.
132
+
133
+ Returns
134
+ -------
135
+ :
136
+ A scope of the named granularity by either raising
137
+ or lowering the original scope to match. If `granularity`
138
+ already matches this scope, it is returned unchanged.
139
+
140
+ Raises
141
+ ------
142
+ GeographyError
143
+ If the granularity cannot be modified as requested.
144
+ """
145
+ target = CensusGranularity.of(granularity)
146
+ scope = self
147
+ while scope.granularity != granularity:
148
+ if target < CensusGranularity.of(scope.granularity):
149
+ scope = scope.raise_granularity()
150
+ else:
151
+ scope = scope.lower_granularity()
152
+ return scope
153
+
154
+ @staticmethod
155
+ def of(
156
+ name: CensusGranularityName,
157
+ node_ids: Sequence[str],
158
+ year: int,
159
+ ) -> "CensusScope":
160
+ """
161
+ Create a `CensusScope` instance of the named granularity,
162
+ using nodes IDs of the same granularity. This is the same as
163
+ `StateScope.in_states(...)` for example.
164
+
165
+ Parameters
166
+ ----------
167
+ name :
168
+ The name of the Census granularity for the resulting scope.
169
+ node_ids :
170
+ The node IDs to include in the scope; these IDs must identify
171
+ nodes of the same granularity as `name`.
172
+ year :
173
+ The Census delineation year.
174
+ """
175
+ match name:
176
+ case "state":
177
+ return StateScope.in_states(node_ids, year)
178
+ case "county":
179
+ return CountyScope.in_counties(node_ids, year)
180
+ case "tract":
181
+ return TractScope.in_tracts(node_ids, year)
182
+ case "block group":
183
+ return BlockGroupScope.in_block_groups(node_ids, year)
184
+ case x:
185
+ raise ValueError(f"Not a supported granularity: {x}")
186
+
187
+ @abstractmethod
188
+ def get_info(self) -> DataFrame:
189
+ """
190
+ Retrieve TIGER info for the nodes in this scope. This is very similar to the
191
+ `geography` property of `CensusScope`s, but it omits the shape data so it's a
192
+ little faster for use-cases that don't need it.
193
+ """
194
+
195
+
196
+ ##############################
197
+ # Mixins for creating scopes #
198
+ ##############################
199
+
200
+
201
+ # NOTE: these mixins form a hierarchy of constructor methods.
202
+ # It is possible to create a StateScope using a set of states.
203
+ # It it possible to create a CountyScope using a set of states OR counties
204
+ # (where using states implies "all counties within these states").
205
+ # And so on.
206
+ # Scope instances will mix in the valid constructors.
207
+
208
+
209
+ class _InMixin(CensusScope):
210
+ @classmethod
211
+ def _in(
212
+ cls,
213
+ includes_granularity: CensusGranularityName,
214
+ includes: Sequence[str],
215
+ year: int,
216
+ ) -> Self:
217
+ # Utility classmethod for creating scopes.
218
+ g = tiger.get_summary_of(includes_granularity, year)
219
+ return cls(
220
+ includes_granularity=includes_granularity, # type: ignore
221
+ includes=tuple(g.interpret(includes)),
222
+ year=year,
223
+ )
224
+
225
+
226
+ class _InStatesMixin(_InMixin):
227
+ @classmethod
228
+ def in_states(cls, states: Sequence[str], year: int) -> Self:
229
+ """
230
+ Create a scope including all nodes in a set of US states/state-equivalents.
231
+
232
+ Parameters
233
+ ----------
234
+ states :
235
+ The set of states to include. This can be a list of either state names,
236
+ postal codes, or FIPs codes.
237
+ year :
238
+ The Census delineation year.
239
+
240
+ Returns
241
+ -------
242
+ :
243
+ The new scope.
244
+
245
+ Raises
246
+ ------
247
+ GeographyError
248
+ If the year or any entry in `states` is invalid.
249
+ """
250
+ return cls._in("state", states, year)
251
+
252
+
253
+ class _InCountiesMixin(_InMixin):
254
+ @classmethod
255
+ def in_counties(cls, counties: Sequence[str], year: int) -> Self:
256
+ """
257
+ Create a scope including all nodes in a set of US counties/county-equivalents.
258
+
259
+ Parameters
260
+ ----------
261
+ counties :
262
+ The set of counties to include. This can be a list of county names
263
+ (in county-comma-postal-code format, e.g., "Maricopa, AZ") or FIPS codes.
264
+ year :
265
+ The Census delineation year.
266
+
267
+ Returns
268
+ -------
269
+ :
270
+ The new scope.
271
+
272
+ Raises
273
+ ------
274
+ GeographyError
275
+ If the year or any entry in `counties` is invalid.
276
+ """
277
+ return cls._in("county", counties, year)
278
+
279
+
280
+ class _InTractsMixin(_InMixin):
281
+ @classmethod
282
+ def in_tracts(cls, tracts: Sequence[str], year: int) -> Self:
283
+ """
284
+ Create a scope including all nodes in a set of US Census tracts.
285
+
286
+ Parameters
287
+ ----------
288
+ tracts :
289
+ The set of tracts to include, by ID.
290
+ year :
291
+ The Census delineation year.
292
+
293
+ Returns
294
+ -------
295
+ :
296
+ The new scope.
297
+
298
+ Raises
299
+ ------
300
+ GeographyError
301
+ If the year or any entry in `tracts` is invalid.
302
+ """
303
+ return cls._in("tract", tracts, year)
304
+
305
+
306
+ class _InBlockGroupsMixin(_InMixin):
307
+ @classmethod
308
+ def in_block_groups(cls, block_groups: Sequence[str], year: int) -> Self:
309
+ """
310
+ Create a scope including all nodes in a set of US Census block groups.
311
+
312
+ Parameters
313
+ ----------
314
+ block_groups :
315
+ The set of block groups to include, by ID.
316
+ year :
317
+ The Census delineation year.
318
+
319
+ Returns
320
+ -------
321
+ :
322
+ The new scope.
323
+
324
+ Raises
325
+ ------
326
+ GeographyError
327
+ If the year or any entry in `block_groups` is invalid.
328
+ """
329
+ return cls._in("block group", block_groups, year)
330
+
331
+
332
+ ##################################
333
+ # Granularity-specific instances #
334
+ ##################################
335
+
336
+
337
+ # TODO: (Tyler) it might be interesting to replace the "includes" concept
338
+ # with a "parent" scope, which is an actual scope instance. e.g., a TractScope
339
+ # with a parent StateScope would include all tracts in the states included.
340
+ # Possibly more elegant.
341
+
342
+
343
+ @dataclass(frozen=True)
344
+ class StateScope(_InStatesMixin, CensusScope):
345
+ """
346
+ A `CensusScope` at the US State granularity.
347
+
348
+ Typically you'll create one of these using `all` or `in_states`.
349
+
350
+ Parameters
351
+ ----------
352
+ year :
353
+ The Census delineation year.
354
+ includes_granularity :
355
+ Which granularity defines the bounds of this scope?
356
+ includes :
357
+ Which nodes (of `includes_granularity`) are in scope?
358
+ """
359
+
360
+ year: int
361
+ includes_granularity: Literal["state"]
362
+ includes: tuple[str, ...]
363
+ granularity: Literal["state"] = field(init=False, default="state")
364
+
365
+ @classmethod
366
+ def all(cls, year: int) -> Self:
367
+ """
368
+ Create a scope including all US states and state-equivalents.
369
+
370
+ Parameters
371
+ ----------
372
+ year :
373
+ The Census delineation year.
374
+
375
+ Returns
376
+ -------
377
+ :
378
+ The new scope.
379
+ """
380
+ return cls(
381
+ includes_granularity="state",
382
+ includes=tuple(tiger.get_states(year).geoid),
383
+ year=year,
384
+ )
385
+
386
+ def _compute_node_ids(self) -> NDArray[np.str_]:
387
+ # return all nodes
388
+ return np.array(self.includes, dtype=np.str_)
389
+
390
+ def is_all_states(self) -> bool:
391
+ """
392
+ Check if this scope includes every support US state.
393
+
394
+ Returns
395
+ -------
396
+ :
397
+ True if this scope includes all supported US states.
398
+ """
399
+ return np.array_equal(tiger.get_states(self.year).geoid, self.node_ids)
400
+
401
+ @override
402
+ def raise_granularity(self) -> Never:
403
+ raise GeographyError("No granularity higher than state.")
404
+
405
+ @override
406
+ def lower_granularity(self) -> "CountyScope":
407
+ return CountyScope(
408
+ includes_granularity=self.includes_granularity,
409
+ includes=self.includes,
410
+ year=self.year,
411
+ )
412
+
413
+ @property
414
+ def select(self) -> "StateSelector[StateScope, StateSelection]":
415
+ """Create a selection from this scope."""
416
+ return StateSelector(self, StateSelection)
417
+
418
+ @property
419
+ @override
420
+ def labels_option(self) -> NDArray[np.str_]:
421
+ mapping = tiger.get_states(self.year).state_fips_to_code
422
+ return np.array([mapping[x] for x in self.node_ids], dtype=np.str_)
423
+
424
+ @cached_property
425
+ @override
426
+ def geography(self) -> GeoDataFrame: # type: ignore[override]
427
+ gdf = tiger.get_states_geo(self.year)
428
+ in_scope = gdf["GEOID"].isin(self.node_ids)
429
+ return gdf[in_scope].sort_values(by="GEOID").reset_index(drop=True)
430
+
431
+ @override
432
+ def get_info(self) -> DataFrame:
433
+ info_df = tiger.get_states_info(self.year)
434
+ in_scope = info_df["GEOID"].isin(self.node_ids)
435
+ return info_df[in_scope].sort_values(by="GEOID").reset_index(drop=True)
436
+
437
+
438
+ @dataclass(frozen=True)
439
+ class CountyScope(_InStatesMixin, _InCountiesMixin, CensusScope):
440
+ """
441
+ A `CensusScope` at the US County granularity.
442
+
443
+ Typically you'll create one of these using `all`, `in_states`, or `in_counties`.
444
+
445
+ Parameters
446
+ ----------
447
+ year :
448
+ The Census delineation year.
449
+ includes_granularity :
450
+ Which granularity defines the bounds of this scope?
451
+ includes :
452
+ Which nodes (of `includes_granularity`) are in scope?
453
+ """
454
+
455
+ year: int
456
+ includes_granularity: Literal["state", "county"]
457
+ includes: tuple[str, ...]
458
+ granularity: Literal["county"] = field(init=False, default="county")
459
+
460
+ @classmethod
461
+ def all(cls, year: int) -> Self:
462
+ """
463
+ Create a scope including all US counties and county-equivalents.
464
+
465
+ Parameters
466
+ ----------
467
+ year :
468
+ The Census delineation year.
469
+
470
+ Returns
471
+ -------
472
+ :
473
+ The new scope.
474
+ """
475
+ return cls(
476
+ includes_granularity="county",
477
+ includes=tuple(tiger.get_counties(year).geoid),
478
+ year=year,
479
+ )
480
+
481
+ @override
482
+ def raise_granularity(self) -> StateScope:
483
+ if self.includes_granularity == "county":
484
+ return StateScope(
485
+ includes_granularity="state",
486
+ includes=tuple(STATE.truncate_unique(self.includes)),
487
+ year=self.year,
488
+ )
489
+
490
+ return StateScope(
491
+ includes_granularity=self.includes_granularity,
492
+ includes=self.includes,
493
+ year=self.year,
494
+ )
495
+
496
+ @override
497
+ def lower_granularity(self) -> "TractScope":
498
+ return TractScope(
499
+ includes_granularity=self.includes_granularity,
500
+ includes=self.includes,
501
+ year=self.year,
502
+ )
503
+
504
+ @property
505
+ def select(self) -> "CountySelector[CountyScope, CountySelection]":
506
+ """Create a selection from this scope."""
507
+ return CountySelector(self, CountySelection)
508
+
509
+ @property
510
+ @override
511
+ def labels_option(self) -> NDArray[np.str_]:
512
+ mapping = tiger.get_counties(self.year).county_fips_to_name
513
+ return np.array([mapping[x] for x in self.node_ids], dtype=np.str_)
514
+
515
+ @cached_property
516
+ @override
517
+ def geography(self) -> GeoDataFrame: # type: ignore[override]
518
+ gdf = tiger.get_counties_geo(self.year)
519
+ in_scope = gdf["GEOID"].isin(self.node_ids)
520
+ return gdf[in_scope].sort_values(by="GEOID").reset_index(drop=True)
521
+
522
+ @override
523
+ def get_info(self) -> DataFrame:
524
+ info_df = tiger.get_counties_info(self.year)
525
+ in_scope = info_df["GEOID"].isin(self.node_ids)
526
+ return info_df[in_scope].sort_values(by="GEOID").reset_index(drop=True)
527
+
528
+
529
+ @dataclass(frozen=True)
530
+ class TractScope(_InStatesMixin, _InCountiesMixin, _InTractsMixin, CensusScope):
531
+ """
532
+ A `CensusScope` at the US Tract granularity.
533
+
534
+ Typically you will create one of these using `in_states`, `in_counties`, or
535
+ `in_tracts`.
536
+
537
+ Parameters
538
+ ----------
539
+ year :
540
+ The Census delineation year.
541
+ includes_granularity :
542
+ Which granularity defines the bounds of this scope?
543
+ includes :
544
+ Which nodes (of `includes_granularity`) are in scope?
545
+ """
546
+
547
+ year: int
548
+ includes_granularity: Literal["state", "county", "tract"]
549
+ includes: tuple[str, ...]
550
+ granularity: Literal["tract"] = field(init=False, default="tract")
551
+
552
+ @override
553
+ def raise_granularity(self) -> CountyScope:
554
+ if self.includes_granularity == "tract":
555
+ return CountyScope(
556
+ includes_granularity="county",
557
+ includes=tuple(COUNTY.truncate_unique(self.includes)),
558
+ year=self.year,
559
+ )
560
+
561
+ return CountyScope(
562
+ includes_granularity=self.includes_granularity,
563
+ includes=self.includes,
564
+ year=self.year,
565
+ )
566
+
567
+ @override
568
+ def lower_granularity(self) -> "BlockGroupScope":
569
+ return BlockGroupScope(
570
+ year=self.year,
571
+ includes_granularity=self.includes_granularity,
572
+ includes=self.includes,
573
+ )
574
+
575
+ @property
576
+ def select(self) -> "TractSelector[TractScope, TractSelection]":
577
+ """Create a selection from this scope."""
578
+ return TractSelector(self, TractSelection)
579
+
580
+ @cached_property
581
+ @override
582
+ def geography(self) -> GeoDataFrame: # type: ignore[override]
583
+ states = list({STATE.extract(x) for x in self.node_ids})
584
+ gdf = tiger.get_tracts_geo(self.year, states)
585
+ in_scope = gdf["GEOID"].isin(self.node_ids)
586
+ return gdf[in_scope].sort_values(by="GEOID").reset_index(drop=True)
587
+
588
+ @override
589
+ def get_info(self) -> DataFrame:
590
+ states = list({STATE.extract(x) for x in self.node_ids})
591
+ info_df = tiger.get_tracts_info(self.year, states)
592
+ in_scope = info_df["GEOID"].isin(self.node_ids)
593
+ return info_df[in_scope].sort_values(by="GEOID").reset_index(drop=True)
594
+
595
+
596
+ @dataclass(frozen=True)
597
+ class BlockGroupScope(
598
+ _InStatesMixin, _InCountiesMixin, _InTractsMixin, _InBlockGroupsMixin, CensusScope
599
+ ):
600
+ """
601
+ A `CensusScope` at the US Block Group granularity.
602
+
603
+ Typically you will create one of these using `in_states`, `in_counties`,
604
+ `in_tracts`, or `in_block_groups`.
605
+
606
+ Parameters
607
+ ----------
608
+ year :
609
+ The Census delineation year.
610
+ includes_granularity :
611
+ Which granularity defines the bounds of this scope?
612
+ includes :
613
+ Which nodes (of `includes_granularity`) are in scope?
614
+ """
615
+
616
+ year: int
617
+ includes_granularity: Literal["state", "county", "tract", "block group"]
618
+ includes: tuple[str, ...]
619
+ granularity: Literal["block group"] = field(init=False, default="block group")
620
+
621
+ @override
622
+ def raise_granularity(self) -> TractScope:
623
+ if self.includes_granularity == "block group":
624
+ return TractScope(
625
+ includes_granularity="tract",
626
+ includes=tuple(TRACT.truncate_unique(self.includes)),
627
+ year=self.year,
628
+ )
629
+
630
+ return TractScope(
631
+ includes_granularity=self.includes_granularity,
632
+ includes=self.includes,
633
+ year=self.year,
634
+ )
635
+
636
+ @override
637
+ def lower_granularity(self) -> Never:
638
+ raise GeographyError("No valid granularity lower than block group.")
639
+
640
+ @property
641
+ def select(self) -> "BlockGroupSelector[BlockGroupScope, BlockGroupSelection]":
642
+ """Create a selection from this scope."""
643
+ return BlockGroupSelector(self, BlockGroupSelection)
644
+
645
+ @cached_property
646
+ @override
647
+ def geography(self) -> GeoDataFrame: # type: ignore[override]
648
+ states = list({STATE.extract(x) for x in self.node_ids})
649
+ gdf = tiger.get_block_groups_geo(self.year, states)
650
+ in_scope = gdf["GEOID"].isin(self.node_ids)
651
+ return gdf[in_scope].sort_values(by="GEOID").reset_index(drop=True)
652
+
653
+ @override
654
+ def get_info(self) -> DataFrame:
655
+ states = list({STATE.extract(x) for x in self.node_ids})
656
+ info_df = tiger.get_block_groups_info(self.year, states)
657
+ in_scope = info_df["GEOID"].isin(self.node_ids)
658
+ return info_df[in_scope].sort_values(by="GEOID").reset_index(drop=True)
659
+
660
+
661
+ #####################
662
+ # Geo axis strategy #
663
+ #####################
664
+
665
+
666
+ @strategy_to_scope.register
667
+ def _census_strategy_to_scope(
668
+ scope: CensusScope,
669
+ strategy: GeoStrategy[CensusScope],
670
+ ) -> GeoScope:
671
+ selected = scope.node_ids[strategy.selection]
672
+ match (strategy.grouping, strategy.aggregation):
673
+ case (None, None):
674
+ # No grouping or aggregation: new scope is just a subselection.
675
+ result_granularity = scope.granularity
676
+ result_nodes = cast(list[str], selected.tolist())
677
+ case (None, _):
678
+ # No grouping, some aggregation reduces to one node.
679
+ return CustomScope(["*"])
680
+ # TODO: (Tyler) it would be possible to maintain a census scope
681
+ # in the case where all the selected nodes share a common container,
682
+ # e.g., I've selected only Arizona counties. We could detect the
683
+ # maximal shared geoid prefix that corresponds to a granularity level
684
+ # and use that. I need to think about whether or not this is desirable,
685
+ # because it would be a pain to implement.
686
+ case (CensusGrouping(), _):
687
+ # Grouped by a CensusGrouping: create a new scope with nodes from the
688
+ # group mapping of the selected nodes.
689
+ g = strategy.grouping
690
+ result_granularity = g.granularity
691
+ result_nodes = cast(list[str], filter_unique(g.map(selected)))
692
+ case (g, _):
693
+ # Some other kind of grouping; fall back to CustomScope.
694
+ # TODO: (Tyler) it may be possible to apply the same granularity detection
695
+ # here as above... but again I dunno if that's a good idea.
696
+ return CustomScope(g.map(selected))
697
+
698
+ match result_granularity:
699
+ case "state":
700
+ return StateScope.in_states(result_nodes, scope.year)
701
+ case "county":
702
+ return CountyScope.in_counties(result_nodes, scope.year)
703
+ case "tract":
704
+ return TractScope.in_tracts(result_nodes, scope.year)
705
+ case "block group":
706
+ return BlockGroupScope.in_block_groups(result_nodes, scope.year)
707
+ case x:
708
+ err = f"Unsupported granularity {x}"
709
+ raise GeographyError(err)
710
+
711
+
712
+ @dataclass(frozen=True)
713
+ class CensusGrouping(GeoGrouping):
714
+ """
715
+ A geo-axis grouping for Census geo scopes, for example, "group by state".
716
+
717
+ Parameters
718
+ ----------
719
+ granularity :
720
+ The granularity to group by.
721
+ """
722
+
723
+ granularity: CensusGranularityName
724
+ """The granularity to group by."""
725
+
726
+ @override
727
+ def map(self, node_ids: NDArray[np.str_]) -> NDArray[np.str_]:
728
+ gran = CensusGranularity.of(self.granularity)
729
+ return np.array([gran.truncate(g) for g in node_ids], dtype=np.str_)
730
+
731
+
732
+ @dataclass(frozen=True)
733
+ class StateSelection(GeoSelection[CensusScope]):
734
+ """A geo selection on a `StateScope`."""
735
+
736
+
737
+ @dataclass(frozen=True)
738
+ class CountySelection(GeoSelection[CensusScope]):
739
+ """A geo selection on a `CountyScope`."""
740
+
741
+ def group(self, grouping: Literal["state"] | GeoGrouping) -> GeoGroup[CensusScope]:
742
+ """
743
+ Group the geo series using the specified grouping.
744
+
745
+ Parameters
746
+ ----------
747
+ grouping :
748
+ The grouping to use. You can specify a supported string value --
749
+ all of which act as shortcuts for common `GeoGrouping` instances --
750
+ or you can provide a `GeoGrouping` instance to perform custom grouping.
751
+
752
+ The shortcut values are:
753
+
754
+ - "state": equivalent to `CensusGrouping("state")`
755
+
756
+ Returns
757
+ -------
758
+ :
759
+ The group strategy.
760
+ """
761
+ match grouping:
762
+ case "state":
763
+ grouping = CensusGrouping(grouping)
764
+ case _:
765
+ pass
766
+ return GeoGroup(self.scope, self.selection, grouping)
767
+
768
+
769
+ @dataclass(frozen=True)
770
+ class TractSelection(GeoSelection[CensusScope]):
771
+ """A geo selection on a `TractScope`."""
772
+
773
+ def group(
774
+ self, grouping: Literal["state", "county"] | GeoGrouping
775
+ ) -> GeoGroup[CensusScope]:
776
+ """
777
+ Group the geo series using the specified grouping.
778
+
779
+ Parameters
780
+ ----------
781
+ grouping :
782
+ The grouping to use. You can specify a supported string value --
783
+ all of which act as shortcuts for common `GeoGrouping` instances --
784
+ or you can provide a `GeoGrouping` instance to perform custom grouping.
785
+
786
+ The shortcut values are:
787
+
788
+ - "state": equivalent to `CensusGrouping("state")`
789
+ - "county": equivalent to `CensusGrouping("county")`
790
+
791
+ Returns
792
+ -------
793
+ :
794
+ The group strategy.
795
+ """
796
+ match grouping:
797
+ case "state":
798
+ grouping = CensusGrouping(grouping)
799
+ case "county":
800
+ grouping = CensusGrouping(grouping)
801
+ case _:
802
+ pass
803
+ return GeoGroup(self.scope, self.selection, grouping)
804
+
805
+
806
+ @dataclass(frozen=True)
807
+ class BlockGroupSelection(GeoSelection[CensusScope]):
808
+ """A geo selection on a `BlockGroupScope`."""
809
+
810
+ def group(
811
+ self, grouping: Literal["state", "county", "tract"] | GeoGrouping
812
+ ) -> GeoGroup[CensusScope]:
813
+ """
814
+ Group the geo series using the specified grouping.
815
+
816
+ Parameters
817
+ ----------
818
+ grouping :
819
+ The grouping to use. You can specify a supported string value --
820
+ all of which act as shortcuts for common `GeoGrouping` instances --
821
+ or you can provide a `GeoGrouping` instance to perform custom grouping.
822
+
823
+ The shortcut values are:
824
+
825
+ - "state": equivalent to `CensusGrouping("state")`
826
+ - "county": equivalent to `CensusGrouping("county")`
827
+ - "tract": equivalent to `CensusGrouping("tract")`
828
+ """
829
+ match grouping:
830
+ case "state":
831
+ grouping = CensusGrouping(grouping)
832
+ case "county":
833
+ grouping = CensusGrouping(grouping)
834
+ case "tract":
835
+ grouping = CensusGrouping(grouping)
836
+ case _:
837
+ pass
838
+ return GeoGroup(self.scope, self.selection, grouping)
839
+
840
+
841
+ # NOTE: these Selector classes form a hierarchy of shared functionality.
842
+ # With a StateScope, you can select by geoid and state.
843
+ # With a CountyScope, you can select by geoid, state, AND county.
844
+ # And so on.
845
+
846
+ CensusScopeT = TypeVar("CensusScopeT", bound=CensusScope)
847
+ """The type of geo scope."""
848
+
849
+ CensusSelectionT = TypeVar(
850
+ "CensusSelectionT",
851
+ bound=(StateSelection | CountySelection | TractSelection | BlockGroupSelection),
852
+ )
853
+ """The type of geo selection."""
854
+
855
+
856
+ @dataclass(frozen=True)
857
+ class _CensusSelector(GeoSelector[CensusScopeT, CensusSelectionT]):
858
+ """Base class for Census scope selectors with shared functions."""
859
+
860
+ _scope: CensusScopeT
861
+ """The original scope."""
862
+ _selection_class: type[CensusSelectionT]
863
+ """The class of the selection produced."""
864
+ _node_id_to_label: Mapping[str, str] | None = field(init=False, default=None)
865
+ """The mapping to use for `node_id_to_label` (see: GeoStrategy)"""
866
+
867
+ def by_geoid(self, *geoids: str) -> CensusSelectionT:
868
+ """
869
+ Select nodes by GEOID. It is possible to select all nodes within
870
+ a coarser granularity by passing those GEOIDs, however all GEOIDs
871
+ given must be the same granularity.
872
+
873
+ Parameters
874
+ ----------
875
+ *geoids :
876
+ The GEOIDs to select, as var-args.
877
+
878
+ Returns
879
+ -------
880
+ :
881
+ The geo selection.
882
+ """
883
+ scope_gran = CensusGranularity.of(self._scope.granularity)
884
+ scope_geoid_len = scope_gran.length
885
+ if any(len(x) > scope_geoid_len for x in geoids):
886
+ err = f"Selection geoids must be {scope_gran.name}-level or coarser."
887
+ raise GeographyError(err)
888
+
889
+ mask = np.zeros_like(self._scope.node_ids, dtype=np.bool_)
890
+ for i, node in enumerate(self._scope.node_ids):
891
+ mask[i] = any(node.startswith(sel) for sel in geoids)
892
+ return self._from_mask(mask)
893
+
894
+ def by_slice(
895
+ self,
896
+ start: int,
897
+ stop: int | None = None,
898
+ step: int | None = None,
899
+ ) -> CensusSelectionT:
900
+ """
901
+ Select nodes by specifying a slice on the node indices.
902
+
903
+ Parameters
904
+ ----------
905
+ start :
906
+ The initial index.
907
+ stop :
908
+ The stop index (exclusive of the endpoint), or `None`
909
+ for no endpoint.
910
+ step :
911
+ The interval between selected indices, or `None` to
912
+ default to every index.
913
+
914
+ Returns
915
+ -------
916
+ :
917
+ The geo selection.
918
+ """
919
+ return self._from_mask(mask(self._scope.nodes, slice(start, stop, step)))
920
+
921
+ def by_indices(self, indices: list[int]) -> CensusSelectionT:
922
+ """
923
+ Select nodes by specifying the node indices to include.
924
+
925
+ Parameters
926
+ ----------
927
+ indices :
928
+ The indices to include.
929
+
930
+ Returns
931
+ -------
932
+ :
933
+ The geo selection.
934
+ """
935
+ return self._from_mask(mask(self._scope.nodes, indices))
936
+
937
+
938
+ @dataclass(frozen=True)
939
+ class StateSelector(_CensusSelector[CensusScopeT, CensusSelectionT]):
940
+ """
941
+ A geo selector on a `StateScope`.
942
+
943
+ Most of the time you obtain one of these using a scope's `select` property.
944
+ """
945
+
946
+ def by_state(self, *identifiers: str) -> CensusSelectionT:
947
+ """
948
+ Select all nodes within a set of states.
949
+
950
+ Parameters
951
+ ----------
952
+ *identifiers :
953
+ The set of states to include, as var-args. This can be a list of either
954
+ state names, postal codes, or FIPs codes.
955
+
956
+ Returns
957
+ -------
958
+ :
959
+ The geo selection.
960
+ """
961
+ states = tiger.get_states(self._scope.year)
962
+ geoids = states.interpret(identifiers)
963
+ return self.by_geoid(*geoids)
964
+
965
+
966
+ @dataclass(frozen=True)
967
+ class CountySelector(StateSelector[CensusScopeT, CensusSelectionT]):
968
+ """
969
+ A geo selector on a `CountyScope`.
970
+
971
+ Most of the time you obtain one of these using a scope's `select` property.
972
+ """
973
+
974
+ def by_county(self, *identifiers: str) -> CensusSelectionT:
975
+ """
976
+ Select all nodes within a set of counties.
977
+
978
+ Parameters
979
+ ----------
980
+ *identifiers :
981
+ The set of counties to include, as var-args. This can be a list of
982
+ county names (in county-comma-postal-code format, e.g., "Maricopa, AZ")
983
+ or FIPS codes.
984
+
985
+ Returns
986
+ -------
987
+ :
988
+ The geo selection.
989
+ """
990
+ counties = tiger.get_counties(self._scope.year)
991
+ geoids = counties.interpret(identifiers)
992
+ return self.by_geoid(*geoids)
993
+
994
+
995
+ @dataclass(frozen=True)
996
+ class TractSelector(CountySelector[CensusScopeT, CensusSelectionT]):
997
+ """
998
+ A geo selector on a `TractScope`.
999
+
1000
+ Most of the time you obtain one of these using a scope's `select` property.
1001
+ """
1002
+
1003
+ def by_tract(self, *identifiers: str) -> CensusSelectionT:
1004
+ """
1005
+ Select all nodes within a set of tracts.
1006
+
1007
+ Parameters
1008
+ ----------
1009
+ *identifiers :
1010
+ The set of tracts to include by ID, as var-args.
1011
+
1012
+ Returns
1013
+ -------
1014
+ :
1015
+ The geo selection.
1016
+ """
1017
+ tracts = tiger.get_tracts(self._scope.year)
1018
+ geoids = tracts.interpret(identifiers)
1019
+ return self.by_geoid(*geoids)
1020
+
1021
+
1022
+ @dataclass(frozen=True)
1023
+ class BlockGroupSelector(TractSelector[CensusScopeT, CensusSelectionT]):
1024
+ """
1025
+ A geo selector on a `BlockGroupScope`.
1026
+
1027
+ Most of the time you obtain one of these using a scope's `select` property.
1028
+ """
1029
+
1030
+ def by_block_group(self, *identifiers: str) -> CensusSelectionT:
1031
+ """
1032
+ Select all nodes within a set of block groups.
1033
+
1034
+ Parameters
1035
+ ----------
1036
+ *identifiers :
1037
+ The set of block groups to include by ID, as var-args.
1038
+
1039
+ Returns
1040
+ -------
1041
+ :
1042
+ The geo selection.
1043
+ """
1044
+ block_groups = tiger.get_block_groups(self._scope.year)
1045
+ geoids = block_groups.interpret(identifiers)
1046
+ return self.by_geoid(*geoids)
1047
+
1048
+
1049
+ __all__ = [
1050
+ "CensusScope",
1051
+ "StateScope",
1052
+ "CountyScope",
1053
+ "TractScope",
1054
+ "BlockGroupScope",
1055
+ "CensusGrouping",
1056
+ ]