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,457 @@
1
+ """
2
+ The geographic scope of a simulation describes the locations which are included in the
3
+ model. Each location is a discrete place. While interactions between locations may be
4
+ described by model data or arise from the movements of individuals, the geo scope itself
5
+ is agnostic to these dynamics.
6
+
7
+ `GeoScope` is generic, modeling geography in a very abstract way. Specialized classes
8
+ exist to describe geographic systems that model real world geography, e.g., the system
9
+ of delineations defined by the US Census Bureau.
10
+ """
11
+
12
+ from abc import ABC, abstractmethod
13
+ from dataclasses import dataclass, field
14
+ from functools import singledispatch
15
+ from typing import Generic, Literal, Never, Protocol, TypeVar, final, runtime_checkable
16
+
17
+ import numpy as np
18
+ from geopandas import GeoDataFrame
19
+ from numpy.typing import NDArray
20
+
21
+
22
+ @runtime_checkable
23
+ class GeoScope(Protocol):
24
+ """The common interface expected of all geo scopes."""
25
+
26
+ @property
27
+ @abstractmethod
28
+ def node_ids(self) -> NDArray[np.str_]:
29
+ """The list of node IDs included in this scope."""
30
+
31
+ @property
32
+ def nodes(self) -> int:
33
+ """The number of nodes in this scope."""
34
+ return len(self.node_ids)
35
+
36
+ def index_of(self, node_id: str) -> int:
37
+ """
38
+ Return the index of a given node by its ID string.
39
+
40
+ Parameters
41
+ ----------
42
+ node_id :
43
+ The ID to check for.
44
+
45
+ Returns
46
+ -------
47
+ :
48
+ The index if `node_id` exists in this scope.
49
+
50
+ Raises
51
+ ------
52
+ ValueError
53
+ If `node_id` is not found.
54
+ """
55
+ idxs, *_ = np.where(self.node_ids == node_id)
56
+ if len(idxs) == 0:
57
+ raise ValueError(f"'{node_id}' not present in geo scope.")
58
+ return idxs[0]
59
+
60
+ @property
61
+ def labels_option(self) -> NDArray[np.str_] | None:
62
+ """
63
+ An optional text label for each node. If this returns `None`,
64
+ convention is to use the node IDs as the labels.
65
+ """
66
+ # NOTE: override this method if friendly names are possible
67
+ return None
68
+
69
+ @property
70
+ def labels(self) -> NDArray[np.str_]:
71
+ """
72
+ The best text label for each node.
73
+
74
+ This uses `labels_option` if available and falls back to `node_ids`.
75
+ """
76
+ if (labels := self.labels_option) is not None:
77
+ return labels
78
+ return self.node_ids
79
+
80
+ @property
81
+ @abstractmethod
82
+ def geography(self) -> GeoDataFrame | Never:
83
+ """
84
+ Retrieves the shapes corresponding to the nodes of this scope as a
85
+ `GeoDataFrame`. Note that this is not possible for all types of `GeoScope`.
86
+
87
+ Returns
88
+ -------
89
+ :
90
+ The geography.
91
+
92
+ Raises
93
+ ------
94
+ GeographyError
95
+ If we cannot fetch geography for this type of scope.
96
+ """
97
+ # NOTE: implementations should:
98
+ # - if geography is NOT supported:
99
+ # - override the return type to `Never`
100
+ # - if geography IS supported:
101
+ # - override the return type to `GeoDataFrame`
102
+ # - use @cached_property as repeated access of the geography is expected;
103
+ # however Pylance errors this so you can mark it `typed: ignore[override]`
104
+
105
+
106
+ #############################################
107
+ # Geo scope quantity select/group/aggregate #
108
+ #############################################
109
+
110
+
111
+ GeoScopeT = TypeVar("GeoScopeT", bound=GeoScope)
112
+ """A type of `GeoScope`."""
113
+ GeoScopeT_co = TypeVar("GeoScopeT_co", covariant=True, bound=GeoScope)
114
+ """A type of `GeoScope`: covariant."""
115
+
116
+ GeoAggMethod = Literal["sum", "min", "max"]
117
+ """Methods for aggregating results along the geo axis."""
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class GeoStrategy(ABC, Generic[GeoScopeT_co]):
122
+ """
123
+ A strategy for dealing with the spatial axis, e.g., in processing results.
124
+ Strategies can include selection of a subset, grouping, and aggregation.
125
+
126
+ Typically you will create one of these buy calling methods on a `GeoSelector`
127
+ instance.
128
+
129
+ `GeoStrategy` is generic in the type of `GeoScope` it works with (`GeoScopeT_co`).
130
+ """
131
+
132
+ scope: GeoScopeT_co
133
+ """The original scope."""
134
+ selection: NDArray[np.bool_]
135
+ """A boolean mask for selection of a subset of geo nodes."""
136
+ grouping: "GeoGrouping | None"
137
+ """A method for grouping geo nodes."""
138
+ aggregation: GeoAggMethod | None
139
+ """
140
+ A method for aggregating by group
141
+ (if no grouping is specified, selected nodes are treated as one group).
142
+ """
143
+
144
+ @property
145
+ def indices(self) -> tuple[int, ...]:
146
+ """
147
+ A tuple containing the indices from the original scope that are selected by this
148
+ strategy.
149
+ """
150
+ return tuple(i for i, selected in enumerate(self.selection) if selected)
151
+
152
+ @final
153
+ def to_scope(self) -> GeoScope:
154
+ """
155
+ Convert this strategy to the scope that results from applying this strategy.
156
+
157
+ For example, if your original scope included all tracts in the US and the
158
+ strategy selects Arizona and groups by county, this method would return a scope
159
+ containing all counties in Arizona.
160
+
161
+ Returns
162
+ -------
163
+ :
164
+ A new scope instance.
165
+
166
+ Raises
167
+ ------
168
+ NotImplementedError
169
+ If this type of scope does not support this operation.
170
+ """
171
+ # NOTE: in order to support this, you must provide a singledispatch
172
+ # implementation of `strategy_to_scope` that covers the GeoScope subtype.
173
+ return strategy_to_scope(self.scope, self)
174
+
175
+
176
+ @singledispatch
177
+ def strategy_to_scope(scope: GeoScopeT, strategy: GeoStrategy[GeoScopeT]) -> GeoScope:
178
+ """
179
+ Convert a `GeoStrategy` instance to the `GeoScope` that would result from
180
+ applying the strategy.
181
+
182
+ Warning
183
+ -------
184
+ This function is intended for epymorph's internal use; users should instead call
185
+ `to_scope` on a `GeoStrategy` object.
186
+
187
+ Parameters
188
+ ----------
189
+ scope :
190
+ The original scope.
191
+ strategy :
192
+ The strategy to apply.
193
+
194
+ Returns
195
+ -------
196
+ :
197
+ The new scope instance.
198
+
199
+ Raises
200
+ ------
201
+ NotImplementedError
202
+ If this type of scope does not support this operation.
203
+ """
204
+ # This is a singledispatch function so scope implementations can opt to support
205
+ # this feature if it makes sense.
206
+
207
+ # NOTE: it might seem unnecessary to pass `scope` and `strategy` separately since
208
+ # the strategy contains the scope. However, singledispatch mechanics can't use
209
+ # the strategy's generic type declaration as the basis for dispatch, so we have
210
+ # to pass the scope as the first argument.
211
+ # In usage, be careful not to pass arguments that disagree with each other.
212
+ raise NotImplementedError()
213
+
214
+
215
+ class GeoGrouping(ABC):
216
+ """
217
+ Defines a geo-axis grouping scheme. This is essentially a function that maps
218
+ the simulation geo axis info (node IDs) into a new series which describes
219
+ the group membership of each geo axis row.
220
+
221
+ Certain groupings may only be valid for specific types of `GeoScope`.
222
+ """
223
+
224
+ @abstractmethod
225
+ def map(self, node_ids: NDArray[np.str_]) -> NDArray[np.str_]:
226
+ """
227
+ Produce a column that describes the group membership of each node.
228
+
229
+ The returned column will be used as the basis of a `groupby` operation.
230
+
231
+ Parameters
232
+ ----------
233
+ node_ids :
234
+ The node IDs to group.
235
+
236
+ Returns
237
+ -------
238
+ :
239
+ An array of the same length as `node_ids` where each value defines which
240
+ group the original node ID belongs to.
241
+ """
242
+
243
+
244
+ class _CanGeoAggregate(GeoStrategy[GeoScopeT_co]):
245
+ """Base functionality for geo strategies that support aggregation operations."""
246
+
247
+ def agg(self, agg: GeoAggMethod) -> "GeoAggregation[GeoScopeT_co]":
248
+ """
249
+ Apply the named aggregation for each geo node group.
250
+
251
+ Parameters
252
+ ----------
253
+ agg :
254
+ The aggregation to apply.
255
+
256
+ Returns
257
+ -------
258
+ :
259
+ The geo aggregation.
260
+ """
261
+ return GeoAggregation(self.scope, self.selection, self.grouping, agg)
262
+
263
+ def sum(self) -> "GeoAggregation[GeoScopeT_co]":
264
+ """
265
+ Perform a sum for each geo node group.
266
+
267
+ Returns
268
+ -------
269
+ :
270
+ The geo aggregation.
271
+ """
272
+ return self.agg("sum")
273
+
274
+ def min(self) -> "GeoAggregation[GeoScopeT_co]":
275
+ """
276
+ Take the min value for each geo node group.
277
+
278
+ Returns
279
+ -------
280
+ :
281
+ The geo aggregation.
282
+ """
283
+ return self.agg("min")
284
+
285
+ def max(self) -> "GeoAggregation[GeoScopeT_co]":
286
+ """
287
+ Take the max value for each geo node group.
288
+
289
+ Returns
290
+ -------
291
+ :
292
+ The geo aggregation.
293
+ """
294
+ return self.agg("max")
295
+
296
+
297
+ @dataclass(frozen=True)
298
+ class GeoSelection(_CanGeoAggregate[GeoScopeT_co], GeoStrategy[GeoScopeT_co]):
299
+ """
300
+ A kind of `GeoStrategy` describing a sub-selection operation on a geo scope.
301
+ A selection performs no grouping or aggregation.
302
+
303
+ Typically you will create one of these by calling methods on a `GeoSelector`
304
+ instance.
305
+
306
+ Parameters
307
+ ----------
308
+ scope :
309
+ The original scope.
310
+ selection :
311
+ A boolean mask for selection of a subset of geo nodes.
312
+ """
313
+
314
+ scope: GeoScopeT_co
315
+ """The original scope."""
316
+ selection: NDArray[np.bool_]
317
+ """A boolean mask for selection of a subset of geo nodes."""
318
+ grouping: None = field(init=False, default=None)
319
+ """A method for grouping geo nodes."""
320
+ aggregation: None = field(init=False, default=None)
321
+ """
322
+ A method for aggregating by group
323
+ (if no grouping is specified, selected nodes are treated as one group).
324
+ """
325
+
326
+ # NOTE: subclass this to provide appropriate grouping methods.
327
+
328
+
329
+ @dataclass(frozen=True)
330
+ class GeoGroup(_CanGeoAggregate[GeoScopeT_co], GeoStrategy[GeoScopeT_co]):
331
+ """
332
+ A kind of `GeoStrategy` describing a grouping operation on a geo scope,
333
+ with an optional sub-selection.
334
+
335
+ Typically you will create one of these by calling methods on a `GeoSelection`
336
+ instance.
337
+
338
+ Parameters
339
+ ----------
340
+ scope :
341
+ The original scope.
342
+ selection :
343
+ A boolean mask for selection of a subset of geo nodes.
344
+ grouping :
345
+ A method for grouping geo nodes.
346
+ """
347
+
348
+ scope: GeoScopeT_co
349
+ """The original scope."""
350
+ selection: NDArray[np.bool_]
351
+ """A boolean mask for selection of a subset of geo nodes."""
352
+ grouping: GeoGrouping
353
+ """A method for grouping geo nodes."""
354
+ aggregation: None = field(init=False, default=None)
355
+ """
356
+ A method for aggregating by group
357
+ (if no grouping is specified, selected nodes are treated as one group).
358
+ """
359
+
360
+
361
+ @dataclass(frozen=True)
362
+ class GeoAggregation(GeoStrategy[GeoScopeT_co]):
363
+ """
364
+ Describes a group-and-aggregate operation on a geo scope,
365
+ with an optional sub-selection.
366
+
367
+ Typically you will create one of these by calling methods on a `GeoSelection`
368
+ instance.
369
+
370
+ Parameters
371
+ ----------
372
+ scope :
373
+ The original scope.
374
+ selection :
375
+ A boolean mask for selection of a subset of geo nodes.
376
+ grouping :
377
+ A method for grouping geo nodes.
378
+ aggregation :
379
+ A method for aggregating by group
380
+ (if no grouping is specified, selected nodes are treated as one group).
381
+ """
382
+
383
+ scope: GeoScopeT_co
384
+ """The original scope."""
385
+ selection: NDArray[np.bool_]
386
+ """A boolean mask for selection of a subset of geo nodes."""
387
+ grouping: GeoGrouping | None
388
+ """A method for grouping geo nodes."""
389
+ aggregation: GeoAggMethod
390
+ """
391
+ A method for aggregating by group
392
+ (if no grouping is specified, selected nodes are treated as one group).
393
+ """
394
+
395
+
396
+ GeoSelectionT_co = TypeVar("GeoSelectionT_co", covariant=True, bound=GeoSelection)
397
+ """The type of geo selection."""
398
+
399
+
400
+ @dataclass(frozen=True)
401
+ class GeoSelector(Generic[GeoScopeT_co, GeoSelectionT_co]):
402
+ """
403
+ A utility class for making a selection on a particular kind of GeoScope.
404
+ Most of the time you obtain one of these using a `GeoScope`'s `select` property.
405
+ """
406
+
407
+ _scope: GeoScopeT_co
408
+ """The original scope."""
409
+ _selection_class: type[GeoSelectionT_co]
410
+ """The class of the selection produced."""
411
+
412
+ def _from_mask(self, mask: NDArray[np.bool_]) -> GeoSelectionT_co:
413
+ """Construct a geo selection instance of the proper type given a mask."""
414
+ return self._selection_class(self._scope, mask)
415
+
416
+ def all(self) -> GeoSelectionT_co:
417
+ """
418
+ Select all geo nodes.
419
+
420
+ Returns
421
+ -------
422
+ :
423
+ The geo selection.
424
+ """
425
+ mask = np.ones_like(self._scope.node_ids, dtype=np.bool_)
426
+ return self._from_mask(mask)
427
+
428
+ def by_id(self, *ids: str) -> GeoSelectionT_co:
429
+ """
430
+ Select geo nodes by their ID (exact matches only).
431
+
432
+ Parameters
433
+ ----------
434
+ *ids :
435
+ Node IDs to include in the selection, as var-args.
436
+
437
+ Returns
438
+ -------
439
+ :
440
+ The geo selection.
441
+ """
442
+ mask = np.zeros_like(self._scope.node_ids, dtype=np.bool_)
443
+ for i, node in enumerate(self._scope.node_ids):
444
+ mask[i] = any(node == sel for sel in ids)
445
+ return self._from_mask(mask)
446
+
447
+
448
+ __all__ = [
449
+ "GeoScope",
450
+ "GeoStrategy",
451
+ "strategy_to_scope",
452
+ "GeoGrouping",
453
+ "GeoSelection",
454
+ "GeoGroup",
455
+ "GeoAggregation",
456
+ "GeoSelector",
457
+ ]