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
File without changes
File without changes
@@ -0,0 +1,171 @@
1
+ """
2
+ Implements `BasicSimulator`: an epymorph simulation algorithm for performing single run,
3
+ forward simulations.
4
+ """
5
+
6
+ from typing import Callable, Generic, TypeVar
7
+
8
+ import numpy as np
9
+
10
+ from epymorph.attribute import NamePattern
11
+ from epymorph.data_type import SimDType
12
+ from epymorph.error import (
13
+ DataAttributeError,
14
+ InitError,
15
+ IPMSimError,
16
+ MMSimError,
17
+ SimCompilationError,
18
+ SimValidationError,
19
+ ValidationError,
20
+ error_gate,
21
+ )
22
+ from epymorph.event import EventBus, OnStart, OnTick
23
+ from epymorph.rume import RUME
24
+ from epymorph.simulation import ParamValue, simulation_clock
25
+ from epymorph.simulator.basic.ipm_exec import IPMExecutor
26
+ from epymorph.simulator.basic.mm_exec import MovementExecutor
27
+ from epymorph.simulator.basic.output import Output
28
+ from epymorph.simulator.world_list import ListWorld
29
+ from epymorph.util import CovariantMapping
30
+
31
+ _events = EventBus()
32
+
33
+ RUMEType = TypeVar("RUMEType", bound=RUME)
34
+ """A type of `RUME`."""
35
+
36
+
37
+ class BasicSimulator(Generic[RUMEType]):
38
+ """
39
+ A simulator for running singular simulation passes and producing time-series output.
40
+ The most basic simulator.
41
+
42
+ This class is generic in the type of RUME used to create it (`RUMEType`).
43
+
44
+ Parameters
45
+ ----------
46
+ rume :
47
+ The rume to use for the simulation.
48
+ """
49
+
50
+ rume: RUMEType
51
+ """The RUME to use for the simulation."""
52
+ ipm_exec: IPMExecutor
53
+ """The class responsible for executing disease simulation."""
54
+ mm_exec: MovementExecutor
55
+ """The class responsible for executing movement simulation."""
56
+
57
+ def __init__(self, rume: RUMEType):
58
+ self.rume = rume
59
+
60
+ def run(
61
+ self,
62
+ /,
63
+ params: CovariantMapping[str | NamePattern, ParamValue] | None = None,
64
+ rng_factory: Callable[[], np.random.Generator] | None = None,
65
+ ) -> Output[RUMEType]:
66
+ """
67
+ Run a forward simulation on the RUME and produce one realization (output).
68
+
69
+ Parameters
70
+ ----------
71
+ params :
72
+ The set of parameters to override for the sake of this
73
+ run. Specified as a dictionary of name/value pairs, where values
74
+ can be in any form normally allowed for the construction of a RUME.
75
+ Any parameter not overridden uses the value from the RUME.
76
+ rng_factory :
77
+ A function used to construct the random number generator for this
78
+ run. This can be used to provide a seeded random number generator
79
+ if consistent results are desired. By default `BasicSimulator` creates
80
+ a new random number generator for each run, using numpy's default rng
81
+ logic.
82
+
83
+ Returns
84
+ -------
85
+ :
86
+ The simulation results.
87
+ """
88
+
89
+ rume = self.rume
90
+
91
+ rng = (rng_factory or np.random.default_rng)()
92
+
93
+ with error_gate(
94
+ "evaluating simulation attributes",
95
+ ValidationError,
96
+ SimCompilationError,
97
+ ):
98
+ try:
99
+ data = rume.evaluate_params(override_params=params, rng=rng)
100
+ except DataAttributeError as e:
101
+ sub_es = e.exceptions if isinstance(e, ExceptionGroup) else (e,)
102
+ err = "\n".join(
103
+ [
104
+ "RUME attribute requirements were not met. See errors:",
105
+ *(f"- {e}" for e in sub_es),
106
+ ]
107
+ )
108
+ raise SimValidationError(err) from None
109
+
110
+ # Reject any parameter that evaluates to a masked numpy array.
111
+ # This indicates unresolved data issues from an ADRIO.
112
+ for key, value in data.raw_values.items():
113
+ if np.ma.is_masked(value):
114
+ err = (
115
+ f"Parameter value {key} contains unresolved issues. Use ADRIO "
116
+ "constructor options to address all data issues as appropriate "
117
+ "before execution."
118
+ )
119
+ raise SimValidationError(err)
120
+
121
+ with error_gate("initializing the simulation", InitError):
122
+ initial_values = rume.initialize(data, rng)
123
+ world = ListWorld.from_initials(initial_values)
124
+
125
+ with error_gate("compiling the simulation", SimCompilationError):
126
+ ipm_exec = IPMExecutor(rume, world, data, rng)
127
+ movement_exec = MovementExecutor(rume, world, data, rng)
128
+
129
+ name = self.__class__.__name__
130
+ _events.on_start.publish(OnStart(name, rume))
131
+
132
+ days = rume.time_frame.days
133
+ taus = rume.num_tau_steps
134
+ S = days * taus
135
+ N = rume.scope.nodes
136
+ C = rume.ipm.num_compartments
137
+ E = rume.ipm.num_events
138
+ visit_compartments = np.zeros((S, N, C), dtype=SimDType)
139
+ visit_events = np.zeros((S, N, E), dtype=SimDType)
140
+ home_compartments = np.zeros((S, N, C), dtype=SimDType)
141
+ home_events = np.zeros((S, N, E), dtype=SimDType)
142
+
143
+ # Run the simulation!
144
+ for tick in simulation_clock(rume.time_frame, rume.tau_step_lengths):
145
+ t = tick.sim_index
146
+
147
+ # First do movement
148
+ with error_gate("executing movement", MMSimError, DataAttributeError):
149
+ movement_exec.apply(tick)
150
+
151
+ # Then do IPM
152
+ with error_gate("executing the IPM", IPMSimError, DataAttributeError):
153
+ vcs, ves, hcs, hes = ipm_exec.apply(tick)
154
+ visit_compartments[t] = vcs
155
+ visit_events[t] = ves
156
+ home_compartments[t] = hcs
157
+ home_events[t] = hes
158
+
159
+ _events.on_tick.publish(OnTick(t, S))
160
+
161
+ _events.on_finish.publish(None)
162
+
163
+ # Assemble output.
164
+ return Output(
165
+ rume=rume,
166
+ initial=initial_values,
167
+ visit_compartments=visit_compartments,
168
+ visit_events=visit_events,
169
+ home_compartments=home_compartments,
170
+ home_events=home_events,
171
+ )
@@ -0,0 +1,437 @@
1
+ """
2
+ `IPMExecutor` is part of the internal workings of `BasicSimulator`, implementing the
3
+ logic for processing the IPM phase of the simulation. Most users will not use this
4
+ module directly.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ from functools import reduce
9
+ from typing import ClassVar, Iterator, NamedTuple, Sequence
10
+
11
+ import numpy as np
12
+ from numpy.typing import NDArray
13
+
14
+ from epymorph.compartment_model import (
15
+ BaseCompartmentModel,
16
+ EdgeDef,
17
+ ForkDef,
18
+ TransitionDef,
19
+ exogenous_states,
20
+ )
21
+ from epymorph.data_type import AttributeValue, SimArray, SimDType
22
+ from epymorph.database import DataResolver
23
+ from epymorph.error import (
24
+ IPMSimInvalidForkError,
25
+ IPMSimLessThanZeroError,
26
+ IPMSimNaNError,
27
+ )
28
+ from epymorph.rume import RUME
29
+ from epymorph.simulation import Tick
30
+ from epymorph.simulator.world import Cohort, World
31
+ from epymorph.sympy_shim import SympyLambda, lambdify, lambdify_list
32
+ from epymorph.util import index_of
33
+
34
+
35
+ class Result(NamedTuple):
36
+ """The result from executing a single IPM step."""
37
+
38
+ visit_compartments: SimArray
39
+ """updated compartments as a result of these events (an (N,C) array) tracked by the
40
+ location where the individuals currently are"""
41
+ visit_events: SimArray
42
+ """events that happened this tick (an (N,E) array) tracked by the location where
43
+ the event occurred"""
44
+ home_compartments: SimArray
45
+ """updated compartments as a result of these events (an (N,C) array) tracked by the
46
+ location that the individuals consider home"""
47
+ home_events: SimArray
48
+ """events that happened this tick (an (N,E) array) tracked by the home location
49
+ of the individuals effected"""
50
+
51
+
52
+ ############################################################
53
+ # StandardIpmExecutor
54
+ ############################################################
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class CompiledEdge:
59
+ """Lambdified `EdgeDef` (no fork). Effectively: `poisson(rate * tau)`."""
60
+
61
+ size: ClassVar[int] = 1
62
+ """The number of edges in this transition."""
63
+ rate_lambda: SympyLambda
64
+ """The lambdified edge rate."""
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class CompiledFork:
69
+ """Lambdified `ForkDef`. Effectively: `multinomial(poisson(rate * tau), prob)`."""
70
+
71
+ size: int
72
+ """The number of edges in this transition."""
73
+ rate_lambda: SympyLambda
74
+ """The lambdified edge base rate."""
75
+ prob_lambda: SympyLambda
76
+ """The lambdified edge fork probabilities."""
77
+
78
+
79
+ CompiledTransition = CompiledEdge | CompiledFork
80
+ """A transition is either a fork or a plain edge."""
81
+
82
+
83
+ def _compile_transitions(model: BaseCompartmentModel) -> list[CompiledTransition]:
84
+ # The parameters to pass to all rate lambdas
85
+ rate_params = [*model.symbols.all_compartments, *model.symbols.all_requirements]
86
+
87
+ def f(transition: TransitionDef) -> CompiledTransition:
88
+ match transition:
89
+ case EdgeDef(_, rate, _, _):
90
+ rate_lambda = lambdify(rate_params, rate)
91
+ return CompiledEdge(rate_lambda)
92
+ case ForkDef(rate, edges, prob):
93
+ size = len(edges)
94
+ rate_lambda = lambdify(rate_params, rate)
95
+ prob_lambda = lambdify_list(rate_params, prob)
96
+ return CompiledFork(size, rate_lambda, prob_lambda)
97
+
98
+ return [f(t) for t in model.transitions]
99
+
100
+
101
+ def _make_apply_matrix(ipm: BaseCompartmentModel) -> SimArray:
102
+ """
103
+ Calc apply matrix; this matrix is used to apply a set of events
104
+ to the compartments they impact. In general, an event indicates
105
+ a transition from one state to another, so it is subtracted from one
106
+ and added to the other. Events involving exogenous states, however,
107
+ either add or subtract from the model but not both. By nature, they
108
+ alter the number of individuals in the model. Matrix values are {+1, 0, -1}.
109
+ """
110
+ csymbols = ipm.symbols.all_compartments
111
+ matrix_size = (ipm.num_events, ipm.num_compartments)
112
+ apply_matrix = np.zeros(matrix_size, dtype=SimDType)
113
+ for eidx, e in enumerate(ipm.events):
114
+ if e.compartment_from not in exogenous_states:
115
+ apply_matrix[eidx, index_of(csymbols, e.compartment_from)] = -1
116
+ if e.compartment_to not in exogenous_states:
117
+ apply_matrix[eidx, index_of(csymbols, e.compartment_to)] = +1
118
+ return apply_matrix
119
+
120
+
121
+ class IPMExecutor:
122
+ """
123
+ The standard implementation of compartment model IPM execution.
124
+
125
+ Parameters
126
+ ----------
127
+ rume :
128
+ The RUME.
129
+ world :
130
+ The world state.
131
+ data_resolver :
132
+ The evaluated data attributes of the simulation.
133
+ rng :
134
+ The simulation RNG.
135
+ """
136
+
137
+ _rume: RUME
138
+ """The RUME."""
139
+ _world: World
140
+ """The world state."""
141
+ _rng: np.random.Generator
142
+ """The simulation RNG."""
143
+
144
+ _trxs: list[CompiledTransition]
145
+ """Compiled transitions."""
146
+ _apply_matrix: NDArray[SimDType]
147
+ """
148
+ A matrix defining how each event impacts each compartment
149
+ (subtracting or adding individuals).
150
+ """
151
+ _events_leaving_compartment: list[list[int]]
152
+ """
153
+ Mapping from compartment index to the list of event indices
154
+ which source from that compartment.
155
+ """
156
+ _source_compartment_for_event: list[int]
157
+ """Mapping from event index to the compartment index it sources from."""
158
+ _attr_values: Iterator[list[AttributeValue]]
159
+ """
160
+ A generator for the list of arguments (from attributes) needed to evaluate
161
+ transition functions.
162
+ """
163
+
164
+ def __init__(
165
+ self,
166
+ rume: RUME,
167
+ world: World,
168
+ data: DataResolver,
169
+ rng: np.random.Generator,
170
+ ):
171
+ ipm = rume.ipm
172
+ csymbols = ipm.symbols.all_compartments
173
+
174
+ # Calc list of events leaving each compartment (each may have 0, 1, or more)
175
+ events_leaving_compartment = [
176
+ [eidx for eidx, e in enumerate(ipm.events) if e.compartment_from == c]
177
+ for c in csymbols
178
+ ]
179
+
180
+ # Calc the source compartment for each event
181
+ source_compartment_for_event = [
182
+ index_of(csymbols, e.compartment_from) for e in ipm.events
183
+ ]
184
+
185
+ self._rume = rume
186
+ self._world = world
187
+ self._rng = rng
188
+
189
+ self._trxs = _compile_transitions(ipm)
190
+ self._apply_matrix = _make_apply_matrix(ipm)
191
+ self._events_leaving_compartment = events_leaving_compartment
192
+ self._source_compartment_for_event = source_compartment_for_event
193
+ self._attr_values = data.resolve_txn_series(
194
+ ipm.requirements_dict.items(),
195
+ rume.num_tau_steps,
196
+ )
197
+
198
+ def apply(self, tick: Tick) -> Result:
199
+ """
200
+ Apply the IPM for this tick, mutating the world state.
201
+
202
+ Parameters
203
+ ----------
204
+ tick :
205
+ Which tick to process.
206
+
207
+ Returns
208
+ -------
209
+ :
210
+ The location-specific events that happened this tick (an (N,E) array)
211
+ and the new compartments resulting from these events (an (N,C) array).
212
+ """
213
+ N = self._rume.scope.nodes
214
+ C = self._rume.ipm.num_compartments
215
+ E = self._rume.ipm.num_events
216
+
217
+ # (home_node, visit_node, :)
218
+ events = np.zeros((N, N, E), dtype=SimDType)
219
+ compartments = np.zeros((N, N, C), dtype=SimDType)
220
+
221
+ for visit_node in range(N):
222
+ # Sum all cohorts present in this node to get an effective total population.
223
+ cohorts = self._world.get_cohorts(visit_node)
224
+ effective = reduce(
225
+ lambda a, b: a + b,
226
+ map(lambda x: x.compartments, cohorts),
227
+ )
228
+
229
+ # Determine how many events happen in this tick.
230
+ node_events = self._events(tick, visit_node, effective) # (E,) array
231
+
232
+ # Distribute events to the cohorts, proportional to their population.
233
+ cohort_events = self._distribute(cohorts, node_events) # (X,E) array
234
+
235
+ # Now that events are assigned to cohorts,
236
+ # convert to compartment deltas using apply matrix.
237
+ self._world.apply_cohort_delta(
238
+ visit_node,
239
+ np.matmul(cohort_events, self._apply_matrix, dtype=SimDType), # (X,C)
240
+ )
241
+
242
+ # Collect compartment/event info.
243
+ for i, x in enumerate(cohorts):
244
+ home = x.return_location
245
+ events[home, visit_node, :] = cohort_events[i, :]
246
+ compartments[home, visit_node, :] = x.compartments
247
+
248
+ return Result(
249
+ visit_compartments=compartments.sum(axis=0),
250
+ visit_events=events.sum(axis=0),
251
+ home_compartments=compartments.sum(axis=1),
252
+ home_events=events.sum(axis=1),
253
+ )
254
+
255
+ def _events(self, tick: Tick, node: int, effective_pop: SimArray) -> SimArray:
256
+ """
257
+ Calculate how many events will happen this tick, correcting
258
+ for the possibility of overruns. An (E,) array.
259
+ """
260
+
261
+ rate_args = [*effective_pop, *next(self._attr_values)]
262
+
263
+ # Evaluate the event rates and do random draws for all transition events.
264
+ occur = np.zeros(self._rume.ipm.num_events, dtype=SimDType)
265
+ index = 0
266
+ for t in self._trxs:
267
+ try:
268
+ match t:
269
+ case CompiledEdge(rate_lambda):
270
+ # get rate from lambda expression, catch divide by zero error
271
+ rate = rate_lambda(rate_args)
272
+ if rate < 0:
273
+ err = self._get_default_error_args(rate_args, node, tick)
274
+ raise IPMSimLessThanZeroError(err)
275
+ occur[index] = self._rng.poisson(rate * tick.tau)
276
+ case CompiledFork(size, rate_lambda, prob_lambda):
277
+ # get rate from lambda expression, catch divide by zero error
278
+ rate = rate_lambda(rate_args)
279
+ if rate < 0:
280
+ err = self._get_default_error_args(rate_args, node, tick)
281
+ raise IPMSimLessThanZeroError(err)
282
+ prob = prob_lambda(rate_args)
283
+ if any(n < 0 for n in prob):
284
+ err = self._get_invalid_prob_args(rate_args, node, tick, t)
285
+ raise IPMSimInvalidForkError(err)
286
+ occur[index : (index + size)] = self._rng.multinomial(
287
+ n=self._rng.poisson(rate * tick.tau),
288
+ pvals=prob,
289
+ )
290
+ index += t.size
291
+ except (ZeroDivisionError, FloatingPointError):
292
+ err = self._get_zero_division_args(rate_args, node, tick, t)
293
+ raise IPMSimNaNError(err) from None
294
+
295
+ # Check for event overruns leaving each compartment and correct counts.
296
+ for cidx, eidxs in enumerate(self._events_leaving_compartment):
297
+ available = effective_pop[cidx]
298
+ n = len(eidxs)
299
+ if n == 0:
300
+ # Compartment has no outward edges; nothing to do here.
301
+ continue
302
+ elif n == 1:
303
+ # Compartment only has one outward edge; just "min".
304
+ eidx = eidxs[0]
305
+ occur[eidx] = min(occur[eidx], available)
306
+ elif n == 2:
307
+ # Compartment has two outward edges:
308
+ # use hypergeo to select which events "actually" happened.
309
+ desired0, desired1 = occur[eidxs]
310
+ if desired0 + desired1 > available:
311
+ drawn0 = self._rng.hypergeometric(desired0, desired1, available)
312
+ occur[eidxs] = [drawn0, available - drawn0]
313
+ else:
314
+ # Compartment has more than two outwards edges:
315
+ # use multivariate hypergeometric to select which events
316
+ # "actually" happened.
317
+ desired = occur[eidxs]
318
+ if np.sum(desired) > available:
319
+ occur[eidxs] = self._rng.multivariate_hypergeometric(
320
+ desired, available
321
+ )
322
+ return occur
323
+
324
+ def _distribute(
325
+ self,
326
+ cohorts: Sequence[Cohort],
327
+ events: NDArray[SimDType], # (E,) array
328
+ ) -> NDArray[SimDType]:
329
+ """Distribute events across a location's cohorts. Returns an (X,E) result."""
330
+ cohort_array = np.array(
331
+ [x.compartments for x in cohorts],
332
+ dtype=SimDType,
333
+ ) # (X,C) array
334
+
335
+ (X, _) = cohort_array.shape
336
+ (E,) = events.shape
337
+
338
+ # Each cohort is responsible for a proportion of the total population:
339
+ total = cohort_array.sum()
340
+ if total > 0:
341
+ cohort_proportion = cohort_array.sum(axis=1) / total
342
+ else:
343
+ # If total population is zero, weight each cohort equally.
344
+ cohort_proportion = np.ones(X) / X
345
+
346
+ occurrences = np.zeros((X, E), dtype=SimDType)
347
+
348
+ for eidx in range(E):
349
+ occur: int = events[eidx] # type: ignore
350
+ cidx = self._source_compartment_for_event[eidx]
351
+ if cidx == -1:
352
+ # event is coming from an exogenous source
353
+ # randomly distribute to cohorts based on their share of the population
354
+ selected = self._rng.multinomial(
355
+ occur,
356
+ cohort_proportion,
357
+ ).astype(SimDType)
358
+ else:
359
+ # event is coming from a modeled compartment
360
+ selected = self._rng.multivariate_hypergeometric(
361
+ cohort_array[:, cidx],
362
+ occur,
363
+ ).astype(SimDType)
364
+ cohort_array[:, cidx] -= selected
365
+ occurrences[:, eidx] = selected
366
+
367
+ return occurrences
368
+
369
+ def _get_default_error_args(
370
+ self, rate_attrs: list, node: int, tick: Tick
371
+ ) -> list[tuple[str, dict]]:
372
+ """Assemble arguments error messages."""
373
+ cvals = {
374
+ name: value
375
+ for name, value in zip(
376
+ [c.name.full for c in self._rume.ipm.compartments],
377
+ rate_attrs[: self._rume.ipm.num_compartments],
378
+ )
379
+ }
380
+ pvals = {
381
+ attribute.name: value
382
+ for attribute, value in zip(
383
+ self._rume.ipm.requirements,
384
+ rate_attrs[self._rume.ipm.num_compartments :],
385
+ )
386
+ }
387
+ return [
388
+ ("Node : Timestep", {node: tick.step}),
389
+ ("compartment values", cvals),
390
+ ("ipm params", pvals),
391
+ ]
392
+
393
+ def _get_invalid_prob_args(
394
+ self,
395
+ rate_attrs: list,
396
+ node: int,
397
+ tick: Tick,
398
+ transition: CompiledFork,
399
+ ) -> list[tuple[str, dict]]:
400
+ """Assemble arguments error messages."""
401
+ arg_list = self._get_default_error_args(rate_attrs, node, tick)
402
+
403
+ transition_index = self._trxs.index(transition)
404
+ corr_transition = self._rume.ipm.transitions[transition_index]
405
+ if isinstance(corr_transition, ForkDef):
406
+ trx_vals = {
407
+ str(corr_transition): corr_transition.rate,
408
+ "Probabilities": ", ".join(
409
+ [str(expr) for expr in corr_transition.probs]
410
+ ),
411
+ }
412
+ arg_list.append(
413
+ ("corresponding fork transition and probabilities", trx_vals)
414
+ )
415
+
416
+ return arg_list
417
+
418
+ def _get_zero_division_args(
419
+ self,
420
+ rate_attrs: list,
421
+ node: int,
422
+ tick: Tick,
423
+ transition: CompiledEdge | CompiledFork,
424
+ ) -> list[tuple[str, dict]]:
425
+ """Assemble arguments for error messages."""
426
+ arg_list = self._get_default_error_args(rate_attrs, node, tick)
427
+
428
+ transition_index = self._trxs.index(transition)
429
+ corr_transition = self._rume.ipm.transitions[transition_index]
430
+ if isinstance(corr_transition, EdgeDef):
431
+ trx = {str(corr_transition.name): corr_transition.rate}
432
+ arg_list.append(("corresponding transition", trx))
433
+ elif isinstance(corr_transition, ForkDef):
434
+ trx = {str(corr_transition): corr_transition.rate}
435
+ arg_list.append(("corresponding fork transition", trx))
436
+
437
+ return arg_list