epymorph 1.0.0b0__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 (102) 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 +602 -0
  5. epymorph/adrio/adrio.py +215 -0
  6. epymorph/adrio/cdc.py +781 -0
  7. epymorph/adrio/commuting_flows.py +237 -0
  8. epymorph/adrio/csv.py +387 -0
  9. epymorph/adrio/humidity.py +84 -0
  10. epymorph/adrio/lodes.py +624 -0
  11. epymorph/adrio/numpy.py +119 -0
  12. epymorph/adrio/prism.py +543 -0
  13. epymorph/adrio/respiratory_cdc.py +489 -0
  14. epymorph/adrio/us_tiger.py +217 -0
  15. epymorph/attribute.py +301 -0
  16. epymorph/cache.py +494 -0
  17. epymorph/cli/__init__.py +0 -0
  18. epymorph/cli/cache.py +77 -0
  19. epymorph/cli/main.py +29 -0
  20. epymorph/compartment_model.py +1335 -0
  21. epymorph/data/__init__.py +1 -0
  22. epymorph/data/ipm/__init__.py +22 -0
  23. epymorph/data/ipm/no.py +14 -0
  24. epymorph/data/ipm/pei.py +40 -0
  25. epymorph/data/ipm/seirs.py +50 -0
  26. epymorph/data/ipm/sirh.py +55 -0
  27. epymorph/data/ipm/sirs.py +48 -0
  28. epymorph/data/ipm/sparsemod.py +96 -0
  29. epymorph/data/mm/__init__.py +22 -0
  30. epymorph/data/mm/centroids.py +76 -0
  31. epymorph/data/mm/flat.py +61 -0
  32. epymorph/data/mm/icecube.py +50 -0
  33. epymorph/data/mm/no.py +29 -0
  34. epymorph/data/mm/pei.py +105 -0
  35. epymorph/data/mm/sparsemod.py +73 -0
  36. epymorph/data/pei.py +424 -0
  37. epymorph/data_shape.py +475 -0
  38. epymorph/data_type.py +129 -0
  39. epymorph/data_usage.py +171 -0
  40. epymorph/database.py +1010 -0
  41. epymorph/error.py +183 -0
  42. epymorph/event.py +188 -0
  43. epymorph/geography/__init__.py +0 -0
  44. epymorph/geography/custom.py +61 -0
  45. epymorph/geography/scope.py +214 -0
  46. epymorph/geography/us_census.py +622 -0
  47. epymorph/geography/us_geography.py +278 -0
  48. epymorph/geography/us_tiger.py +755 -0
  49. epymorph/initializer.py +596 -0
  50. epymorph/kit.py +90 -0
  51. epymorph/log/__init__.py +0 -0
  52. epymorph/log/file.py +108 -0
  53. epymorph/log/messaging.py +129 -0
  54. epymorph/log/movement.py +151 -0
  55. epymorph/movement_model.py +274 -0
  56. epymorph/parameter_fitting/__init__.py +0 -0
  57. epymorph/parameter_fitting/distribution.py +68 -0
  58. epymorph/parameter_fitting/dynamics.py +19 -0
  59. epymorph/parameter_fitting/filter/__init__.py +0 -0
  60. epymorph/parameter_fitting/filter/base_filter.py +50 -0
  61. epymorph/parameter_fitting/filter/particle.py +32 -0
  62. epymorph/parameter_fitting/filter/particle_filter.py +296 -0
  63. epymorph/parameter_fitting/likelihood.py +54 -0
  64. epymorph/parameter_fitting/output.py +73 -0
  65. epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
  66. epymorph/parameter_fitting/perturbation.py +19 -0
  67. epymorph/parameter_fitting/utils/__init__.py +0 -0
  68. epymorph/parameter_fitting/utils/data_loader.py +111 -0
  69. epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
  70. epymorph/parameter_fitting/utils/observations.py +63 -0
  71. epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
  72. epymorph/parameter_fitting/utils/params_perturb.py +43 -0
  73. epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
  74. epymorph/parameter_fitting/utils/resampler.py +249 -0
  75. epymorph/parameter_fitting/utils/utils.py +101 -0
  76. epymorph/params.py +248 -0
  77. epymorph/py.typed +0 -0
  78. epymorph/rume.py +700 -0
  79. epymorph/simulation.py +706 -0
  80. epymorph/simulator/__init__.py +0 -0
  81. epymorph/simulator/basic/__init__.py +0 -0
  82. epymorph/simulator/basic/basic_simulator.py +145 -0
  83. epymorph/simulator/basic/ipm_exec.py +406 -0
  84. epymorph/simulator/basic/mm_exec.py +197 -0
  85. epymorph/simulator/basic/output.py +181 -0
  86. epymorph/simulator/world.py +83 -0
  87. epymorph/simulator/world_list.py +196 -0
  88. epymorph/strata.py +12 -0
  89. epymorph/sympy_shim.py +55 -0
  90. epymorph/time.py +649 -0
  91. epymorph/tools/__init__.py +0 -0
  92. epymorph/tools/data.py +218 -0
  93. epymorph/tools/ipm_diagram.py +165 -0
  94. epymorph/tools/out_map.py +426 -0
  95. epymorph/tools/out_plot.py +412 -0
  96. epymorph/tools/out_table.py +575 -0
  97. epymorph/util.py +825 -0
  98. epymorph-1.0.0b0.dist-info/METADATA +57 -0
  99. epymorph-1.0.0b0.dist-info/RECORD +102 -0
  100. epymorph-1.0.0b0.dist-info/WHEEL +5 -0
  101. epymorph-1.0.0b0.dist-info/entry_points.txt +2 -0
  102. epymorph-1.0.0b0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,412 @@
