-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmm_exec.py
198 lines (166 loc) · 6.65 KB
/
mm_exec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""
Movement executor classes handle the logic for processing the movement step of the simulation.
"""
from abc import ABC, abstractmethod
import numpy as np
from numpy.typing import NDArray
from epymorph.data_type import SimDType
from epymorph.engine.world import World
from epymorph.error import AttributeException, MmCompileException
from epymorph.event import (MovementEventsMixin, OnMovementClause,
OnMovementFinish, OnMovementStart)
from epymorph.movement.compile import compile_spec
from epymorph.movement.movement_model import (MovementContext, MovementModel,
PredefData, TravelClause)
from epymorph.movement.parser import MovementSpec
from epymorph.simulation import Tick, resolve_tick
from epymorph.util import row_normalize
class MovementExecutor(ABC):
"""
Abstract interface responsible for advancing the simulation state due to the MM.
"""
@abstractmethod
def apply(self, world: World, tick: Tick) -> None:
"""
Applies movement for this tick, mutating the world state.
"""
def calculate_travelers(
# General movement model info.
ctx: MovementContext,
predef: PredefData,
# Clause info.
clause: TravelClause,
clause_mobility: NDArray[np.bool_],
tick: Tick,
local_cohorts: NDArray[SimDType],
) -> OnMovementClause:
"""
Calculate the number of travelers resulting from this movement clause for this tick.
This evaluates the requested number movers, modulates that based on the available movers,
then selects exactly which individuals (by compartment) should move.
Returns an (N,N,C) array; from-source-to-destination-by-compartment.
"""
_, N, C, _ = ctx.dim.TNCE
clause_movers = clause.requested(ctx, predef, tick)
np.fill_diagonal(clause_movers, 0)
clause_sum = clause_movers.sum(axis=1, dtype=SimDType)
available_movers = local_cohorts * clause_mobility
available_sum = available_movers.sum(axis=1, dtype=SimDType)
# If clause requested total is greater than the total available,
# use mvhg to select as many as possible.
if not np.any(clause_sum > available_sum):
throttled = False
requested_movers = clause_movers
requested_sum = clause_sum
else:
throttled = True
requested_movers = clause_movers.copy()
for src in range(N):
if clause_sum[src] > available_sum[src]:
requested_movers[src, :] = ctx.rng.multivariate_hypergeometric(
colors=requested_movers[src, :],
nsample=available_sum[src]
)
requested_sum = requested_movers.sum(axis=1, dtype=SimDType)
# The probability a mover from a src will go to a dst.
requested_prb = row_normalize(requested_movers, requested_sum, dtype=SimDType)
travelers_cs = np.zeros((N, N, C), dtype=SimDType)
for src in range(N):
if requested_sum[src] == 0:
continue
# Select which individuals will be leaving this node.
mover_cs = ctx.rng.multivariate_hypergeometric(
available_movers[src, :],
requested_sum[src]
).astype(SimDType)
# Select which location they are each going to.
# (Each row contains the compartments for a destination.)
travelers_cs[src, :, :] = ctx.rng.multinomial(
mover_cs,
requested_prb[src, :]
).T.astype(SimDType)
return OnMovementClause(
tick.index,
tick.day,
tick.step,
clause.name,
clause_movers,
travelers_cs,
requested_sum.sum(),
throttled,
)
############################################################
# StandardMovementExecutor
############################################################
class StandardMovementExecutor(MovementEventsMixin, MovementExecutor):
"""The standard implementation of movement model execution."""
_model: MovementModel
_predef: PredefData
_predef_hash: int | None
_mobility: NDArray[np.bool_]
_ctx: MovementContext
def __init__(
self,
ctx: MovementContext,
mm: MovementSpec,
compartment_mobility: NDArray[np.bool_],
):
MovementEventsMixin.__init__(self)
self._model = compile_spec(mm, ctx.rng)
self._predef = {}
self._predef_hash = None
self._mobility = compartment_mobility
self._ctx = ctx
self._check_predef()
def _check_predef(self) -> None:
"""Check if predefs need to be re-calc'd, and if so, do so."""
curr_hash = self._model.predef_context_hash(self._ctx)
if curr_hash != self._predef_hash:
try:
self._predef = self._model.predef(self._ctx)
self._predef_hash = curr_hash
except KeyError as e:
msg = f"Missing attribute {e} required by movement model predef."
raise AttributeException(msg) from None
if not isinstance(self._predef, dict):
msg = f"Movement predef: did not return a dictionary result (got: {type(self._predef)})"
raise MmCompileException(msg)
def apply(self, world: World, tick: Tick) -> None:
"""Applies movement for this tick, mutating the world state."""
self.on_movement_start.publish(
OnMovementStart(tick.index, tick.day, tick.step))
self._check_predef()
# Process travel clauses.
total = 0
for clause in self._model.clauses:
if not clause.predicate(self._ctx, tick):
continue
local_array = world.get_local_array()
clause_event = calculate_travelers(
self._ctx, self._predef,
clause, self._mobility, tick, local_array,
)
self.on_movement_clause.publish(clause_event)
travelers = clause_event.actual
returns = clause.returns(self._ctx, tick)
return_tick = resolve_tick(self._ctx.dim, tick, returns)
world.apply_travel(travelers, return_tick)
total += travelers.sum()
# Process return clause.
return_movers = world.apply_return(tick, return_stats=True)
return_total = return_movers.sum()
total += return_total
self.on_movement_clause.publish(
OnMovementClause(
tick.index,
tick.day,
tick.step,
"return",
return_movers,
return_movers,
return_total,
False,
)
)
self.on_movement_finish.publish(
OnMovementFinish(tick.index, tick.day, tick.step, total))