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/simulation.py ADDED
@@ -0,0 +1,991 @@
1
+ """General simulation requisites and utility functions."""
2
+
3
+ import functools
4
+ import re
5
+ from abc import ABC, ABCMeta, abstractmethod
6
+ from copy import deepcopy
7
+ from datetime import date, timedelta
8
+ from typing import (
9
+ Any,
10
+ Callable,
11
+ Generic,
12
+ Iterable,
13
+ Mapping,
14
+ NamedTuple,
15
+ Never,
16
+ Self,
17
+ Sequence,
18
+ Type,
19
+ TypeGuard,
20
+ TypeVar,
21
+ Union,
22
+ final,
23
+ )
24
+
25
+ import numpy as np
26
+ from jsonpickle.util import is_picklable
27
+ from numpy.random import SeedSequence
28
+ from numpy.typing import NDArray
29
+ from sympy import Expr
30
+
31
+ from epymorph.attribute import (
32
+ NAME_PLACEHOLDER,
33
+ AbsoluteName,
34
+ AttributeDef,
35
+ AttributeName,
36
+ NamePattern,
37
+ )
38
+ from epymorph.compartment_model import BaseCompartmentModel
39
+ from epymorph.data_shape import DataShape, Dimensions
40
+ from epymorph.data_type import (
41
+ AttributeArray,
42
+ ScalarDType,
43
+ ScalarValue,
44
+ StructDType,
45
+ StructValue,
46
+ )
47
+ from epymorph.database import (
48
+ Database,
49
+ DataResolver,
50
+ RecursiveValue,
51
+ ReqTree,
52
+ is_recursive_value,
53
+ )
54
+ from epymorph.error import MissingContextError
55
+ from epymorph.geography.scope import GeoScope
56
+ from epymorph.time import TimeFrame
57
+ from epymorph.util import are_instances, are_unique
58
+
59
+
60
+ def default_rng(
61
+ seed: int | SeedSequence | None = None,
62
+ ) -> Callable[[], np.random.Generator]:
63
+ """
64
+ Construct to create a factory function for a simulation's
65
+ random number generator.
66
+
67
+ Parameters
68
+ ----------
69
+ seed :
70
+ Construct a generate with this random seed. By default, the generator will be
71
+ "unseeded", that is seeded in an unpredictable way.
72
+
73
+ Returns
74
+ -------
75
+ :
76
+ A function that creates a random number generator.
77
+ """
78
+ return lambda: np.random.default_rng(seed)
79
+
80
+
81
+ ###################
82
+ # Simulation time #
83
+ ###################
84
+
85
+
86
+ class Tick(NamedTuple):
87
+ """
88
+ Represents a single time-step in a simulation, by analogy to the ticking of a clock.
89
+ This tuple bundles the related information for a single tick. For instance, each
90
+ time step corresponds to a calendar day, a numeric day (i.e., relative to the start
91
+ of the simulation), which tau step this corresponds to, and so on.
92
+ """
93
+
94
+ sim_index: int
95
+ """Which simulation step are we on? (0,1,2,3,...)"""
96
+ day: int
97
+ """Which day increment are we on? Same for each tau step: (0,0,1,1,2,2,...)"""
98
+ date: date
99
+ """The calendar date corresponding to `day`"""
100
+ step: int
101
+ """Which tau step are we on, by index? (0,1,0,1,0,1,...)"""
102
+ tau: float
103
+ """What's the tau length of the current step? (0.666,0.333,0.666,0.333,...)"""
104
+
105
+
106
+ class TickIndex(NamedTuple):
107
+ """
108
+ An index identifying tau steps within a day.
109
+ For example, if a RUME's movement model declares three tau steps,
110
+ the first six tick indices will be 0, 1, 2, 0, 1, 2.
111
+ Indices 3 or more would be invalid for this RUME.
112
+ """
113
+
114
+ step: int
115
+ """The index of the tau step."""
116
+
117
+
118
+ class TickDelta(NamedTuple):
119
+ """
120
+ An offset relative to a tick, expressed as a number of whole days which should
121
+ elapse and the step on which to end up. In applying this delta, it does not matter
122
+ which step we start on.
123
+
124
+ See Also
125
+ --------
126
+ [epymorph.simulation.resolve_tick_delta][], the function which combines an
127
+ absolute tick with a relative delta to get another absolute tick.
128
+ """
129
+
130
+ days: int
131
+ """The number of whole days."""
132
+ step: int
133
+ """Which tau step within that day, by index."""
134
+
135
+
136
+ NEVER = TickDelta(-1, -1)
137
+ """
138
+ A special `TickDelta` which expresses an event that should never happen.
139
+ Any `Tick` plus `NEVER` equals `NEVER`.
140
+ """
141
+
142
+
143
+ def resolve_tick_delta(tau_steps_per_day: int, tick: Tick, delta: TickDelta) -> int:
144
+ """
145
+ Add a delta to a tick to get the index of the resulting tick.
146
+
147
+ Parameters
148
+ ----------
149
+ tau_steps_per_day :
150
+ The number of simulation tau steps per day.
151
+ tick :
152
+ The tick to start from.
153
+ delta :
154
+ A delta to add to `tick`.
155
+
156
+ Returns
157
+ -------
158
+ :
159
+ The result of adding `delta` to `tick`, as a tick index.
160
+ """
161
+ return (
162
+ -1
163
+ if delta.days == -1
164
+ else tick.sim_index - tick.step + (tau_steps_per_day * delta.days) + delta.step
165
+ )
166
+
167
+
168
+ def simulation_clock(
169
+ time_frame: TimeFrame,
170
+ tau_step_lengths: list[float],
171
+ ) -> Iterable[Tick]:
172
+ """
173
+ Generate the sequence of ticks which makes up the simulation clock.
174
+
175
+ Parameters
176
+ ----------
177
+ time_frame :
178
+ A simulation's time frame.
179
+ tau_step_lengths :
180
+ The simulation tau steps as fractions of one day.
181
+
182
+ Returns
183
+ -------
184
+ :
185
+ The sequence of ticks as determined by the simulation's start date,
186
+ duration, and tau steps configuration.
187
+ """
188
+ one_day = timedelta(days=1)
189
+ tau_steps = list(enumerate(tau_step_lengths))
190
+ curr_index = 0
191
+ curr_date = time_frame.start_date
192
+ for day in range(time_frame.days):
193
+ for step, tau in tau_steps:
194
+ yield Tick(curr_index, day, curr_date, step, tau)
195
+ curr_index += 1
196
+ curr_date += one_day
197
+
198
+
199
+ ##############################
200
+ # Simulation parameter types #
201
+ ##############################
202
+
203
+
204
+ ListValue = Sequence[Union[ScalarValue, StructValue, "ListValue"]]
205
+ """
206
+ A type alias which describes acceptable input forms for parameter values which are
207
+ lists. (Necessary because this type is recursive: lists can be nested inside lists.)
208
+ """
209
+
210
+ ParamValue = Union[
211
+ ScalarValue,
212
+ StructValue,
213
+ ListValue,
214
+ "SimulationFunction",
215
+ Expr,
216
+ NDArray[ScalarDType | StructDType],
217
+ ]
218
+ """
219
+ A type alias which describes all acceptable input forms for parameter values:
220
+
221
+ - scalars (according to [epymorph.data_type.ScalarValue][])
222
+ - tuples (single structured values, according to
223
+ [epymorph.data_type.StructValue][])
224
+ - Python lists of scalars or tuples, which may be nested
225
+ - [epymorph.simulation.SimulationFunction][] instances
226
+ - Numpy arrays
227
+ - sympy expressions
228
+ """
229
+
230
+
231
+ ########################
232
+ # Simulation functions #
233
+ ########################
234
+
235
+
236
+ class Context(ABC):
237
+ """
238
+ The evaluation context of a `SimulationFunction`.
239
+
240
+ See Also
241
+ --------
242
+ This class is abstract so you won't instantiate it as a normal class;
243
+ instead you may use static method [epymorph.simulation.Context.of][].
244
+ """
245
+
246
+ # NOTE: We want SimulationFunction instances to be able to access properties of the
247
+ # simulation by using various methods on `self`. But we also want to instantiate
248
+ # SimulationFunctions before the simulation context exists! Hence this object
249
+ # starts out "empty" and will be swapped for a "full" context when the function
250
+ # is evaluated in a simulation context object. Partial contexts exist to allow easy
251
+ # one-off evaluation of SimulationFunctions without a full RUME.
252
+
253
+ _args: dict[str, Any]
254
+ """Remember the arguments that were used to construct this context instance."""
255
+
256
+ @property
257
+ @abstractmethod
258
+ def name(self) -> AbsoluteName:
259
+ """The name under which this attribute is being evaluated."""
260
+
261
+ @abstractmethod
262
+ def data(self, attribute: AttributeDef) -> AttributeArray:
263
+ """
264
+ Retrieve the value of an attribute.
265
+
266
+ Parameters
267
+ ----------
268
+ attribute :
269
+ The attribute to retrieve.
270
+
271
+ Returns
272
+ -------
273
+ :
274
+ The attribute's value.
275
+ """
276
+
277
+ @property
278
+ @abstractmethod
279
+ def scope(self) -> GeoScope:
280
+ """The simulation `GeoScope`."""
281
+
282
+ @property
283
+ @abstractmethod
284
+ def time_frame(self) -> TimeFrame:
285
+ """The simulation time frame."""
286
+
287
+ @property
288
+ @abstractmethod
289
+ def ipm(self) -> BaseCompartmentModel:
290
+ """The simulation's IPM."""
291
+
292
+ @property
293
+ @abstractmethod
294
+ def rng(self) -> np.random.Generator:
295
+ """The simulation's random number generator."""
296
+
297
+ @property
298
+ @abstractmethod
299
+ def dim(self) -> Dimensions:
300
+ """Simulation dimensions."""
301
+
302
+ @final
303
+ def replace(
304
+ self,
305
+ name: AbsoluteName | None = None,
306
+ data: DataResolver | None = None,
307
+ scope: GeoScope | None = None,
308
+ time_frame: TimeFrame | None = None,
309
+ ipm: BaseCompartmentModel | None = None,
310
+ rng: np.random.Generator | None = None,
311
+ ) -> "Context":
312
+ """
313
+ Create a new context by overriding some or all of this context's values.
314
+
315
+ Parameters
316
+ ----------
317
+ name :
318
+ The name in which a `SimulationFunction` is being evaluated.
319
+ data :
320
+ Data attributes which may be required by the function.
321
+ scope :
322
+ The geo scope.
323
+ time_frame :
324
+ The simulation time frame.
325
+ ipm :
326
+ The IPM.
327
+ rng :
328
+ A random number generator to use.
329
+
330
+ Returns
331
+ -------
332
+ :
333
+ The new context.
334
+ """
335
+ arg = self._args
336
+ return Context.of(
337
+ name=name or arg["name"],
338
+ data=data or arg["data"],
339
+ scope=scope or arg["scope"],
340
+ time_frame=time_frame or arg["time_frame"],
341
+ ipm=ipm or arg["ipm"],
342
+ rng=rng or arg["rng"],
343
+ )
344
+
345
+ @final
346
+ def hash(self, requirements: Sequence[AttributeDef]) -> int:
347
+ """
348
+ Compute a hash for the context, assuming the given set of requirements.
349
+ This is used to quickly identify if the context has changed between evaluations.
350
+
351
+ Parameters
352
+ ----------
353
+ requirements :
354
+ The subset of requirements that are important to include when computing the
355
+ hash. This allows the hash to ignore changes to attributes which aren't
356
+ critical to a particular use-case.
357
+
358
+ Returns
359
+ -------
360
+ :
361
+ The hash value.
362
+ """
363
+ name = self.name
364
+
365
+ if (data := self._args.get("data")) is not None:
366
+ req_hashes = (
367
+ data.resolve(name.with_id(req.name), req).tobytes()
368
+ for req in requirements
369
+ )
370
+ else:
371
+ req_hashes = (None,)
372
+
373
+ if (ipm := self._args.get("ipm")) is not None:
374
+ C = ipm.num_compartments
375
+ E = ipm.num_events
376
+ ipm_hash = (ipm.__class__.__name__, C, E)
377
+ else:
378
+ ipm_hash = None
379
+
380
+ scope = self._args.get("scope")
381
+ time_frame = self._args.get("time_frame")
382
+
383
+ # Note that `None` is a hashable value.
384
+ hash_values = tuple([str(name), scope, time_frame, ipm_hash, *req_hashes])
385
+ return hash(hash_values)
386
+
387
+ @staticmethod
388
+ def of(
389
+ name: AbsoluteName = NAME_PLACEHOLDER,
390
+ data: DataResolver | None = None,
391
+ scope: GeoScope | None = None,
392
+ time_frame: TimeFrame | None = None,
393
+ ipm: BaseCompartmentModel | None = None,
394
+ rng: np.random.Generator | None = None,
395
+ ) -> "Context":
396
+ """
397
+ Create a new context instance, which may be a partial or complete context.
398
+
399
+ Parameters
400
+ ----------
401
+ name :
402
+ The name in which a `SimulationFunction` is being evaluated.
403
+ data :
404
+ Data attributes which may be required by the function.
405
+ scope :
406
+ The geo scope.
407
+ time_frame :
408
+ The simulation time frame.
409
+ ipm :
410
+ The IPM.
411
+ rng :
412
+ A random number generator to use.
413
+
414
+ Returns
415
+ -------
416
+ :
417
+ The new context.
418
+ """
419
+
420
+ # NOTE: this function dynamically creates a concrete version of Context
421
+ # which is an abstract class. This allows us to handle partial context in an
422
+ # efficient manner. Rather than doing an if-check on every attribute access,
423
+ # we can just construct properties and methods which already know if they have
424
+ # a value or must raise a MissingContextError if accessed.
425
+
426
+ def make_missing_context(component: str):
427
+ def missing_context(self, *args, **kwargs) -> Never:
428
+ err = (
429
+ f"Missing function context '{component}' during evaluation.\n"
430
+ f"The simulation function tried to access '{component}' but this "
431
+ "has not been provided. Call `with_context()` first, providing all "
432
+ "context that is required by this function. Then call `evaluate()` "
433
+ "on the returned object to compute the value."
434
+ )
435
+ raise MissingContextError(err)
436
+
437
+ return property(missing_context)
438
+
439
+ def make_getter(component, value):
440
+ if value is None:
441
+ return make_missing_context(component)
442
+ return property(lambda self: value)
443
+
444
+ def make_data_getter():
445
+ if data is None:
446
+ return make_missing_context("data")
447
+
448
+ def data_getter(self, attribute: AttributeDef) -> AttributeArray:
449
+ n = name.to_namespace().to_absolute(attribute.name)
450
+ return data.resolve(n, attribute) # type: ignore
451
+
452
+ return data_getter
453
+
454
+ dim = Dimensions.of(
455
+ T=time_frame.duration_days if time_frame is not None else None,
456
+ N=scope.nodes if scope is not None else None,
457
+ C=ipm.num_compartments if ipm is not None else None,
458
+ E=ipm.num_events if ipm is not None else None,
459
+ )
460
+
461
+ args = {
462
+ "name": name,
463
+ "data": data,
464
+ "scope": scope,
465
+ "time_frame": time_frame,
466
+ "ipm": ipm,
467
+ "rng": rng,
468
+ }
469
+
470
+ instance = type(
471
+ "ContextInstance",
472
+ (Context,),
473
+ {
474
+ "_args": args,
475
+ "name": make_getter("name", name),
476
+ "scope": make_getter("scope", scope),
477
+ "time_frame": make_getter("time_frame", time_frame),
478
+ "ipm": make_getter("ipm", ipm),
479
+ "rng": make_getter("rng", rng),
480
+ "dim": make_getter("dim", dim),
481
+ "data": make_data_getter(),
482
+ },
483
+ )
484
+ return instance()
485
+
486
+
487
+ def validate_context_for_shape(context: Context, shape: DataShape) -> None:
488
+ """
489
+ Check that the elements of a context which are required to compute the given
490
+ shape have been provided in the context. For example, if the shape contains an "N"
491
+ axis, the context must include a scope or else there's no knowing how long that axis
492
+ should be.
493
+
494
+ Parameters
495
+ ----------
496
+ context :
497
+ The simulation context.
498
+ shape :
499
+ The shape to check.
500
+
501
+ Raises
502
+ ------
503
+ MissingContextError
504
+ If any required context has not been provided.
505
+ """
506
+
507
+ # NOTE: this check ensures this function remains in sync with all defined shapes.
508
+ # We could easily add another axis designation to DataShape but forget to update
509
+ # this function.
510
+ shape_str = str(shape)
511
+ if re.search("[^TNCEAx]", shape_str) is not None:
512
+ err = (
513
+ f"Unsupported character in shape designation: {shape_str}"
514
+ "This indicates that the `validate_context_for_shape` function was not "
515
+ "correctly updated when new shape designations were added."
516
+ )
517
+ raise RuntimeError(err)
518
+
519
+ # Check for required context.
520
+ if "N" in shape_str:
521
+ context.scope # scope is required
522
+ if "T" in shape_str:
523
+ context.time_frame # time_frame is required
524
+ if "C" in shape_str or "E" in shape_str:
525
+ context.ipm # ipm is required
526
+
527
+
528
+ _EMPTY_CONTEXT = Context.of(NAME_PLACEHOLDER)
529
+
530
+ _TypeT = TypeVar("_TypeT")
531
+
532
+
533
+ class SimulationFunctionClass(ABCMeta):
534
+ """`SimulationFunction` metaclass; enforces proper implementation."""
535
+
536
+ def __new__(
537
+ cls: Type[_TypeT],
538
+ name: str,
539
+ bases: tuple[type, ...],
540
+ dct: dict[str, Any],
541
+ ) -> _TypeT:
542
+ # Check requirements if this class overrides it.
543
+ # (Otherwise class will inherit from parent.)
544
+ if (reqs := dct.get("requirements")) is not None:
545
+ # The user may specify requirements as a property, in which case we
546
+ # can't validate much about the implementation.
547
+ if not isinstance(reqs, property):
548
+ # But if it's a static value, check types:
549
+ if not isinstance(reqs, (list, tuple)):
550
+ raise TypeError(
551
+ f"Invalid requirements in {name}: "
552
+ "please specify as a list or tuple."
553
+ )
554
+ if not are_instances(reqs, AttributeDef):
555
+ raise TypeError(
556
+ f"Invalid requirements in {name}: "
557
+ "must be instances of AttributeDef."
558
+ )
559
+ if not are_unique(r.name for r in reqs):
560
+ raise TypeError(
561
+ f"Invalid requirements in {name}: "
562
+ "requirement names must be unique."
563
+ )
564
+ # Make requirements list immutable
565
+ dct["requirements"] = tuple(reqs)
566
+
567
+ # Check serializable
568
+ if not is_picklable(name, cls):
569
+ raise TypeError(
570
+ f"Invalid simulation function {name}: "
571
+ "classes must be serializable (using jsonpickle)."
572
+ )
573
+
574
+ # NOTE: is_picklable() is misleading here; it does not guarantee that instances
575
+ # of a class are picklable, nor (if you called it against an instance) that all
576
+ # of the instance's attributes are picklable. jsonpickle simply ignores
577
+ # unpicklable fields, decoding objects into attribute swiss cheese.
578
+ # It will be more effective to check that all of the attributes of an object
579
+ # are picklable before we try to serialize it...
580
+ # Thus I don't think we can guarantee picklability at class definition time.
581
+ # Something like:
582
+ # [(n, is_picklable(n, x)) for n, x in obj.__dict__.items()] # noqa: ERA001
583
+ # Why worry? Lambda functions are probably the most likely problem;
584
+ # they're not picklable by default.
585
+ # But a simple workaround is to use a def function and,
586
+ # if needed, partial function application.
587
+
588
+ if (orig_evaluate := dct.get("evaluate")) is not None:
589
+
590
+ @functools.wraps(orig_evaluate)
591
+ def evaluate(self, *args, **kwargs):
592
+ result = orig_evaluate(self, *args, **kwargs)
593
+ self.validate(result)
594
+ return result
595
+
596
+ dct["evaluate"] = evaluate
597
+
598
+ return super().__new__(cls, name, bases, dct)
599
+
600
+
601
+ ResultT = TypeVar("ResultT")
602
+ """The result type of a `SimulationFunction`."""
603
+
604
+ DeferResultT = TypeVar("DeferResultT")
605
+ """The result type of a `SimulationFunction` during deference."""
606
+ DeferFunctionT = TypeVar("DeferFunctionT", bound="BaseSimulationFunction")
607
+ """The type of a `SimulationFunction` during deference."""
608
+
609
+
610
+ class BaseSimulationFunction(ABC, Generic[ResultT], metaclass=SimulationFunctionClass):
611
+ """
612
+ A function which runs in the context of a simulation to produce a value
613
+ (as a numpy array).
614
+
615
+ Instances may access the context in which they are being evaluated using
616
+ attributes and methods present on "self":
617
+ `name`, `data`, `scope`, `time_frame`, `ipm`, `rng`, and `dim`, and may use
618
+ methods like `defer` to pass their context on to another function for
619
+ direct evaluation.
620
+
621
+ This class is generic on the type of result it produces (`ResultT`).
622
+
623
+
624
+ See Also
625
+ --------
626
+ Refer to
627
+ [epymorph.simulation.SimulationFunction][] and
628
+ [epymorph.simulation.SimulationTickFunction][] for more concrete subclasses.
629
+ """
630
+
631
+ # NOTE: this base class exists so that we don't limit the signature of `evaluate`.
632
+ # `SimulationTickFunction` evaluates using the current tick, while
633
+ # `SimulationFunction` does not require any parameters.
634
+
635
+ requirements: Sequence[AttributeDef] | property = ()
636
+ """
637
+ The attribute definitions describing the data requirements for this function.
638
+
639
+ For advanced use-cases, you may specify requirements as a property if you need it
640
+ to be dynamically computed.
641
+ """
642
+
643
+ randomized: bool = False
644
+ """Should this function be re-evaluated every time it's referenced in a RUME?
645
+ (Mostly useful for randomized results.) If False, even a function that utilizes
646
+ the context RNG will only be computed once, resulting in a single random value
647
+ that is shared by all references during evaluation."""
648
+
649
+ _ctx: Context = _EMPTY_CONTEXT
650
+
651
+ @property
652
+ def class_name(self) -> str:
653
+ """The class name of the `SimulationFunction`."""
654
+ return f"{self.__class__.__module__}.{self.__class__.__qualname__}"
655
+
656
+ def validate(self, result: ResultT) -> None:
657
+ """
658
+ Override this method to validate the function evaluation result.
659
+ If not overridden, the default is to do no validation.
660
+ Implementations should raise an appropriate error if results
661
+ are not valid.
662
+
663
+ Parameters
664
+ ----------
665
+ result :
666
+ The result produced from function evaluation.
667
+ """
668
+
669
+ @final
670
+ def with_context(
671
+ self,
672
+ name: AbsoluteName = NAME_PLACEHOLDER,
673
+ params: Mapping[str, ParamValue] | None = None,
674
+ scope: GeoScope | None = None,
675
+ time_frame: TimeFrame | None = None,
676
+ ipm: BaseCompartmentModel | None = None,
677
+ rng: np.random.Generator | None = None,
678
+ ) -> Self:
679
+ """
680
+ Construct a clone of this instance which has access to the given context.
681
+
682
+ All elements of the context are optional, allowing users who wish to
683
+ quickly evaluate a function in a one-off situation to provide only the
684
+ partial context that is strictly necessary. (It's very tedious to create
685
+ fake context when it isn't strictly needed.) For example, a function
686
+ might be able to calculate a result knowing only the geo scope and time frame.
687
+ During normal function evaluation, such as when running a simulation,
688
+ the full context is always provided and available.
689
+
690
+ Parameters
691
+ ----------
692
+ name :
693
+ The name used for the value this function produces, according
694
+ to the evaluation context. Defaults to a generic placeholder
695
+ name.
696
+ params :
697
+ Additional parameter values we may need to evaluate this function.
698
+ scope :
699
+ The geo scope.
700
+ time_frame :
701
+ The time frame.
702
+ ipm :
703
+ The IPM.
704
+ rng :
705
+ A random number generator instance.
706
+
707
+ Returns
708
+ -------
709
+ :
710
+ A clone with new context information.
711
+
712
+ Raises
713
+ ------
714
+ MissingContextError
715
+ If the function tries to use a part of the context that hasn't been
716
+ provided.
717
+ """
718
+ # This version allows users to specify data using strings for names.
719
+ # epymorph should use `with_context_internal()` whenever possible.
720
+
721
+ if params is None:
722
+ params = {}
723
+ try:
724
+ for p in params:
725
+ AttributeName(p)
726
+ except ValueError:
727
+ err = (
728
+ "When evaluating a sim function this way, namespaced params "
729
+ "are not allowed (names using '::') because those values would "
730
+ "not be able to contribute to the evaluation. "
731
+ "Specify param names as simple strings instead."
732
+ )
733
+ raise ValueError(err)
734
+ reqs = ReqTree.of(
735
+ {name.with_id(req.name): req for req in self.requirements},
736
+ Database({NamePattern.parse(k): v for k, v in params.items()}),
737
+ )
738
+ data = reqs.evaluate(scope, time_frame, ipm, rng)
739
+ ctx = Context.of(name, data, scope, time_frame, ipm, rng)
740
+ return self.with_context_internal(ctx)
741
+
742
+ def with_context_internal(self, context: Context) -> Self:
743
+ """
744
+ Construct a clone of this instance which has access to the given context.
745
+
746
+ This method is intended for usage internal to epymorph's systems.
747
+ Typical usage will use `with_context` instead.
748
+ """
749
+ # clone this instance, then run evaluate on that; accomplishes two things:
750
+ # 1. don't have to worry about cleaning up _ctx
751
+ # 2. instances can use @cached_property without surprising results
752
+ clone = deepcopy(self)
753
+ setattr(clone, "_ctx", context)
754
+ return clone
755
+
756
+ @final
757
+ def defer_context(
758
+ self,
759
+ other: DeferFunctionT,
760
+ scope: GeoScope | None = None,
761
+ time_frame: TimeFrame | None = None,
762
+ ) -> DeferFunctionT:
763
+ """
764
+ Defer processing to another instance of a `SimulationFunction`.
765
+
766
+ This method is intended for usage internal to epymorph's system.
767
+ Typical usage will use `defer` instead.
768
+ """
769
+ new_ctx = self._ctx.replace(
770
+ scope=scope,
771
+ time_frame=time_frame,
772
+ )
773
+ return other.with_context_internal(new_ctx)
774
+
775
+ @final
776
+ @property
777
+ def name(self) -> AbsoluteName:
778
+ """The name under which this attribute is being evaluated."""
779
+ return self._ctx.name
780
+
781
+ @final
782
+ def data(self, attribute: AttributeDef | str) -> NDArray:
783
+ """
784
+ Retrieve the value of a requirement. You must declare the attribute in this
785
+ function's `requirements` list.
786
+
787
+ Parameters
788
+ ----------
789
+ attribute :
790
+ The attribute to get, identified either by its name (string) or its
791
+ definition object.
792
+
793
+ Returns
794
+ -------
795
+ :
796
+ The attribute value.
797
+
798
+ Raises
799
+ ------
800
+ ValueError
801
+ If the attribute is not in the function's requirements declaration.
802
+ """
803
+ if isinstance(attribute, str):
804
+ name = attribute
805
+ req = next((r for r in self.requirements if r.name == attribute), None)
806
+ else:
807
+ name = attribute.name
808
+ req = attribute
809
+ if req is None or req not in self.requirements:
810
+ raise ValueError(
811
+ f"Simulation function {self.__class__.__name__} "
812
+ f"accessed an attribute ({name}) "
813
+ "which you did not declare as a requirement."
814
+ )
815
+ return self._ctx.data(req)
816
+
817
+ @final
818
+ @property
819
+ def context(self) -> Context:
820
+ """The full context object."""
821
+ return self._ctx
822
+
823
+ @final
824
+ @property
825
+ def scope(self) -> GeoScope:
826
+ """The simulation geo scope."""
827
+ return self._ctx.scope
828
+
829
+ @final
830
+ @property
831
+ def time_frame(self) -> TimeFrame:
832
+ """The simulation time frame."""
833
+ return self._ctx.time_frame
834
+
835
+ @final
836
+ @property
837
+ def ipm(self) -> BaseCompartmentModel:
838
+ """The simulation IPM."""
839
+ return self._ctx.ipm
840
+
841
+ @final
842
+ @property
843
+ def rng(self) -> np.random.Generator:
844
+ """The simulation's random number generator."""
845
+ return self._ctx.rng
846
+
847
+ @final
848
+ @property
849
+ def dim(self) -> Dimensions:
850
+ """
851
+ The simulation's dimensional information.
852
+ This is a re-packaging of information contained
853
+ in other context elements, like the geo scope.
854
+ """
855
+ return self._ctx.dim
856
+
857
+
858
+ @is_recursive_value.register
859
+ def _(value: BaseSimulationFunction) -> TypeGuard[RecursiveValue]:
860
+ return True
861
+
862
+
863
+ class SimulationFunction(BaseSimulationFunction[ResultT]):
864
+ """
865
+ A function which runs in the context of a RUME to produce a value
866
+ (as a numpy array). The value must be independent of the simulation state,
867
+ and they will often be evaluated before the simulation starts.
868
+
869
+ `SimulationFunction` is an abstract class. In typical usage you will not
870
+ implement a `SimulationFunction` directly, but rather one of its
871
+ more-specific child classes.
872
+
873
+ `SimulationFunction` is generic in the type of result it produces (`ResultT`).
874
+
875
+ See Also
876
+ --------
877
+ Notable child classes of SimulationFunction include
878
+ [epymorph.initializer.Initializer][],
879
+ [epymorph.adrio.adrio.ADRIO][], and
880
+ [epymorph.params.ParamFunction][].
881
+ """
882
+
883
+ @abstractmethod
884
+ def evaluate(self) -> ResultT:
885
+ """
886
+ Implement this method to provide logic for the function.
887
+ Use self methods and properties to access the simulation context or defer
888
+ processing to another function.
889
+
890
+ Returns
891
+ -------
892
+ :
893
+ The result value.
894
+ """
895
+
896
+ @final
897
+ def defer(
898
+ self,
899
+ other: "SimulationFunction[DeferResultT]",
900
+ scope: GeoScope | None = None,
901
+ time_frame: TimeFrame | None = None,
902
+ ) -> DeferResultT:
903
+ """
904
+ Defer processing to another instance of a `SimulationFunction`, returning
905
+ the result of evaluation.
906
+
907
+ This function is generic in the type of result returned by the function
908
+ to which we are deferring (`DeferResultT`).
909
+
910
+ Parameters
911
+ ----------
912
+ other :
913
+ The other function to defer to.
914
+ scope :
915
+ Override the geo scope for evaluation; if None, use the same scope.
916
+ time_frame :
917
+ Override the time frame for evaluation; if None, use the same time frame.
918
+
919
+ Returns
920
+ -------
921
+ :
922
+ The result value.
923
+ """
924
+ return self.defer_context(other, scope, time_frame).evaluate()
925
+
926
+
927
+ class SimulationTickFunction(BaseSimulationFunction[ResultT]):
928
+ """
929
+ A function which runs in the context of a RUME to produce a value
930
+ (as a numpy array) which is expected to vary over the run of a simulation.
931
+
932
+ In typical usage you will not implement a `SimulationTickFunction` directly,
933
+ but rather one of its more-specific child classes.
934
+
935
+ `SimulationTickFunction` is generic in the type of result it produces (`ResultT`).
936
+
937
+ See Also
938
+ --------
939
+ The only notable child class is [epymorph.movement_model.MovementClause][].
940
+ """
941
+
942
+ @abstractmethod
943
+ def evaluate(self, tick: Tick) -> ResultT:
944
+ """
945
+ Implement this method to provide logic for the function.
946
+ Use self methods and properties to access the simulation context or defer
947
+ processing to another function.
948
+
949
+ Parameters
950
+ ----------
951
+ tick :
952
+ The simulation tick being evaluated.
953
+
954
+ Returns
955
+ -------
956
+ :
957
+ The result value.
958
+ """
959
+
960
+ @final
961
+ def defer(
962
+ self,
963
+ other: "SimulationTickFunction[DeferResultT]",
964
+ tick: Tick,
965
+ scope: GeoScope | None = None,
966
+ time_frame: TimeFrame | None = None,
967
+ ) -> DeferResultT:
968
+ """
969
+ Defer processing to another instance of a `SimulationTickFunction`, returning
970
+ the result of evaluation.
971
+
972
+ This function is generic in the type of result returned by the function
973
+ to which we are deferring (`DeferResultT`).
974
+
975
+ Parameters
976
+ ----------
977
+ other :
978
+ The other function to defer to.
979
+ tick :
980
+ The simulation tick being evaluated.
981
+ scope :
982
+ Override the geo scope for evaluation; if None, use the same scope.
983
+ time_frame :
984
+ Override the time frame for evaluation; if None, use the same time frame.
985
+
986
+ Returns
987
+ -------
988
+ :
989
+ The result value.
990
+ """
991
+ return self.defer_context(other, scope, time_frame).evaluate(tick)