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,575 @@
1
+ """
2
+ Tools for rendering tables from epymorph simulation output data.
3
+ """
4
+
5
+ import dataclasses
6
+ from typing import Callable, Literal, Sequence, overload
7
+ from warnings import warn
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from pandas.core.groupby.generic import DataFrameGroupBy
12
+ from sparklines import sparklines
13
+ from sympy import Symbol
14
+
15
+ from epymorph.compartment_model import (
16
+ CompartmentDef,
17
+ EdgeDef,
18
+ QuantityAggregation,
19
+ QuantitySelection,
20
+ )
21
+ from epymorph.geography.scope import GeoAggregation, GeoSelection
22
+ from epymorph.time import NBins, TimeAggregation, TimeSelection
23
+ from epymorph.tools.data import Output, munge
24
+ from epymorph.util import filter_unique
25
+
26
+ OrderingOptions = Literal["location", "quantity"]
27
+ FormatOptions = Literal["dataframe", "string", "print"]
28
+
29
+
30
+ def to_sparklines(values):
31
+ """A Pandas aggregation function that produces a sparkline result."""
32
+ # NOTE: I tried using the same max value for each quantity;
33
+ # in a way this improves comparison between locations, but means that
34
+ # large locations "drown out" smaller locations, hiding the dynamics.
35
+ # I made the judgement call that the dynamics were more important here.
36
+ # If you want to understand relative scale you should use a line graph.
37
+ # NOTE: I'm checking for max == 0 here because if min and max are both zero,
38
+ # sparkline draws a mid-height box instead of a min-height box;
39
+ # with this adjustment, all-zero data looks like zeros.
40
+ maximum = values.max()
41
+ if maximum == 0:
42
+ maximum = 1.0
43
+ (spark,) = sparklines(values, minimum=0, maximum=maximum, num_lines=1)
44
+ return spark
45
+
46
+
47
+ def _process_output(
48
+ out: Output,
49
+ geo: GeoSelection | GeoAggregation,
50
+ time: TimeSelection | TimeAggregation,
51
+ quantity: QuantitySelection | QuantityAggregation,
52
+ ordering: OrderingOptions,
53
+ column_names: Sequence[str],
54
+ process_groups: Callable[[DataFrameGroupBy], pd.DataFrame],
55
+ ) -> pd.DataFrame:
56
+ # The different tables share a lot of data processing logic.
57
+ # The only significant difference is how to turn
58
+ # the grouped (geo,quantity) time series into values.
59
+ # This difference is factored out by taking a lambda for processing groups.
60
+
61
+ # Prepare a consistent sort order.
62
+ # By default: we sort by location (alphanumeric by node_id),
63
+ # then by quantity in IPM declaration order (compartments then events).
64
+ # Passing ordering "quantity" just flips the ordering of two columns.
65
+
66
+ # Compute the grouped time series.
67
+ data_df = munge(out, geo, time, quantity)
68
+
69
+ # Before melting, disambiguate any quantities with the same name.
70
+ q_mapping = quantity.disambiguate_groups()
71
+
72
+ groups_df = (
73
+ data_df.set_axis(["time", "geo", *q_mapping.keys()], axis=1)
74
+ .melt(id_vars=["time", "geo"], var_name="quantity")
75
+ .drop(columns="time")
76
+ .groupby(["geo", "quantity"], sort=False)
77
+ )
78
+
79
+ # Process the groups into values.
80
+ result_df = process_groups(groups_df)
81
+
82
+ # Set column names.
83
+ result_df = result_df.set_axis(["geo", "quantity", *column_names], axis=1)
84
+
85
+ # If this is a multistrata model add a column for "other strata";
86
+ # for any quantities that are meta edge events, the value of this column
87
+ # are which other strata are involved (by examining the rate expression).
88
+ # For compartments and events that are purely intrastrata, this should be blank.
89
+ if quantity.ipm.is_multistrata:
90
+ strata = quantity.ipm.strata
91
+
92
+ def which_strata(s: Symbol) -> str | None:
93
+ for x in strata:
94
+ if str(s).endswith(f"_{x}"):
95
+ return x
96
+ return None
97
+
98
+ def calc_other_strata(e: EdgeDef) -> str:
99
+ # If we can't tell which other strata are involved,
100
+ # just return empty string.
101
+ own_strata = which_strata(e.compartment_from)
102
+ if own_strata is None:
103
+ return ""
104
+ other_strata = filter_unique(
105
+ strata
106
+ for strata in (
107
+ which_strata(x)
108
+ for x in e.rate.free_symbols
109
+ if isinstance(x, Symbol)
110
+ )
111
+ if strata is not None and strata != own_strata
112
+ )
113
+ return ",".join(other_strata)
114
+
115
+ map_other_strata = {
116
+ name: calc_other_strata(q) if isinstance(q, EdgeDef) else ""
117
+ for name, q in zip(q_mapping.keys(), quantity.selected)
118
+ }
119
+ other_strata = result_df["quantity"].apply(lambda x: map_other_strata[x])
120
+ result_df.insert(2, column="other strata", value=other_strata)
121
+
122
+ # Sort rows.
123
+ def sort_key(series):
124
+ if series.name == "quantity":
125
+ quantity_order = {s: i for i, s in enumerate(q_mapping.keys())}
126
+ return series.apply(lambda x: quantity_order[x])
127
+ else:
128
+ return series
129
+
130
+ sort_cols = ["quantity", "geo"] if ordering == "quantity" else ["geo", "quantity"]
131
+ result_df = result_df.sort_values(sort_cols, key=sort_key, ignore_index=True)
132
+
133
+ # Restore quantity names (now in rows).
134
+ qs = result_df["quantity"].apply(lambda x: q_mapping[x])
135
+ result_df = result_df.assign(quantity=qs)
136
+
137
+ # If we have a way to do this, replace node IDs with friendly labels.
138
+ result_scope = geo.to_scope()
139
+ if (labels := result_scope.labels_option) is not None:
140
+ geo_map = dict(zip(result_scope.node_ids, labels))
141
+ result_df["geo"] = result_df["geo"].apply(lambda x: geo_map[x])
142
+
143
+ return result_df
144
+
145
+
146
+ class TableRenderer:
147
+ """Provides a number of methods for rendering an output in tabular form.
148
+
149
+ Examples
150
+ --------
151
+ Most commonly, you will use TableRenderer starting from a simulation output object
152
+ that supports it:
153
+
154
+ ```python
155
+ out = BasicSimulation(rume).run()
156
+ out.table.quantiles(...)
157
+ ```
158
+ """
159
+
160
+ output: Output
161
+
162
+ def __init__(self, output: Output):
163
+ self.output = output
164
+
165
+ def _format_output(self, result_df: pd.DataFrame, result_format: FormatOptions):
166
+ match result_format:
167
+ case "dataframe":
168
+ return result_df
169
+ case "string":
170
+ return result_df.to_string()
171
+ case "print":
172
+ print(result_df.to_string(index=False)) # noqa: T201
173
+ return None
174
+ case x:
175
+ msg = f"Invalid result_format: {x}"
176
+ raise ValueError(msg)
177
+
178
+ @overload
179
+ def quantiles(
180
+ self,
181
+ quantiles: Sequence[float],
182
+ geo: GeoSelection | GeoAggregation,
183
+ time: TimeSelection | TimeAggregation,
184
+ quantity: QuantitySelection | QuantityAggregation,
185
+ *,
186
+ ordering: Literal["location", "quantity"] = "location",
187
+ result_format: Literal["dataframe"] = "dataframe",
188
+ column_names: Sequence[str] | None = None,
189
+ ) -> pd.DataFrame: ...
190
+
191
+ @overload
192
+ def quantiles(
193
+ self,
194
+ quantiles: Sequence[float],
195
+ geo: GeoSelection | GeoAggregation,
196
+ time: TimeSelection | TimeAggregation,
197
+ quantity: QuantitySelection | QuantityAggregation,
198
+ *,
199
+ ordering: Literal["location", "quantity"] = "location",
200
+ result_format: Literal["string"],
201
+ column_names: Sequence[str] | None = None,
202
+ ) -> str: ...
203
+
204
+ @overload
205
+ def quantiles(
206
+ self,
207
+ quantiles: Sequence[float],
208
+ geo: GeoSelection | GeoAggregation,
209
+ time: TimeSelection | TimeAggregation,
210
+ quantity: QuantitySelection | QuantityAggregation,
211
+ *,
212
+ ordering: Literal["location", "quantity"] = "location",
213
+ result_format: Literal["print"],
214
+ column_names: Sequence[str] | None = None,
215
+ ) -> None: ...
216
+
217
+ def quantiles(
218
+ self,
219
+ quantiles: Sequence[float],
220
+ geo: GeoSelection | GeoAggregation,
221
+ time: TimeSelection | TimeAggregation,
222
+ quantity: QuantitySelection | QuantityAggregation,
223
+ *,
224
+ ordering: Literal["location", "quantity"] = "location",
225
+ result_format: Literal["dataframe", "string", "print"] = "dataframe",
226
+ column_names: Sequence[str] | None = None,
227
+ ) -> pd.DataFrame | str | None:
228
+ """
229
+ Renders a table showing time-series quantiles for the given selections.
230
+
231
+ Parameters
232
+ ----------
233
+ quantiles : Sequence[float]
234
+ the list of quantiles to calculate and display, in the range [0,1]
235
+ geo : GeoSelection | GeoAggregation
236
+ the geographic selection to make on the output data
237
+ time : TimeSelection | TimeAggregation
238
+ the time selection to make on the output data
239
+ quantity : QuantitySelection | QuantityAggregation
240
+ the quantity selection to make on the output data
241
+ ordering : {"location", "quantity"}
242
+ controls the ordering of rows in the result;
243
+ both location and quantity are used to sort the resulting rows,
244
+ this just decides which gets priority
245
+ result_format : {"dataframe", "string", "print"}
246
+ controls the type of the result of this method;
247
+ "dataframe" returns a Pandas DataFrame,
248
+ "string" returns the stringified table, and
249
+ "print" just prints the stringified table directly and returns None
250
+ column_names : Sequence[str], optional
251
+ overrides the default names of the quantiles columns;
252
+ by default, this is just the quantile value itself
253
+
254
+ Returns
255
+ -------
256
+ DataFrame | str | None
257
+ according to the value of the `result_format` parameter
258
+ """
259
+ _quantiles = np.array(quantiles)
260
+ if len(quantiles) == 0:
261
+ err = "Please provide a list of quantiles to calculate."
262
+ raise ValueError(err)
263
+ if np.any(_quantiles < 0) or np.any(_quantiles > 1):
264
+ err = "Invalid quantiles: must be in the range [0.0, 1.0]"
265
+ raise ValueError(err)
266
+ if column_names is None:
267
+ column_names = [str(x) for x in quantiles]
268
+
269
+ result_df = _process_output(
270
+ self.output,
271
+ geo,
272
+ time,
273
+ quantity,
274
+ ordering,
275
+ column_names,
276
+ lambda df: (
277
+ # `pivot` is more appropriate than `pivot_table` because we don't want
278
+ # aggregation to happen accidentally
279
+ df.quantile(_quantiles) # noqa: PD010
280
+ .reset_index()
281
+ .pivot(index=["geo", "quantity"], columns=["level_2"])
282
+ .reset_index()
283
+ ),
284
+ )
285
+ return self._format_output(result_df, result_format)
286
+
287
+ @overload
288
+ def range(
289
+ self,
290
+ geo: GeoSelection | GeoAggregation,
291
+ time: TimeSelection | TimeAggregation,
292
+ quantity: QuantitySelection | QuantityAggregation,
293
+ *,
294
+ ordering: Literal["location", "quantity"] = "location",
295
+ result_format: Literal["dataframe"] = "dataframe",
296
+ ) -> pd.DataFrame: ...
297
+
298
+ @overload
299
+ def range(
300
+ self,
301
+ geo: GeoSelection | GeoAggregation,
302
+ time: TimeSelection | TimeAggregation,
303
+ quantity: QuantitySelection | QuantityAggregation,
304
+ *,
305
+ ordering: Literal["location", "quantity"] = "location",
306
+ result_format: Literal["string"],
307
+ ) -> str: ...
308
+
309
+ @overload
310
+ def range(
311
+ self,
312
+ geo: GeoSelection | GeoAggregation,
313
+ time: TimeSelection | TimeAggregation,
314
+ quantity: QuantitySelection | QuantityAggregation,
315
+ *,
316
+ ordering: Literal["location", "quantity"] = "location",
317
+ result_format: Literal["print"],
318
+ ) -> None: ...
319
+
320
+ def range(
321
+ self,
322
+ geo: GeoSelection | GeoAggregation,
323
+ time: TimeSelection | TimeAggregation,
324
+ quantity: QuantitySelection | QuantityAggregation,
325
+ *,
326
+ ordering: Literal["location", "quantity"] = "location",
327
+ result_format: Literal["dataframe", "string", "print"] = "dataframe",
328
+ ) -> pd.DataFrame | str | None:
329
+ """
330
+ Renders a table showing minimum and maximum values over time for the given
331
+ selections. This is equivalent to calling `quantiles()` with 0 and 1.
332
+
333
+ Parameters
334
+ ----------
335
+ geo : GeoSelection | GeoAggregation
336
+ the geographic selection to make on the output data
337
+ time : TimeSelection | TimeAggregation
338
+ the time selection to make on the output data
339
+ quantity : QuantitySelection | QuantityAggregation
340
+ the quantity selection to make on the output data
341
+ ordering : {"location", "quantity"}
342
+ controls the ordering of rows in the result;
343
+ both location and quantity are used to sort the resulting rows,
344
+ this just decides which gets priority
345
+ result_format : {"dataframe", "string", "print"}
346
+ controls the type of the result of this method;
347
+ "dataframe" returns a Pandas DataFrame,
348
+ "string" returns the stringified table, and
349
+ "print" just prints the stringified table directly and returns None
350
+
351
+ Returns
352
+ -------
353
+ DataFrame | str | None
354
+ according to the value of the `result_format` parameter
355
+ """
356
+ return self.quantiles(
357
+ quantiles=(0.0, 1.0),
358
+ geo=geo,
359
+ time=time,
360
+ quantity=quantity,
361
+ ordering=ordering,
362
+ result_format=result_format,
363
+ column_names=("min", "max"),
364
+ )
365
+
366
+ @overload
367
+ def sum(
368
+ self,
369
+ geo: GeoSelection | GeoAggregation,
370
+ time: TimeSelection | TimeAggregation,
371
+ quantity: QuantitySelection | QuantityAggregation,
372
+ *,
373
+ ordering: Literal["location", "quantity"] = "location",
374
+ result_format: Literal["dataframe"] = "dataframe",
375
+ ) -> pd.DataFrame: ...
376
+
377
+ @overload
378
+ def sum(
379
+ self,
380
+ geo: GeoSelection | GeoAggregation,
381
+ time: TimeSelection | TimeAggregation,
382
+ quantity: QuantitySelection | QuantityAggregation,
383
+ *,
384
+ ordering: Literal["location", "quantity"] = "location",
385
+ result_format: Literal["string"],
386
+ ) -> str: ...
387
+
388
+ @overload
389
+ def sum(
390
+ self,
391
+ geo: GeoSelection | GeoAggregation,
392
+ time: TimeSelection | TimeAggregation,
393
+ quantity: QuantitySelection | QuantityAggregation,
394
+ *,
395
+ ordering: Literal["location", "quantity"] = "location",
396
+ result_format: Literal["print"],
397
+ ) -> None: ...
398
+
399
+ def sum(
400
+ self,
401
+ geo: GeoSelection | GeoAggregation,
402
+ time: TimeSelection | TimeAggregation,
403
+ quantity: QuantitySelection | QuantityAggregation,
404
+ *,
405
+ ordering: Literal["location", "quantity"] = "location",
406
+ result_format: Literal["dataframe", "string", "print"] = "dataframe",
407
+ ) -> pd.DataFrame | str | None:
408
+ """
409
+ Renders a table showing summed values over time for the given selections.
410
+
411
+ Because it is not valid to sum compartment values over time -- this would be
412
+ double-counting individuals in a way that has no physical meaning --
413
+ compartment quantities are automatically omitted even if they are part of the
414
+ selection, so only events are reflected in the result.
415
+
416
+ Parameters
417
+ ----------
418
+ geo : GeoSelection | GeoAggregation
419
+ the geographic selection to make on the output data
420
+ time : TimeSelection | TimeAggregation
421
+ the time selection to make on the output data
422
+ quantity : QuantitySelection | QuantityAggregation
423
+ the quantity selection to make on the output data
424
+ ordering : {"location", "quantity"}
425
+ controls the ordering of rows in the result;
426
+ both location and quantity are used to sort the resulting rows,
427
+ this just decides which gets priority
428
+ result_format : {"dataframe", "string", "print"}
429
+ controls the type of the result of this method;
430
+ "dataframe" returns a Pandas DataFrame,
431
+ "string" returns the stringified table, and
432
+ "print" just prints the stringified table directly and returns None
433
+
434
+ Returns
435
+ -------
436
+ DataFrame | str | None
437
+ according to the value of the `result_format` parameter
438
+ """
439
+ if any(isinstance(q, CompartmentDef) for q in quantity.selected):
440
+ warn(
441
+ "Although your selection includes IPM compartments, "
442
+ "`sum()` has removed these from the output.\nThis is because "
443
+ "adding a time-series of compartment values is likely to "
444
+ "double-count individuals and produce a misleading result.\n"
445
+ "Adding a time-series of event occurrences, on the other hand, is fine."
446
+ )
447
+
448
+ # Since it doesn't make real sense to sum compartment values,
449
+ # exclude compartments from selection.
450
+ C, E = quantity.ipm.num_compartments, quantity.ipm.num_events
451
+ m = np.zeros(shape=C + E, dtype=np.bool_)
452
+ m[C:] = True
453
+ quantity = dataclasses.replace(quantity, selection=quantity.selection & m)
454
+
455
+ result_df = _process_output(
456
+ self.output,
457
+ geo,
458
+ time,
459
+ quantity,
460
+ ordering,
461
+ ["sum"],
462
+ lambda df: df.sum().reset_index(),
463
+ )
464
+ return self._format_output(result_df, result_format)
465
+
466
+ @overload
467
+ def chart(
468
+ self,
469
+ geo: GeoSelection | GeoAggregation,
470
+ time: TimeSelection | TimeAggregation,
471
+ quantity: QuantitySelection | QuantityAggregation,
472
+ *,
473
+ chart_length: int = 20,
474
+ ordering: Literal["location", "quantity"] = "location",
475
+ result_format: Literal["dataframe"] = "dataframe",
476
+ ) -> pd.DataFrame: ...
477
+
478
+ @overload
479
+ def chart(
480
+ self,
481
+ geo: GeoSelection | GeoAggregation,
482
+ time: TimeSelection | TimeAggregation,
483
+ quantity: QuantitySelection | QuantityAggregation,
484
+ *,
485
+ chart_length: int = 20,
486
+ ordering: Literal["location", "quantity"] = "location",
487
+ result_format: Literal["string"],
488
+ ) -> str: ...
489
+
490
+ @overload
491
+ def chart(
492
+ self,
493
+ geo: GeoSelection | GeoAggregation,
494
+ time: TimeSelection | TimeAggregation,
495
+ quantity: QuantitySelection | QuantityAggregation,
496
+ *,
497
+ chart_length: int = 20,
498
+ ordering: Literal["location", "quantity"] = "location",
499
+ result_format: Literal["print"],
500
+ ) -> None: ...
501
+
502
+ def chart(
503
+ self,
504
+ geo: GeoSelection | GeoAggregation,
505
+ time: TimeSelection | TimeAggregation,
506
+ quantity: QuantitySelection | QuantityAggregation,
507
+ *,
508
+ chart_length: int = 20,
509
+ ordering: Literal["location", "quantity"] = "location",
510
+ result_format: Literal["dataframe", "string", "print"] = "dataframe",
511
+ ) -> pd.DataFrame | str | None:
512
+ """
513
+ Renders a table showing a rough time series bar chart for the given selections
514
+ using ASCII characters.
515
+
516
+ It is of course limited by the fact that this is a
517
+ relatively coarse display method. The y-axis of each chart is on its own scale,
518
+ and thus is not comparable to others. However the x-axis is on a shared scale,
519
+ so this can give you an idea of the time-series behavior of your simulation
520
+ and relative timing between the selected quantities and locations.
521
+
522
+ Parameters
523
+ ----------
524
+ geo : GeoSelection | GeoAggregation
525
+ the geographic selection to make on the output data
526
+ time : TimeSelection | TimeAggregation
527
+ the time selection to make on the output data
528
+ quantity : QuantitySelection | QuantityAggregation
529
+ the quantity selection to make on the output data
530
+ chart_length : int, default=20
531
+ approximately how many characters should we use to render the charts?
532
+ This is simply a ballpark, similar to automatically selecting the number
533
+ of bins in a histogram, so you may get more or less than you ask for.
534
+ Multiple days may be compressed into one bin, but one day will never be
535
+ split between bins. The last bin may contain less days of data than the
536
+ rest of the bins.
537
+ ordering : {"location", "quantity"}
538
+ controls the ordering of rows in the result;
539
+ both location and quantity are used to sort the resulting rows,
540
+ this just decides which gets priority
541
+ result_format : {"dataframe", "string", "print"}
542
+ controls the type of the result of this method;
543
+ "dataframe" returns a Pandas DataFrame,
544
+ "string" returns the stringified table, and
545
+ "print" just prints the stringified table directly and returns None
546
+
547
+ Returns
548
+ -------
549
+ DataFrame | str | None
550
+ according to the value of the `result_format` parameter
551
+ """
552
+ if isinstance(time, TimeSelection):
553
+ # Unless the user supplies their own TimeAggregation,
554
+ # use NBins to condense the series.
555
+ time = time.group(NBins(chart_length)).agg()
556
+
557
+ result_df = _process_output(
558
+ self.output,
559
+ geo,
560
+ time,
561
+ quantity,
562
+ ordering,
563
+ ["chart"],
564
+ lambda df: df.agg(to_sparklines).reset_index(),
565
+ )
566
+ return self._format_output(result_df, result_format)
567
+
568
+
569
+ class TableRendererMixin(Output):
570
+ "Mixin class that adds a convenient method for rendering tables from an output."
571
+
572
+ @property
573
+ def table(self) -> TableRenderer:
574
+ """Render a table from this output."""
575
+ return TableRenderer(self)