1
+ """
2
+ Tools for rendering graphs from epymorph simulation output data.
3
+ """
4
+
5
+ from datetime import timedelta
6
+ from itertools import cycle
7
+ from typing import Callable, Literal, OrderedDict
8
+
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ import pandas as pd
12
+ from matplotlib.axes import Axes
13
+ from matplotlib.dates import AutoDateLocator, DateFormatter
14
+ from matplotlib.lines import Line2D
15
+ from matplotlib.ticker import EngFormatter
16
+
17
+ from epymorph.compartment_model import (
18
+ QuantityAggregation,
19
+ QuantitySelection,
20
+ )
21
+ from epymorph.geography.scope import GeoAggregation, GeoSelection
22
+ from epymorph.time import TimeAggregation, TimeSelection
23
+ from epymorph.tools.data import Output, munge
24
+ from epymorph.util import identity
25
+
26
+ OrderingOption = Literal["location", "quantity"]
27
+ TimeFormatOption = Literal["auto", "date", "day"]
28
+
29
+
30
+ class PlotRenderer:
31
+ """Provides methods for rendering an output in plot form.
32
+
33
+ Examples
34
+ --------
35
+ Most commonly, you will use PlotRenderer starting from a simulation output object
36
+ that supports it:
37
+
38
+ ```python
39
+ out = BasicSimulation(rume).run()
40
+ out.plot.line(...)
41
+ ```
42
+ """
43
+
44
+ output: Output
45
+
46
+ def __init__(self, output: Output):
47
+ self.output = output
48
+
49
+ def _sorting(
50
+ self,
51
+ quantities_disambiguated: OrderedDict[str, str],
52
+ ordering: OrderingOption,
53
+ ) -> Callable:
54
+ # Return a sort key function that implements the requested ordering option.
55
+ quantity_order = {s: i for i, s in enumerate(quantities_disambiguated.keys())}
56
+
57
+ if ordering == "quantity":
58
+
59
+ def qty_sort(group):
60
+ (location, quantity), _ = group
61
+ return (quantity_order[quantity], location)
62
+
63
+ return qty_sort
64
+
65
+ else:
66
+
67
+ def loc_sort(group):
68
+ (location, quantity), _ = group
69
+ return (location, quantity_order[quantity])
70
+
71
+ return loc_sort
72
+
73
+ def _time_format(
74
+ self,
75
+ time: TimeSelection | TimeAggregation, # what format did we produce?
76
+ requested_time_format: TimeFormatOption, # what format do we want?
77
+ ) -> tuple[
78
+ Literal["tick", "date", "day", "other"], # what format can we actually do?
79
+ Callable[[pd.Series], pd.Series], # converts time axis into format
80
+ ]:
81
+ """Figures out time-axis formatting for plots. This is basically a
82
+ best-effort negotiation depending on the time format we have after
83
+ applying time selection/aggregation (if any) and the time format
84
+ requested."""
85
+
86
+ tau_step_lengths = self.output.rume.tau_step_lengths
87
+ num_tau_steps = self.output.rume.num_tau_steps
88
+ start_date = self.output.rume.time_frame.start_date
89
+ S = self.output.rume.num_ticks
90
+ T = self.output.rume.time_frame.days
91
+ match (time.group_format, requested_time_format):
92
+ case ("tick", "auto" | "day"):
93
+ # Convert ticks to simulation-day scale:
94
+ # e.g.: [0.333, 1.0, 1.333, ...]
95
+ # NOTE: each tick is represented as the end of its timespan
96
+ def ticks_to_days(time_groups: pd.Series) -> pd.Series:
97
+ deltas = np.array(tau_step_lengths).cumsum()
98
+ days = (
99
+ np.arange(T).repeat(num_tau_steps) #
100
+ + np.tile(deltas, T)
101
+ )
102
+ ticks = np.arange(S)
103
+ time_map = dict(zip(ticks, days))
104
+ return time_groups.apply(lambda x: time_map[x])
105
+
106
+ return "day", ticks_to_days
107
+
108
+ case ("tick", "date"):
109
+ # Convert ticks to date scale:
110
+ # e.g.: [2020-01-01T08:00, 2020-01-02T00:00, 2020-01-02T08:00, ...]
111
+ # NOTE: each tick is represented as the end of its timespan
112
+ def ticks_to_dates(time_groups: pd.Series) -> pd.Series:
113
+ deltas = np.array(
114
+ [timedelta(days=x) for x in tau_step_lengths],
115
+ dtype=np.timedelta64,
116
+ ).cumsum()
117
+ dates = (
118
+ pd.date_range(start=start_date, periods=T).repeat(
119
+ num_tau_steps
120
+ ) #
121
+ + np.tile(deltas, T) #
122
+ )
123
+ ticks = np.arange(S)
124
+ time_map = dict(zip(ticks, dates))
125
+ return time_groups.apply(lambda x: time_map[x])
126
+
127
+ return "date", ticks_to_dates
128
+
129
+ case ("date", "day"):
130
+ # Convert dates to simulation-day scale:
131
+ # e.g.: [0, 1, 2, 3, 4, ...]
132
+ # Note: this can produce "negative" days;
133
+ # e.g., if you group by week but the first day of the week is Monday
134
+ # and you start the sim on a Tuesday.
135
+ def dates_to_days(time_groups: pd.Series) -> pd.Series:
136
+ start = pd.Timestamp(start_date)
137
+ return time_groups.apply(lambda x: (x - start).days)
138
+
139
+ return "day", dates_to_days
140
+
141
+ case (actual, _):
142
+ # Any other combo doesn't need to be or can't be mapped.
143
+ return actual, identity
144
+
145
+ def line(
146
+ self,
147
+ geo: GeoSelection | GeoAggregation,
148
+ time: TimeSelection | TimeAggregation,
149
+ quantity: QuantitySelection | QuantityAggregation,
150
+ *,
151
+ label_format: str = "{n}: {q}",
152
+ legend: Literal["on", "off", "outside", "auto"] = "auto",
153
+ line_kwargs: list[dict] | None = None,
154
+ ordering: Literal["location", "quantity"] = "location",
155
+ time_format: Literal["auto", "date", "day"] = "auto",
156
+ title: str | None = None,
157
+ transform: Callable[[pd.DataFrame], pd.DataFrame] | None = None,
158
+ ) -> None:
159
+ """Renders a line plot using matplotlib showing the given selections.
160
+
161
+ The plot will be immediately rendered by this function by calling `plt.show()`.
162
+ This is intended as a quick plotting method to cover most casual use-cases.
163
+ If you want more control over how the plot is drawn, see method `line_plt()`.
164
+
165
+ Parameters
166
+ ----------
167
+ geo : GeoSelection | GeoAggregation
168
+ the geographic selection to make on the output data
169
+ time : TimeSelection | TimeAggregation
170
+ the time selection to make on the output data
171
+ quantity : QuantitySelection | QuantityAggregation
172
+ the quantity selection to make on the output data
173
+ label_format : str, default="{n}: {q}"
174
+ a format for the items displayed in the legend;
175
+ the string will be used in a call to `format()`
176
+ with the replacement variables `{n}` for the name of the geo node
177
+ and `{q}` for the name of the quantity
178
+ legend : {"auto", "on", "off", "outside"}
179
+ whether and how to draw the plot legend.
180
+
181
+ - "auto" will draw the legend unless it would be too large
182
+ - "on" forces the legend to be drawn
183
+ - "off" forces the legend to not be drawn
184
+ - "outside" forces the legend to be drawn next to the plot area
185
+ (instead of inside it)
186
+ line_kwargs : list[dict], optional
187
+ a list of keyword arguments to be passed to the matplotlib function
188
+ that draws each line. If the list contains less items than there are lines,
189
+ we will cycle through the list as many times as needed. Lines are drawn
190
+ in the order defined by the `ordering` parameter.
191
+ See matplotlib documentation for the supported options.
192
+ ordering : {"location", "quantity"}
193
+ controls the order in which lines will be drawn;
194
+ both location and quantity are used to sort the resulting rows,
195
+ this just decides which gets priority
196
+ time_format : {"auto", "date", "day"}
197
+ controls the formatting of the time axis (the horizontal axis);
198
+ "auto" will use the format defined by the grouping of the `time` parameter,
199
+ "date" attempts to display calendar dates,
200
+ "day" attempts to display days numerically indexed from the start of the
201
+ simulation with the first day being 0.
202
+ If the system cannot convert to the requested time format, this argument
203
+ may be ignored.
204
+ title : str, optional
205
+ a title to draw on the plot
206
+ transform : Callable[[pd.DataFrame], pd.DataFrame], optional
207
+ allows you to specify an arbitrary transform function for the source
208
+ dataframe before we plot it, e.g., to rescale the values.
209
+ The function will be called once per geo/quantity group -- once per line,
210
+ essentially -- with a dataframe that contains just the data for that group.
211
+ The dataframe given as the argument is the result of applying
212
+ all selections and the projection if specified.
213
+ You should return a dataframe with the same format, where the
214
+ values of the data column have been modified for your purposes.
215
+
216
+ Dataframe columns:
217
+
218
+ - "time": the time series column
219
+ - "geo": the node ID (same value per group)
220
+ - "quantity": the label of the quantity (same value per group)
221
+ - "value": the data column
222
+ """
223
+
224
+ # Adjust figsize to make room for an outside legend, if needed
225
+ # By default, the layout engine would "steal" area from the plot
226
+ # to render the legend outside. Instead we'll widen the figure.
227
+ def_figsize = plt.rcParams["figure.figsize"]
228
+ if legend == "outside":
229
+ legend_width = 1.28 # width chosen because it seems to look nice
230
+ fig_width, fig_height = def_figsize
231
+ figsize = (fig_width + legend_width, fig_height)
232
+ else:
233
+ figsize = def_figsize
234
+
235
+ try:
236
+ _, ax = plt.subplots(layout="constrained", figsize=figsize)
237
+ lines = self.line_plt(
238
+ ax,
239
+ geo,
240
+ time,
241
+ quantity,
242
+ line_kwargs=line_kwargs,
243
+ label_format=label_format,
244
+ ordering=ordering,
245
+ time_format=time_format,
246
+ transform=transform,
247
+ )
248
+ # Make sure the plot does not grow if we widened the figure.
249
+ x, y, w, h = ax.get_position(original=True).bounds
250
+ ax.set_position((x, y, w * def_figsize[0] / figsize[0], h))
251
+
252
+ # Y-axis
253
+ plt.ylabel("count")
254
+ ax.yaxis.set_major_formatter(EngFormatter(sep=""))
255
+
256
+ # X-axis
257
+ _time_format, _ = self._time_format(time, time_format)
258
+ if _time_format == "date":
259
+ plt.xlabel("date")
260
+ ax.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d"))
261
+ ax.xaxis.set_major_locator(
262
+ AutoDateLocator(minticks=6, maxticks=12, interval_multiples=True)
263
+ )
264
+ plt.xticks(rotation=45)
265
+ elif _time_format == "day":
266
+ plt.xlabel("day")
267
+ elif _time_format == "tick":
268
+ plt.xlabel("tick")
269
+ else:
270
+ plt.xticks(rotation=45)
271
+ plt.xlabel("time")
272
+
273
+ # Legend
274
+ if legend == "auto":
275
+ # auto: show a legend if there are at most 12 lines.
276
+ legend = "on" if len(lines) <= 12 else "off"
277
+
278
+ if legend == "on":
279
+ plt.legend()
280
+ elif legend == "outside":
281
+ plt.legend(loc="center left", bbox_to_anchor=(1.0, 0.5))
282
+
283
+ if title is not None:
284
+ plt.title(title)
285
+ plt.show()
286
+ except:
287
+ plt.close()
288
+ raise
289
+
290
+ def line_plt(
291
+ self,
292
+ ax: Axes,
293
+ geo: GeoSelection | GeoAggregation,
294
+ time: TimeSelection | TimeAggregation,
295
+ quantity: QuantitySelection | QuantityAggregation,
296
+ *,
297
+ label_format: str = "{n}: {q}",
298
+ line_kwargs: list[dict] | None = None,
299
+ ordering: Literal["location", "quantity"] = "location",
300
+ time_format: Literal["auto", "date", "day"] = "auto",
301
+ transform: Callable[[pd.DataFrame], pd.DataFrame] | None = None,
302
+ ) -> list[Line2D]:
303
+ """Draws lines onto the given matplotlib Axes to show the given selections.
304
+ This is a variant of the method `line()` that gives you more control over
305
+ the rendering of a plot by letting you do most of the work with
306
+ matplotlib's API.
307
+
308
+ Parameters
309
+ ----------
310
+ ax : matplotlib.axes.Axes
311
+ the plot axes on which to draw lines
312
+ geo : GeoSelection | GeoAggregation
313
+ the geographic selection to make on the output data
314
+ time : TimeSelection | TimeAggregation
315
+ the time selection to make on the output data
316
+ quantity : QuantitySelection | QuantityAggregation
317
+ the quantity selection to make on the output data
318
+ label_format : str, default="{n}: {q}"
319
+ a format for the items displayed in the legend;
320
+ the string will be used in a call to `format()`
321
+ with the replacement variables `{n}` for the name of the geo node
322
+ and `{q}` for the name of the quantity
323
+ line_kwargs : list[dict], optional
324
+ a list of keyword arguments to be passed to the matplotlib function
325
+ that draws each line. If the list contains less items than there are lines,
326
+ we will cycle through the list as many times as needed. Lines are drawn
327
+ in the order defined by the `ordering` parameter.
328
+ See matplotlib documentation for the supported options.
329
+ ordering : {"location", "quantity}
330
+ controls the order in which lines will be drawn;
331
+ both location and quantity are used to sort the resulting rows,
332
+ this just decides which gets priority
333
+ time_format : {"auto", "date", "day"}
334
+ controls the formatting of the time axis (the horizontal axis);
335
+ "auto" will use the format defined by the grouping of the `time` parameter,
336
+ "date" attempts to display calendar dates,
337
+ "day" attempts to display days numerically indexed from the start of the
338
+ simulation with the first day being 0.
339
+ If the system cannot convert to the requested time format, this argument
340
+ may be ignored.
341
+ transform : Callable[[pd.DataFrame], pd.DataFrame], optional
342
+ allows you to specify an arbitrary transform function for the source
343
+ dataframe before we plot it, e.g., to rescale the values.
344
+ The function will be called once per geo/quantity group -- one per line,
345
+ essentially -- with a dataframe that contains just the data for that group.
346
+ The dataframe given as the argument is the result of applying
347
+ all selections and the projection if specified.
348
+ You should return a dataframe with the same format, where the
349
+ values of the data column have been modified for your purposes.
350
+
351
+ Dataframe columns:
352
+ - "time": the time series column
353
+ - "geo": the node ID (same value per group)
354
+ - "quantity": the label of the quantity (same value per group)
355
+ - "value": the data column
356
+
357
+ Returns
358
+ -------
359
+ list[matplotlib.lines.Line2D]
360
+ the Line2D object for each line drawn; you can use this to have finer
361
+ control over the presentation of the lines
362
+ """
363
+ if line_kwargs is None or len(line_kwargs) == 0:
364
+ line_kwargs = [{}]
365
+ if transform is None:
366
+ transform = identity
367
+
368
+ data_df = munge(self.output, geo, time, quantity)
369
+
370
+ # Map time labels:
371
+ _, map_time_axis = self._time_format(time, time_format)
372
+ data_df["time"] = map_time_axis(data_df["time"])
373
+
374
+ # Map geo labels:
375
+ result_scope = geo.to_scope()
376
+ if (labels := result_scope.labels_option) is not None:
377
+ geo_map = dict(zip(result_scope.node_ids, labels))
378
+ data_df["geo"] = data_df["geo"].apply(lambda x: geo_map[x])
379
+
380
+ # Before melting, disambiguate any quantities with the same name.
381
+ q_mapping = quantity.disambiguate_groups()
382
+
383
+ groups_df = (
384
+ data_df.set_axis(["time", "geo", *q_mapping.keys()], axis=1)
385
+ .melt(id_vars=["time", "geo"], var_name="quantity")
386
+ .groupby(["geo", "quantity"], sort=False)
387
+ )
388
+
389
+ sort_key = self._sorting(q_mapping, ordering)
390
+
391
+ lines = list[Line2D]()
392
+ for (group, data), kwargs in zip(
393
+ sorted(groups_df, key=sort_key),
394
+ cycle(line_kwargs),
395
+ ):
396
+ n_label, q_label_dis = group
397
+ q_label = q_mapping[q_label_dis]
398
+ label = label_format.format(n=n_label, q=q_label)
399
+ curr_kwargs = {"label": label, **kwargs}
400
+ data = transform(data.assign(quantity=q_label))
401
+ ls = ax.plot(data["time"], data["value"], **curr_kwargs)
402
+ lines.extend(ls)
403
+ return lines
404
+
405
+
406
+ class PlotRendererMixin(Output):
407
+ "Mixin class that adds a convenient method for rendering plots from an output."
408
+
409
+ @property
410
+ def plot(self) -> PlotRenderer:
411
+ """Render a plot from this output."""
412
+ return PlotRenderer(self)