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