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/trends.py ADDED
@@ -0,0 +1,305 @@
1
+ """Regional trend summary templates: diverging bar and state-vs-trend quadrant."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import matplotlib.pyplot as plt
8
+ import matplotlib.ticker as mtick
9
+ import numpy as np
10
+ import pandas as pd
11
+ from matplotlib.axes import Axes
12
+ from matplotlib.figure import Figure
13
+
14
+ from stplot.config import Config, ensure_config, resolve_column, resolve_palette
15
+ from stplot.theme.mpl import mpl_theme, style_axes
16
+ from stplot.transform.columns import validate_columns
17
+ from stplot.transform.filters import derive_trend_direction_3level
18
+
19
+
20
+ def trend_diverging_bar(
21
+ df: pd.DataFrame,
22
+ *,
23
+ group_col: str | None = None,
24
+ direction_col: str | None = None,
25
+ auto_derive_direction: bool = True,
26
+ palette: dict[str, str] | None = None,
27
+ show_n: bool = True,
28
+ title: str | None = None,
29
+ xlabel: str = "Percentage of sites (%)",
30
+ figsize: tuple[float, float] | None = None,
31
+ ax: Axes | None = None,
32
+ config: str | Path | Config | None = None,
33
+ ) -> tuple[Figure, Axes]:
34
+ """Plot a LAWA-style diverging horizontal stacked bar chart of trends around 0%.
35
+
36
+ ``Improving`` extends right (+%), ``Degrading`` extends left (-%), and
37
+ ``Indeterminate`` is centered symmetrically around 0%.
38
+
39
+ Required columns (resolved via ``config.columns`` unless explicitly overridden):
40
+ - ``group_col`` (default key: ``"indicator"``)
41
+ - ``direction_col`` (optional; if omitted and ``auto_derive_direction=True``,
42
+ derived via :func:`stplot.transform.derive_trend_direction_3level`)
43
+
44
+ Returns:
45
+ Tuple of ``(fig, ax)``.
46
+ """
47
+ cfg = ensure_config(config)
48
+ resolved_group = resolve_column(group_col, cfg, "indicator")
49
+ validate_columns(df, [resolved_group], context="trend_diverging_bar")
50
+
51
+ work = df.copy()
52
+ if direction_col is not None:
53
+ validate_columns(work, [direction_col], context="trend_diverging_bar")
54
+ resolved_dir = direction_col
55
+ elif auto_derive_direction and (
56
+ cfg.columns.get("trend_confidence") in work.columns
57
+ or cfg.columns.get("trend_category") in work.columns
58
+ ):
59
+ work = derive_trend_direction_3level(work, out_col="_stplot_trend_dir", config=cfg)
60
+ resolved_dir = "_stplot_trend_dir"
61
+ else:
62
+ resolved_dir = resolve_column(None, cfg, "trend_direction")
63
+ validate_columns(work, [resolved_dir], context="trend_diverging_bar")
64
+
65
+ work = work[work[resolved_dir].isin(["Improving", "Indeterminate", "Degrading"])]
66
+ counts = pd.crosstab(work[resolved_group], work[resolved_dir])
67
+ for col_name in ("Degrading", "Indeterminate", "Improving"):
68
+ if col_name not in counts.columns:
69
+ counts[col_name] = 0
70
+ counts = counts[["Degrading", "Indeterminate", "Improving"]]
71
+
72
+ totals = counts.sum(axis=1)
73
+ pcts = counts.div(totals.replace(0, pd.NA), axis=0).mul(100.0).fillna(0.0)
74
+ # Sort by % Improving descending (top bar = best improving)
75
+ pcts = pcts.sort_values(by="Improving", ascending=True)
76
+ totals = totals.loc[pcts.index]
77
+
78
+ resolved_palette = resolve_palette(palette, cfg, "trend_directions")
79
+ c_imp = resolved_palette.get("Improving", "#29b6f6")
80
+ c_ind = resolved_palette.get("Indeterminate", "#e6e600")
81
+ c_deg = resolved_palette.get("Degrading", "#ff6666")
82
+
83
+ with mpl_theme(cfg):
84
+ if ax is None:
85
+ fig_h = max(4.2, 0.52 * len(pcts) + 1.6)
86
+ fig, ax = plt.subplots(figsize=figsize or (10.5, fig_h))
87
+ else:
88
+ fig = ax.figure # type: ignore[assignment]
89
+
90
+ y_pos = np.arange(len(pcts))
91
+ ind_vals = pcts["Indeterminate"].to_numpy(dtype=float)
92
+ imp_vals = pcts["Improving"].to_numpy(dtype=float)
93
+ deg_vals = pcts["Degrading"].to_numpy(dtype=float)
94
+
95
+ # Center Indeterminate symmetrically around 0
96
+ ax.barh(
97
+ y_pos, ind_vals, left=-ind_vals / 2.0, height=0.58, color=c_ind, label="Indeterminate"
98
+ )
99
+ ax.barh(y_pos, imp_vals, left=ind_vals / 2.0, height=0.58, color=c_imp, label="Improving")
100
+ ax.barh(
101
+ y_pos,
102
+ -deg_vals,
103
+ left=-ind_vals / 2.0,
104
+ height=0.58,
105
+ color=c_deg,
106
+ label="Degrading",
107
+ )
108
+
109
+ ax.axvline(0, color=cfg.theme.text_color, linewidth=1.1, zorder=5)
110
+ ax.set_xlim(-105, 105)
111
+ ax.xaxis.set_major_formatter(mtick.FuncFormatter(lambda x, _pos: f"{abs(int(x))}%"))
112
+
113
+ y_labels = [
114
+ f"{grp} (n = {int(n)})" if show_n else str(grp)
115
+ for grp, n in zip(pcts.index, totals.to_numpy(), strict=True)
116
+ ]
117
+ ax.set_yticks(y_pos)
118
+ ax.set_yticklabels(y_labels)
119
+
120
+ style_axes(ax, title=None, xlabel=xlabel, ylabel=None, config=cfg)
121
+ if title:
122
+ ax.set_title(
123
+ title,
124
+ fontsize=cfg.theme.title_size,
125
+ fontweight=cfg.theme.title_weight,
126
+ color=cfg.theme.text_color,
127
+ pad=28,
128
+ )
129
+ ax.yaxis.grid(False)
130
+ ax.legend(
131
+ loc="upper center",
132
+ bbox_to_anchor=(0.5, 1.13),
133
+ ncol=3,
134
+ frameon=False,
135
+ fontsize=cfg.theme.legend_size,
136
+ )
137
+
138
+ return fig, ax
139
+
140
+
141
+ def state_trend_quadrant(
142
+ df: pd.DataFrame,
143
+ *,
144
+ state_col: str | None = None,
145
+ trend_col: str | None = None,
146
+ band_col: str | None = None,
147
+ label_col: str | None = None,
148
+ indicator: str | None = None,
149
+ indicator_directions: dict[str, str] | None = None,
150
+ state_threshold: float | None = None,
151
+ higher_state_is_worse: bool | None = None,
152
+ log_x: bool = True,
153
+ annotate_top_n: int = 6,
154
+ palette: dict[str, str] | None = None,
155
+ title: str | None = None,
156
+ xlabel: str | None = None,
157
+ ylabel: str = "Percent annual change (%/year)",
158
+ figsize: tuple[float, float] | None = None,
159
+ ax: Axes | None = None,
160
+ config: str | Path | Config | None = None,
161
+ ) -> tuple[Figure, Axes]:
162
+ """Plot a 4-quadrant State vs Trend management prioritization scatter plot.
163
+
164
+ Plots current state metric on the x-axis against ``Percent.annual.change`` on the
165
+ y-axis, dividing the space into four actionable management quadrants:
166
+ *Good & Improving*, *Good but Degrading (Watchlist)*, *Poor but Improving*, and
167
+ *Poor & Degrading (Priority)*.
168
+
169
+ When ``higher_state_is_worse`` is ``None``, polarity is resolved automatically from
170
+ ``indicator`` (or a single unique value in ``config.columns["indicator"]``) via
171
+ ``indicator_directions`` / ``config.indicator_directions`` (defaulting to ``True``).
172
+
173
+ Returns:
174
+ Tuple of ``(fig, ax)``.
175
+ """
176
+ from stplot.config import is_lower_better
177
+
178
+ cfg = ensure_config(config)
179
+ resolved_state = resolve_column(state_col, cfg, "state_value")
180
+ resolved_trend = resolve_column(trend_col, cfg, "pct_annual_change")
181
+ validate_columns(df, [resolved_state, resolved_trend], context="state_trend_quadrant")
182
+
183
+ inferred_ind = indicator
184
+ if inferred_ind is None:
185
+ ind_col = cfg.columns.get("indicator")
186
+ if ind_col and ind_col in df.columns:
187
+ uniq = df[ind_col].dropna().astype(str).unique()
188
+ if len(uniq) == 1:
189
+ inferred_ind = str(uniq[0])
190
+ resolved_higher_worse = is_lower_better(
191
+ inferred_ind,
192
+ cfg,
193
+ lower_is_better=higher_state_is_worse,
194
+ overrides=indicator_directions,
195
+ default=True,
196
+ )
197
+
198
+ resolved_band = band_col if band_col is not None else cfg.columns.get("state_band")
199
+ resolved_label = label_col if label_col is not None else cfg.columns.get("site_id")
200
+ resolved_palette = resolve_palette(palette, cfg, "state_bands")
201
+
202
+ work = df.dropna(subset=[resolved_state, resolved_trend]).copy()
203
+ if log_x:
204
+ work = work[work[resolved_state] > 0]
205
+
206
+ x_thresh = (
207
+ float(state_threshold)
208
+ if state_threshold is not None
209
+ else float(work[resolved_state].median())
210
+ )
211
+
212
+ with mpl_theme(cfg):
213
+ if ax is None:
214
+ fig, ax = plt.subplots(figsize=figsize or (10.0, 6.5))
215
+ else:
216
+ fig = ax.figure # type: ignore[assignment]
217
+
218
+ if resolved_band and resolved_band in work.columns:
219
+ for band, sub in work.groupby(resolved_band):
220
+ ax.scatter(
221
+ sub[resolved_state],
222
+ sub[resolved_trend],
223
+ s=95,
224
+ color=resolved_palette.get(str(band), cfg.theme.accent_color),
225
+ edgecolors="#222222",
226
+ linewidths=0.8,
227
+ label=f"Grade {band}" if len(str(band)) == 1 else str(band),
228
+ zorder=4,
229
+ )
230
+ else:
231
+ ax.scatter(
232
+ work[resolved_state],
233
+ work[resolved_trend],
234
+ s=95,
235
+ color=cfg.theme.accent_color,
236
+ edgecolors="#222222",
237
+ linewidths=0.8,
238
+ zorder=4,
239
+ )
240
+
241
+ if log_x:
242
+ from stplot.theme.mpl import format_log_axis
243
+
244
+ format_log_axis(ax, "x")
245
+
246
+ ax.margins(x=0.14, y=0.18)
247
+ ax.axvline(x_thresh, color=cfg.theme.text_color, linestyle="--", linewidth=1.1, zorder=2)
248
+ ax.axhline(0.0, color=cfg.theme.text_color, linestyle="--", linewidth=1.1, zorder=2)
249
+
250
+ # Subtle quadrant corner labels
251
+ if resolved_higher_worse:
252
+ q_tl, q_tr = "Good & Degrading\n(Watchlist)", "Poor & Degrading\n(Priority)"
253
+ q_bl, q_br = "Good & Improving", "Poor & Improving"
254
+ else:
255
+ q_tl, q_tr = "Poor & Improving", "Good & Improving"
256
+ q_bl, q_br = "Poor & Degrading\n(Priority)", "Good & Degrading\n(Watchlist)"
257
+
258
+ quad_style = {
259
+ "fontsize": cfg.theme.caption_size,
260
+ "color": cfg.theme.caption_color,
261
+ "fontweight": "bold",
262
+ "alpha": 0.85,
263
+ }
264
+ ax.text(0.02, 0.97, q_tl, transform=ax.transAxes, ha="left", va="top", **quad_style)
265
+ ax.text(0.98, 0.97, q_tr, transform=ax.transAxes, ha="right", va="top", **quad_style)
266
+ ax.text(0.02, 0.03, q_bl, transform=ax.transAxes, ha="left", va="bottom", **quad_style)
267
+ ax.text(0.98, 0.03, q_br, transform=ax.transAxes, ha="right", va="bottom", **quad_style)
268
+
269
+ # Annotate extreme/priority sites with smart left/right alignment
270
+ if annotate_top_n > 0 and resolved_label and resolved_label in work.columns:
271
+ scored = work.assign(
272
+ _score=work[resolved_trend].abs() + (work[resolved_state].rank(pct=True) * 5.0)
273
+ ).nlargest(annotate_top_n, "_score")
274
+ for _, row in scored.iterrows():
275
+ px, py = float(row[resolved_state]), float(row[resolved_trend])
276
+ align_right = px >= x_thresh
277
+ ax.annotate(
278
+ str(row[resolved_label]),
279
+ (px, py),
280
+ xytext=(-7 if align_right else 7, -10 if py > 3.5 else 5),
281
+ textcoords="offset points",
282
+ ha="right" if align_right else "left",
283
+ fontsize=cfg.theme.caption_size - 0.5,
284
+ color=cfg.theme.text_color,
285
+ zorder=5,
286
+ )
287
+
288
+ style_axes(
289
+ ax,
290
+ title=title,
291
+ xlabel=xlabel or resolved_state,
292
+ ylabel=ylabel,
293
+ config=cfg,
294
+ )
295
+ if resolved_band and resolved_band in work.columns:
296
+ ax.legend(
297
+ title="NOF Grade",
298
+ loc="upper left",
299
+ bbox_to_anchor=(1.02, 1.0),
300
+ frameon=False,
301
+ fontsize=cfg.theme.legend_size,
302
+ title_fontsize=cfg.theme.legend_size,
303
+ )
304
+
305
+ return fig, ax
@@ -0,0 +1,24 @@
1
+ """Templated Word (.docx) report generation helpers."""
2
+
3
+ from stplot.reporting.captions import CaptionTracker, generate_figure_caption
4
+ from stplot.reporting.html_companion import build_html_companion
5
+ from stplot.reporting.templates import (
6
+ create_npsfm_report_template,
7
+ create_one_plan_report_template,
8
+ )
9
+ from stplot.reporting.word import (
10
+ add_styled_table,
11
+ create_starter_docx_template,
12
+ render_docx_report,
13
+ )
14
+
15
+ __all__ = [
16
+ "CaptionTracker",
17
+ "add_styled_table",
18
+ "build_html_companion",
19
+ "create_npsfm_report_template",
20
+ "create_one_plan_report_template",
21
+ "create_starter_docx_template",
22
+ "generate_figure_caption",
23
+ "render_docx_report",
24
+ ]
@@ -0,0 +1,177 @@
1
+ """Automated figure and table caption generators with sequential numbering."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+
10
+ from stplot.config import Config, ensure_config, resolve_label
11
+ from stplot.transform.qa import split_full_and_preliminary
12
+
13
+
14
+ def generate_figure_caption(
15
+ chart_description: str,
16
+ *,
17
+ df: pd.DataFrame | None = None,
18
+ indicator: str | None = None,
19
+ scope: str | None = None,
20
+ period: str | None = None,
21
+ site_col: str | None = None,
22
+ filter_col: str | None = None,
23
+ figure_number: int | str | None = None,
24
+ prefix: str = "Figure",
25
+ note: str | None = None,
26
+ config: str | Path | Config | None = None,
27
+ ) -> str:
28
+ """Generate a standardized, data-aware caption for a report figure or table.
29
+
30
+ Automatically resolves human-readable indicator/FMU labels (including macrons) and,
31
+ when ``df`` is supplied, computes unique site counts plus Full vs Preliminary record
32
+ counts (via ``FilterOK`` / ``nOK``) so captions never drift out of sync with the data.
33
+
34
+ Args:
35
+ chart_description: Core description of what the figure shows (e.g.,
36
+ ``"NPS-FM State Band distribution by FMU"``).
37
+ df: Optional DataFrame used to derive ``n`` site and data-sufficiency counts.
38
+ indicator: Optional raw indicator code or display name (resolved via ``config.labels``).
39
+ scope: Optional geographic or domain scope (e.g., ``"Manawatu"`` or ``"Rivers (SoE)"``).
40
+ period: Optional reporting period string (e.g., ``"2021–2025"``).
41
+ site_col: Optional site column override (defaults to ``config.columns["site_id"]``).
42
+ filter_col: Optional data-sufficiency column override (defaults to
43
+ ``config.columns["filter_ok"]``).
44
+ figure_number: Optional number or chapter label (e.g., ``1`` or ``"2.1"``).
45
+ prefix: Caption prefix (default ``"Figure"``; use ``"Table"`` for tables).
46
+ note: Optional trailing note appended after a period.
47
+ config: Optional Config object, preset name, or path to YAML/TOML config.
48
+
49
+ Returns:
50
+ Formatted caption string.
51
+ """
52
+ cfg = ensure_config(config)
53
+
54
+ # Leading label
55
+ lead = f"{prefix} {figure_number}: " if figure_number is not None else ""
56
+
57
+ # Subject prefix from scope / indicator
58
+ subject_parts: list[str] = []
59
+ if scope:
60
+ subject_parts.append(resolve_label(scope, cfg))
61
+ if indicator:
62
+ subject_parts.append(resolve_label(indicator, cfg))
63
+
64
+ if subject_parts:
65
+ body = f"{' — '.join(subject_parts)}: {chart_description.strip().rstrip('.')}"
66
+ else:
67
+ body = chart_description.strip().rstrip(".")
68
+
69
+ # Parenthetical metadata (period, n sites, full vs preliminary)
70
+ meta_parts: list[str] = []
71
+ if period:
72
+ meta_parts.append(str(period))
73
+
74
+ if df is not None and len(df) > 0:
75
+ r_site = site_col if site_col is not None else cfg.columns.get("site_id")
76
+ r_filter = filter_col if filter_col is not None else cfg.columns.get("filter_ok")
77
+
78
+ if r_filter and r_filter in df.columns:
79
+ full_df, prelim_df = split_full_and_preliminary(df, filter_col=r_filter, config=cfg)
80
+ if r_site and r_site in df.columns:
81
+ n_full_sites = int(full_df[r_site].nunique())
82
+ n_prelim_sites = int(prelim_df[r_site].nunique())
83
+ if n_prelim_sites > 0:
84
+ meta_parts.append(
85
+ f"n = {n_full_sites:,} full sites, {n_prelim_sites:,} preliminary"
86
+ )
87
+ else:
88
+ meta_parts.append(f"n = {n_full_sites:,} sites")
89
+ else:
90
+ if len(prelim_df) > 0:
91
+ meta_parts.append(f"n = {len(full_df):,} full, {len(prelim_df):,} preliminary")
92
+ else:
93
+ meta_parts.append(f"n = {len(full_df):,} records")
94
+ elif r_site and r_site in df.columns:
95
+ meta_parts.append(f"n = {int(df[r_site].nunique()):,} sites")
96
+ else:
97
+ meta_parts.append(f"n = {len(df):,} records")
98
+
99
+ meta_str = f" ({'; '.join(meta_parts)})" if meta_parts else ""
100
+ note_str = f" {note.strip()}" if note else ""
101
+ return f"{lead}{body}{meta_str}.{note_str}"
102
+
103
+
104
+ @dataclass
105
+ class CaptionTracker:
106
+ """Stateful counter for automatically numbering figures and tables across a report."""
107
+
108
+ chapter: int | str | None = None
109
+ figure_count: int = 0
110
+ table_count: int = 0
111
+ config: str | Path | Config | None = None
112
+
113
+ def set_chapter(self, chapter: int | str | None, *, reset: bool = True) -> None:
114
+ """Switch to a new chapter prefix (e.g., ``2`` -> ``Figure 2.1``)."""
115
+ self.chapter = chapter
116
+ if reset:
117
+ self.figure_count = 0
118
+ self.table_count = 0
119
+
120
+ def _fmt_num(self, count: int) -> str:
121
+ return f"{self.chapter}.{count}" if self.chapter is not None else str(count)
122
+
123
+ def next_figure(
124
+ self,
125
+ description: str,
126
+ *,
127
+ df: pd.DataFrame | None = None,
128
+ indicator: str | None = None,
129
+ scope: str | None = None,
130
+ period: str | None = None,
131
+ site_col: str | None = None,
132
+ filter_col: str | None = None,
133
+ note: str | None = None,
134
+ ) -> str:
135
+ """Increment the figure counter and return the formatted figure caption."""
136
+ self.figure_count += 1
137
+ return generate_figure_caption(
138
+ description,
139
+ df=df,
140
+ indicator=indicator,
141
+ scope=scope,
142
+ period=period,
143
+ site_col=site_col,
144
+ filter_col=filter_col,
145
+ figure_number=self._fmt_num(self.figure_count),
146
+ prefix="Figure",
147
+ note=note,
148
+ config=self.config,
149
+ )
150
+
151
+ def next_table(
152
+ self,
153
+ description: str,
154
+ *,
155
+ df: pd.DataFrame | None = None,
156
+ indicator: str | None = None,
157
+ scope: str | None = None,
158
+ period: str | None = None,
159
+ site_col: str | None = None,
160
+ filter_col: str | None = None,
161
+ note: str | None = None,
162
+ ) -> str:
163
+ """Increment the table counter and return the formatted table caption."""
164
+ self.table_count += 1
165
+ return generate_figure_caption(
166
+ description,
167
+ df=df,
168
+ indicator=indicator,
169
+ scope=scope,
170
+ period=period,
171
+ site_col=site_col,
172
+ filter_col=filter_col,
173
+ figure_number=self._fmt_num(self.table_count),
174
+ prefix="Table",
175
+ note=note,
176
+ config=self.config,
177
+ )