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,154 @@
1
+ """Upstream/Downstream site pairing helper for discharge impact plots."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+
10
+ from stplot.config import Config, ensure_config, resolve_column
11
+ from stplot.io.tabular import read_results
12
+ from stplot.transform.columns import validate_columns
13
+
14
+ _US_PATTERN = re.compile(r"\bu/s\b|\bupstream\b", flags=re.IGNORECASE)
15
+ _DS_PATTERN = re.compile(r"\bd/s\b|\bdownstream\b", flags=re.IGNORECASE)
16
+
17
+
18
+ def _extract_discharge_name(site_name: str) -> tuple[str | None, str | None]:
19
+ """Return ``(role, discharge_label)`` if ``site_name`` matches u/s or d/s naming."""
20
+ if _US_PATTERN.search(site_name):
21
+ cleaned = _US_PATTERN.sub("", site_name)
22
+ role = "upstream"
23
+ elif _DS_PATTERN.search(site_name):
24
+ cleaned = _DS_PATTERN.sub("", site_name)
25
+ role = "downstream"
26
+ else:
27
+ return None, None
28
+
29
+ # Extract text after "at" (e.g., "Mangaatua at u/s Woodville STP" -> "Woodville STP")
30
+ parts = re.split(r"\bat\b", cleaned, maxsplit=1, flags=re.IGNORECASE)
31
+ label = parts[-1].strip(" -–—")
32
+ label = re.sub(r"\s+", " ", label)
33
+ return role, label or site_name
34
+
35
+
36
+ def pair_upstream_downstream(
37
+ df: pd.DataFrame,
38
+ pairs: pd.DataFrame | str | Path | None = None,
39
+ *,
40
+ site_col: str | None = None,
41
+ value_col: str | None = None,
42
+ grade_col: str | None = None,
43
+ period_col: str | None = None,
44
+ group_col: str | None = None,
45
+ pair_label_col: str = "DischargeSite",
46
+ pair_upstream_col: str = "UpstreamSite",
47
+ pair_downstream_col: str = "DownstreamSite",
48
+ config: str | Path | Config | None = None,
49
+ ) -> pd.DataFrame:
50
+ """Pair long-format upstream and downstream records into wide comparison format.
51
+
52
+ Produces a DataFrame with ``DischargeSite``, ``UpstreamValue``, ``DownstreamValue``,
53
+ and (when available) ``UpstreamGrade``, ``DownstreamGrade``, ``period_col``, and
54
+ ``group_col`` — ready to pass directly to
55
+ :func:`stplot.plots.upstream_downstream_comparison` or
56
+ :func:`stplot.plots.upstream_downstream_timeseries`.
57
+
58
+ Args:
59
+ df: Long-format results DataFrame (not mutated).
60
+ pairs: Optional lookup DataFrame or CSV/Excel path specifying explicit pairs via
61
+ ``pair_label_col``, ``pair_upstream_col``, and ``pair_downstream_col`` (plus any
62
+ extra columns such as ``District``). If omitted, pairs are inferred automatically
63
+ from ``u/s`` and ``d/s`` patterns in ``site_col``.
64
+ site_col: Site ID column in ``df`` (defaults to ``config.columns["site_id"]``).
65
+ value_col: Numeric value column in ``df`` (defaults to ``config.columns["state_value"]``).
66
+ grade_col: Optional NOF grade column (defaults to ``config.columns["state_band"]``
67
+ if present).
68
+ period_col: Optional rolling-period column to preserve for time-series pairing.
69
+ group_col: Optional district/FMU column to carry through from ``df`` or ``pairs``.
70
+ pair_label_col: Discharge label column name in ``pairs`` and output.
71
+ pair_upstream_col: Upstream site column name in ``pairs``.
72
+ pair_downstream_col: Downstream site column name in ``pairs``.
73
+ config: Optional Config object, preset name, or path to YAML/TOML config.
74
+
75
+ Returns:
76
+ Paired wide DataFrame.
77
+ """
78
+ cfg = ensure_config(config)
79
+ resolved_site = resolve_column(site_col, cfg, "site_id")
80
+ resolved_val = resolve_column(value_col, cfg, "state_value")
81
+ validate_columns(df, [resolved_site, resolved_val], context="pair_upstream_downstream")
82
+
83
+ resolved_grade = grade_col if grade_col is not None else cfg.columns.get("state_band")
84
+ has_grade = bool(resolved_grade and resolved_grade in df.columns)
85
+ has_period = bool(period_col and period_col in df.columns)
86
+
87
+ key_cols = [period_col] if has_period and period_col else []
88
+
89
+ if pairs is not None:
90
+ pairs_df = read_results(pairs) if isinstance(pairs, (str, Path)) else pairs.copy()
91
+ validate_columns(
92
+ pairs_df,
93
+ [pair_label_col, pair_upstream_col, pair_downstream_col],
94
+ context="pair_upstream_downstream(pairs)",
95
+ )
96
+ us_cols = [resolved_site, resolved_val, *key_cols]
97
+ ds_cols = [resolved_site, resolved_val, *key_cols]
98
+ if has_grade and resolved_grade:
99
+ us_cols.append(resolved_grade)
100
+ ds_cols.append(resolved_grade)
101
+
102
+ us_sub = df[us_cols].rename(
103
+ columns={
104
+ resolved_site: pair_upstream_col,
105
+ resolved_val: "UpstreamValue",
106
+ **({resolved_grade: "UpstreamGrade"} if has_grade and resolved_grade else {}),
107
+ }
108
+ )
109
+ ds_sub = df[ds_cols].rename(
110
+ columns={
111
+ resolved_site: pair_downstream_col,
112
+ resolved_val: "DownstreamValue",
113
+ **({resolved_grade: "DownstreamGrade"} if has_grade and resolved_grade else {}),
114
+ }
115
+ )
116
+
117
+ merged = pairs_df.merge(us_sub, on=pair_upstream_col, how="left")
118
+ merge_keys = [pair_downstream_col, *key_cols]
119
+ merged = merged.merge(ds_sub, on=merge_keys, how="left")
120
+ return merged
121
+
122
+ # Automatic pairing via u/s and d/s naming in site_col
123
+ work = df.copy()
124
+ parsed = work[resolved_site].astype(str).map(_extract_discharge_name)
125
+ work["_role"] = [r for r, _ in parsed]
126
+ work[pair_label_col] = [lbl for _, lbl in parsed]
127
+ work = work[work["_role"].notna()].copy()
128
+
129
+ us = work[work["_role"] == "upstream"].copy()
130
+ ds = work[work["_role"] == "downstream"].copy()
131
+
132
+ join_keys = [pair_label_col, *key_cols]
133
+ us_keep = [*join_keys, resolved_val]
134
+ ds_keep = [*join_keys, resolved_val]
135
+ if has_grade and resolved_grade:
136
+ us_keep.append(resolved_grade)
137
+ ds_keep.append(resolved_grade)
138
+ if group_col and group_col in work.columns:
139
+ us_keep.append(group_col)
140
+
141
+ us_renamed = us[us_keep].rename(
142
+ columns={
143
+ resolved_val: "UpstreamValue",
144
+ **({resolved_grade: "UpstreamGrade"} if has_grade and resolved_grade else {}),
145
+ }
146
+ )
147
+ ds_renamed = ds[ds_keep].rename(
148
+ columns={
149
+ resolved_val: "DownstreamValue",
150
+ **({resolved_grade: "DownstreamGrade"} if has_grade and resolved_grade else {}),
151
+ }
152
+ )
153
+
154
+ return us_renamed.merge(ds_renamed, on=join_keys, how="outer")
stplot/transform/qa.py ADDED
@@ -0,0 +1,297 @@
1
+ """Pre-flight data QA auditing and Full vs Preliminary results splitting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import pandas as pd
10
+
11
+ from stplot.config import Config, ensure_config, resolve_column
12
+
13
+ _DEFAULT_OK_VALUES = {"TRUE", "T", "1", "OK", "YES", "PASS", "VALID"}
14
+
15
+
16
+ def _is_ok_mask(
17
+ series: pd.Series, ok_values: tuple[Any, ...] | list[Any] | None = None
18
+ ) -> pd.Series:
19
+ """Return boolean mask identifying full/sufficient records (FilterOK=True or nOK='OK')."""
20
+ if ok_values is not None:
21
+ ok_set = {str(v).strip().upper() for v in ok_values}
22
+ return series.notna() & series.astype(str).str.strip().str.upper().isin(ok_set)
23
+
24
+ if pd.api.types.is_bool_dtype(series):
25
+ return series.fillna(False).astype(bool)
26
+
27
+ return series.notna() & series.astype(str).str.strip().str.upper().isin(_DEFAULT_OK_VALUES)
28
+
29
+
30
+ def split_full_and_preliminary(
31
+ df: pd.DataFrame,
32
+ *,
33
+ filter_col: str | None = None,
34
+ ok_values: tuple[Any, ...] | list[Any] | None = None,
35
+ config: str | Path | Config | None = None,
36
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
37
+ """Split a results DataFrame into ``(full_df, preliminary_df)`` by data sufficiency.
38
+
39
+ Supports both NZ NPS-FM (``FilterOK`` boolean/string) and Horizons One Plan
40
+ (``nOK == "OK"`` vs ``"Insufficient data"`` / ``"Insufficient FLOW data"``), without
41
+ silently dropping preliminary records.
42
+
43
+ Args:
44
+ df: Input results DataFrame (not mutated).
45
+ filter_col: Column indicating data sufficiency (defaults to
46
+ ``config.columns["filter_ok"]``).
47
+ ok_values: Optional explicit collection of values treated as full/sufficient.
48
+ config: Optional Config object, preset name, or path to YAML/TOML config.
49
+
50
+ Returns:
51
+ Tuple of ``(full_df, preliminary_df)`` copies.
52
+
53
+ Raises:
54
+ KeyError: If the resolved ``filter_col`` is not present in ``df``.
55
+ """
56
+ cfg = ensure_config(config)
57
+ r_filter = resolve_column(filter_col, cfg, "filter_ok")
58
+ if r_filter not in df.columns:
59
+ available = ", ".join(map(str, df.columns))
60
+ raise KeyError(
61
+ f"split_full_and_preliminary: Data-sufficiency column '{r_filter}' not found. "
62
+ f"Available columns: [{available}]."
63
+ )
64
+
65
+ mask = _is_ok_mask(df[r_filter], ok_values=ok_values)
66
+ full_df = df.loc[mask].copy().reset_index(drop=True)
67
+ prelim_df = df.loc[~mask].copy().reset_index(drop=True)
68
+ return full_df, prelim_df
69
+
70
+
71
+ @dataclass
72
+ class AuditReport:
73
+ """Structured pre-flight QA audit report for a state or trends results DataFrame."""
74
+
75
+ n_rows: int
76
+ n_cols: int
77
+ config_name: str
78
+ missing_columns: list[str] = field(default_factory=list)
79
+ filter_col: str | None = None
80
+ n_full: int = 0
81
+ n_preliminary: int = 0
82
+ pct_full: float = 100.0
83
+ preliminary_reasons: dict[str, int] = field(default_factory=dict)
84
+ n_duplicates: int = 0
85
+ duplicate_key_cols: list[str] = field(default_factory=list)
86
+ n_unassigned_zones: int = 0
87
+ n_missing_coords: int = 0
88
+ unmapped_labels: list[str] = field(default_factory=list)
89
+ unmapped_directions: list[str] = field(default_factory=list)
90
+ warnings: list[str] = field(default_factory=list)
91
+
92
+ @property
93
+ def has_warnings(self) -> bool:
94
+ """Return True if any QA warnings were recorded."""
95
+ return len(self.warnings) > 0
96
+
97
+ def to_dict(self) -> dict[str, Any]:
98
+ """Serialize the audit report to a plain dictionary."""
99
+ return {
100
+ "n_rows": self.n_rows,
101
+ "n_cols": self.n_cols,
102
+ "config_name": self.config_name,
103
+ "missing_columns": list(self.missing_columns),
104
+ "filter_col": self.filter_col,
105
+ "n_full": self.n_full,
106
+ "n_preliminary": self.n_preliminary,
107
+ "pct_full": round(self.pct_full, 1),
108
+ "preliminary_reasons": dict(self.preliminary_reasons),
109
+ "n_duplicates": self.n_duplicates,
110
+ "duplicate_key_cols": list(self.duplicate_key_cols),
111
+ "n_unassigned_zones": self.n_unassigned_zones,
112
+ "n_missing_coords": self.n_missing_coords,
113
+ "unmapped_labels": list(self.unmapped_labels),
114
+ "unmapped_directions": list(self.unmapped_directions),
115
+ "warnings": list(self.warnings),
116
+ }
117
+
118
+ def to_dataframe(self) -> pd.DataFrame:
119
+ """Return a concise 2-column QA summary DataFrame suitable for tables/HTML."""
120
+ rows = [
121
+ ("Total Rows", f"{self.n_rows:,}"),
122
+ ("Config Preset", self.config_name),
123
+ (
124
+ "Full Results (OK)",
125
+ f"{self.n_full:,} ({self.pct_full:.1f}%)" if self.filter_col else "Not checked",
126
+ ),
127
+ (
128
+ "Preliminary / Insufficient",
129
+ f"{self.n_preliminary:,}" if self.filter_col else "Not checked",
130
+ ),
131
+ ("Duplicate Key Rows", f"{self.n_duplicates:,}"),
132
+ ("Unassigned / Missing FMUs", f"{self.n_unassigned_zones:,}"),
133
+ ("Missing Coordinates (X/Y)", f"{self.n_missing_coords:,}"),
134
+ (
135
+ "Unmapped Indicator Labels",
136
+ ", ".join(self.unmapped_labels) if self.unmapped_labels else "None",
137
+ ),
138
+ (
139
+ "Unmapped Indicator Directions",
140
+ ", ".join(self.unmapped_directions) if self.unmapped_directions else "None",
141
+ ),
142
+ ]
143
+ return pd.DataFrame(rows, columns=["Check", "Result"])
144
+
145
+ def summary_text(self) -> str:
146
+ """Return a human-readable multi-line QA summary."""
147
+ lines = [
148
+ f"stplot Pre-Flight QA Audit ({self.config_name}): "
149
+ f"{self.n_rows:,} rows × {self.n_cols} cols",
150
+ ]
151
+ if self.filter_col:
152
+ lines.append(
153
+ f" • Data sufficiency ({self.filter_col}): "
154
+ f"{self.n_full:,} Full ({self.pct_full:.1f}%) | "
155
+ f"{self.n_preliminary:,} Preliminary"
156
+ )
157
+ if self.preliminary_reasons:
158
+ breakdown = ", ".join(f"{k}: {v}" for k, v in self.preliminary_reasons.items())
159
+ lines.append(f" Breakdown: {breakdown}")
160
+ if self.warnings:
161
+ lines.append(" • Warnings:")
162
+ for w in self.warnings:
163
+ lines.append(f" - {w}")
164
+ else:
165
+ lines.append(" • Status: All checks passed with no warnings.")
166
+ return "\n".join(lines)
167
+
168
+
169
+ def audit_results_data(
170
+ df: pd.DataFrame,
171
+ *,
172
+ required_keys: list[str] | tuple[str, ...] | None = None,
173
+ site_col: str | None = None,
174
+ indicator_col: str | None = None,
175
+ period_col: str | None = None,
176
+ zone_col: str | None = None,
177
+ filter_col: str | None = None,
178
+ x_col: str | None = None,
179
+ y_col: str | None = None,
180
+ ok_values: tuple[Any, ...] | list[Any] | None = None,
181
+ config: str | Path | Config | None = None,
182
+ ) -> AuditReport:
183
+ """Run a non-mutating pre-flight QA audit on a state or trends results DataFrame.
184
+
185
+ Checks schema completeness, Full vs Preliminary data sufficiency (``FilterOK`` / ``nOK``),
186
+ duplicate `(site, indicator, period)` rows, unassigned FMUs/zones, missing coordinates,
187
+ and indicator codes missing from ``config.labels`` or ``config.indicator_directions``.
188
+
189
+ Returns:
190
+ An :class:`AuditReport` instance with ``.summary_text()``, ``.to_dataframe()``,
191
+ and ``.to_dict()``.
192
+ """
193
+ cfg = ensure_config(config)
194
+ warnings: list[str] = []
195
+
196
+ def _opt_col(override: str | None, key: str) -> str | None:
197
+ if override is not None:
198
+ return override
199
+ return cfg.columns.get(key)
200
+
201
+ r_site = _opt_col(site_col, "site_id")
202
+ r_ind = _opt_col(indicator_col, "indicator")
203
+ r_period = _opt_col(period_col, "period")
204
+ r_zone = _opt_col(zone_col, "zone")
205
+ r_filter = _opt_col(filter_col, "filter_ok")
206
+ r_x = _opt_col(x_col, "x")
207
+ r_y = _opt_col(y_col, "y")
208
+
209
+ # 1. Missing required columns
210
+ missing_cols: list[str] = []
211
+ if required_keys:
212
+ for k in required_keys:
213
+ col_name = cfg.columns.get(k, k)
214
+ if col_name not in df.columns:
215
+ missing_cols.append(col_name)
216
+ if missing_cols:
217
+ warnings.append(f"Missing expected column(s): {missing_cols}")
218
+
219
+ # 2. Full vs Preliminary split
220
+ n_rows = len(df)
221
+ n_full = n_rows
222
+ n_prelim = 0
223
+ pct_full = 100.0 if n_rows > 0 else 0.0
224
+ prelim_reasons: dict[str, int] = {}
225
+ used_filter: str | None = None
226
+
227
+ if r_filter and r_filter in df.columns:
228
+ used_filter = r_filter
229
+ mask = _is_ok_mask(df[r_filter], ok_values=ok_values)
230
+ n_full = int(mask.sum())
231
+ n_prelim = int((~mask).sum())
232
+ pct_full = (100.0 * n_full / n_rows) if n_rows > 0 else 0.0
233
+ if n_prelim > 0:
234
+ raw_non_ok = df.loc[~mask, r_filter].fillna("<NaN>").astype(str)
235
+ prelim_reasons = {str(k): int(v) for k, v in raw_non_ok.value_counts().items()}
236
+ warnings.append(
237
+ f"{n_prelim:,} preliminary/insufficient row(s) found in '{r_filter}' "
238
+ f"({100.0 - pct_full:.1f}%). Use split_full_and_preliminary() before plotting."
239
+ )
240
+
241
+ # 3. Duplicate key rows
242
+ dup_keys = [c for c in (r_site, r_ind, r_period) if c and c in df.columns]
243
+ n_dups = int(df.duplicated(subset=dup_keys, keep=False).sum()) if len(dup_keys) >= 2 else 0
244
+ if n_dups > 0:
245
+ warnings.append(f"{n_dups:,} duplicate row(s) detected on {dup_keys}.")
246
+
247
+ # 4. Unassigned / missing zones (check zone, falling back to fmu)
248
+ n_unassigned = 0
249
+ zone_target = r_zone if (r_zone and r_zone in df.columns) else cfg.columns.get("fmu")
250
+ if zone_target and zone_target in df.columns:
251
+ z_str = df[zone_target].fillna("").astype(str).str.strip().str.lower()
252
+ n_unassigned = int(z_str.isin({"", "unassigned", "nan", "none"}).sum())
253
+ if n_unassigned > 0:
254
+ warnings.append(f"{n_unassigned:,} row(s) have missing or unassigned '{zone_target}'.")
255
+
256
+ # 5. Missing coordinates
257
+ n_missing_coords = 0
258
+ if r_x and r_y and r_x in df.columns and r_y in df.columns:
259
+ x_num = pd.to_numeric(df[r_x], errors="coerce")
260
+ y_num = pd.to_numeric(df[r_y], errors="coerce")
261
+ n_missing_coords = int((x_num.isna() | y_num.isna()).sum())
262
+ if n_missing_coords > 0:
263
+ warnings.append(f"{n_missing_coords:,} row(s) are missing numeric '{r_x}'/'{r_y}'.")
264
+
265
+ # 6. Unmapped indicators (labels & directions)
266
+ unmapped_labels: list[str] = []
267
+ unmapped_dirs: list[str] = []
268
+ if r_ind and r_ind in df.columns:
269
+ inds = sorted(df[r_ind].dropna().astype(str).unique().tolist())
270
+ lbl_keys = {k.lower() for k in cfg.labels}
271
+ dir_keys = {k.lower() for k in cfg.indicator_directions}
272
+ unmapped_labels = [i for i in inds if i.lower() not in lbl_keys]
273
+ unmapped_dirs = [i for i in inds if i.lower() not in dir_keys]
274
+ if unmapped_dirs:
275
+ warnings.append(
276
+ f"Indicator(s) not in config.indicator_directions (defaulting to lower_is_better): "
277
+ f"{unmapped_dirs}"
278
+ )
279
+
280
+ return AuditReport(
281
+ n_rows=n_rows,
282
+ n_cols=len(df.columns),
283
+ config_name=cfg.name,
284
+ missing_columns=missing_cols,
285
+ filter_col=used_filter,
286
+ n_full=n_full,
287
+ n_preliminary=n_prelim,
288
+ pct_full=pct_full,
289
+ preliminary_reasons=prelim_reasons,
290
+ n_duplicates=n_dups,
291
+ duplicate_key_cols=dup_keys,
292
+ n_unassigned_zones=n_unassigned,
293
+ n_missing_coords=n_missing_coords,
294
+ unmapped_labels=unmapped_labels,
295
+ unmapped_directions=unmapped_dirs,
296
+ warnings=warnings,
297
+ )