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
epymorph/rume.py ADDED
@@ -0,0 +1,871 @@
1
+ """
2
+ A RUME (Runnable Modeling Experiment) is a package containing the critical components
3
+ of an epymorph experiment. Particular simulation tasks may require more information,
4
+ but will certainly not require less. A GPM (Geo-Population Model) is a subset of this
5
+ configuration, and it is possible to combine multiple GPMs into one multi-strata RUME.
6
+ """
7
+
8
+ import textwrap
9
+ from abc import ABC, abstractmethod
10
+ from copy import deepcopy
11
+ from dataclasses import dataclass, field
12
+ from functools import cached_property
13
+ from itertools import accumulate, pairwise, starmap
14
+ from typing import (
15
+ Callable,
16
+ Generic,
17
+ Mapping,
18
+ NamedTuple,
19
+ OrderedDict,
20
+ Sequence,
21
+ TypeVar,
22
+ final,
23
+ )
24
+
25
+ import numpy as np
26
+ from numpy.typing import NDArray
27
+ from sympy import Symbol
28
+ from typing_extensions import override
29
+
30
+ from epymorph.attribute import (
31
+ AbsoluteName,
32
+ AttributeDef,
33
+ ModuleNamePattern,
34
+ NamePattern,
35
+ )
36
+ from epymorph.cache import CACHE_PATH
37
+ from epymorph.compartment_model import (
38
+ BaseCompartmentModel,
39
+ CombinedCompartmentModel,
40
+ CompartmentModel,
41
+ MetaEdgeBuilder,
42
+ MultiStrataModelSymbols,
43
+ TransitionDef,
44
+ )
45
+ from epymorph.data_shape import Shapes
46
+ from epymorph.data_type import SimArray, dtype_str
47
+ from epymorph.data_usage import CanEstimateData, estimate_report
48
+ from epymorph.database import (
49
+ Database,
50
+ DatabaseWithFallback,
51
+ DatabaseWithStrataFallback,
52
+ DataResolver,
53
+ ReqTree,
54
+ )
55
+ from epymorph.error import InitError
56
+ from epymorph.geography.scope import GeoScope
57
+ from epymorph.initializer import Initializer
58
+ from epymorph.movement_model import MovementClause, MovementModel
59
+ from epymorph.params import ParamSymbol, simulation_symbols
60
+ from epymorph.simulation import (
61
+ Context,
62
+ ParamValue,
63
+ SimulationFunction,
64
+ TickDelta,
65
+ TickIndex,
66
+ )
67
+ from epymorph.strata import DEFAULT_STRATA, META_STRATA, gpm_strata
68
+ from epymorph.time import TimeFrame
69
+ from epymorph.util import (
70
+ CovariantMapping,
71
+ KeyValue,
72
+ are_unique,
73
+ map_values,
74
+ )
75
+
76
+ #######
77
+ # GPM #
78
+ #######
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class GPM:
83
+ """
84
+ A GPM (short for Geo-Population Model) combines an IPM, MM, and
85
+ initialization scheme. Most often, a GPM is used to define one strata
86
+ in a multi-strata RUME.
87
+
88
+ Parameters
89
+ ----------
90
+ name :
91
+ The name to use to identify the GPM.
92
+ ipm :
93
+ The IPM for the GPM.
94
+ mm :
95
+ The MM for the GPM.
96
+ init :
97
+ The initializer for the GPM.
98
+ params :
99
+ Parameter values specific to this GPM. When a GPM is used in a RUME,
100
+ RUME parameters will override GPM parameters if there's overlap.
101
+
102
+ See Also
103
+ --------
104
+ [epymorph.rume.MultiStrataRUME.build][] which uses GPMs.
105
+ """
106
+
107
+ name: str
108
+ """The name to use to identify the GPM."""
109
+ ipm: CompartmentModel
110
+ """The IPM for the GPM."""
111
+ mm: MovementModel
112
+ """The MM for the GPM."""
113
+ init: Initializer
114
+ """The initializer for the GPM."""
115
+ params: Mapping[ModuleNamePattern, ParamValue] | None = field(default=None)
116
+ """
117
+ Parameter values specific to this GPM. When a GPM is used in a RUME, RUME parameters
118
+ will override GPM parameters if there's overlap.
119
+ """
120
+
121
+ # NOTE: constructing a ModuleNamePattern object is a bit awkward from an interface
122
+ # perspective; much more ergonomic to just be able to use strings -- but that
123
+ # requires a parsing call. Doing that parsing here is awkward for a dataclass.
124
+ # And we could design around that but I'm not certain this feature isn't destinated
125
+ # to be removed anyway... so for now users will have to do the parsing or maybe
126
+ # we'll add a utility function that effectively does this:
127
+ # params = {ModuleNamePattern.parse(k): v for k, v in (params or {}).items()} # noqa: E501, ERA001
128
+
129
+
130
+ ########
131
+ # RUME #
132
+ ########
133
+
134
+
135
+ GEO_LABELS = KeyValue(
136
+ AbsoluteName(META_STRATA, "geo", "label"),
137
+ AttributeDef(
138
+ "label",
139
+ str,
140
+ Shapes.N,
141
+ comment="Labels to use for each geo node.",
142
+ ),
143
+ )
144
+ """
145
+ A special attribute which, if provided to a RUME ("meta::geo::label"), will be used as
146
+ labels for the geo node. Otherwise labels will be taken from the geo scope.
147
+ """
148
+
149
+
150
+ class CombineTauStepsResult(NamedTuple):
151
+ """The result of the `combine_tau_steps` function."""
152
+
153
+ new_tau_steps: tuple[float, ...]
154
+ """The lengths of the output tau steps."""
155
+ start_mapping: dict[str, dict[int, int]]
156
+ """
157
+ A per-strata mapping for the start of tau step bounds;
158
+ from original tau step index to new tau step index.
159
+ """
160
+ stop_mapping: dict[str, dict[int, int]]
161
+ """
162
+ A per-strata mapping for the end of tau step bounds;
163
+ from original tau step index to new tau step index.
164
+ """
165
+
166
+
167
+ def combine_tau_steps(
168
+ strata_tau_lengths: dict[str, Sequence[float]],
169
+ ) -> CombineTauStepsResult:
170
+ """
171
+ Combine multiple tau step schemes to calculate a unified scheme which is compatible
172
+ with all of them while using the fewest possible number of tau steps.
173
+
174
+ Parameters
175
+ ----------
176
+ strata_tau_lengths :
177
+ A mapping containing each strata name (key) and the list of tau lengths (value).
178
+
179
+ Returns
180
+ -------
181
+ :
182
+ A tuple containing the information required to adjust movement models to the
183
+ combined tau step scheme.
184
+
185
+ Examples
186
+ --------
187
+ For tau steps `[1/3, 2/3]` and tau steps `[1/2, 1/2]` --
188
+ the combined tau steps are `[1/3, 1/6, 1/2]`.
189
+ """
190
+
191
+ # Convert the tau lengths into the starting point and stopping point for each
192
+ # tau step.
193
+ # Starts and stops are expressed as fractions of one day.
194
+ def tau_starts(taus: Sequence[float]) -> Sequence[float]:
195
+ return [0.0, *accumulate(taus)][:-1]
196
+
197
+ def tau_stops(taus: Sequence[float]) -> Sequence[float]:
198
+ return [*accumulate(taus)]
199
+
200
+ strata_tau_starts = map_values(tau_starts, strata_tau_lengths)
201
+ strata_tau_stops = map_values(tau_stops, strata_tau_lengths)
202
+
203
+ # Now we combine all the tau starts set-wise, and sort.
204
+ # These will be the tau steps for our combined simulation.
205
+ combined_tau_starts = list({s for curr in strata_tau_starts.values() for s in curr})
206
+ combined_tau_starts.sort()
207
+ combined_tau_stops = list({s for curr in strata_tau_stops.values() for s in curr})
208
+ combined_tau_stops.sort()
209
+
210
+ # Now calculate the combined tau lengths.
211
+ combined_tau_lengths = tuple(
212
+ stop - start for start, stop in zip(combined_tau_starts, combined_tau_stops)
213
+ )
214
+
215
+ # But the individual strata MMs are indexed by their original tau steps,
216
+ # so we need to calculate the appropriate re-indexing to the new tau steps
217
+ # which will allow us to convert [strata MM tau index] -> [total sim tau index].
218
+ tau_start_mapping = {
219
+ name: {i: combined_tau_starts.index(x) for i, x in enumerate(curr)}
220
+ for name, curr in strata_tau_starts.items()
221
+ }
222
+ tau_stop_mapping = {
223
+ name: {i: combined_tau_stops.index(x) for i, x in enumerate(curr)}
224
+ for name, curr in strata_tau_stops.items()
225
+ }
226
+
227
+ return CombineTauStepsResult(
228
+ combined_tau_lengths, tau_start_mapping, tau_stop_mapping
229
+ )
230
+
231
+
232
+ def remap_taus(
233
+ strata_mms: list[tuple[str, MovementModel]],
234
+ ) -> OrderedDict[str, MovementModel]:
235
+ """
236
+ Adjust a set of movement models which may use different tau step schemes such that
237
+ they all use a unified tau step scheme which is compatible with all of them.
238
+
239
+ This step is performed automatically when constructing a multi-strata RUME.
240
+
241
+ Parameters
242
+ ----------
243
+ strata_mms :
244
+ The list of tuples of strata name and the movement model for that strata.
245
+
246
+ Returns
247
+ -------
248
+ :
249
+ The adjusted movement model for each strata.
250
+ """
251
+ new_tau_steps, start_mapping, stop_mapping = combine_tau_steps(
252
+ {strata: mm.steps for strata, mm in strata_mms}
253
+ )
254
+
255
+ def clause_remap_tau(clause: MovementClause, strata: str) -> MovementClause:
256
+ leave_step = start_mapping[strata][clause.leaves.step]
257
+ return_step = (
258
+ stop_mapping[strata][clause.returns.step]
259
+ if clause.returns.step >= 0
260
+ else -1 # "never"
261
+ )
262
+
263
+ clone = deepcopy(clause)
264
+ clone.leaves = TickIndex(leave_step)
265
+ clone.returns = TickDelta(clause.returns.days, return_step)
266
+ return clone
267
+
268
+ def model_remap_tau(orig_model: MovementModel, strata: str) -> MovementModel:
269
+ clone = deepcopy(orig_model)
270
+ clone.steps = new_tau_steps
271
+ clone.clauses = tuple(clause_remap_tau(c, strata) for c in orig_model.clauses)
272
+ return clone
273
+
274
+ return OrderedDict(
275
+ [
276
+ (strata_name, model_remap_tau(model, strata_name))
277
+ for strata_name, model in strata_mms
278
+ ]
279
+ )
280
+
281
+
282
+ GeoScopeT = TypeVar("GeoScopeT", bound=GeoScope)
283
+ """A type of `GeoScope`."""
284
+ GeoScopeT_co = TypeVar("GeoScopeT_co", covariant=True, bound=GeoScope)
285
+ """A type of `GeoScope`, covariant."""
286
+
287
+
288
+ @dataclass(frozen=True)
289
+ class RUME(ABC, Generic[GeoScopeT_co]):
290
+ """
291
+ A RUME (or Runnable Modeling Experiment) contains the configuration of an
292
+ epymorph-style simulation. It brings together one or more IPMs, MMs, initialization
293
+ routines, and a geo-temporal scope. Model parameters can also be specified.
294
+
295
+ RUMEs are often used to construct a simulation -- in the most basic case, running a
296
+ forward simulation and producing time-series results of disease progression.
297
+
298
+ `RUME` is generic on the type of `GeoScope` used to construct it (`GeoScopeT_co`).
299
+
300
+ See Also
301
+ --------
302
+ `RUME` is an abstract parent class; users will typically use
303
+ [epymorph.rume.SingleStrataRUME.build][] and
304
+ [epymorph.rume.MultiStrataRUMEBuilder][] to construct concrete RUMEs.
305
+ """
306
+
307
+ strata: Sequence[GPM]
308
+ """The strata for the RUME expressed as GPMs."""
309
+ ipm: BaseCompartmentModel
310
+ """The effective IPM for the RUME, made by combining all strata IPMs."""
311
+ mms: OrderedDict[str, MovementModel]
312
+ """ The effective MMs for the RUME by strata, made by combining all strata MMs."""
313
+ scope: GeoScopeT_co
314
+ """The geo scope. This is shared by all strata."""
315
+ time_frame: TimeFrame
316
+ """The simulation time frame."""
317
+ params: Mapping[NamePattern, ParamValue]
318
+ """Parameter values for the RUME."""
319
+
320
+ tau_step_lengths: list[float] = field(init=False)
321
+ """The lengths of each tau step in the simulation as fractions of a day."""
322
+ num_tau_steps: int = field(init=False)
323
+ """The number of tau steps per day in the simulation."""
324
+ num_ticks: int = field(init=False)
325
+ """
326
+ The number of total simulation ticks, the product of multiplying
327
+ the number of simulation days from the time frame by the number of tau steps
328
+ per day.
329
+ """
330
+
331
+ def __post_init__(self):
332
+ if not are_unique(g.name for g in self.strata):
333
+ msg = "Strata names must be unique; duplicate found."
334
+ raise ValueError(msg)
335
+
336
+ # We can get the tau step lengths from a movement model.
337
+ # In a multistrata model, there will be multiple remapped MMs,
338
+ # but they all have the same set of tau steps so it doesn't matter
339
+ # which we use. (Using the first one is safe.)
340
+ first_strata = self.strata[0].name
341
+ steps = self.mms[first_strata].steps
342
+ object.__setattr__(self, "tau_step_lengths", steps)
343
+ object.__setattr__(self, "num_tau_steps", len(steps))
344
+ object.__setattr__(self, "num_ticks", len(steps) * self.time_frame.days)
345
+
346
+ @cached_property
347
+ def requirements(self) -> Mapping[AbsoluteName, AttributeDef]:
348
+ """The attributes required by the RUME."""
349
+
350
+ def generate_items():
351
+ # IPM attributes are already fully named.
352
+ yield from self.ipm.requirements_dict.items()
353
+ # Name the MM and Init attributes.
354
+ for gpm in self.strata:
355
+ strata_name = gpm_strata(gpm.name)
356
+ for a in gpm.mm.requirements:
357
+ yield AbsoluteName(strata_name, "mm", a.name), a
358
+ for a in gpm.init.requirements:
359
+ yield AbsoluteName(strata_name, "init", a.name), a
360
+
361
+ return OrderedDict(generate_items())
362
+
363
+ def _params_database(
364
+ self,
365
+ override_params: CovariantMapping[str | NamePattern, ParamValue] | None = None,
366
+ ) -> Database[ParamValue]:
367
+ label_name, _ = GEO_LABELS
368
+ params_db = DatabaseWithStrataFallback(
369
+ # RUME params are high priority,
370
+ data={**self.params},
371
+ # with fall back to strata params.
372
+ children={
373
+ **{
374
+ gpm_strata(gpm.name): Database(
375
+ {
376
+ k.to_absolute(gpm_strata(gpm.name)): v
377
+ for k, v in (gpm.params or {}).items()
378
+ }
379
+ )
380
+ for gpm in self.strata
381
+ },
382
+ # And provide a low-priority default for node labels.
383
+ "meta": Database({label_name.to_pattern(): self.scope.labels}),
384
+ },
385
+ )
386
+ # If override_params is not empty, wrap in another layer
387
+ # where override_params have the highest priority.
388
+ if override_params is not None and len(override_params) > 0:
389
+ params_db = DatabaseWithFallback(
390
+ {NamePattern.of(k): v for k, v in override_params.items()},
391
+ params_db,
392
+ )
393
+ return params_db
394
+
395
+ @cached_property
396
+ def compartment_mask(self) -> Mapping[str, NDArray[np.bool_]]:
397
+ """
398
+ Masks that describe which compartments belong in the given strata.
399
+ For example: if the model has three strata ('a', 'b', and 'c') with
400
+ three compartments each,
401
+ `strata_compartment_mask('b')` returns `[F F F T T T F F F]`.
402
+ """
403
+
404
+ def mask(length: int, true_slice: slice) -> NDArray[np.bool_]:
405
+ # A boolean array with the given slice set to True, all others False
406
+ m = np.zeros(shape=length, dtype=np.bool_)
407
+ m[true_slice] = True
408
+ return m
409
+
410
+ # num of compartments in the combined IPM
411
+ C = self.ipm.num_compartments
412
+ # num of compartments in each strata
413
+ strata_cs = [gpm.ipm.num_compartments for gpm in self.strata]
414
+ # start and stop index for each strata
415
+ strata_ranges = pairwise([0, *accumulate(strata_cs)])
416
+ # map stata name to the mask for each strata
417
+ return dict(
418
+ zip(
419
+ [g.name for g in self.strata],
420
+ [mask(C, s) for s in starmap(slice, strata_ranges)],
421
+ )
422
+ )
423
+
424
+ @cached_property
425
+ def compartment_mobility(self) -> Mapping[str, NDArray[np.bool_]]:
426
+ """
427
+ Masks that describe which compartments should be considered
428
+ subject to movement in a particular strata.
429
+
430
+ Currently a compartment is exempted from movement calculations if it is tagged
431
+ "immobile".
432
+ """
433
+ # The mobility mask for all strata.
434
+ all_mobility = np.array(
435
+ ["immobile" not in c.tags for c in self.ipm.compartments], dtype=np.bool_
436
+ )
437
+ # Mobility for a single strata is
438
+ # all_mobility boolean-and whether the compartment is in that strata.
439
+ return {
440
+ strata.name: all_mobility & self.compartment_mask[strata.name]
441
+ for strata in self.strata
442
+ }
443
+
444
+ @abstractmethod
445
+ def name_display_formatter(self) -> Callable[[AbsoluteName | NamePattern], str]:
446
+ """
447
+ Create function for formatting attribute/parameter names.
448
+
449
+ Returns
450
+ -------
451
+ :
452
+ The formatter function.
453
+ """
454
+
455
+ def params_description(self) -> str:
456
+ """Provide a description of all attributes required by the RUME."""
457
+ format_name = self.name_display_formatter()
458
+ lines = []
459
+ for name, attr in self.requirements.items():
460
+ properties = [
461
+ f"type: {dtype_str(attr.type)}",
462
+ f"shape: {attr.shape}",
463
+ ]
464
+ if attr.default_value is not None:
465
+ properties.append(f"default: {attr.default_value}")
466
+ lines.append(f"{format_name(name)} ({', '.join(properties)})")
467
+ if attr.comment is not None:
468
+ comment_lines = textwrap.wrap(
469
+ attr.comment,
470
+ initial_indent=" ",
471
+ subsequent_indent=" ",
472
+ )
473
+ lines.extend(comment_lines)
474
+ lines.append("")
475
+ return "\n".join(lines)
476
+
477
+ def generate_params_dict(self) -> str:
478
+ """
479
+ Generate a skeleton dictionary you can use to provide parameter values
480
+ to the RUME.
481
+ """
482
+ format_name = self.name_display_formatter()
483
+ lines = ["{"]
484
+ for name, attr in self.requirements.items():
485
+ value = "PLACEHOLDER"
486
+ if attr.default_value is not None:
487
+ value = str(attr.default_value)
488
+ lines.append(f' "{format_name(name)}": {value},')
489
+ lines.append("}")
490
+ return "\n".join(lines)
491
+
492
+ @staticmethod
493
+ def symbols(*symbols: ParamSymbol) -> tuple[Symbol, ...]:
494
+ """
495
+ Retrieve the sympy symbols used to represent simulation quantities.
496
+
497
+ Parameters
498
+ ----------
499
+ *symbols :
500
+ The symbols to retrieve, as var-args.
501
+
502
+ Returns
503
+ -------
504
+ :
505
+ A tuple containing the symbols requested, in the order
506
+ requested.
507
+ """
508
+ return simulation_symbols(*symbols)
509
+
510
+ def estimate_data(
511
+ self,
512
+ *,
513
+ max_bandwidth: int = 1000**2, # default: 1 MB/s
514
+ ) -> None:
515
+ """
516
+ Print a report estimating the data requirements of this RUME.
517
+
518
+ Includes data which must be downloaded and how much will be added to the file
519
+ cache. Provides a projected download time based on the given assumed maximum
520
+ network bandwidth.
521
+
522
+ Parameters
523
+ ----------
524
+ max_bandwidth :
525
+ The assumed maximum network download speed in bytes per second.
526
+ Default is 1 MB/s.
527
+ """
528
+
529
+ ctx = Context.of(
530
+ scope=self.scope,
531
+ time_frame=self.time_frame,
532
+ ipm=self.ipm,
533
+ )
534
+ estimates = [
535
+ p.with_context_internal(ctx).estimate_data()
536
+ for p in self.params.values()
537
+ if isinstance(p, SimulationFunction) and isinstance(p, CanEstimateData)
538
+ ]
539
+
540
+ lines = list[str]()
541
+ if len(estimates) == 0:
542
+ lines.append("ADRIO data usage is either negligible or non-estimable.")
543
+ else:
544
+ lines.append("ADRIO data usage estimation:")
545
+ lines.extend(estimate_report(CACHE_PATH, estimates, max_bandwidth))
546
+
547
+ for l in lines:
548
+ print(l) # noqa: T201
549
+
550
+ def requirements_tree(
551
+ self,
552
+ override_params: CovariantMapping[str | NamePattern, ParamValue] | None = None,
553
+ ) -> ReqTree:
554
+ """
555
+ Compute the requirements tree for the given RUME.
556
+
557
+ Parameters
558
+ ----------
559
+ override_params :
560
+ When computing requirements, use these values to override
561
+ any that are provided by the RUME itself. If keys are provided as strings,
562
+ they must be able to be parsed as `NamePattern`s.
563
+
564
+ Returns
565
+ -------
566
+ :
567
+ The requirements tree.
568
+
569
+ Raises
570
+ ------
571
+ DataAttributeError
572
+ If the tree cannot be evaluated, for instance, due to containing circular
573
+ dependencies.
574
+ """
575
+ label_name, label_def = GEO_LABELS
576
+ return ReqTree.of(
577
+ requirements={
578
+ # Start with our top-level requirements.
579
+ **self.requirements,
580
+ # Artificially require the geo labels attribute.
581
+ label_name: label_def,
582
+ },
583
+ params=self._params_database(override_params),
584
+ )
585
+
586
+ def evaluate_params(
587
+ self,
588
+ rng: np.random.Generator,
589
+ override_params: CovariantMapping[str | NamePattern, ParamValue] | None = None,
590
+ ) -> DataResolver:
591
+ """
592
+ Evaluate the parameters of this RUME.
593
+
594
+ Parameters
595
+ ----------
596
+ rng :
597
+ The random number generator to use during evaluation
598
+ override_params :
599
+ Use these values to override any that are provided by the RUME itself.
600
+ If keys are provided as strings, they must be able to be parsed as
601
+ `NamePattern`s.
602
+
603
+ Returns
604
+ -------
605
+ :
606
+ The resolver containing the evaluated values.
607
+
608
+ Raises
609
+ ------
610
+ DataAttributeError
611
+ If the parameters cannot be evaluated for any reason, such as missing or
612
+ invalid parameter values.
613
+ """
614
+ ps = None
615
+ if override_params is not None and len(override_params) > 0:
616
+ ps = {NamePattern.of(k): v for k, v in override_params.items()}
617
+
618
+ reqs = self.requirements_tree(ps)
619
+ return reqs.evaluate(self.scope, self.time_frame, self.ipm, rng)
620
+
621
+ def initialize(self, data: DataResolver, rng: np.random.Generator) -> SimArray:
622
+ """
623
+ Evaluate the Initializer(s) for this RUME.
624
+
625
+ Parameters
626
+ ----------
627
+ data :
628
+ The resolved parameters for this RUME.
629
+ rng :
630
+ The random number generator to use. Generally this should be the same
631
+ RNG used to evaluate parameters.
632
+
633
+ Returns
634
+ -------
635
+ :
636
+ the initial values ((N,C)-shaped array) for all geo scope nodes and
637
+ IPM compartments
638
+
639
+ Raises
640
+ ------
641
+ InitError
642
+ If initialization fails for any reason or produces invalid values.
643
+ """
644
+
645
+ def gpm_ctx(gpm: GPM) -> Context:
646
+ return Context.of(
647
+ name=AbsoluteName(gpm_strata(gpm.name), "init", "init"),
648
+ data=data,
649
+ scope=self.scope,
650
+ time_frame=self.time_frame,
651
+ ipm=gpm.ipm,
652
+ rng=rng,
653
+ )
654
+
655
+ try:
656
+ return np.column_stack(
657
+ [
658
+ gpm.init.with_context_internal(gpm_ctx(gpm)).evaluate()
659
+ for gpm in self.strata
660
+ ]
661
+ )
662
+ except InitError as e:
663
+ raise e
664
+ except Exception as e:
665
+ raise InitError("Initializer failed during evaluation.") from e
666
+
667
+
668
+ @dataclass(frozen=True)
669
+ class SingleStrataRUME(RUME[GeoScopeT_co]):
670
+ """
671
+ A RUME with a single strata. We recommend using the more-convenient static method
672
+ `SingleStrataRUME.build` instead of the normal class constructor.
673
+
674
+ `SingleStrataRUME` is generic on the type of `GeoScope` used to construct it
675
+ (`GeoScopeT_co`).
676
+ """
677
+
678
+ ipm: CompartmentModel
679
+
680
+ @staticmethod
681
+ def build(
682
+ ipm: CompartmentModel,
683
+ mm: MovementModel,
684
+ init: Initializer,
685
+ scope: GeoScopeT,
686
+ time_frame: TimeFrame,
687
+ params: CovariantMapping[str | NamePattern, ParamValue],
688
+ ) -> "SingleStrataRUME[GeoScopeT]":
689
+ """
690
+ Create a RUME with a single strata.
691
+
692
+ This method is generic on the type of `GeoScope` used (`GeoScopeT`).
693
+
694
+ Parameters
695
+ ----------
696
+ ipm :
697
+ The compartmental model.
698
+ mm :
699
+ The movement model.
700
+ init :
701
+ The logic for setting the initial conditions of the simulation.
702
+ scope :
703
+ The geo scope.
704
+ time_frame :
705
+ The time frame to simulate.
706
+ params :
707
+ Parameter values that will be used to fulfill the data requirements
708
+ of the various modules of the RUME.
709
+
710
+ Returns
711
+ -------
712
+ :
713
+ The RUME instance.
714
+ """
715
+ return SingleStrataRUME(
716
+ strata=[GPM(DEFAULT_STRATA, ipm, mm, init)],
717
+ ipm=ipm,
718
+ mms=OrderedDict([(DEFAULT_STRATA, mm)]),
719
+ scope=scope,
720
+ time_frame=time_frame,
721
+ params={NamePattern.of(k): v for k, v in params.items()},
722
+ )
723
+
724
+ @override
725
+ def name_display_formatter(self) -> Callable[[AbsoluteName | NamePattern], str]:
726
+ return lambda n: f"{n.module}::{n.id}"
727
+
728
+
729
+ @dataclass(frozen=True)
730
+ class MultiStrataRUME(RUME[GeoScopeT_co]):
731
+ """
732
+ A RUME with multiple strata.
733
+
734
+ `MultiStrataRUME` is generic on the type of `GeoScope` used to construct it
735
+ (`GeoScopeT_co`).
736
+
737
+ See Also
738
+ --------
739
+ [epymorph.rume.MultiStrataRUMEBuilder][] for a more user-friendly way to construct
740
+ multistrata RUMEs.
741
+ """
742
+
743
+ ipm: CombinedCompartmentModel
744
+
745
+ @staticmethod
746
+ def build(
747
+ strata: Sequence[GPM],
748
+ meta_requirements: Sequence[AttributeDef],
749
+ meta_edges: MetaEdgeBuilder,
750
+ scope: GeoScopeT,
751
+ time_frame: TimeFrame,
752
+ params: CovariantMapping[str | NamePattern, ParamValue],
753
+ ) -> "MultiStrataRUME[GeoScopeT]":
754
+ """
755
+ Create a multistrata RUME by combining one GPM per strata.
756
+
757
+ This function is not the recommended way to create multistrata RUMEs;
758
+ see `MultiStrataRUMEBuilder` instead.
759
+
760
+ This method is generic on the type of `GeoScope` used (`GeoScopeT`).
761
+
762
+ Parameters
763
+ ----------
764
+ strata :
765
+ Define the strata for this RUME by providing a GPM for each.
766
+ meta_requirements :
767
+ Define any data requirements used for the meta-edges of the combined IPM.
768
+ meta_edges :
769
+ A function which constructs the meta-edges of the combined IPM.
770
+ scope :
771
+ The geo scope.
772
+ time_frame :
773
+ The time frame to simulate.
774
+ params :
775
+ Parameter values that will be used to fulfill the data requirements
776
+ of the various modules of the RUME.
777
+
778
+ Returns
779
+ -------
780
+ :
781
+ The RUME instance.
782
+ """
783
+ return MultiStrataRUME(
784
+ strata=strata,
785
+ # Combine IPMs
786
+ ipm=CombinedCompartmentModel(
787
+ strata=[(gpm.name, gpm.ipm) for gpm in strata],
788
+ meta_requirements=meta_requirements,
789
+ meta_edges=meta_edges,
790
+ ),
791
+ # Combine MMs
792
+ mms=remap_taus([(gpm.name, gpm.mm) for gpm in strata]),
793
+ scope=scope,
794
+ time_frame=time_frame,
795
+ params={NamePattern.of(k): v for k, v in params.items()},
796
+ )
797
+
798
+ @override
799
+ def name_display_formatter(self) -> Callable[[AbsoluteName | NamePattern], str]:
800
+ return str
801
+
802
+
803
+ class MultiStrataRUMEBuilder(ABC):
804
+ """
805
+ The recommended way to define and create multistrata RUMEs. Implement this class
806
+ and then call `build` to obtain an instance.
807
+ """
808
+
809
+ strata: Sequence[GPM]
810
+ """The strata that are part of this RUME."""
811
+
812
+ meta_requirements: Sequence[AttributeDef]
813
+ """
814
+ A set of additional requirements which are needed by the meta-edges
815
+ in our combined compartment model.
816
+ """
817
+
818
+ @abstractmethod
819
+ def meta_edges(self, symbols: MultiStrataModelSymbols) -> Sequence[TransitionDef]:
820
+ """
821
+ When implementing a MultiStrataRumeBuilder, override this method
822
+ to define the meta-transition-edges -- the edges which represent
823
+ cross-strata interactions.
824
+
825
+ Parameters
826
+ ----------
827
+ symbols :
828
+ The model's symbols library, to obtain compartment and parameter symbols
829
+ needed to build transition rate expressions.
830
+
831
+ Returns
832
+ -------
833
+ :
834
+ The set of transitions to add to the resulting combined IPM.
835
+ """
836
+
837
+ @final
838
+ def build(
839
+ self,
840
+ scope: GeoScopeT,
841
+ time_frame: TimeFrame,
842
+ params: CovariantMapping[str | NamePattern, ParamValue],
843
+ ) -> MultiStrataRUME[GeoScopeT]:
844
+ """
845
+ Complete the RUME definition and construct an instance.
846
+
847
+ This method is generic on the type of `GeoScope` used (`GeoScopeT`).
848
+
849
+ Parameters
850
+ ----------
851
+ scope :
852
+ The geo scope.
853
+ time_frame :
854
+ The time frame to simulate.
855
+ params :
856
+ Parameter values that will be used to fulfill the data requirements
857
+ of the various modules of the RUME.
858
+
859
+ Returns
860
+ -------
861
+ :
862
+ The RUME instance.
863
+ """
864
+ return MultiStrataRUME[GeoScopeT].build(
865
+ self.strata,
866
+ self.meta_requirements,
867
+ self.meta_edges,
868
+ scope,
869
+ time_frame,
870
+ params,
871
+ )