stplot 0.1.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 (49) hide show
  1. stplot/__init__.py +21 -0
  2. stplot/config/__init__.py +33 -0
  3. stplot/config/loader.py +106 -0
  4. stplot/config/models.py +328 -0
  5. stplot/config/presets/__init__.py +1 -0
  6. stplot/config/presets/default.yaml +208 -0
  7. stplot/config/presets/horizons_one_plan.yaml +59 -0
  8. stplot/io/__init__.py +6 -0
  9. stplot/io/spatial.py +72 -0
  10. stplot/io/tabular.py +154 -0
  11. stplot/plots/__init__.py +122 -0
  12. stplot/plots/barbell.py +400 -0
  13. stplot/plots/batch.py +135 -0
  14. stplot/plots/domains.py +1143 -0
  15. stplot/plots/executive.py +474 -0
  16. stplot/plots/export.py +74 -0
  17. stplot/plots/infographics.py +1118 -0
  18. stplot/plots/lollipop.py +285 -0
  19. stplot/plots/maps.py +738 -0
  20. stplot/plots/matrix.py +190 -0
  21. stplot/plots/one_plan.py +642 -0
  22. stplot/plots/paired.py +437 -0
  23. stplot/plots/scorecards.py +1940 -0
  24. stplot/plots/state.py +373 -0
  25. stplot/plots/state_trends.py +1413 -0
  26. stplot/plots/tables.py +107 -0
  27. stplot/plots/timeseries.py +607 -0
  28. stplot/plots/trends.py +305 -0
  29. stplot/reporting/__init__.py +24 -0
  30. stplot/reporting/captions.py +177 -0
  31. stplot/reporting/html_companion.py +339 -0
  32. stplot/reporting/templates.py +485 -0
  33. stplot/reporting/word.py +369 -0
  34. stplot/theme/__init__.py +25 -0
  35. stplot/theme/folium.py +62 -0
  36. stplot/theme/mpl.py +181 -0
  37. stplot/theme/plotly.py +130 -0
  38. stplot/transform/__init__.py +60 -0
  39. stplot/transform/categories.py +51 -0
  40. stplot/transform/columns.py +103 -0
  41. stplot/transform/filters.py +385 -0
  42. stplot/transform/merge.py +173 -0
  43. stplot/transform/pairing.py +154 -0
  44. stplot/transform/qa.py +297 -0
  45. stplot/transform/tables.py +573 -0
  46. stplot/transform/zones.py +354 -0
  47. stplot-0.1.0.dist-info/METADATA +235 -0
  48. stplot-0.1.0.dist-info/RECORD +49 -0
  49. stplot-0.1.0.dist-info/WHEEL +4 -0
