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
@@ -0,0 +1,573 @@
1
+ """Monitoring network, sample-count, and data-sufficiency summary table builders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pandas as pd
8
+
9
+ from stplot.config import Config, ensure_config, resolve_column, resolve_label
10
+ from stplot.transform.columns import validate_columns
11
+ from stplot.transform.qa import _is_ok_mask
12
+
13
+
14
+ def build_network_summary_table(
15
+ df: pd.DataFrame,
16
+ *,
17
+ group_col: str | None = None,
18
+ site_col: str | None = None,
19
+ indicator_col: str | None = None,
20
+ filter_col: str | None = None,
21
+ sample_col: str | None = None,
22
+ total_label: str = "Whole Region",
23
+ config: str | Path | Config | None = None,
24
+ ) -> pd.DataFrame:
25
+ """Build a monitoring network breakdown table (sites, indicators, full/preliminary, samples).
26
+
27
+ Summarises each group (e.g., FMU, Domain, or Site Status) with:
28
+ - ``Sites (n)``: unique monitoring sites
29
+ - ``Indicators (n)``: unique attributes (when indicator column is present)
30
+ - ``Records (n)``: total site-indicator rows
31
+ - ``Full (OK)``, ``Preliminary``, ``% Full`` (when data-sufficiency column is present)
32
+ - ``Total Samples`` & ``Median Samples`` (when ``sample_col`` is provided & present)
33
+ Appends a ``Whole Region`` total row at the bottom.
34
+
35
+ Returns:
36
+ Clean summary ``pd.DataFrame`` ready for Word (``.docx``) or HTML Companion tables.
37
+ """
38
+ cfg = ensure_config(config)
39
+ r_group = resolve_column(group_col, cfg, "zone")
40
+ if r_group not in df.columns and cfg.columns.get("fmu") in df.columns:
41
+ r_group = cfg.columns["fmu"]
42
+ r_site = resolve_column(site_col, cfg, "site_id")
43
+ validate_columns(df, [r_group, r_site], context="build_network_summary_table")
44
+
45
+ r_ind = indicator_col if indicator_col is not None else cfg.columns.get("indicator")
46
+ has_ind = bool(r_ind and r_ind in df.columns)
47
+ r_filter = filter_col if filter_col is not None else cfg.columns.get("filter_ok")
48
+ has_filter = bool(r_filter and r_filter in df.columns)
49
+ has_samples = bool(sample_col and sample_col in df.columns)
50
+
51
+ work = df.copy()
52
+ work["_grp"] = work[r_group].fillna("Unassigned").astype(str)
53
+ if has_filter:
54
+ work["_ok"] = _is_ok_mask(work[r_filter])
55
+ if has_samples:
56
+ work["_n_samp"] = pd.to_numeric(work[sample_col], errors="coerce")
57
+
58
+ def _summarise_slice(label: str, sub: pd.DataFrame) -> dict[str, object]:
59
+ row: dict[str, object] = {
60
+ "Group": resolve_label(label, cfg) if label != total_label else total_label,
61
+ "Sites (n)": int(sub[r_site].nunique()),
62
+ }
63
+ if has_ind:
64
+ row["Indicators (n)"] = int(sub[r_ind].nunique())
65
+ row["Records (n)"] = int(len(sub))
66
+ if has_filter:
67
+ n_ok = int(sub["_ok"].sum())
68
+ n_pre = int((~sub["_ok"]).sum())
69
+ pct = (100.0 * n_ok / len(sub)) if len(sub) > 0 else 0.0
70
+ row["Full (OK)"] = n_ok
71
+ row["Preliminary"] = n_pre
72
+ row["% Full"] = f"{pct:.1f}%"
73
+ if has_samples:
74
+ valid_s = sub["_n_samp"].dropna()
75
+ row["Total Samples"] = int(valid_s.sum()) if not valid_s.empty else 0
76
+ row["Median Samples"] = f"{float(valid_s.median()):.0f}" if not valid_s.empty else "—"
77
+ return row
78
+
79
+ rows = [_summarise_slice(str(grp), sub) for grp, sub in work.groupby("_grp", sort=False)]
80
+ rows.append(_summarise_slice(total_label, work))
81
+ return pd.DataFrame(rows)
82
+
83
+
84
+ def build_data_sufficiency_table(
85
+ df: pd.DataFrame,
86
+ *,
87
+ group_col: str | None = None,
88
+ filter_col: str | None = None,
89
+ total_label: str = "Whole Region",
90
+ config: str | Path | Config | None = None,
91
+ ) -> pd.DataFrame:
92
+ """Cross-tabulate data sufficiency (``nOK`` / ``FilterOK``) counts by group with ``% Full``.
93
+
94
+ Ideal for report appendices showing exact counts of ``OK``, ``Insufficient data``,
95
+ and ``Insufficient FLOW data`` per FMU or per indicator.
96
+
97
+ Returns:
98
+ Summary ``pd.DataFrame`` with one row per group plus a ``Whole Region`` total row.
99
+ """
100
+ cfg = ensure_config(config)
101
+ r_group = resolve_column(group_col, cfg, "zone")
102
+ if r_group not in df.columns and cfg.columns.get("fmu") in df.columns:
103
+ r_group = cfg.columns["fmu"]
104
+ r_filter = resolve_column(filter_col, cfg, "filter_ok")
105
+ validate_columns(df, [r_group, r_filter], context="build_data_sufficiency_table")
106
+
107
+ work = df.copy()
108
+ work["_grp"] = (
109
+ work[r_group].fillna("Unassigned").astype(str).map(lambda g: resolve_label(g, cfg))
110
+ )
111
+ work["_status"] = work[r_filter].fillna("Missing").astype(str)
112
+ work["_ok"] = _is_ok_mask(work[r_filter])
113
+
114
+ ct = pd.crosstab(work["_grp"], work["_status"])
115
+ # Put OK/True first if present
116
+ preferred = [c for c in ("OK", "True", "TRUE", "1") if c in ct.columns]
117
+ others = [c for c in ct.columns if c not in preferred]
118
+ ct = ct[preferred + sorted(others)]
119
+
120
+ ct["Total"] = ct.sum(axis=1)
121
+ ok_by_grp = work.groupby("_grp")["_ok"].mean().reindex(ct.index) * 100.0
122
+ ct["% Full"] = ok_by_grp.map(lambda v: f"{v:.1f}%")
123
+
124
+ # Append Whole Region total row
125
+ tot_row: dict[str, object] = {c: int(ct[c].sum()) for c in preferred + sorted(others)}
126
+ tot_n = int(ct["Total"].sum())
127
+ tot_row["Total"] = tot_n
128
+ tot_pct = (100.0 * float(work["_ok"].mean())) if len(work) > 0 else 0.0
129
+ tot_row["% Full"] = f"{tot_pct:.1f}%"
130
+
131
+ out = ct.reset_index().rename(columns={"_grp": "Group"})
132
+ tot_df = pd.DataFrame([{"Group": total_label, **tot_row}])
133
+ return pd.concat([out, tot_df], ignore_index=True)
134
+
135
+
136
+ def build_indicator_coverage_table(
137
+ df: pd.DataFrame,
138
+ *,
139
+ group_col: str | None = None,
140
+ indicator_col: str | None = None,
141
+ site_col: str | None = None,
142
+ full_only: bool = False,
143
+ filter_col: str | None = None,
144
+ total_label: str = "Total Sites",
145
+ config: str | Path | Config | None = None,
146
+ ) -> pd.DataFrame:
147
+ """Build a Group (FMU) × Indicator matrix of unique monitored site counts.
148
+
149
+ Args:
150
+ df: Results DataFrame.
151
+ group_col: Grouping column (defaults to ``config.columns["zone"]`` / ``fmu``).
152
+ indicator_col: Indicator column (defaults to ``config.columns["indicator"]``).
153
+ site_col: Site identifier column (defaults to ``config.columns["site_id"]``).
154
+ full_only: If True, count only Full/OK rows (using ``filter_col``).
155
+ filter_col: Optional data-sufficiency column override.
156
+ total_label: Label for the bottom total row.
157
+ config: Optional Config object, preset name, or path to YAML/TOML config.
158
+
159
+ Returns:
160
+ DataFrame with Group rows, Indicator columns (unique site counts), and a total row.
161
+ """
162
+ cfg = ensure_config(config)
163
+ r_group = resolve_column(group_col, cfg, "zone")
164
+ if r_group not in df.columns and cfg.columns.get("fmu") in df.columns:
165
+ r_group = cfg.columns["fmu"]
166
+ r_ind = resolve_column(indicator_col, cfg, "indicator")
167
+ r_site = resolve_column(site_col, cfg, "site_id")
168
+ validate_columns(df, [r_group, r_ind, r_site], context="build_indicator_coverage_table")
169
+
170
+ work = df.copy()
171
+ if full_only:
172
+ r_filter = resolve_column(filter_col, cfg, "filter_ok")
173
+ if r_filter in work.columns:
174
+ work = work.loc[_is_ok_mask(work[r_filter])].copy()
175
+
176
+ work["_grp"] = (
177
+ work[r_group].fillna("Unassigned").astype(str).map(lambda g: resolve_label(g, cfg))
178
+ )
179
+ work["_ind"] = work[r_ind].astype(str).map(lambda i: resolve_label(i, cfg))
180
+
181
+ piv = work.groupby(["_grp", "_ind"])[r_site].nunique().unstack(fill_value=0)
182
+ piv["Any Indicator (n)"] = (
183
+ work.groupby("_grp")[r_site].nunique().reindex(piv.index).fillna(0).astype(int)
184
+ )
185
+
186
+ # Bottom total row (unique sites across whole region per indicator)
187
+ tot_row: dict[str, object] = {"Group": total_label}
188
+ for col in piv.columns:
189
+ if col == "Any Indicator (n)":
190
+ tot_row[col] = int(work[r_site].nunique())
191
+ else:
192
+ tot_row[col] = int(work.loc[work["_ind"] == col, r_site].nunique())
193
+
194
+ out = piv.reset_index().rename(columns={"_grp": "Group"})
195
+ return pd.concat([out, pd.DataFrame([tot_row])], ignore_index=True)
196
+
197
+
198
+ def build_exceedance_watchlist_table(
199
+ df: pd.DataFrame,
200
+ *,
201
+ site_col: str | None = None,
202
+ group_col: str | None = None,
203
+ indicator_col: str | None = None,
204
+ band_col: str | None = None,
205
+ value_col: str | None = None,
206
+ trend_col: str | None = None,
207
+ slope_col: str | None = None,
208
+ exceedance_values: tuple[object, ...] = ("D", "E", "Fail", "FAIL", False, "False"),
209
+ config: str | Path | Config | None = None,
210
+ ) -> pd.DataFrame:
211
+ """Build a prioritized National Bottom Line / One Plan exceedance watchlist table.
212
+
213
+ Filters rows whose state band/result is in ``exceedance_values`` (default: Band ``D``/``E``
214
+ or One Plan ``Fail``) and sorts so **Poor & Degrading** sites appear first.
215
+
216
+ Returns:
217
+ Sorted watchlist ``pd.DataFrame`` ready for council reports and appendices.
218
+ """
219
+ from stplot.transform.filters import derive_trend_direction_3level
220
+
221
+ cfg = ensure_config(config)
222
+ r_site = resolve_column(site_col, cfg, "site_id")
223
+ r_band = resolve_column(band_col, cfg, "state_band")
224
+ validate_columns(df, [r_site, r_band], context="build_exceedance_watchlist_table")
225
+
226
+ r_group = group_col if group_col is not None else cfg.columns.get("zone")
227
+ if r_group not in df.columns and cfg.columns.get("fmu") in df.columns:
228
+ r_group = cfg.columns["fmu"]
229
+ r_ind = indicator_col if indicator_col is not None else cfg.columns.get("indicator")
230
+ r_val = value_col if value_col is not None else cfg.columns.get("state_value")
231
+ r_trend = trend_col if trend_col is not None else cfg.columns.get("trend_direction")
232
+ r_slope = slope_col if slope_col is not None else cfg.columns.get("pct_annual_change")
233
+
234
+ exc_set = {str(v).strip().upper() for v in exceedance_values}
235
+ work = df.copy()
236
+ mask = work[r_band].astype(str).str.strip().str.upper().isin(exc_set)
237
+ work = work.loc[mask].copy()
238
+ if work.empty:
239
+ return pd.DataFrame(columns=["Site", "FMU", "Indicator", "State", "Trend", "Priority"])
240
+
241
+ has_trend = bool(r_trend and r_trend in work.columns)
242
+ if has_trend:
243
+ raw_t = work[r_trend].astype(str).str.strip()
244
+ if raw_t.isin({"Improving", "Indeterminate", "Degrading", "Not Analysed"}).mean() >= 0.5:
245
+ work["_t3"] = raw_t
246
+ else:
247
+ work = derive_trend_direction_3level(
248
+ work, confidence_col=r_trend, out_col="_t3", config=cfg
249
+ )
250
+ else:
251
+ work["_t3"] = "Not Analysed"
252
+
253
+ priority_rank = {"Degrading": 0, "Indeterminate": 1, "Not Analysed": 2, "Improving": 3}
254
+ band_rank = {"E": 0, "FAIL": 0, "FALSE": 0, "D": 1}
255
+ work["_p_ord"] = work["_t3"].map(lambda t: priority_rank.get(str(t), 2))
256
+ work["_b_ord"] = (
257
+ work[r_band].astype(str).str.strip().str.upper().map(lambda b: band_rank.get(b, 2))
258
+ )
259
+ work = work.sort_values(by=["_p_ord", "_b_ord", r_site], kind="stable").reset_index(drop=True)
260
+
261
+ out = pd.DataFrame({"Site": work[r_site].astype(str)})
262
+ if r_group and r_group in work.columns:
263
+ out["FMU"] = (
264
+ work[r_group].fillna("Unassigned").astype(str).map(lambda g: resolve_label(g, cfg))
265
+ )
266
+ if r_ind and r_ind in work.columns:
267
+ out["Indicator"] = work[r_ind].astype(str).map(lambda i: resolve_label(i, cfg))
268
+ out["State"] = work[r_band].astype(str)
269
+ if r_val and r_val in work.columns:
270
+ out["Value"] = work[r_val]
271
+ if has_trend:
272
+ out["Trend"] = work["_t3"]
273
+ if r_slope and r_slope in work.columns:
274
+ out["%/yr"] = pd.to_numeric(work[r_slope], errors="coerce").map(
275
+ lambda v: f"{v:+.1f}%" if pd.notna(v) else "—"
276
+ )
277
+ out["Priority"] = work["_t3"].map(
278
+ lambda t: (
279
+ "Urgent Action"
280
+ if t == "Degrading"
281
+ else ("Monitor" if t == "Improving" else "Watchlist")
282
+ )
283
+ )
284
+ return out
285
+
286
+
287
+ def build_site_master_table(
288
+ df: pd.DataFrame,
289
+ *,
290
+ site_col: str | None = None,
291
+ group_col: str | None = None,
292
+ status_col: str | None = None,
293
+ indicator_col: str | None = None,
294
+ band_col: str | None = None,
295
+ trend_col: str | None = None,
296
+ config: str | Path | Config | None = None,
297
+ ) -> pd.DataFrame:
298
+ """Build a compact Site × Indicator master appendix table combining State and Trend.
299
+
300
+ Each indicator cell displays the State grade (e.g., ``B`` or ``Pass``), and when
301
+ ``trend_col`` is present, appends a directional arrow (e.g., ``B (↗)``, ``D (↘)``).
302
+
303
+ Returns:
304
+ Wide appendix ``pd.DataFrame`` with one row per site.
305
+ """
306
+ cfg = ensure_config(config)
307
+ r_site = resolve_column(site_col, cfg, "site_id")
308
+ r_ind = resolve_column(indicator_col, cfg, "indicator")
309
+ r_band = resolve_column(band_col, cfg, "state_band")
310
+ validate_columns(df, [r_site, r_ind, r_band], context="build_site_master_table")
311
+
312
+ r_group = group_col if group_col is not None else cfg.columns.get("zone")
313
+ if r_group not in df.columns and cfg.columns.get("fmu") in df.columns:
314
+ r_group = cfg.columns["fmu"]
315
+ r_status = status_col if status_col is not None else cfg.columns.get("site_status")
316
+ r_trend = trend_col if trend_col is not None else cfg.columns.get("trend_direction")
317
+
318
+ sym_map = {"Improving": "↗", "Indeterminate": "→", "Degrading": "↘"}
319
+ work = df.copy()
320
+ work["_ind"] = work[r_ind].astype(str).map(lambda i: resolve_label(i, cfg))
321
+ if r_trend and r_trend in work.columns:
322
+ work["_cell"] = [
323
+ f"{b} ({sym_map[str(t)]})" if str(t) in sym_map else str(b)
324
+ for b, t in zip(work[r_band], work[r_trend], strict=True)
325
+ ]
326
+ else:
327
+ work["_cell"] = work[r_band].astype(str)
328
+
329
+ piv = work.pivot_table(index=r_site, columns="_ind", values="_cell", aggfunc="first").fillna(
330
+ "—"
331
+ )
332
+ meta_cols = [r_site]
333
+ if r_group and r_group in work.columns:
334
+ meta_cols.append(r_group)
335
+ if r_status and r_status in work.columns:
336
+ meta_cols.append(r_status)
337
+
338
+ meta = work[meta_cols].drop_duplicates(subset=[r_site]).set_index(r_site)
339
+ if r_group and r_group in meta.columns:
340
+ meta[r_group] = (
341
+ meta[r_group].fillna("Unassigned").astype(str).map(lambda g: resolve_label(g, cfg))
342
+ )
343
+ meta = meta.rename(columns={r_group: "FMU"})
344
+ if r_status and r_status in meta.columns:
345
+ meta = meta.rename(columns={r_status: "Site Group"})
346
+
347
+ out = meta.join(piv, how="right").reset_index().rename(columns={r_site: "Site"})
348
+ if "FMU" in out.columns:
349
+ out = out.sort_values(by=["FMU", "Site"], kind="stable").reset_index(drop=True)
350
+ return out
351
+
352
+
353
+ def build_grade_change_table(
354
+ df: pd.DataFrame,
355
+ *,
356
+ from_period: str,
357
+ to_period: str,
358
+ group_col: str | None = None,
359
+ site_col: str | None = None,
360
+ period_col: str | None = None,
361
+ band_col: str | None = None,
362
+ indicator_col: str | None = None,
363
+ band_order: list[str] | None = None,
364
+ total_label: str = "Whole Region",
365
+ config: str | Path | Config | None = None,
366
+ ) -> pd.DataFrame:
367
+ """Build a period-to-period grade shift summary table (Improved / Same / Degraded / Net).
368
+
369
+ Compares ``from_period`` against ``to_period`` for matched sites (or site-indicators),
370
+ counting how many improved by >= 1 band, stayed unchanged, or degraded by >= 1 band.
371
+
372
+ Returns:
373
+ Summary ``pd.DataFrame`` per group plus a ``Whole Region`` total row.
374
+ """
375
+ from stplot.config import resolve_category_order
376
+
377
+ cfg = ensure_config(config)
378
+ r_site = resolve_column(site_col, cfg, "site_id")
379
+ r_period = resolve_column(period_col, cfg, "period")
380
+ r_band = resolve_column(band_col, cfg, "state_band")
381
+ validate_columns(df, [r_site, r_period, r_band], context="build_grade_change_table")
382
+
383
+ r_group = group_col if group_col is not None else cfg.columns.get("zone")
384
+ if r_group not in df.columns and cfg.columns.get("fmu") in df.columns:
385
+ r_group = cfg.columns["fmu"]
386
+ r_ind = indicator_col if indicator_col is not None else cfg.columns.get("indicator")
387
+
388
+ order = resolve_category_order(band_order, cfg, "state_bands")
389
+ rank_map = {b: i for i, b in enumerate(order) if b != "Not assessed"}
390
+
391
+ work = df.copy()
392
+ work["_p"] = work[r_period].astype(str)
393
+ key_cols = [r_site]
394
+ if r_ind and r_ind in work.columns:
395
+ key_cols.append(r_ind)
396
+ if r_group and r_group in work.columns:
397
+ key_cols.append(r_group)
398
+
399
+ df_from = work[work["_p"] == str(from_period)][[*key_cols, r_band]].rename(
400
+ columns={r_band: "_b0"}
401
+ )
402
+ df_to = work[work["_p"] == str(to_period)][[*key_cols, r_band]].rename(columns={r_band: "_b1"})
403
+ merged = pd.merge(df_from, df_to, on=key_cols, how="inner")
404
+ merged["_r0"] = merged["_b0"].astype(str).map(rank_map)
405
+ merged["_r1"] = merged["_b1"].astype(str).map(rank_map)
406
+ merged = merged.dropna(subset=["_r0", "_r1"]).copy()
407
+
408
+ # Lower index = better band (A=0, B=1, C=2, D=3, E=4)
409
+ merged["_shift"] = merged["_r0"] - merged["_r1"] # >0 = improved, <0 = degraded
410
+
411
+ def _row_summary(label: str, sub: pd.DataFrame) -> dict[str, object]:
412
+ n = len(sub)
413
+ n_imp = int((sub["_shift"] > 0).sum())
414
+ n_same = int((sub["_shift"] == 0).sum())
415
+ n_deg = int((sub["_shift"] < 0).sum())
416
+ net = n_imp - n_deg
417
+ return {
418
+ "Group": resolve_label(label, cfg) if label != total_label else total_label,
419
+ "Matched (n)": n,
420
+ "Improved ≥1 Band": f"{n_imp} ({100.0 * n_imp / n:.0f}%)" if n else "0",
421
+ "No Change": f"{n_same} ({100.0 * n_same / n:.0f}%)" if n else "0",
422
+ "Degraded ≥1 Band": f"{n_deg} ({100.0 * n_deg / n:.0f}%)" if n else "0",
423
+ "Net Shift": f"{net:+d}",
424
+ }
425
+
426
+ rows: list[dict[str, object]] = []
427
+ if r_group and r_group in merged.columns:
428
+ for grp, sub in merged.groupby(r_group, sort=False):
429
+ rows.append(_row_summary(str(grp), sub))
430
+ rows.append(_row_summary(total_label, merged))
431
+ return pd.DataFrame(rows)
432
+
433
+
434
+ def build_top_movers_table(
435
+ df: pd.DataFrame,
436
+ *,
437
+ n: int = 5,
438
+ site_col: str | None = None,
439
+ group_col: str | None = None,
440
+ indicator_col: str | None = None,
441
+ indicator: str | None = None,
442
+ band_col: str | None = None,
443
+ slope_col: str | None = None,
444
+ confidence_col: str | None = None,
445
+ lower_is_better: bool | None = None,
446
+ indicator_directions: dict[str, str] | None = None,
447
+ config: str | Path | Config | None = None,
448
+ ) -> pd.DataFrame:
449
+ """Build a leaderboard table of the top ``n`` fastest-improving and top ``n`` degrading sites.
450
+
451
+ Automatically respects ``config.indicator_directions`` polarity (so positive ``%/yr`` is
452
+ improving for Clarity/MCI, while negative ``%/yr`` is improving for DRP/E. coli).
453
+
454
+ Returns:
455
+ DataFrame with ``Category`` (``"Top Improving"`` / ``"Top Degrading"``), site, FMU,
456
+ grade, ``%/yr`` slope, and optional trend confidence.
457
+ """
458
+ from stplot.config import is_lower_better
459
+
460
+ cfg = ensure_config(config)
461
+ r_site = resolve_column(site_col, cfg, "site_id")
462
+ r_slope = resolve_column(slope_col, cfg, "pct_annual_change")
463
+ validate_columns(df, [r_site, r_slope], context="build_top_movers_table")
464
+
465
+ r_group = group_col if group_col is not None else cfg.columns.get("zone")
466
+ if r_group not in df.columns and cfg.columns.get("fmu") in df.columns:
467
+ r_group = cfg.columns["fmu"]
468
+ r_ind = indicator_col if indicator_col is not None else cfg.columns.get("indicator")
469
+ r_band = band_col if band_col is not None else cfg.columns.get("state_band")
470
+ r_conf = confidence_col if confidence_col is not None else cfg.columns.get("trend_confidence")
471
+
472
+ work = df.copy()
473
+ work["_slope"] = pd.to_numeric(work[r_slope], errors="coerce")
474
+ work = work.dropna(subset=["_slope"]).reset_index(drop=True)
475
+ if work.empty:
476
+ return pd.DataFrame(columns=["Category", "Site", "%/yr"])
477
+
478
+ inferred_ind = indicator
479
+ if inferred_ind is None and r_ind and r_ind in work.columns:
480
+ uniq = work[r_ind].dropna().astype(str).unique()
481
+ if len(uniq) == 1:
482
+ inferred_ind = str(uniq[0])
483
+
484
+ low_good = is_lower_better(
485
+ inferred_ind,
486
+ cfg,
487
+ lower_is_better=lower_is_better,
488
+ overrides=indicator_directions,
489
+ default=True,
490
+ )
491
+ # Improvement score: positive = improving regardless of indicator polarity
492
+ work["_imp_score"] = -work["_slope"] if low_good else work["_slope"]
493
+
494
+ top_imp = work[work["_imp_score"] > 0].nlargest(n, "_imp_score").copy()
495
+ top_imp["_cat"] = "Top Improving"
496
+ top_deg = work[work["_imp_score"] < 0].nsmallest(n, "_imp_score").copy()
497
+ top_deg["_cat"] = "Top Degrading"
498
+
499
+ combined = pd.concat([top_imp, top_deg], ignore_index=True)
500
+ out = pd.DataFrame({"Category": combined["_cat"], "Site": combined[r_site].astype(str)})
501
+ if r_group and r_group in combined.columns:
502
+ out["FMU"] = (
503
+ combined[r_group].fillna("Unassigned").astype(str).map(lambda g: resolve_label(g, cfg))
504
+ )
505
+ if r_band and r_band in combined.columns:
506
+ out["State"] = combined[r_band].astype(str)
507
+ out["%/yr"] = combined["_slope"].map(lambda v: f"{v:+.1f}%")
508
+ if r_conf and r_conf in combined.columns:
509
+ out["Confidence"] = combined[r_conf].astype(str)
510
+ return out
511
+
512
+
513
+ def select_top_bottom_sites(
514
+ df: pd.DataFrame,
515
+ *,
516
+ n: int = 5,
517
+ value_col: str | None = None,
518
+ indicator_col: str | None = None,
519
+ indicator: str | None = None,
520
+ lower_is_better: bool | None = None,
521
+ indicator_directions: dict[str, str] | None = None,
522
+ group_label_col: str = "RankGroup",
523
+ config: str | Path | Config | None = None,
524
+ ) -> pd.DataFrame:
525
+ """Select the Best ``n`` and Worst ``n`` sites from a regional or FMU DataFrame.
526
+
527
+ Automatically resolves indicator polarity via ``config.indicator_directions`` (so lowest
528
+ values are Best for DRP/E. coli, while highest values are Best for Clarity/MCI) and
529
+ adds a ``RankGroup`` column (``"Top N (Best)"`` / ``"Bottom N (Worst)"``).
530
+
531
+ Returns:
532
+ Non-mutated DataFrame containing up to ``2 * n`` sites sorted from best to worst.
533
+ """
534
+ from stplot.config import is_lower_better
535
+
536
+ cfg = ensure_config(config)
537
+ r_val = resolve_column(value_col, cfg, "state_value")
538
+ validate_columns(df, [r_val], context="select_top_bottom_sites")
539
+
540
+ r_ind = indicator_col if indicator_col is not None else cfg.columns.get("indicator")
541
+ work = df.copy()
542
+ work["_v"] = pd.to_numeric(work[r_val], errors="coerce")
543
+ work = work.dropna(subset=["_v"]).reset_index(drop=True)
544
+ if work.empty:
545
+ work[group_label_col] = pd.Series(dtype=str)
546
+ return work.drop(columns=["_v"])
547
+
548
+ inferred_ind = indicator
549
+ if inferred_ind is None and r_ind and r_ind in work.columns:
550
+ uniq = work[r_ind].dropna().astype(str).unique()
551
+ if len(uniq) == 1:
552
+ inferred_ind = str(uniq[0])
553
+
554
+ low_good = is_lower_better(
555
+ inferred_ind,
556
+ cfg,
557
+ lower_is_better=lower_is_better,
558
+ overrides=indicator_directions,
559
+ default=True,
560
+ )
561
+ ordered = work.sort_values(by="_v", ascending=low_good, kind="stable").reset_index(drop=True)
562
+ if len(ordered) <= 2 * n:
563
+ mid = len(ordered) // 2
564
+ best = ordered.iloc[:mid].copy()
565
+ worst = ordered.iloc[mid:].copy()
566
+ else:
567
+ best = ordered.head(n).copy()
568
+ worst = ordered.tail(n).copy()
569
+
570
+ best[group_label_col] = f"Top {len(best)} (Best)"
571
+ worst[group_label_col] = f"Bottom {len(worst)} (Worst)"
572
+ out = pd.concat([best, worst], ignore_index=True).drop(columns=["_v"])
573
+ return out