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.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +1378 -0
- epymorph/adrio/adrio.py +953 -0
- epymorph/adrio/cdc.py +1826 -0
- epymorph/adrio/commuting_flows.py +283 -0
- epymorph/adrio/csv.py +499 -0
- epymorph/adrio/humidity.py +206 -0
- epymorph/adrio/lodes.py +509 -0
- epymorph/adrio/numpy.py +160 -0
- epymorph/adrio/prism.py +345 -0
- epymorph/adrio/processing.py +1221 -0
- epymorph/adrio/soda.py +602 -0
- epymorph/adrio/us_tiger.py +289 -0
- epymorph/adrio/validation.py +382 -0
- epymorph/attribute.py +614 -0
- epymorph/cache.py +680 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +78 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1873 -0
- epymorph/data/__init__.py +1 -0
- epymorph/data/ipm/__init__.py +22 -0
- epymorph/data/ipm/no.py +14 -0
- epymorph/data/ipm/pei.py +40 -0
- epymorph/data/ipm/seirs.py +50 -0
- epymorph/data/ipm/sirh.py +55 -0
- epymorph/data/ipm/sirs.py +48 -0
- epymorph/data/ipm/sparsemod.py +96 -0
- epymorph/data/mm/__init__.py +22 -0
- epymorph/data/mm/centroids.py +76 -0
- epymorph/data/mm/flat.py +61 -0
- epymorph/data/mm/icecube.py +50 -0
- epymorph/data/mm/no.py +29 -0
- epymorph/data/mm/pei.py +105 -0
- epymorph/data/mm/sparsemod.py +73 -0
- epymorph/data/pei.py +424 -0
- epymorph/data_shape.py +593 -0
- epymorph/data_type.py +185 -0
- epymorph/data_usage.py +258 -0
- epymorph/database.py +1301 -0
- epymorph/error.py +195 -0
- epymorph/event.py +196 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +93 -0
- epymorph/geography/scope.py +457 -0
- epymorph/geography/us_census.py +1056 -0
- epymorph/geography/us_geography.py +502 -0
- epymorph/geography/us_tiger.py +1083 -0
- epymorph/initializer.py +786 -0
- epymorph/kit.py +107 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +128 -0
- epymorph/log/messaging.py +139 -0
- epymorph/log/movement.py +228 -0
- epymorph/movement_model.py +347 -0
- epymorph/parameter_fitting/__init__.py +0 -0
- epymorph/parameter_fitting/distribution.py +68 -0
- epymorph/parameter_fitting/dynamics.py +19 -0
- epymorph/parameter_fitting/filter/__init__.py +0 -0
- epymorph/parameter_fitting/filter/base_filter.py +50 -0
- epymorph/parameter_fitting/filter/particle.py +32 -0
- epymorph/parameter_fitting/filter/particle_filter.py +296 -0
- epymorph/parameter_fitting/likelihood.py +54 -0
- epymorph/parameter_fitting/output.py +73 -0
- epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
- epymorph/parameter_fitting/perturbation.py +19 -0
- epymorph/parameter_fitting/utils/__init__.py +0 -0
- epymorph/parameter_fitting/utils/data_loader.py +97 -0
- epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
- epymorph/parameter_fitting/utils/observations.py +63 -0
- epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
- epymorph/parameter_fitting/utils/params_perturb.py +43 -0
- epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
- epymorph/parameter_fitting/utils/resampler.py +258 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +438 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +871 -0
- epymorph/simulation.py +991 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +171 -0
- epymorph/simulator/basic/ipm_exec.py +437 -0
- epymorph/simulator/basic/mm_exec.py +244 -0
- epymorph/simulator/basic/output.py +213 -0
- epymorph/simulator/world.py +149 -0
- epymorph/simulator/world_list.py +274 -0
- epymorph/strata.py +24 -0
- epymorph/sympy_shim.py +57 -0
- epymorph/time.py +1197 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +297 -0
- epymorph/tools/ipm_diagram.py +208 -0
- epymorph/tools/out_map.py +551 -0
- epymorph/tools/out_plot.py +423 -0
- epymorph/tools/out_table.py +582 -0
- epymorph/util.py +1036 -0
- epymorph-1.0.0.dist-info/METADATA +57 -0
- epymorph-1.0.0.dist-info/RECORD +104 -0
- epymorph-1.0.0.dist-info/WHEEL +5 -0
- epymorph-1.0.0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`MMExecutor` is part of the internal workings of `BasicSimulator`, implementing the
|
|
3
|
+
logic for processing the movement phase of the simulation. Most users will not use this
|
|
4
|
+
module directly.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from numpy.typing import NDArray
|
|
9
|
+
|
|
10
|
+
from epymorph.attribute import ModuleNamespace
|
|
11
|
+
from epymorph.data_type import SimDType
|
|
12
|
+
from epymorph.database import DataResolver
|
|
13
|
+
from epymorph.error import MMSimError
|
|
14
|
+
from epymorph.event import EventBus, OnMovementClause, OnMovementFinish, OnMovementStart
|
|
15
|
+
from epymorph.movement_model import MovementClause
|
|
16
|
+
from epymorph.rume import RUME
|
|
17
|
+
from epymorph.simulation import (
|
|
18
|
+
Context,
|
|
19
|
+
Tick,
|
|
20
|
+
resolve_tick_delta,
|
|
21
|
+
)
|
|
22
|
+
from epymorph.simulator.world import World
|
|
23
|
+
from epymorph.strata import gpm_strata
|
|
24
|
+
from epymorph.util import row_normalize
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def calculate_travelers(
|
|
28
|
+
clause_name: str,
|
|
29
|
+
clause_mobility: NDArray[np.bool_],
|
|
30
|
+
requested_movers: NDArray[SimDType],
|
|
31
|
+
available_movers: NDArray[SimDType],
|
|
32
|
+
tick: Tick,
|
|
33
|
+
rng: np.random.Generator,
|
|
34
|
+
) -> OnMovementClause:
|
|
35
|
+
"""
|
|
36
|
+
Calculate the number of travelers resulting from this movement clause for this tick.
|
|
37
|
+
This evaluates the requested number movers, modulates that based on the available
|
|
38
|
+
movers, then selects exactly which individuals (by compartment) should move.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
clause_name :
|
|
43
|
+
The movement clause to process.
|
|
44
|
+
clause_mobility :
|
|
45
|
+
The mask describing which compartments are subject to movement.
|
|
46
|
+
requested_movers :
|
|
47
|
+
The movers requested by the clause, an (N,N) array.
|
|
48
|
+
available_movers :
|
|
49
|
+
The number of eligible movers in each location, an (N,C) array.
|
|
50
|
+
tick :
|
|
51
|
+
The tick to process.
|
|
52
|
+
rng :
|
|
53
|
+
The source of randomness.
|
|
54
|
+
|
|
55
|
+
Returns
|
|
56
|
+
-------
|
|
57
|
+
:
|
|
58
|
+
The effecitve movement, as an (N,N,C) array;
|
|
59
|
+
"from source to destination, by compartment".
|
|
60
|
+
"""
|
|
61
|
+
# Extract number of nodes and cohorts from the provided array.
|
|
62
|
+
(N, C) = available_movers.shape
|
|
63
|
+
|
|
64
|
+
initial_requested_movers = requested_movers
|
|
65
|
+
np.fill_diagonal(requested_movers, 0)
|
|
66
|
+
requested_sum = requested_movers.sum(axis=1, dtype=SimDType)
|
|
67
|
+
|
|
68
|
+
available_movers = available_movers * clause_mobility
|
|
69
|
+
available_sum = available_movers.sum(axis=1, dtype=SimDType)
|
|
70
|
+
|
|
71
|
+
# If clause requested total is greater than the total available,
|
|
72
|
+
# use mvhg to select as many as possible.
|
|
73
|
+
if not np.any(requested_sum > available_sum):
|
|
74
|
+
throttled = False
|
|
75
|
+
else:
|
|
76
|
+
throttled = True
|
|
77
|
+
requested_movers = requested_movers.copy()
|
|
78
|
+
for src in range(N):
|
|
79
|
+
if requested_sum[src] > available_sum[src]:
|
|
80
|
+
requested_movers[src, :] = rng.multivariate_hypergeometric(
|
|
81
|
+
colors=requested_movers[src, :], nsample=available_sum[src]
|
|
82
|
+
)
|
|
83
|
+
requested_sum = requested_movers.sum(axis=1, dtype=SimDType)
|
|
84
|
+
|
|
85
|
+
# The probability a mover from a src will go to a dst.
|
|
86
|
+
requested_prb = row_normalize(requested_movers, requested_sum, dtype=SimDType)
|
|
87
|
+
|
|
88
|
+
travelers_cs = np.zeros((N, N, C), dtype=SimDType)
|
|
89
|
+
for src in range(N):
|
|
90
|
+
if requested_sum[src] == 0:
|
|
91
|
+
continue
|
|
92
|
+
|
|
93
|
+
# Select which individuals will be leaving this node.
|
|
94
|
+
mover_cs = rng.multivariate_hypergeometric(
|
|
95
|
+
available_movers[src, :], requested_sum[src]
|
|
96
|
+
).astype(SimDType)
|
|
97
|
+
|
|
98
|
+
# Select which location they are each going to.
|
|
99
|
+
# (Each row contains the compartments for a destination.)
|
|
100
|
+
travelers_cs[src, :, :] = rng.multinomial(
|
|
101
|
+
mover_cs, requested_prb[src, :]
|
|
102
|
+
).T.astype(SimDType)
|
|
103
|
+
|
|
104
|
+
return OnMovementClause(
|
|
105
|
+
tick.sim_index,
|
|
106
|
+
tick.day,
|
|
107
|
+
tick.step,
|
|
108
|
+
clause_name,
|
|
109
|
+
initial_requested_movers,
|
|
110
|
+
travelers_cs,
|
|
111
|
+
requested_sum.sum(),
|
|
112
|
+
throttled,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
_events = EventBus()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class MovementExecutor:
|
|
120
|
+
"""
|
|
121
|
+
The standard implementation of movement execution.
|
|
122
|
+
|
|
123
|
+
rume :
|
|
124
|
+
The RUME.
|
|
125
|
+
world :
|
|
126
|
+
The world state.
|
|
127
|
+
data_resolver :
|
|
128
|
+
The evaluated data attributes of the simulation.
|
|
129
|
+
rng :
|
|
130
|
+
The simulation RNG.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
_rume: RUME
|
|
134
|
+
"""The RUME."""
|
|
135
|
+
_world: World
|
|
136
|
+
"""The world state."""
|
|
137
|
+
_rng: np.random.Generator
|
|
138
|
+
"""The simulation RNG."""
|
|
139
|
+
|
|
140
|
+
_clauses: list[tuple[str, MovementClause]]
|
|
141
|
+
"""Movement clauses with context applied."""
|
|
142
|
+
|
|
143
|
+
def __init__(
|
|
144
|
+
self,
|
|
145
|
+
rume: RUME,
|
|
146
|
+
world: World,
|
|
147
|
+
data: DataResolver,
|
|
148
|
+
rng: np.random.Generator,
|
|
149
|
+
):
|
|
150
|
+
self._rume = rume
|
|
151
|
+
self._world = world
|
|
152
|
+
self._rng = rng
|
|
153
|
+
|
|
154
|
+
# Clone and set context on clauses.
|
|
155
|
+
self._clauses = []
|
|
156
|
+
for strata, model in self._rume.mms.items():
|
|
157
|
+
namespace = ModuleNamespace(gpm_strata(strata), "mm")
|
|
158
|
+
for clause in model.clauses:
|
|
159
|
+
ctx = Context.of(
|
|
160
|
+
namespace.to_absolute(clause.clause_name),
|
|
161
|
+
data,
|
|
162
|
+
rume.scope,
|
|
163
|
+
rume.time_frame,
|
|
164
|
+
rume.ipm,
|
|
165
|
+
rng,
|
|
166
|
+
)
|
|
167
|
+
c = clause.with_context_internal(ctx)
|
|
168
|
+
self._clauses.append((strata, c))
|
|
169
|
+
|
|
170
|
+
def apply(self, tick: Tick) -> None:
|
|
171
|
+
"""
|
|
172
|
+
Apply movement for this tick, mutating the world state.
|
|
173
|
+
|
|
174
|
+
Parameters
|
|
175
|
+
----------
|
|
176
|
+
tick :
|
|
177
|
+
The tick to process.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
_events.on_movement_start.publish(
|
|
181
|
+
OnMovementStart(tick.sim_index, tick.day, tick.step)
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# Process travel clauses.
|
|
185
|
+
total = 0
|
|
186
|
+
for strata, clause in self._clauses:
|
|
187
|
+
if not clause.is_active(tick):
|
|
188
|
+
continue
|
|
189
|
+
|
|
190
|
+
try:
|
|
191
|
+
requested_movers = clause.evaluate(tick)
|
|
192
|
+
np.fill_diagonal(requested_movers, 0)
|
|
193
|
+
except Exception as e:
|
|
194
|
+
# NOTE: catching exceptions here is necessary to get nice error messages
|
|
195
|
+
# for some value error cause by incorrect parameter and/or clause
|
|
196
|
+
# definition
|
|
197
|
+
msg = (
|
|
198
|
+
f"Error from applying clause '{clause.__class__.__name__}': "
|
|
199
|
+
"see exception trace"
|
|
200
|
+
)
|
|
201
|
+
raise MMSimError(msg) from e
|
|
202
|
+
|
|
203
|
+
available_movers = self._world.get_local_array()
|
|
204
|
+
clause_event = calculate_travelers(
|
|
205
|
+
clause.clause_name,
|
|
206
|
+
self._rume.compartment_mobility[strata],
|
|
207
|
+
requested_movers,
|
|
208
|
+
available_movers,
|
|
209
|
+
tick,
|
|
210
|
+
self._rng,
|
|
211
|
+
)
|
|
212
|
+
_events.on_movement_clause.publish(clause_event)
|
|
213
|
+
travelers = clause_event.actual
|
|
214
|
+
|
|
215
|
+
return_tick = resolve_tick_delta(
|
|
216
|
+
self._rume.num_tau_steps,
|
|
217
|
+
tick,
|
|
218
|
+
clause.returns,
|
|
219
|
+
)
|
|
220
|
+
self._world.apply_travel(travelers, return_tick)
|
|
221
|
+
total += travelers.sum()
|
|
222
|
+
|
|
223
|
+
# Process return clause.
|
|
224
|
+
return_movers_nnc = self._world.apply_return(tick, return_stats=True)
|
|
225
|
+
return_movers_nn = return_movers_nnc.sum(axis=2)
|
|
226
|
+
return_total = return_movers_nn.sum()
|
|
227
|
+
total += return_total
|
|
228
|
+
|
|
229
|
+
_events.on_movement_clause.publish(
|
|
230
|
+
OnMovementClause(
|
|
231
|
+
tick.sim_index,
|
|
232
|
+
tick.day,
|
|
233
|
+
tick.step,
|
|
234
|
+
"return",
|
|
235
|
+
return_movers_nn,
|
|
236
|
+
return_movers_nnc,
|
|
237
|
+
return_total,
|
|
238
|
+
False,
|
|
239
|
+
)
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
_events.on_movement_finish.publish(
|
|
243
|
+
OnMovementFinish(tick.sim_index, tick.day, tick.step, total)
|
|
244
|
+
)
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""The simulation results for basic simulations."""
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from typing import Generic, Literal, TypeVar
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
from numpy.typing import NDArray
|
|
11
|
+
from typing_extensions import override
|
|
12
|
+
|
|
13
|
+
from epymorph.data_type import SimDType
|
|
14
|
+
from epymorph.geography.scope import GeoScope
|
|
15
|
+
from epymorph.rume import RUME
|
|
16
|
+
from epymorph.tools.out_map import MapRendererMixin
|
|
17
|
+
from epymorph.tools.out_plot import PlotRendererMixin
|
|
18
|
+
from epymorph.tools.out_table import TableRendererMixin
|
|
19
|
+
|
|
20
|
+
RUMEType_co = TypeVar("RUMEType_co", covariant=True, bound=RUME[GeoScope])
|
|
21
|
+
"""The type of a `RUME` used to produce an `Output`."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Output(
|
|
26
|
+
TableRendererMixin,
|
|
27
|
+
PlotRendererMixin,
|
|
28
|
+
MapRendererMixin,
|
|
29
|
+
Generic[RUMEType_co],
|
|
30
|
+
):
|
|
31
|
+
"""
|
|
32
|
+
The output of a `BasicSimulation` run, including time series for compartment data
|
|
33
|
+
and transition events for all locations.
|
|
34
|
+
|
|
35
|
+
Parameters
|
|
36
|
+
----------
|
|
37
|
+
rume :
|
|
38
|
+
The `RUME` used in the simulation that generated this output.
|
|
39
|
+
initial :
|
|
40
|
+
The simulation's initial compartments by location and compartment.
|
|
41
|
+
visit_compartments :
|
|
42
|
+
Compartment data collected in the node where individuals are visiting.
|
|
43
|
+
visit_events :
|
|
44
|
+
Event data collected in the node where individuals are visiting.
|
|
45
|
+
home_compartments :
|
|
46
|
+
Compartment data collected in the node where individuals reside.
|
|
47
|
+
home_events :
|
|
48
|
+
Event data collected in the node where individuals reside.
|
|
49
|
+
|
|
50
|
+
See Also
|
|
51
|
+
--------
|
|
52
|
+
[epymorph.simulator.basic.basic_simulator.BasicSimulator][] which is the most common
|
|
53
|
+
way to create an output.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
rume: RUMEType_co # type: ignore (pylance can't tell that rume is immutable)
|
|
57
|
+
"""The `RUME` used in the simulation that generated this output."""
|
|
58
|
+
|
|
59
|
+
initial: NDArray[SimDType]
|
|
60
|
+
"""
|
|
61
|
+
The simulation's initial compartments by location and compartment.
|
|
62
|
+
Array of shape (N,C) where N is the number of locations,
|
|
63
|
+
and C is the number of compartments
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
visit_compartments: NDArray[SimDType]
|
|
67
|
+
"""
|
|
68
|
+
Compartment data collected in the node where individuals are visiting.
|
|
69
|
+
See `compartments` for more information.
|
|
70
|
+
"""
|
|
71
|
+
visit_events: NDArray[SimDType]
|
|
72
|
+
"""
|
|
73
|
+
Event data collected in the node where individuals are visiting.
|
|
74
|
+
See `events` for more information.
|
|
75
|
+
"""
|
|
76
|
+
home_compartments: NDArray[SimDType]
|
|
77
|
+
"""
|
|
78
|
+
Compartment data collected in the node where individuals reside.
|
|
79
|
+
See `compartments` for more information.
|
|
80
|
+
"""
|
|
81
|
+
home_events: NDArray[SimDType]
|
|
82
|
+
"""
|
|
83
|
+
Event data collected in the node where individuals reside.
|
|
84
|
+
See `events` for more information.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
data_mode: Literal["visit", "home"] = field(default="visit")
|
|
88
|
+
"""
|
|
89
|
+
Controls which data is returned by the `compartments` and `events` properties.
|
|
90
|
+
Although you can access both data sets, it's helpful to have a default for things
|
|
91
|
+
like our plotting and mapping tools. Defaults to "visit".
|
|
92
|
+
|
|
93
|
+
See `data_by_visit` and `data_by_home`
|
|
94
|
+
to obtain an Output object that uses a different data mode.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
def _with_data_mode(self, data_mode: Literal["visit", "home"]) -> "Output":
|
|
98
|
+
return (
|
|
99
|
+
self
|
|
100
|
+
if self.data_mode == data_mode
|
|
101
|
+
else dataclasses.replace(self, data_mode=data_mode)
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
@cached_property
|
|
105
|
+
def data_by_visit(self) -> "Output":
|
|
106
|
+
"""
|
|
107
|
+
Return an `Output` object that contains the same set of data, but uses
|
|
108
|
+
'visit' as the default data mode.
|
|
109
|
+
"""
|
|
110
|
+
return self._with_data_mode("visit")
|
|
111
|
+
|
|
112
|
+
@cached_property
|
|
113
|
+
def data_by_home(self) -> "Output":
|
|
114
|
+
"""
|
|
115
|
+
Return an `Output` object that contains the same set of data, but uses
|
|
116
|
+
'home' as the default data mode.
|
|
117
|
+
"""
|
|
118
|
+
return self._with_data_mode("home")
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def compartments(self) -> NDArray[SimDType]:
|
|
122
|
+
"""
|
|
123
|
+
Compartment data by timestep, location, and compartment.
|
|
124
|
+
Array of shape (S,N,C) where S is the number of ticks in the simulation,
|
|
125
|
+
N is the number of locations, and C is the number of compartments.
|
|
126
|
+
"""
|
|
127
|
+
if self.data_mode == "visit":
|
|
128
|
+
return self.visit_compartments
|
|
129
|
+
else:
|
|
130
|
+
return self.home_compartments
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def events(self) -> NDArray[SimDType]:
|
|
134
|
+
"""
|
|
135
|
+
Event data by timestep, location, and event.
|
|
136
|
+
Array of shape (S,N,E) where S is the number of ticks in the simulation,
|
|
137
|
+
N is the number of locations, and E is the number of events.
|
|
138
|
+
"""
|
|
139
|
+
if self.data_mode == "visit":
|
|
140
|
+
return self.visit_events
|
|
141
|
+
else:
|
|
142
|
+
return self.home_events
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def events_per_day(self) -> NDArray[SimDType]:
|
|
146
|
+
"""
|
|
147
|
+
Returns this output's `incidence` from a per-tick value to a per-day value.
|
|
148
|
+
Returns a shape (T,N,E) array, where T is the number of simulation days.
|
|
149
|
+
"""
|
|
150
|
+
S = self.rume.num_ticks
|
|
151
|
+
N = self.rume.scope.nodes
|
|
152
|
+
E = self.rume.ipm.num_events
|
|
153
|
+
taus = self.rume.num_tau_steps
|
|
154
|
+
return np.sum(
|
|
155
|
+
self.events.reshape((S // taus, taus, N, E)), axis=1, dtype=SimDType
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def ticks_in_days(self) -> NDArray[np.float64]:
|
|
160
|
+
"""
|
|
161
|
+
Create a series with as many values as there are simulation ticks,
|
|
162
|
+
but in the scale of fractional days. That is: the cumulative sum of
|
|
163
|
+
the simulation's tau step lengths across the simulation duration.
|
|
164
|
+
Returns a shape (S,) array, where S is the number of simulation ticks.
|
|
165
|
+
"""
|
|
166
|
+
return np.cumsum(
|
|
167
|
+
np.tile(self.rume.tau_step_lengths, self.rume.time_frame.days),
|
|
168
|
+
dtype=np.float64,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
@override
|
|
173
|
+
def dataframe(self) -> pd.DataFrame:
|
|
174
|
+
"""Returns the output data as a data frame, using the current data mode."""
|
|
175
|
+
# NOTE: reshape ordering is critical, because the index column creation
|
|
176
|
+
# must assume ordering happens in a specific way.
|
|
177
|
+
# C ordering causes the later index (node) to change fastest and the
|
|
178
|
+
# earlier index (time) to change slowest. (The quantity index is left as-is.)
|
|
179
|
+
# Thus "tick" goes 0,0,0,...,1,1,1,... (similar situation with "date")
|
|
180
|
+
# and "node" goes 1,2,3,...,1,2,3,...
|
|
181
|
+
C = self.rume.ipm.num_compartments
|
|
182
|
+
E = self.rume.ipm.num_events
|
|
183
|
+
N = self.rume.scope.nodes
|
|
184
|
+
S = self.rume.num_ticks
|
|
185
|
+
tau_steps = self.rume.num_tau_steps
|
|
186
|
+
data_np = np.concatenate(
|
|
187
|
+
(self.compartments, self.events),
|
|
188
|
+
axis=2,
|
|
189
|
+
).reshape((-1, C + E), order="C")
|
|
190
|
+
|
|
191
|
+
# Here I'm concatting two DFs sideways so that the index columns come first.
|
|
192
|
+
# Could use insert, but this is nicer.
|
|
193
|
+
return pd.concat(
|
|
194
|
+
(
|
|
195
|
+
# A dataframe for the various indices
|
|
196
|
+
pd.DataFrame(
|
|
197
|
+
{
|
|
198
|
+
"tick": np.arange(S).repeat(N),
|
|
199
|
+
"date": self.rume.time_frame.to_numpy().repeat(N * tau_steps),
|
|
200
|
+
"node": np.tile(self.rume.scope.node_ids, S),
|
|
201
|
+
}
|
|
202
|
+
),
|
|
203
|
+
# A dataframe for the data columns
|
|
204
|
+
pd.DataFrame(
|
|
205
|
+
data=data_np,
|
|
206
|
+
columns=[
|
|
207
|
+
*(c.name.full for c in self.rume.ipm.compartments),
|
|
208
|
+
*(e.name.full for e in self.rume.ipm.events),
|
|
209
|
+
],
|
|
210
|
+
),
|
|
211
|
+
),
|
|
212
|
+
axis=1, # stick them together side-by-side
|
|
213
|
+
)
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The `World` represents the simulation state at a given point in time.
|
|
3
|
+
`World` implementations keep track of how many locations are being simulated,
|
|
4
|
+
and the compartmental breakdown of individuals in each of those locations.
|
|
5
|
+
They also keep track of groups of individuals which have moved between locations
|
|
6
|
+
and will eventually be returning or moving to another location.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from abc import ABC, abstractmethod
|
|
10
|
+
from typing import Literal, Protocol, Sequence, overload
|
|
11
|
+
|
|
12
|
+
from numpy.typing import NDArray
|
|
13
|
+
|
|
14
|
+
from epymorph.data_type import SimDType
|
|
15
|
+
from epymorph.simulation import Tick
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Cohort(Protocol):
|
|
19
|
+
"""
|
|
20
|
+
A group of individuals who may be home or traveling.
|
|
21
|
+
|
|
22
|
+
If they are traveling, they may have a location to which they'll return and
|
|
23
|
+
knowledge of when to do so.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
compartments: NDArray[SimDType]
|
|
27
|
+
"""The group membership by compartment. A (C,)-shaped array."""
|
|
28
|
+
return_location: int
|
|
29
|
+
"""
|
|
30
|
+
The location to which this cohort will return, or if they are home, the location
|
|
31
|
+
where they currently are.
|
|
32
|
+
"""
|
|
33
|
+
return_tick: int
|
|
34
|
+
"""The simulation tick on which they will return. -1 implies never."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class World(ABC):
|
|
38
|
+
"""An abstract world model."""
|
|
39
|
+
|
|
40
|
+
@abstractmethod
|
|
41
|
+
def get_cohorts(self, location_idx: int) -> Sequence[Cohort]:
|
|
42
|
+
"""
|
|
43
|
+
Iterate over the cohorts present in a single location.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
location_idx :
|
|
48
|
+
The index of the location.
|
|
49
|
+
|
|
50
|
+
Returns
|
|
51
|
+
-------
|
|
52
|
+
:
|
|
53
|
+
The cohorts present in the location.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
@abstractmethod
|
|
57
|
+
def get_cohort_array(self, location_idx: int) -> NDArray[SimDType]:
|
|
58
|
+
"""
|
|
59
|
+
Retrieve the cohorts in a single location as a numpy array.
|
|
60
|
+
|
|
61
|
+
Parameters
|
|
62
|
+
----------
|
|
63
|
+
location_idx :
|
|
64
|
+
The index of the location.
|
|
65
|
+
|
|
66
|
+
Returns
|
|
67
|
+
-------
|
|
68
|
+
:
|
|
69
|
+
The cohorts at the location. This is an (X,C)-shaped array where X is the
|
|
70
|
+
number of cohorts, which can be arbitrarily long.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
@abstractmethod
|
|
74
|
+
def get_local_array(self) -> NDArray[SimDType]:
|
|
75
|
+
"""
|
|
76
|
+
Get the local populations of each node.
|
|
77
|
+
|
|
78
|
+
This is the individuals which are theoretically eligible for movement.
|
|
79
|
+
|
|
80
|
+
Returns
|
|
81
|
+
-------
|
|
82
|
+
:
|
|
83
|
+
The local populations as an (N,C)-shaped array.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
@abstractmethod
|
|
87
|
+
def apply_cohort_delta(self, location_idx: int, delta: NDArray[SimDType]) -> None:
|
|
88
|
+
"""
|
|
89
|
+
Apply a transition delta for all cohorts at the given location, updating the
|
|
90
|
+
populations in each compartment.
|
|
91
|
+
|
|
92
|
+
Parameters
|
|
93
|
+
----------
|
|
94
|
+
location_idx :
|
|
95
|
+
The index of the location.
|
|
96
|
+
delta :
|
|
97
|
+
The transitions delta, an (X,C)-shape array where X is the number of cohorts
|
|
98
|
+
and each value is the net positive or negative change to the compartment's
|
|
99
|
+
population.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
@abstractmethod
|
|
103
|
+
def apply_travel(self, travelers: NDArray[SimDType], return_tick: int) -> None:
|
|
104
|
+
"""
|
|
105
|
+
Apply travel flows to the entire world, updating the cohorts at each location.
|
|
106
|
+
|
|
107
|
+
Parameters
|
|
108
|
+
----------
|
|
109
|
+
travelers :
|
|
110
|
+
An (N,N,C)-shaped array determining who should travel
|
|
111
|
+
-- from-source-to-destination-by-compartment.
|
|
112
|
+
return_tick :
|
|
113
|
+
The tick on which any newly-moved cohort should return home.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
@abstractmethod
|
|
117
|
+
@overload
|
|
118
|
+
def apply_return(self, tick: Tick, *, return_stats: Literal[False]) -> None: ...
|
|
119
|
+
|
|
120
|
+
@abstractmethod
|
|
121
|
+
@overload
|
|
122
|
+
def apply_return(
|
|
123
|
+
self, tick: Tick, *, return_stats: Literal[True]
|
|
124
|
+
) -> NDArray[SimDType]: ...
|
|
125
|
+
|
|
126
|
+
@abstractmethod
|
|
127
|
+
def apply_return(
|
|
128
|
+
self, tick: Tick, *, return_stats: bool
|
|
129
|
+
) -> NDArray[SimDType] | None:
|
|
130
|
+
"""
|
|
131
|
+
Apply return-home flows to the entire world, updating the cohorts at each
|
|
132
|
+
location. This finds cohorts which should return home (by looking at their
|
|
133
|
+
return tick) and does so.
|
|
134
|
+
|
|
135
|
+
Parameters
|
|
136
|
+
----------
|
|
137
|
+
tick :
|
|
138
|
+
The current simulation tick.
|
|
139
|
+
return_stats :
|
|
140
|
+
True to collect movement statistics and provide them as the function's
|
|
141
|
+
return value.
|
|
142
|
+
|
|
143
|
+
Returns
|
|
144
|
+
-------
|
|
145
|
+
:
|
|
146
|
+
If `return_stats` is True, an (N,N,C)-shaped array containing the
|
|
147
|
+
number of individuals moved during this return phase. Otherwise returns
|
|
148
|
+
`None`.
|
|
149
|
+
"""
|