stplot/plots/paired.py ADDED
@@ -0,0 +1,437 @@
1
+ """Upstream vs Downstream paired comparison and rolling-period plot templates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import matplotlib.pyplot as plt
9
+ import pandas as pd
10
+ from matplotlib.axes import Axes
11
+ from matplotlib.figure import Figure
12
+ from matplotlib.lines import Line2D
13
+ from matplotlib.patches import Patch
14
+
15
+ from stplot.config import Config, ensure_config, resolve_palette
16
+ from stplot.theme.mpl import mpl_theme, style_axes
17
+ from stplot.transform.columns import validate_columns
18
+
19
+
20
+ def upstream_downstream_comparison(
21
+ df: pd.DataFrame,
22
+ *,
23
+ site_col: str = "DischargeSite",
24
+ upstream_val_col: str = "UpstreamValue",
25
+ downstream_val_col: str = "DownstreamValue",
26
+ upstream_grade_col: str | None = "UpstreamGrade",
27
+ downstream_grade_col: str | None = "DownstreamGrade",
28
+ group_col: str | None = None,
29
+ log_scale: bool = True,
30
+ upstream_color: str = "#1f77b4",
31
+ downstream_color: str = "#d62728",
32
+ title: str | None = None,
33
+ note: str | None = None,
34
+ ylabel: str | None = None,
35
+ figsize: tuple[float, float] | None = None,
36
+ ax: Axes | None = None,
37
+ config: str | Path | Config | None = None,
38
+ ) -> tuple[Figure, Axes]:
39
+ """Plot paired Upstream (▲) vs Downstream (▼) values grouped by district/zone.
40
+
41
+ Draws dashed vertical connectors between upstream and downstream triangles, with
42
+ optional NOF grade letters printed inside each triangle and alternating shaded
43
+ background bands for groups (e.g., territorial authorities ``MDC``, ``PNCC``, ``RDC``).
44
+
45
+ Args:
46
+ df: Paired DataFrame with one row per discharge/STP site.
47
+ site_col: Column containing discharge site labels on the x-axis.
48
+ upstream_val_col: Column containing upstream numeric values.
49
+ downstream_val_col: Column containing downstream numeric values.
50
+ upstream_grade_col: Optional column containing upstream NOF grade letters.
51
+ downstream_grade_col: Optional column containing downstream NOF grade letters.
52
+ group_col: Optional district/zone grouping column used to shade and label spans.
53
+ log_scale: If True, use a logarithmic y-axis.
54
+ upstream_color: Fill color for upward upstream triangles.
55
+ downstream_color: Fill color for downward downstream triangles.
56
+ title: Optional chart title.
57
+ note: Optional italic note box placed at top-left.
58
+ ylabel: Optional y-axis label.
59
+ figsize: Optional ``(width, height)`` override when ``ax`` is None.
60
+ ax: Optional existing Matplotlib ``Axes`` to draw onto.
61
+ config: Optional Config object, preset name, or path to YAML/TOML config.
62
+
63
+ Returns:
64
+ Tuple of ``(fig, ax)``.
65
+ """
66
+ cfg = ensure_config(config)
67
+ required = [site_col, upstream_val_col, downstream_val_col]
68
+ if group_col is not None:
69
+ required.append(group_col)
70
+ validate_columns(df, required, context="upstream_downstream_comparison")
71
+
72
+ work = df.copy().reset_index(drop=True)
73
+ if group_col is not None:
74
+ work = work.sort_values(by=[group_col], kind="stable").reset_index(drop=True)
75
+
76
+ with mpl_theme(cfg):
77
+ if ax is None:
78
+ fig, ax = plt.subplots(figsize=figsize or (12.5, 6.2))
79
+ else:
80
+ fig = ax.figure # type: ignore[assignment]
81
+
82
+ # Alternating shaded background bands by group
83
+ group_spans: list[tuple[str, float, float]] = []
84
+ if group_col is not None:
85
+ current_group = None
86
+ start_idx = 0
87
+ for idx, grp in enumerate(work[group_col].astype(str)):
88
+ if grp != current_group:
89
+ if current_group is not None:
90
+ group_spans.append((current_group, start_idx - 0.45, idx - 0.55))
91
+ current_group = grp
92
+ start_idx = idx
93
+ if current_group is not None:
94
+ group_spans.append((current_group, start_idx - 0.45, len(work) - 0.55))
95
+
96
+ for band_idx, (_, x0, x1) in enumerate(group_spans):
97
+ if band_idx % 2 == 0:
98
+ ax.axvspan(x0, x1, color="#eef4fa", alpha=0.75, zorder=0)
99
+
100
+ for idx, row in work.iterrows():
101
+ u_val = row[upstream_val_col]
102
+ d_val = row[downstream_val_col]
103
+ if pd.notna(u_val) and pd.notna(d_val):
104
+ ax.plot(
105
+ [idx, idx],
106
+ [u_val, d_val],
107
+ linestyle="--",
108
+ color="#7f8c8d",
109
+ linewidth=1.0,
110
+ zorder=2,
111
+ )
112
+ if pd.notna(u_val):
113
+ ax.scatter(
114
+ idx,
115
+ u_val,
116
+ marker="^",
117
+ s=260,
118
+ color=upstream_color,
119
+ edgecolors="#1a252f",
120
+ linewidths=0.9,
121
+ zorder=4,
122
+ )
123
+ if upstream_grade_col and upstream_grade_col in work.columns:
124
+ grade = row[upstream_grade_col]
125
+ if pd.notna(grade):
126
+ ax.text(
127
+ idx,
128
+ u_val,
129
+ str(grade),
130
+ ha="center",
131
+ va="center",
132
+ color="#ffffff",
133
+ fontsize=7.5,
134
+ fontweight="bold",
135
+ zorder=5,
136
+ )
137
+ if pd.notna(d_val):
138
+ ax.scatter(
139
+ idx,
140
+ d_val,
141
+ marker="v",
142
+ s=260,
143
+ color=downstream_color,
144
+ edgecolors="#1a252f",
145
+ linewidths=0.9,
146
+ zorder=4,
147
+ )
148
+ if downstream_grade_col and downstream_grade_col in work.columns:
149
+ grade = row[downstream_grade_col]
150
+ if pd.notna(grade):
151
+ ax.text(
152
+ idx,
153
+ d_val,
154
+ str(grade),
155
+ ha="center",
156
+ va="center",
157
+ color="#ffffff",
158
+ fontsize=7.5,
159
+ fontweight="bold",
160
+ zorder=5,
161
+ )
162
+
163
+ if log_scale:
164
+ from stplot.theme.mpl import format_log_axis
165
+
166
+ format_log_axis(ax, "y")
167
+
168
+ ax.set_xticks(range(len(work)))
169
+ ax.set_xticklabels(work[site_col].astype(str), rotation=90, ha="center")
170
+ ax.set_xlim(-0.6, len(work) - 0.4)
171
+
172
+ style_axes(ax, title=None, xlabel=None, ylabel=ylabel, config=cfg)
173
+ if title:
174
+ ax.set_title(
175
+ title,
176
+ fontsize=cfg.theme.title_size,
177
+ color=cfg.theme.text_color,
178
+ fontweight=cfg.theme.title_weight,
179
+ pad=32,
180
+ )
181
+
182
+ if note:
183
+ ax.text(
184
+ 0.0,
185
+ 1.025,
186
+ note,
187
+ transform=ax.transAxes,
188
+ fontsize=cfg.theme.caption_size,
189
+ style="italic",
190
+ color=cfg.theme.text_color,
191
+ bbox={"facecolor": "#ffffff", "edgecolor": cfg.theme.spine_color, "pad": 3},
192
+ )
193
+
194
+ handles = [
195
+ Line2D(
196
+ [0],
197
+ [0],
198
+ marker="^",
199
+ color="w",
200
+ label="Upstream",
201
+ markerfacecolor=upstream_color,
202
+ markeredgecolor="#1a252f",
203
+ markersize=10,
204
+ ),
205
+ Line2D(
206
+ [0],
207
+ [0],
208
+ marker="v",
209
+ color="w",
210
+ label="Downstream",
211
+ markerfacecolor=downstream_color,
212
+ markeredgecolor="#1a252f",
213
+ markersize=10,
214
+ ),
215
+ ]
216
+ ax.legend(
217
+ handles=handles,
218
+ loc="upper right",
219
+ bbox_to_anchor=(1.0, 1.095),
220
+ ncol=2,
221
+ frameon=False,
222
+ fontsize=cfg.theme.legend_size,
223
+ )
224
+
225
+ # Group labels beneath the x-axis tick labels
226
+ if group_spans:
227
+ for grp_name, x0, x1 in group_spans:
228
+ mid = (x0 + x1) / 2.0
229
+ ax.text(
230
+ mid,
231
+ -0.28,
232
+ grp_name,
233
+ transform=ax.get_xaxis_transform(),
234
+ ha="center",
235
+ va="top",
236
+ fontsize=cfg.theme.tick_size,
237
+ fontweight="bold",
238
+ color=cfg.theme.text_color,
239
+ )
240
+
241
+ return fig, ax
242
+
243
+
244
+ def upstream_downstream_timeseries(
245
+ df: pd.DataFrame,
246
+ *,
247
+ period_col: str | None = None,
248
+ upstream_val_col: str = "UpstreamValue",
249
+ downstream_val_col: str = "DownstreamValue",
250
+ upstream_grade_col: str | None = "UpstreamGrade",
251
+ downstream_grade_col: str | None = "DownstreamGrade",
252
+ upstream_label: str = "Upstream",
253
+ downstream_label: str = "Downstream",
254
+ band_thresholds: dict[str, tuple[float, float]] | None = None,
255
+ log_scale: bool = True,
256
+ upstream_color: str = "#7b939e",
257
+ downstream_color: str = "#111111",
258
+ palette: dict[str, str] | None = None,
259
+ title: str | None = None,
260
+ note: str | None = None,
261
+ ylabel: str | None = None,
262
+ figsize: tuple[float, float] | None = None,
263
+ ax: Axes | None = None,
264
+ config: str | Path | Config | None = None,
265
+ ) -> tuple[Figure, Axes]:
266
+ """Plot rolling-period Upstream (▲) vs Downstream (▼) values with NOF band shading.
267
+
268
+ Args:
269
+ df: DataFrame with one row per rolling period (e.g., ``"2008 - 2012"``).
270
+ period_col: Period column name. Defaults to ``config.columns["period"]``.
271
+ upstream_val_col: Column containing upstream values.
272
+ downstream_val_col: Column containing downstream values.
273
+ upstream_grade_col: Optional column containing upstream NOF grade letters.
274
+ downstream_grade_col: Optional column containing downstream NOF grade letters.
275
+ upstream_label: Legend label for the upstream site.
276
+ downstream_label: Legend label for the downstream site.
277
+ band_thresholds: Optional mapping of band label to ``(ymin, ymax)`` intervals
278
+ for pastel horizontal background shading (e.g.,
279
+ ``{"A": (0.002, 0.03), "B": (0.03, 0.05)}``).
280
+ log_scale: If True, use a logarithmic y-axis.
281
+ upstream_color: Marker fill color for upstream triangles.
282
+ downstream_color: Marker fill color for downstream triangles.
283
+ palette: Optional state band palette override for background shading.
284
+ title: Optional chart title.
285
+ note: Optional italic note displayed above the plot.
286
+ ylabel: Optional y-axis label.
287
+ figsize: Optional ``(width, height)`` override when ``ax`` is None.
288
+ ax: Optional existing Matplotlib ``Axes`` to draw onto.
289
+ config: Optional Config object, preset name, or path to YAML/TOML config.
290
+
291
+ Returns:
292
+ Tuple of ``(fig, ax)``.
293
+ """
294
+ cfg = ensure_config(config)
295
+ p_col = period_col if period_col is not None else cfg.columns.get("period", "yearz")
296
+ validate_columns(
297
+ df,
298
+ [p_col, upstream_val_col, downstream_val_col],
299
+ context="upstream_downstream_timeseries",
300
+ )
301
+
302
+ resolved_palette = resolve_palette(palette, cfg, "state_bands")
303
+ work = df.copy().reset_index(drop=True)
304
+ x_positions = list(range(len(work)))
305
+
306
+ with mpl_theme(cfg):
307
+ if ax is None:
308
+ fig, ax = plt.subplots(figsize=figsize or (11.0, 5.5))
309
+ else:
310
+ fig = ax.figure # type: ignore[assignment]
311
+
312
+ band_handles: list[Patch] = []
313
+ if band_thresholds:
314
+ for band_name, (ymin, ymax) in band_thresholds.items():
315
+ band_color = resolved_palette.get(band_name, "#cccccc")
316
+ ax.axhspan(ymin, ymax, color=band_color, alpha=0.22, zorder=0)
317
+ band_handles.append(
318
+ Patch(facecolor=band_color, alpha=0.6, label=f"Band {band_name}")
319
+ )
320
+
321
+ for idx, row in work.iterrows():
322
+ u_val = row[upstream_val_col]
323
+ d_val = row[downstream_val_col]
324
+ if pd.notna(u_val):
325
+ ax.scatter(
326
+ idx,
327
+ u_val,
328
+ marker="^",
329
+ s=240,
330
+ color=upstream_color,
331
+ edgecolors="#1a252f",
332
+ linewidths=0.9,
333
+ zorder=4,
334
+ )
335
+ if upstream_grade_col and upstream_grade_col in work.columns:
336
+ grade = row[upstream_grade_col]
337
+ if pd.notna(grade):
338
+ ax.text(
339
+ idx,
340
+ u_val,
341
+ str(grade),
342
+ ha="center",
343
+ va="center",
344
+ color="#111111",
345
+ fontsize=7.5,
346
+ fontweight="bold",
347
+ zorder=5,
348
+ )
349
+ if pd.notna(d_val):
350
+ ax.scatter(
351
+ idx,
352
+ d_val,
353
+ marker="v",
354
+ s=240,
355
+ color=downstream_color,
356
+ edgecolors="#111111",
357
+ linewidths=0.9,
358
+ zorder=4,
359
+ )
360
+ if downstream_grade_col and downstream_grade_col in work.columns:
361
+ grade = row[downstream_grade_col]
362
+ if pd.notna(grade):
363
+ ax.text(
364
+ idx,
365
+ d_val,
366
+ str(grade),
367
+ ha="center",
368
+ va="center",
369
+ color="#ffffff",
370
+ fontsize=7.5,
371
+ fontweight="bold",
372
+ zorder=5,
373
+ )
374
+
375
+ if log_scale:
376
+ from stplot.theme.mpl import format_log_axis
377
+
378
+ format_log_axis(ax, "y")
379
+
380
+ ax.set_xticks(x_positions)
381
+ ax.set_xticklabels(work[p_col].astype(str), rotation=90, ha="center")
382
+ ax.set_xlim(-0.6, len(work) - 0.4)
383
+
384
+ style_axes(ax, title=None, xlabel=None, ylabel=ylabel, config=cfg)
385
+ if title:
386
+ ax.set_title(
387
+ title,
388
+ fontsize=cfg.theme.title_size,
389
+ color=cfg.theme.text_color,
390
+ fontweight=cfg.theme.title_weight,
391
+ loc="left",
392
+ pad=24 if note else 10,
393
+ )
394
+
395
+ if note:
396
+ ax.text(
397
+ 0.0,
398
+ 1.02,
399
+ note,
400
+ transform=ax.transAxes,
401
+ fontsize=cfg.theme.caption_size,
402
+ style="italic",
403
+ color=cfg.theme.text_color,
404
+ )
405
+
406
+ handles: list[Any] = [
407
+ Line2D(
408
+ [0],
409
+ [0],
410
+ marker="^",
411
+ color="w",
412
+ label=upstream_label,
413
+ markerfacecolor=upstream_color,
414
+ markeredgecolor="#1a252f",
415
+ markersize=10,
416
+ ),
417
+ Line2D(
418
+ [0],
419
+ [0],
420
+ marker="v",
421
+ color="w",
422
+ label=downstream_label,
423
+ markerfacecolor=downstream_color,
424
+ markeredgecolor="#111111",
425
+ markersize=10,
426
+ ),
427
+ *band_handles,
428
+ ]
429
+ ax.legend(
430
+ handles=handles,
431
+ loc="upper left",
432
+ bbox_to_anchor=(1.02, 1.0),
433
+ frameon=False,
434
+ fontsize=cfg.theme.legend_size,
435
+ )
436
+
437
+ return fig, ax