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,347 @@
1
+ """
2
+ The basis of the movement system in epymorph.
3
+
4
+ Movement models are responsible for dividing up the day into one or more parts, in
5
+ accordance with their desired tempo of movement. For example, commuting patterns of
6
+ work day versus night.
7
+
8
+ Movement mechanics are expressed as a set of clauses which calculate the "requested"
9
+ number of individuals that should move between geospatial nodes at a particular time
10
+ step of the simulation. This is "requested" movement because fewer individuals may wind
11
+ up moving if there are not enough to satisfy the request.
12
+ """
13
+
14
+ import re
15
+ from abc import ABC, ABCMeta, abstractmethod
16
+ from math import isclose
17
+ from typing import Any, Literal, Sequence, Type, TypeVar, cast
18
+
19
+ from numpy.typing import NDArray
20
+ from typing_extensions import override
21
+
22
+ from epymorph.attribute import AttributeDef
23
+ from epymorph.data_type import SimDType
24
+ from epymorph.simulation import (
25
+ NEVER,
26
+ SimulationFunctionClass,
27
+ SimulationTickFunction,
28
+ Tick,
29
+ TickDelta,
30
+ TickIndex,
31
+ )
32
+ from epymorph.util import are_instances
33
+
34
+ DayOfWeek = Literal["M", "T", "W", "Th", "F", "Sa", "Su"]
35
+ """Type for days of the week values."""
36
+
37
+ ALL_DAYS: tuple[DayOfWeek, ...] = ("M", "T", "W", "Th", "F", "Sa", "Su")
38
+ """All days of the week values."""
39
+
40
+ _day_of_week_pattern = r"\b(M|T|W|Th|F|Sa|Su)\b"
41
+
42
+
43
+ def parse_days_of_week(dow: str) -> tuple[DayOfWeek, ...]:
44
+ """
45
+ Parse a list of days of the week using our standard abbreviations:
46
+ M, T, W, Th, F, Sa, Su.
47
+
48
+ Parameters
49
+ ----------
50
+ dow :
51
+ A string containing a list of days of the week.
52
+ The parser is pretty permissive; it ignores invalid parts of the input while
53
+ keeping the valid parts. Any separator is allowed between the day of the week
54
+ themselves.
55
+
56
+ Returns
57
+ -------
58
+ :
59
+ The days of the week parsed from the string. Empty if there are none.
60
+
61
+ Examples
62
+ --------
63
+ >>> parse_days_of_week("M,W,F")
64
+ ('M', 'W', 'F')
65
+ """
66
+ ds = re.findall(_day_of_week_pattern, dow)
67
+ # return the matched days in standard order
68
+ return tuple(x for x in ALL_DAYS if x in ds)
69
+
70
+
71
+ class MovementPredicate(ABC):
72
+ """
73
+ Checks the current tick and responds with true or false.
74
+ Movement predicates are used to determine whether a movement clause
75
+ should be applied for this simulation tick or not.
76
+ """
77
+
78
+ @abstractmethod
79
+ def evaluate(self, tick: Tick) -> bool:
80
+ """
81
+ Check the given tick.
82
+
83
+ Parameters
84
+ ----------
85
+ tick :
86
+ The current simulation tick.
87
+
88
+ Returns
89
+ -------
90
+ :
91
+ The result of the predicate.
92
+ """
93
+
94
+
95
+ class EveryDay(MovementPredicate):
96
+ """Return true for every day."""
97
+
98
+ @override
99
+ def evaluate(self, tick: Tick) -> bool:
100
+ return True
101
+
102
+
103
+ class DayIs(MovementPredicate):
104
+ """
105
+ Checks that the day is in the given set of days of the week.
106
+
107
+ Parameters
108
+ ----------
109
+ week_days :
110
+ The week days for which this predicate should evaluate true.
111
+ Either a list of `DayOfWeek` or a string which will be parsed
112
+ as in `parse_days_of_week`.
113
+ """
114
+
115
+ week_days: tuple[DayOfWeek, ...]
116
+
117
+ def __init__(self, week_days: Sequence[DayOfWeek] | str):
118
+ if isinstance(week_days, str):
119
+ self.week_days = parse_days_of_week(week_days)
120
+ else:
121
+ self.week_days = tuple(week_days)
122
+
123
+ @override
124
+ def evaluate(self, tick: Tick) -> bool:
125
+ return tick.date.weekday() in self.week_days
126
+
127
+
128
+ ##################
129
+ # MovementClause #
130
+ ##################
131
+
132
+
133
+ _TypeT = TypeVar("_TypeT")
134
+
135
+
136
+ class MovementClauseClass(SimulationFunctionClass):
137
+ """The metaclass for `MovementClause` classes; enforces proper implementation."""
138
+
139
+ def __new__(
140
+ cls: Type[_TypeT],
141
+ name: str,
142
+ bases: tuple[type, ...],
143
+ dct: dict[str, Any],
144
+ ) -> _TypeT:
145
+ # Skip these checks for classes we want to treat as abstract:
146
+ if dct.get("_abstract_simfunc", False):
147
+ return super().__new__(cls, name, bases, dct)
148
+
149
+ # Check predicate.
150
+ predicate = dct.get("predicate")
151
+ if predicate is None or not isinstance(predicate, MovementPredicate):
152
+ raise TypeError(
153
+ f"Invalid predicate in {name}: "
154
+ "please specify a MovementPredicate instance."
155
+ )
156
+ # Check leaves.
157
+ leaves = dct.get("leaves")
158
+ if leaves is None or not isinstance(leaves, TickIndex):
159
+ raise TypeError(
160
+ f"Invalid leaves in {name}: please specify a TickIndex instance."
161
+ )
162
+ if leaves.step < 0:
163
+ raise TypeError(
164
+ f"Invalid leaves in {name}: step indices cannot be less than zero."
165
+ )
166
+ # Check returns.
167
+ returns = dct.get("returns")
168
+ if returns is None or not isinstance(returns, TickDelta):
169
+ raise TypeError(
170
+ f"Invalid returns in {name}: please specify a TickDelta instance."
171
+ )
172
+ if returns != NEVER:
173
+ if returns.step < 0:
174
+ raise TypeError(
175
+ f"Invalid returns in {name}: step indices cannot be less than zero."
176
+ )
177
+ if returns.days < 0:
178
+ raise TypeError(
179
+ f"Invalid returns in {name}: days cannot be less than zero."
180
+ )
181
+
182
+ return super().__new__(cls, name, bases, dct)
183
+
184
+
185
+ class MovementClause(
186
+ SimulationTickFunction[NDArray[SimDType]], ABC, metaclass=MovementClauseClass
187
+ ):
188
+ """
189
+ A movement clause is basically a function which calculates _how many_ individuals
190
+ should move between all of the geo nodes.
191
+
192
+ It's up to epymorph's internal mechanisms to decide by random draw _which_
193
+ individuals move (as identified by their disease status, or IPM compartment).
194
+
195
+ The clause also has various settings which determine when the clause is active
196
+ (for example, only move people Monday-Friday at the start of the day)
197
+ and when the individuals that were moved by the clause should return home
198
+ (for example, stay for two days and then return at the end of the day).
199
+ """
200
+
201
+ _abstract_simfunc = True # marking this abstract skips metaclass validation
202
+
203
+ # in addition to requirements (from super), movement clauses must also specify:
204
+
205
+ predicate: MovementPredicate
206
+ """When does this movement clause apply?"""
207
+
208
+ leaves: TickIndex
209
+ """On which tau step does this movement clause apply?"""
210
+
211
+ returns: TickDelta
212
+ """When do the movers from this clause return home?"""
213
+
214
+ def is_active(self, tick: Tick) -> bool:
215
+ """
216
+ Check if this movement clause should be applied this tick.
217
+
218
+ Parameters
219
+ ----------
220
+ tick :
221
+ The current simulation tick.
222
+
223
+ Returns
224
+ -------
225
+ :
226
+ True if the clause should be applied this tick.
227
+ """
228
+ return self.leaves.step == tick.step and self.predicate.evaluate(tick)
229
+
230
+ @property
231
+ def clause_name(self) -> str:
232
+ """A display name to use for the clause."""
233
+ return self.__class__.__name__
234
+
235
+ @abstractmethod
236
+ def evaluate(self, tick: Tick) -> NDArray[SimDType]:
237
+ """
238
+ Implement this method to provide logic for the clause.
239
+ Use self methods and properties to access the simulation context or defer
240
+ processing to another function.
241
+
242
+ Parameters
243
+ ----------
244
+ tick :
245
+ The simulation tick being evaluated.
246
+
247
+ Returns
248
+ -------
249
+ :
250
+ An array describing the requested number of individuals to move from origin
251
+ location (row; axis 0) to destination location (column; axis 1).
252
+ """
253
+
254
+
255
+ #################
256
+ # MovementModel #
257
+ #################
258
+
259
+
260
+ class MovementModelClass(ABCMeta):
261
+ """The metaclass for `MovementModel` classes; enforces proper implementation."""
262
+
263
+ def __new__(
264
+ cls: Type[_TypeT],
265
+ name: str,
266
+ bases: tuple[type, ...],
267
+ dct: dict[str, Any],
268
+ ) -> _TypeT:
269
+ # Skip these checks for known base classes:
270
+ if name in ("MovementModel",):
271
+ return super().__new__(cls, name, bases, dct)
272
+
273
+ # Check tau steps.
274
+ steps = dct.get("steps")
275
+ if steps is None or not isinstance(steps, (list, tuple)):
276
+ raise TypeError(
277
+ f"Invalid steps in {name}: please specify as a list or tuple."
278
+ )
279
+ if not are_instances(steps, float):
280
+ raise TypeError(f"Invalid steps in {name}: must be floating point numbers.")
281
+ if len(steps) == 0:
282
+ raise TypeError(
283
+ f"Invalid steps in {name}: please specify at least one tau step length."
284
+ )
285
+ if not isclose(sum(steps), 1.0, abs_tol=1e-6):
286
+ raise TypeError(f"Invalid steps in {name}: steps must sum to 1.")
287
+ if any(x <= 0 for x in steps):
288
+ raise TypeError(
289
+ f"Invalid steps in {name}: steps must all be greater than 0."
290
+ )
291
+ dct["steps"] = tuple(steps)
292
+
293
+ # Check clauses.
294
+ clauses = dct.get("clauses")
295
+ if clauses is None or not isinstance(clauses, (list, tuple)):
296
+ raise TypeError(
297
+ f"Invalid clauses in {name}: please specify as a list or tuple."
298
+ )
299
+ if not are_instances(clauses, MovementClause):
300
+ raise TypeError(
301
+ f"Invalid clauses in {name}: must be instances of MovementClause."
302
+ )
303
+ if len(clauses) == 0:
304
+ raise TypeError(
305
+ f"Invalid clauses in {name}: please specify at least one clause."
306
+ )
307
+ for c in cast(Sequence[MovementClause], clauses):
308
+ # Check that clause steps are valid.
309
+ num_steps = len(steps)
310
+ if c.leaves.step >= num_steps:
311
+ raise TypeError(
312
+ f"Invalid clauses in {name}: {c.__class__.__name__} "
313
+ f"uses a leave step ({c.leaves.step}) "
314
+ f"which is not a valid index. (steps: {steps})"
315
+ )
316
+ if c.returns.step >= num_steps:
317
+ raise TypeError(
318
+ f"Invalid clauses in {name}: {c.__class__.__name__} "
319
+ f"uses a return step ({c.returns.step}) "
320
+ f"which is not a valid index. (steps: {steps})"
321
+ )
322
+ dct["clauses"] = tuple(clauses)
323
+
324
+ return super().__new__(cls, name, bases, dct)
325
+
326
+
327
+ class MovementModel(ABC, metaclass=MovementModelClass):
328
+ """
329
+ A `MovementModel` (MM) describes a pattern of geospatial movement for
330
+ individuals in the model.
331
+
332
+ The MM defines the tau steps which chop the day up into one or more parts,
333
+ as well as the set of movement clauses which may apply throughout each day.
334
+
335
+ To create a custom MM, you will write an implementation of this class
336
+ and of any required clause classes.
337
+ """
338
+
339
+ steps: Sequence[float]
340
+ """The length and order of tau steps."""
341
+ clauses: Sequence[MovementClause]
342
+ """The movement clauses that make up the model."""
343
+
344
+ @property
345
+ def requirements(self) -> Sequence[AttributeDef]:
346
+ """The combined requirements of all of the clauses in this model."""
347
+ return [req for clause in self.clauses for req in clause.requirements]
File without changes
@@ -0,0 +1,68 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ import numpy as np
4
+ import scipy as sp
5
+
6
+
7
+ class Distribution(ABC):
8
+ """
9
+ Abstract base class for the prior/initial distributions for static/dynamic parameter
10
+ estimation.
11
+ """
12
+
13
+ @abstractmethod
14
+ def rvs(self, size: int, random_state: np.random.Generator):
15
+ """
16
+ Draws independent random variates (aka random deviates, realizations,
17
+ or samples) from the distribution.
18
+
19
+ Parameters
20
+ ----------
21
+ size : int
22
+ Number of random variates to draw.
23
+ random_state : np.random.Generator
24
+ The random number generator to use.
25
+ """
26
+ raise NotImplementedError("Subclasses should implement this method.")
27
+
28
+
29
+ class Uniform(Distribution):
30
+ """
31
+ Continuous uniform distribution on an interval.
32
+
33
+ Attributes
34
+ ----------
35
+ a : float
36
+ The left endpoint of the interval.
37
+ b : float
38
+ The right endpoint of the interval.
39
+ """
40
+
41
+ def __init__(self, a: float, b: float):
42
+ """
43
+ Initializes the parameters of the distribution.
44
+
45
+ Parameters
46
+ ----------
47
+ a : float
48
+ The left endpoint of the the interval.
49
+ b : float
50
+ The right endpoint of the the interval.
51
+ """
52
+ self.a = a
53
+ self.b = b
54
+
55
+ def rvs(self, size=1, random_state: np.random.Generator | None = None):
56
+ """
57
+ Draws from a random continuous uniform distribution on an interval.
58
+
59
+ Parameters
60
+ ----------
61
+ size : int
62
+ Number of random variates to draw.
63
+ random_state : np.random.Generator
64
+ The random number generator to use.
65
+ """
66
+ return sp.stats.uniform(loc=self.a, scale=(self.b - self.a)).rvs(
67
+ size=size, random_state=random_state
68
+ )
@@ -0,0 +1,19 @@
1
+ from abc import ABC
2
+
3
+
4
+ class Dynamics(ABC): ...
5
+
6
+
7
+ class GeometricBrownianMotion(Dynamics):
8
+ """
9
+ Encapsulates the hyperparameters for geometric Brownian motion, where the logarithm
10
+ of geometric Brownian motion is standard Brownian motion.
11
+
12
+ Attributes
13
+ ----------
14
+ voliatility : float, optional
15
+ The voliatility of geometric brownian motion.
16
+ """
17
+
18
+ def __init__(self, volatility=0.1) -> None:
19
+ self.volatility = volatility
File without changes
@@ -0,0 +1,50 @@
1
+ """
2
+ This module defines the abstract base class for filters used in the application.
3
+
4
+ The `BaseFilter` class provides a template for creating various filter implementations
5
+ with customizable parameters. Subclasses must implement the `run` method.
6
+ """
7
+
8
+ from abc import ABC, abstractmethod
9
+ from typing import Any, Dict
10
+
11
+ from epymorph.parameter_fitting.output import ParticleFilterOutput
12
+
13
+
14
+ class BaseFilter(ABC):
15
+ """
16
+ Abstract base class for filters.
17
+
18
+ Attributes
19
+ ----------
20
+ params : Dict[str, Any]
21
+ Parameters for the filter.
22
+ """
23
+
24
+ def __init__(self, **kwargs: Any) -> None:
25
+ """
26
+ Initializes the filter with the given parameters.
27
+
28
+ Parameters
29
+ ----------
30
+ **kwargs
31
+ Arbitrary keyword arguments representing filter parameters.
32
+ """
33
+ self.params: Dict[str, Any] = kwargs
34
+
35
+ @abstractmethod
36
+ def run(self, *args, **kwargs: Any) -> ParticleFilterOutput:
37
+ """
38
+ Abstract method to run the filter. Must be implemented by subclasses.
39
+
40
+ Parameters
41
+ ----------
42
+ **kwargs
43
+ Arbitrary keyword arguments needed to run the filter.
44
+
45
+ Raises
46
+ ------
47
+ NotImplementedError
48
+ If the method is not implemented by a subclass.
49
+ """
50
+ raise NotImplementedError("Subclasses should implement this method.")
@@ -0,0 +1,32 @@
1
+ import numpy as np
2
+
3
+
4
+ class Particle:
5
+ """
6
+ A class representing a single particle with its state and parameters.
7
+
8
+ Attributes
9
+ ----------
10
+ state : np.ndarray
11
+ The state of the particle, initialized through a model-specific method.
12
+ parameters : Dict[str, float]
13
+ The dynamic parameters associated with the particle (e.g., beta).
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ state: np.ndarray,
19
+ parameters: dict[str, np.ndarray],
20
+ ) -> None:
21
+ """
22
+ Initializes a single particle.
23
+
24
+ Parameters
25
+ ----------
26
+ state : np.ndarray
27
+ Initial state of the particle.
28
+ parameters : Dict[str, np.ndarray]
29
+ Dictionary of dynamic parameters for the particle.
30
+ """
31
+ self.state = state
32
+ self.parameters = parameters