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,274 @@
1
+ """
2
+ A `World` implementation -- `ListWorld` -- which tracks the simulation state's
3
+ movement cohorts in a Python list-of-lists.
4
+ """
5
+
6
+ from operator import attrgetter
7
+ from typing import Any, ClassVar, Iterable, Literal, Self, Sequence, overload
8
+
9
+ import numpy as np
10
+ from numpy.typing import NDArray
11
+ from typing_extensions import override
12
+
13
+ from epymorph.data_type import SimDType
14
+ from epymorph.simulation import Tick
15
+ from epymorph.simulator.world import World
16
+
17
+
18
+ class Cohort:
19
+ """
20
+ Represents a group of individuals, divided into IPM compartments as appropriate for
21
+ the simulation. These individuals share the same "home location" and a time at which
22
+ they should return there.
23
+
24
+ These are somewhat abstract concepts, however; a completely nomadic group doesn't
25
+ really have a home location, merely the next location in a chain of movements.
26
+
27
+ Parameters
28
+ ----------
29
+ compartments :
30
+ The group membership by compartment. A (C,)-shaped array.
31
+ return_location :
32
+ The location to which this cohort will return, or if they are home, the location
33
+ where they currently are.
34
+ return_tick :
35
+ The simulation tick on which they will return. -1 implies never.
36
+ """
37
+
38
+ SORT_KEY: ClassVar = attrgetter("return_tick", "return_location")
39
+ """The natural sort order of a Cohort."""
40
+
41
+ compartments: NDArray[SimDType]
42
+ """The group membership by compartment. A (C,)-shaped array."""
43
+ return_location: int
44
+ """
45
+ The location to which this cohort will return, or if they are home, the location
46
+ where they currently are.
47
+ """
48
+ return_tick: int
49
+ """The simulation tick on which they will return. -1 implies never."""
50
+
51
+ # Note: when a population is "home",
52
+ # its `return_location` is the same as their home/current location,
53
+ # and its `return_tick` is set to -1 (the "Never" placeholder value).
54
+
55
+ def __init__(
56
+ self,
57
+ compartments: NDArray[SimDType],
58
+ return_location: int,
59
+ return_tick: int,
60
+ ):
61
+ self.compartments = compartments
62
+ self.return_location = return_location
63
+ self.return_tick = return_tick
64
+
65
+ def can_merge_with(self, other: Self) -> bool:
66
+ """
67
+ Check if two cohorts can be merged.
68
+
69
+ Cohorts at the same location with the same return location and tick can act as
70
+ a single group.
71
+
72
+ Parameters
73
+ ----------
74
+ other :
75
+ The other cohort to consider.
76
+
77
+ Returns
78
+ -------
79
+ :
80
+ True if these cohorts can be merged.
81
+ """
82
+ return (
83
+ self.return_tick == other.return_tick
84
+ and self.return_location == other.return_location
85
+ )
86
+
87
+ def merge_from(self, from_cohort: Self) -> None:
88
+ """
89
+ Merge another cohort into this one, modifying in-place.
90
+
91
+ Parameters
92
+ ----------
93
+ from_cohort :
94
+ The other cohort to be "absorbed" into this one.
95
+ """
96
+ self.compartments += from_cohort.compartments
97
+
98
+ def __eq__(self, other) -> bool:
99
+ if not isinstance(other, Cohort):
100
+ return False
101
+ return (
102
+ np.array_equal(self.compartments, other.compartments)
103
+ and self.return_location == other.return_location
104
+ and self.return_tick == other.return_tick
105
+ )
106
+
107
+ def __repr__(self) -> str:
108
+ return (
109
+ f"Cohort({str(self.compartments)}, "
110
+ f"rloc={self.return_location}, "
111
+ f"rtic={self.return_tick})"
112
+ )
113
+
114
+
115
+ class ListWorld(World):
116
+ """
117
+ A world model which which tracks the simulation state's movement cohorts in a
118
+ Python list-of-lists. That is, the world is a list of locations, and each location
119
+ is a list of cohorts.
120
+
121
+ Parameters
122
+ ----------
123
+ locations :
124
+ The initial state of the world. It is assumed there is at least one location
125
+ and at least one cohort at each.
126
+ """
127
+
128
+ HOME_TICK: ClassVar = -1
129
+ """The value of a population's `return_tick` when the population is home."""
130
+
131
+ nodes: int
132
+ """The number of simulation nodes."""
133
+ compartments: int
134
+ """The number of disease compartments."""
135
+ locations: list[list[Cohort]]
136
+ """All locations and all cohorts at each location."""
137
+
138
+ @classmethod
139
+ def from_initials(cls, initial_compartments: NDArray[SimDType]) -> Self:
140
+ """
141
+ Create a world with the given initial state given as a numpy array.
142
+
143
+ Everyone is assumed to be in their home location, there are no travelers.
144
+
145
+ Parameters
146
+ ----------
147
+ initial_compartments :
148
+ An (N,C)-shaped array of the compartment population at each node.
149
+
150
+ Returns
151
+ -------
152
+ :
153
+ The new world instance.
154
+ """
155
+ locations = [
156
+ [Cohort(cs, i, ListWorld.HOME_TICK)]
157
+ for (i, cs) in enumerate(initial_compartments.copy())
158
+ ]
159
+ return cls(locations)
160
+
161
+ def __init__(self, locations: list[list[Cohort]]):
162
+ self.nodes = len(locations)
163
+ self.compartments = locations[0][0].compartments.shape[0]
164
+ self.locations = locations
165
+
166
+ def normalize(self) -> None:
167
+ """
168
+ Sorts all cohorts within each location and combines mergeable cohorts
169
+ (in place). The world should be normalized after any modification.
170
+ """
171
+ for cohorts in self.locations:
172
+ cohorts.sort(key=Cohort.SORT_KEY)
173
+ # Iterate over all sequential pairs, starting from (0,1)
174
+ j = 1
175
+ while j < len(cohorts):
176
+ prev = cohorts[j - 1]
177
+ curr = cohorts[j]
178
+ if prev.can_merge_with(curr):
179
+ prev.merge_from(curr)
180
+ del cohorts[j]
181
+ else:
182
+ j += 1
183
+
184
+ @override
185
+ def get_cohorts(self, location_idx: int) -> Sequence[Cohort]:
186
+ return self.locations[location_idx]
187
+
188
+ @override
189
+ def get_cohort_array(self, location_idx: int) -> NDArray[SimDType]:
190
+ return np.array(
191
+ [c.compartments for c in self.locations[location_idx]], dtype=SimDType
192
+ )
193
+
194
+ @override
195
+ def get_local_array(self) -> NDArray[SimDType]:
196
+ # assumes world was normalized after any modification
197
+ return np.array(
198
+ [cohorts[0].compartments for cohorts in self.locations], dtype=SimDType
199
+ )
200
+
201
+ def get_local_cohorts(self) -> Iterable[Cohort]:
202
+ """
203
+ Iterate over all locations returning just the local cohort from each.
204
+
205
+ Returns
206
+ -------
207
+ :
208
+ The local cohorts.
209
+ """
210
+ for loc in self.locations:
211
+ yield loc[0]
212
+
213
+ @override
214
+ def apply_cohort_delta(self, location_idx: int, delta: NDArray[SimDType]) -> None:
215
+ for i, cohort in enumerate(self.locations[location_idx]):
216
+ cohort.compartments += delta[i]
217
+
218
+ @override
219
+ def apply_travel(self, travelers: NDArray[SimDType], return_tick: int) -> None:
220
+ travelers_leaving = travelers.sum(axis=1, dtype=SimDType)
221
+ travelers_nxn_sum = travelers.sum(axis=2, dtype=SimDType)
222
+
223
+ # Modify world: remove locals, add movement cohorts.
224
+ for src in range(self.nodes):
225
+ self.locations[src][0].compartments -= travelers_leaving[src]
226
+ for dst in range(self.nodes):
227
+ if src != dst and travelers_nxn_sum[src, dst] > 0:
228
+ # Normally a Cohort's home is the source index.
229
+ # But if the return clause is "never"
230
+ # it needs to be the destination index.
231
+ # This makes the Cohort consider its new location to be home
232
+ # so it will merge with the local population.
233
+ home = dst if return_tick == -1 else src
234
+ p = Cohort(travelers[src, dst, :], home, return_tick)
235
+ self.locations[dst].append(p)
236
+
237
+ self.normalize()
238
+
239
+ @overload
240
+ def apply_return(self, tick: Tick, *, return_stats: Literal[False]) -> None: ...
241
+
242
+ @overload
243
+ def apply_return(
244
+ self, tick: Tick, *, return_stats: Literal[True]
245
+ ) -> NDArray[SimDType]: ...
246
+
247
+ @override
248
+ def apply_return(
249
+ self, tick: Tick, *, return_stats: bool
250
+ ) -> NDArray[SimDType] | None:
251
+ movers: Any = None
252
+ if return_stats:
253
+ size = (self.nodes, self.nodes, self.compartments)
254
+ movers = np.zeros(size, dtype=SimDType)
255
+
256
+ next_locations = [[c] for c in self.get_local_cohorts()]
257
+ for i, location in enumerate(self.locations):
258
+ for cohort in location:
259
+ if cohort.return_tick == ListWorld.HOME_TICK:
260
+ # locals are already where they need to be
261
+ continue
262
+ elif cohort.return_tick == tick.sim_index:
263
+ # cohort ready to go home, merge with locals
264
+ j = cohort.return_location
265
+ next_locations[j][0].compartments += cohort.compartments
266
+ if return_stats:
267
+ movers[i, j, :] = cohort.compartments
268
+ else:
269
+ # cohort staying
270
+ next_locations[i].append(cohort)
271
+
272
+ self.locations = next_locations
273
+ self.normalize()
274
+ return movers if return_stats else None
epymorph/strata.py ADDED
@@ -0,0 +1,24 @@
1
+ """Utilities for epymorph's strata system."""
2
+
3
+ DEFAULT_STRATA = "all"
4
+ """The strata name used as the default, primarily for single-strata simulations."""
5
+
6
+ META_STRATA = "meta"
7
+ """A strata for information that concerns the other strata."""
8
+
9
+
10
+ def gpm_strata(strata_name: str) -> str:
11
+ """
12
+ Format a strata (GPM) name to its internal format.
13
+
14
+ Parameters
15
+ ----------
16
+ strata_name :
17
+ The human-readable strata name.
18
+
19
+ Returns
20
+ -------
21
+ :
22
+ The internal format of the strata's name.
23
+ """
24
+ return f"gpm:{strata_name}"
epymorph/sympy_shim.py ADDED
@@ -0,0 +1,57 @@
1
+ """Provide typed shims for the sympy functions we're using."""
2
+
3
+ from typing import Any, Callable, Mapping, cast
4
+
5
+ import sympy as sy
6
+
7
+
8
+ def to_symbol(name: str) -> sy.Symbol:
9
+ """
10
+ Create a symbol from the given string.
11
+
12
+ To be consistent with the typing given, only include a single symbol.
13
+ (But this is not checked.)
14
+ """
15
+ return cast(sy.Symbol, sy.symbols(name))
16
+
17
+
18
+ def simplify(expr: sy.Expr) -> sy.Expr:
19
+ """Simplify the given expression."""
20
+ return cast(sy.Expr, sy.simplify(expr))
21
+
22
+
23
+ def simplify_sum(exprs: list[sy.Expr]) -> sy.Expr:
24
+ """Simplify the sum of the given expressions."""
25
+ return cast(sy.Expr, sy.simplify(sy.Add(*exprs)))
26
+
27
+
28
+ SympyLambda = Callable[[list[Any]], Any]
29
+ """(Vaguely) describes the result of lambdifying an expression."""
30
+
31
+
32
+ def lambdify(params: list[Any], expr: sy.Expr) -> SympyLambda:
33
+ """
34
+ Create a lambda function from the given expression,
35
+ taking the given parameters and returning a single result.
36
+ """
37
+ # Note: calling lambdify with `[params]` means we will call it with a list of
38
+ # arguments later (rather than having to spread the list)
39
+ # i.e., f([1,2,3]) rather than f(*[1,2,3])
40
+ # This is better because we have to construct the arguments at run-time as lists.
41
+ return cast(SympyLambda, sy.lambdify([params], expr))
42
+
43
+
44
+ def lambdify_list(params: list[Any], exprs: list[sy.Expr]) -> SympyLambda:
45
+ """
46
+ Create a lambda function from the given expressions,
47
+ taking the given parameters and returning a list of results.
48
+ """
49
+ return cast(SympyLambda, sy.lambdify([params], exprs))
50
+
51
+
52
+ def substitute(expr: sy.Expr, symbol_mapping: Mapping[sy.Symbol, sy.Symbol]) -> sy.Expr:
53
+ """
54
+ Substitute symbols in one expression according to the given mapping,
55
+ and return a new expression.
56
+ """
57
+ return cast(sy.Expr, expr.subs(symbol_mapping))