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/kit.py ADDED
@@ -0,0 +1,107 @@
1
+ """
2
+ A convenient star-import for the most-commonly-used features in epymorph.
3
+
4
+ Most of the included symbols are classes or functions which you can find by searching
5
+ their names. The three exceptions are `init`, `ipm`, and `mm` which are whole Python
6
+ modules or packages representing our built-in component libraries.
7
+
8
+ - `init` is the `epymorph.initializer` module
9
+ - `ipm` is the `epymorph.data.ipm` package
10
+ - `mm` is the `epymorph.data.mm` package
11
+
12
+ Included this way, for instance, you can instantiate the built-in SIRS IPM like:
13
+
14
+ ```
15
+ my_ipm = ipm.SIRS()
16
+ ```
17
+ """
18
+
19
+ import epymorph.data.ipm as ipm
20
+ import epymorph.data.mm as mm
21
+ import epymorph.initializer as init
22
+ from epymorph.attribute import AttributeDef
23
+ from epymorph.compartment_model import (
24
+ BIRTH,
25
+ DEATH,
26
+ CompartmentModel,
27
+ ModelSymbols,
28
+ MultiStrataModelSymbols,
29
+ TransitionDef,
30
+ compartment,
31
+ edge,
32
+ fork,
33
+ )
34
+ from epymorph.data_shape import Shapes
35
+ from epymorph.data_type import CentroidDType, CentroidType, SimDType
36
+ from epymorph.geography.custom import CustomScope
37
+ from epymorph.geography.us_census import (
38
+ BlockGroupScope,
39
+ CountyScope,
40
+ StateScope,
41
+ TractScope,
42
+ )
43
+ from epymorph.log.messaging import sim_messaging
44
+ from epymorph.params import (
45
+ ParamFunction,
46
+ ParamFunctionNode,
47
+ ParamFunctionNodeAndCompartment,
48
+ ParamFunctionNodeAndNode,
49
+ ParamFunctionNumpy,
50
+ ParamFunctionScalar,
51
+ ParamFunctionTime,
52
+ ParamFunctionTimeAndNode,
53
+ )
54
+ from epymorph.rume import GPM, MultiStrataRUME, MultiStrataRUMEBuilder, SingleStrataRUME
55
+ from epymorph.simulation import default_rng
56
+ from epymorph.simulator.basic.basic_simulator import BasicSimulator
57
+ from epymorph.time import TimeFrame
58
+
59
+ __all__ = [
60
+ # Built-in Components
61
+ "init",
62
+ "ipm",
63
+ "mm",
64
+ # Compartment Models
65
+ "CompartmentModel",
66
+ "ModelSymbols",
67
+ "TransitionDef",
68
+ "compartment",
69
+ "edge",
70
+ "fork",
71
+ "BIRTH",
72
+ "DEATH",
73
+ # Single Strata RUME
74
+ "SingleStrataRUME",
75
+ # Multi-strata RUME
76
+ "MultiStrataRUME",
77
+ "MultiStrataRUMEBuilder",
78
+ "GPM",
79
+ "MultiStrataModelSymbols",
80
+ # Simulator
81
+ "BasicSimulator",
82
+ "sim_messaging",
83
+ "default_rng",
84
+ # Scopes
85
+ "CustomScope",
86
+ "StateScope",
87
+ "CountyScope",
88
+ "TractScope",
89
+ "BlockGroupScope",
90
+ # ParamFunctions
91
+ "ParamFunction",
92
+ "ParamFunctionNumpy",
93
+ "ParamFunctionScalar",
94
+ "ParamFunctionTime",
95
+ "ParamFunctionNode",
96
+ "ParamFunctionNodeAndNode",
97
+ "ParamFunctionNodeAndCompartment",
98
+ "ParamFunctionTimeAndNode",
99
+ # Utilities and Data Types
100
+ "TimeFrame",
101
+ "AttributeDef",
102
+ "Shapes",
103
+ "SimDType",
104
+ "CentroidType",
105
+ "CentroidDType",
106
+ ]
107
+ """When you do `from epymorph.kit import *` you get all of these symbols."""
File without changes
epymorph/log/file.py ADDED
@@ -0,0 +1,128 @@
1
+ """Logging epymorph simulations to a file."""
2
+
3
+ from contextlib import contextmanager
4
+ from logging import BASIC_FORMAT, DEBUG, NOTSET, FileHandler, Formatter, getLogger
5
+ from time import perf_counter
6
+ from typing import Generator
7
+
8
+ from epymorph.event import (
9
+ ADRIOProgress,
10
+ EventBus,
11
+ OnMovementClause,
12
+ OnMovementFinish,
13
+ OnMovementStart,
14
+ OnStart,
15
+ OnTick,
16
+ )
17
+ from epymorph.util import subscriptions
18
+
19
+ _events = EventBus()
20
+
21
+
22
+ @contextmanager
23
+ def file_log(
24
+ log_file: str = "debug.log",
25
+ log_level: str | int = DEBUG,
26
+ ) -> Generator[None, None, None]:
27
+ """
28
+ Run simulations in this context manager to write detailed simulation activity
29
+ to a log file.
30
+
31
+ Parameters
32
+ ----------
33
+ log_file :
34
+ The path to the log file to write. Can be relative to the current working
35
+ directory.
36
+ log_level :
37
+ The log level to use; accepts any argument valid for
38
+ [logging.Handler.setLevel][].
39
+
40
+ Examples
41
+ --------
42
+ ```python
43
+ with file_log("my_log_file.log"):
44
+ sim = BasicSimulator(rume)
45
+ my_results = sim.run()
46
+ ```
47
+ """
48
+
49
+ # Initialize the logging system and create some Loggers for epymorph subsystems.
50
+ log_handler = FileHandler(log_file, "w", "utf8")
51
+ log_handler.setFormatter(Formatter(BASIC_FORMAT))
52
+
53
+ epy_log = getLogger("epymorph")
54
+ epy_log.addHandler(log_handler)
55
+ epy_log.setLevel(log_level)
56
+
57
+ sim_log = epy_log.getChild("sim")
58
+ adrio_log = epy_log.getChild("adrio")
59
+ mm_log = epy_log.getChild("movement")
60
+
61
+ # Define handlers for each of the events we're interested in.
62
+
63
+ start_time: float | None = None
64
+
65
+ def on_start(e: OnStart) -> None:
66
+ start_date = e.rume.time_frame.start_date
67
+ end_date = e.rume.time_frame.end_date
68
+ duration_days = e.rume.time_frame.days
69
+
70
+ sim_log.info(f"Running simulation ({e.simulator}):")
71
+ sim_log.info(f"- {start_date} to {end_date} ({duration_days} days)")
72
+ sim_log.info(f"- {e.rume.scope.nodes} geo nodes")
73
+
74
+ nonlocal start_time
75
+ start_time = perf_counter()
76
+
77
+ def on_tick(tick: OnTick) -> None:
78
+ sim_log.info("Completed simulation tick %d", tick.tick_index)
79
+
80
+ def on_finish(_: None) -> None:
81
+ sim_log.info("Complete.")
82
+ end_time = perf_counter()
83
+ if start_time is not None:
84
+ sim_log.info(f"Runtime: {(end_time - start_time):.3f}s")
85
+
86
+ def on_adrio_progress(e: ADRIOProgress) -> None:
87
+ if e.final:
88
+ adrio_log.info(f"Loaded ADRIO {e.adrio_name} in ({e.duration:.3f} seconds)")
89
+
90
+ def on_movement_start(e: OnMovementStart) -> None:
91
+ mm_log.info("Processing movement for day %d, step %d.", e.day, e.step)
92
+
93
+ def on_movement_clause(e: OnMovementClause) -> None:
94
+ cl_log = mm_log.getChild(e.clause_name)
95
+ if e.total > 0:
96
+ cl_log.debug("requested:\n%s", e.requested)
97
+ if e.is_throttled:
98
+ cl_log.debug(
99
+ "WARNING: movement is throttled due to insufficient population"
100
+ )
101
+ cl_log.debug("moved:\n%s", e.actual.sum(axis=2))
102
+ cl_log.info("moved %d individuals", e.total)
103
+
104
+ def on_movement_finish(e: OnMovementFinish) -> None:
105
+ mm_log.info(f"Moved a total of {e.total} individuals.")
106
+
107
+ with subscriptions() as subs:
108
+ # Set up a subscriptions context, subscribe our handlers,
109
+ # then yield to the outer context (where the sim should be run).
110
+ subs.subscribe(_events.on_start, on_start)
111
+ subs.subscribe(_events.on_tick, on_tick)
112
+ subs.subscribe(_events.on_finish, on_finish)
113
+
114
+ subs.subscribe(_events.on_adrio_progress, on_adrio_progress)
115
+
116
+ subs.subscribe(_events.on_movement_start, on_movement_start)
117
+ subs.subscribe(_events.on_movement_clause, on_movement_clause)
118
+ subs.subscribe(_events.on_movement_finish, on_movement_finish)
119
+
120
+ yield # to outer context
121
+ # And now our event handlers will be unsubscribed.
122
+
123
+ # Close out the log file.
124
+ # This isn't necessary if we're running on the CLI, but if we're in a
125
+ # Jupyter context, running the sim multiple times would keep appending to the file.
126
+ # For most use-cases, just having one sim run in the log file is preferable.
127
+ epy_log.removeHandler(log_handler)
128
+ epy_log.setLevel(NOTSET)
@@ -0,0 +1,139 @@
1
+ """Displaying epymorph simulation progress in console (or similar outputs)."""
2
+ # ruff: noqa: T201
3
+
4
+ from contextlib import contextmanager
5
+ from functools import partial
6
+ from math import ceil
7
+ from time import perf_counter
8
+ from typing import Generator
9
+
10
+ import humanize
11
+ from humanize import naturalsize
12
+
13
+ from epymorph.attribute import NAME_PLACEHOLDER
14
+ from epymorph.event import ADRIOProgress, EventBus, OnStart, OnTick
15
+ from epymorph.util import progress, subscriptions
16
+
17
+ _events = EventBus()
18
+
19
+
20
+ @contextmanager
21
+ def sim_messaging(
22
+ *,
23
+ adrio: bool = True,
24
+ live: bool = True,
25
+ ) -> Generator[None, None, None]:
26
+ """
27
+ Run simulations in this context manager to output (print) progress messages during
28
+ simulation activity.
29
+
30
+ Parameters
31
+ ----------
32
+ adrio :
33
+ True to include ADRIO progress updates.
34
+ live :
35
+ True if this is being used in an interactive environment like
36
+ the console or a Jupyter Notebook. When rendering static documents
37
+ (such as with Quarto), the output may look better by setting this to False.
38
+
39
+ Examples
40
+ --------
41
+ ```python
42
+ with sim_messaging():
43
+ sim = BasicSimulator(rume)
44
+ my_results = sim.run()
45
+ ```
46
+ """
47
+
48
+ start_time: float | None = None
49
+
50
+ def on_start(e: OnStart) -> None:
51
+ start_date = e.rume.time_frame.start_date
52
+ end_date = e.rume.time_frame.end_date
53
+ duration_days = e.rume.time_frame.days
54
+
55
+ print(f"Running simulation ({e.simulator}):")
56
+ print(f"• {start_date} to {end_date} ({duration_days} days)")
57
+ print(f"• {e.rume.scope.nodes} geo nodes")
58
+ if live:
59
+ print(progress(0.0), end="\r")
60
+
61
+ nonlocal start_time
62
+ start_time = perf_counter()
63
+
64
+ # keeping track of the length of the last line we printed
65
+ # lets us clear any trailing characters when rendering stuff
66
+ # after the progress bar of varying width
67
+ last_progress_length = 0
68
+
69
+ def on_tick(e: OnTick) -> None:
70
+ # NOTE: tick updates will be skipped entirely if `live=False`
71
+ nonlocal last_progress_length
72
+ ticks_complete = e.tick_index + 1
73
+ total_process_time = perf_counter() - start_time
74
+ average_process_time = total_process_time / ticks_complete
75
+
76
+ percent_complete = (e.tick_index + 1) / e.ticks
77
+ ticks_left = e.ticks - ticks_complete
78
+
79
+ # multiply the remaining ticks by the average processing time
80
+ estimate = ticks_left * average_process_time
81
+
82
+ time_remaining = humanize.precisedelta(ceil(estimate), minimum_unit="seconds")
83
+ formatted_time = f"({time_remaining} remaining)"
84
+ line = f" {progress(percent_complete)}"
85
+ # if no time remaining, omit the time progress
86
+ if estimate > 0:
87
+ line += f"{formatted_time}"
88
+ print(line.ljust(last_progress_length), end="\r")
89
+ last_progress_length = len(line)
90
+
91
+ def on_finish(_: None) -> None:
92
+ end_time = perf_counter()
93
+ line = f" {progress(1.0)}"
94
+ print(line.ljust(last_progress_length), end="\n")
95
+ if start_time is not None:
96
+ print(f"Runtime: {(end_time - start_time):.3f}s")
97
+
98
+ def on_adrio_progress(e: ADRIOProgress) -> None:
99
+ nonlocal last_progress_length
100
+ if e.ratio_complete == 0:
101
+ if e.attribute == NAME_PLACEHOLDER:
102
+ print(f"Loading {e.adrio_name}:")
103
+ else:
104
+ print(f"Loading {e.attribute} ({e.adrio_name}):")
105
+ if not e.final:
106
+ if e.download is None:
107
+ dl = ""
108
+ else:
109
+ total, downloaded, speed = e.download
110
+ ff = partial(naturalsize, binary=False) # format file size
111
+ dwn = "?" if downloaded is None else ff(downloaded)
112
+ tot = "?" if total is None else ff(total)
113
+ spd = "?" if speed is None else ff(speed)
114
+ dl = f" {dwn}/{tot} ({spd}/s)"
115
+
116
+ if live:
117
+ line = f" {progress(e.ratio_complete)}{dl}"
118
+ print(line.ljust(last_progress_length), end="\r")
119
+ last_progress_length = len(line)
120
+ else:
121
+ if e.duration is None:
122
+ dur = ""
123
+ else:
124
+ dur = f" ({e.duration:0.3f}s)"
125
+ line = f" {progress(e.ratio_complete)}{dur}"
126
+ print(line.ljust(last_progress_length))
127
+ last_progress_length = 0
128
+
129
+ with subscriptions() as subs:
130
+ # Set up a subscriptions context, subscribe our handlers,
131
+ # then yield to the outer context (ostensibly where the sim will be run).
132
+ subs.subscribe(_events.on_start, on_start)
133
+ if live:
134
+ subs.subscribe(_events.on_tick, on_tick)
135
+ subs.subscribe(_events.on_finish, on_finish)
136
+ if adrio:
137
+ subs.subscribe(_events.on_adrio_progress, on_adrio_progress)
138
+ yield # to outer context
139
+ # And now our event handlers will be unsubscribed.
@@ -0,0 +1,228 @@
1
+ """
2
+ Capturing extremely detailed movement data from a simulation, which can be useful for
3
+ debugging movement models.
4
+ """
5
+
6
+ from abc import abstractmethod
7
+ from contextlib import contextmanager
8
+ from typing import Generator, NamedTuple, Protocol
9
+
10
+ import numpy as np
11
+ from numpy.typing import NDArray
12
+ from typing_extensions import override
13
+
14
+ from epymorph.data_type import SimDType
15
+ from epymorph.event import EventBus, OnMovementClause, OnStart
16
+ from epymorph.rume import RUME
17
+ from epymorph.util import subscriptions
18
+
19
+ _events = EventBus()
20
+
21
+
22
+ class MovementData(Protocol):
23
+ """
24
+ Container for collected simulation movement data. Run the simulation inside a
25
+ `movement_data` context and an instance of this class will be returned. After
26
+ the simulation has completed, you can use this object to retrieve movement data
27
+ either by clause or in aggregate across all clauses.
28
+
29
+ A note about axis ordering: both `requested` and `actual` data are NxN in shape,
30
+ where N is the number of geo nodes in the simulation. We use the convention that
31
+ the first axis represents where the movement is "from" and the second axis
32
+ represents where the movement is "to". Movement due to the return clause is treated
33
+ the same way: returning from work to home for example is recorded as (work, home).
34
+ """
35
+
36
+ @abstractmethod
37
+ def requested_by(self, clause: str) -> NDArray[SimDType]:
38
+ """
39
+ Retrieve the time series (steps) of requested movement by clause.
40
+
41
+ Parameters
42
+ ----------
43
+ clause :
44
+ The clause to fetch.
45
+
46
+ Returns
47
+ -------
48
+ :
49
+ The movement data as a (S,N,N)-shaped array.
50
+ """
51
+
52
+ @abstractmethod
53
+ def actual_by(self, clause: str) -> NDArray[SimDType]:
54
+ """
55
+ Retrieve the time series (steps) of actual movement by clause.
56
+
57
+ Parameters
58
+ ----------
59
+ clause :
60
+ The clause to fetch.
61
+
62
+ Returns
63
+ -------
64
+ :
65
+ The movement data as a (S,N,N,C)-shaped array.
66
+ """
67
+
68
+ @abstractmethod
69
+ def requested_all(self) -> NDArray[SimDType]:
70
+ """
71
+ Retrieve the time series (steps) of requested movement for all clauses.
72
+
73
+ Returns
74
+ -------
75
+ :
76
+ The movement data as a (S,N,N)-shaped array.
77
+ """
78
+
79
+ @abstractmethod
80
+ def actual_all(self) -> NDArray[SimDType]:
81
+ """
82
+ Retrieve the time series (steps) of actual movement for all clauses.
83
+
84
+ Returns
85
+ -------
86
+ :
87
+ The movement data as a (S,N,N,C)-shaped array.
88
+ """
89
+
90
+
91
+ class _Entry(NamedTuple):
92
+ """
93
+ A generic container for any sort of movement data associated with a
94
+ particular clause firing on a particular tick.
95
+ """
96
+
97
+ name: str
98
+ """The clause name."""
99
+ tick: int
100
+ """The tick index."""
101
+ data: NDArray[SimDType]
102
+ """The movement data."""
103
+
104
+
105
+ class _MovementDataBuilder(MovementData):
106
+ """The internal implementation of the `MovementData` protocol."""
107
+
108
+ # Implementation note:
109
+ #
110
+ # Context managers make returning values at the end pretty awkward, while returning
111
+ # a value right away is easy. But doing that here means the end user gets access to
112
+ # the data container before it's finished, which could cause confusion if the user
113
+ # tries to access it while the simulation is in progress.
114
+ #
115
+ # To mitigate that, this implementation keeps a `ready` flag and uses that to
116
+ # prevent premature access to the data.
117
+
118
+ _rume: RUME | None = None
119
+ _requested = list[_Entry]()
120
+ _actual = list[_Entry]()
121
+ _ready: bool = False
122
+
123
+ def _set_rume(self, rume: RUME) -> None:
124
+ if self._rume is not None:
125
+ err = (
126
+ "Invalid state: `movement_data` should only be used to capture one "
127
+ "simulation run."
128
+ )
129
+ raise RuntimeError(err)
130
+ self._rume = rume
131
+
132
+ def _record(self, clause_name: str, tick: int, requested, actual) -> None:
133
+ # Don't allow recording after "ready".
134
+ if self._ready:
135
+ err = (
136
+ "Invalid state: `movement_data` should only be used to capture one "
137
+ "simulation run."
138
+ )
139
+ raise RuntimeError(err)
140
+ self._requested.append(_Entry(clause_name, tick, requested))
141
+ self._actual.append(_Entry(clause_name, tick, actual))
142
+
143
+ def _get_dim_if_ready(self) -> tuple[int, int, int]:
144
+ # Returns the lengths of axes (S,N,C)
145
+ if not self._ready or self._rume is None:
146
+ err = (
147
+ "Invalid state: `movement_data` results cannot be accessed until the "
148
+ "simulation is complete."
149
+ )
150
+ raise RuntimeError(err)
151
+ rume = self._rume
152
+ return (rume.num_ticks, rume.scope.nodes, rume.ipm.num_compartments)
153
+
154
+ @override
155
+ def requested_by(self, clause: str) -> NDArray[SimDType]:
156
+ S, N, _ = self._get_dim_if_ready()
157
+ result = np.zeros((S, N, N), dtype=SimDType)
158
+ for name, tick, data in self._requested:
159
+ if name == clause:
160
+ result[tick, :, :] = data
161
+ return result
162
+
163
+ @override
164
+ def actual_by(self, clause: str) -> NDArray[SimDType]:
165
+ S, N, C = self._get_dim_if_ready()
166
+ result = np.zeros((S, N, N, C), dtype=SimDType)
167
+ for name, tick, data in self._actual:
168
+ if name == clause:
169
+ result[tick, :, :, :] = data
170
+ return result
171
+
172
+ @override
173
+ def requested_all(self) -> NDArray[SimDType]:
174
+ S, N, _ = self._get_dim_if_ready()
175
+ result = np.zeros((S, N, N), dtype=SimDType)
176
+ for _name, tick, data in self._requested:
177
+ result[tick, :, :] += data
178
+ return result
179
+
180
+ @override
181
+ def actual_all(self) -> NDArray[SimDType]:
182
+ S, N, C = self._get_dim_if_ready()
183
+ result = np.zeros((S, N, N, C), dtype=SimDType)
184
+ for _name, tick, data in self._actual:
185
+ result[tick, :, :, :] += data
186
+ return result
187
+
188
+
189
+ @contextmanager
190
+ def movement_data() -> Generator[MovementData, None, None]:
191
+ """
192
+ Run one simulation in this context manager in order to capture
193
+ detailed movement data. This returns a `MovementData` object which
194
+ can be used -- after the context exits -- to retrieve the movement data.
195
+
196
+ Yields
197
+ ------
198
+ :
199
+ The object that will contain the collected movement data.
200
+
201
+ Examples
202
+ --------
203
+ ```python
204
+ with movement_data() as my_data:
205
+ # don't access `my_data` yet, it hasn't recorded anything!
206
+ sim = BasicSimulator(rume)
207
+ my_results = sim.run()
208
+
209
+ # now you can use `my_data`
210
+ total_movement = my_data.actual_all()
211
+ ```
212
+ """
213
+ md = _MovementDataBuilder()
214
+
215
+ def on_start(e: OnStart):
216
+ nonlocal md
217
+ md._set_rume(e.rume)
218
+
219
+ def on_clause(e: OnMovementClause):
220
+ nonlocal md
221
+ md._record(e.clause_name, e.tick, e.requested, e.actual)
222
+
223
+ with subscriptions() as sub:
224
+ sub.subscribe(_events.on_start, on_start)
225
+ sub.subscribe(_events.on_movement_clause, on_clause)
226
+ yield md
227
+ # Once the context completes, the simulation should be done.
228
+ md._ready = True