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,354 @@
1
+ """Management zone assignment and site grouping helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ import pandas as pd
10
+
11
+ from stplot.config import Config, ensure_config, resolve_column
12
+ from stplot.io.spatial import read_spatial
13
+ from stplot.io.tabular import read_results
14
+ from stplot.transform.columns import validate_columns
15
+
16
+
17
+ def assign_zones(
18
+ df: pd.DataFrame,
19
+ lookup: pd.DataFrame | str | Path,
20
+ *,
21
+ site_col: str | None = None,
22
+ zone_col: str | None = None,
23
+ lookup_site_col: str | None = None,
24
+ lookup_zone_col: str | None = None,
25
+ unmatched: str = "Unassigned",
26
+ on_missing: Literal["keep", "warn", "raise"] = "keep",
27
+ config: str | Path | Config | None = None,
28
+ ) -> pd.DataFrame:
29
+ """Assign sites in ``df`` to management zones using a lookup table.
30
+
31
+ Args:
32
+ df: Results DataFrame containing a site identifier column (not mutated).
33
+ lookup: Lookup DataFrame or path to a tabular file mapping sites to zones.
34
+ site_col: Site ID column in ``df``. Defaults to ``config.columns["site_id"]``.
35
+ zone_col: Output zone column name in the returned DataFrame. Defaults to
36
+ ``config.columns["zone"]``.
37
+ lookup_site_col: Site ID column in ``lookup``. Defaults to ``site_col``.
38
+ lookup_zone_col: Zone column in ``lookup``. Defaults to ``zone_col``.
39
+ unmatched: Label assigned to sites not found in ``lookup`` when
40
+ ``on_missing`` is ``"keep"`` or ``"warn"``.
41
+ on_missing: Behavior when sites in ``df`` have no match in ``lookup``:
42
+ - ``"keep"``: Fill unmatched records with ``unmatched``.
43
+ - ``"warn"``: Emit a ``UserWarning`` and fill with ``unmatched``.
44
+ - ``"raise"``: Raise a ``ValueError`` listing the unmatched site IDs.
45
+ config: Optional Config object, preset name, or path to YAML/TOML config.
46
+
47
+ Returns:
48
+ Copy of ``df`` with the ``zone_col`` column populated.
49
+
50
+ Raises:
51
+ KeyError: If required site or zone columns are missing.
52
+ ValueError: If ``on_missing="raise"`` and unmatched sites are found, or if
53
+ ``on_missing`` is invalid.
54
+ """
55
+ if on_missing not in {"keep", "warn", "raise"}:
56
+ raise ValueError(
57
+ f"Invalid on_missing='{on_missing}'. Expected one of: 'keep', 'warn', 'raise'."
58
+ )
59
+
60
+ cfg = ensure_config(config)
61
+ df_site = resolve_column(site_col, cfg, "site_id")
62
+ out_zone = resolve_column(zone_col, cfg, "zone")
63
+ lk_site = lookup_site_col if lookup_site_col is not None else df_site
64
+ lk_zone = lookup_zone_col if lookup_zone_col is not None else out_zone
65
+
66
+ lookup_df = read_results(lookup) if isinstance(lookup, (str, Path)) else lookup
67
+
68
+ validate_columns(df, [df_site], context="assign_zones(df)")
69
+ validate_columns(lookup_df, [lk_site, lk_zone], context="assign_zones(lookup)")
70
+
71
+ zone_map = (
72
+ lookup_df[[lk_site, lk_zone]]
73
+ .drop_duplicates(subset=[lk_site], keep="first")
74
+ .set_index(lk_site)[lk_zone]
75
+ )
76
+
77
+ out = df.copy()
78
+ mapped = out[df_site].map(zone_map)
79
+ missing_mask = mapped.isna()
80
+
81
+ if missing_mask.any():
82
+ missing_sites = sorted(out.loc[missing_mask, df_site].dropna().astype(str).unique())
83
+ msg = (
84
+ f"{int(missing_mask.sum())} row(s) across {len(missing_sites)} site(s) "
85
+ f"were not matched in zone lookup: {missing_sites[:10]}"
86
+ )
87
+ if on_missing == "raise":
88
+ raise ValueError(msg)
89
+ if on_missing == "warn":
90
+ warnings.warn(msg, UserWarning, stacklevel=2)
91
+ mapped = mapped.fillna(unmatched)
92
+
93
+ out[out_zone] = mapped
94
+ return out
95
+
96
+
97
+ def summarise_by_group(
98
+ df: pd.DataFrame,
99
+ *,
100
+ group_col: str | None = None,
101
+ category_col: str | None = None,
102
+ group_key: str = "zone",
103
+ category_key: str = "state_band",
104
+ normalize: bool = False,
105
+ dropna: bool = True,
106
+ config: str | Path | Config | None = None,
107
+ ) -> pd.DataFrame:
108
+ """Compute counts or proportions of a category column within each group.
109
+
110
+ Args:
111
+ df: Input DataFrame (not mutated).
112
+ group_col: Grouping column name. Defaults to ``config.columns[group_key]``.
113
+ category_col: Category column name. Defaults to ``config.columns[category_key]``.
114
+ group_key: Config column key used when ``group_col`` is None.
115
+ category_key: Config column key used when ``category_col`` is None.
116
+ normalize: If True, return row-wise percentages (0–100) instead of raw counts.
117
+ dropna: Whether to exclude NA values from the cross-tabulation.
118
+ config: Optional Config object, preset name, or path to YAML/TOML config.
119
+
120
+ Returns:
121
+ DataFrame indexed by ``group_col`` with columns for each category in ``category_col``.
122
+ """
123
+ cfg = ensure_config(config)
124
+ g_col = resolve_column(group_col, cfg, group_key)
125
+ c_col = resolve_column(category_col, cfg, category_key)
126
+ validate_columns(df, [g_col, c_col], context="summarise_by_group")
127
+
128
+ table = pd.crosstab(
129
+ df[g_col],
130
+ df[c_col],
131
+ dropna=dropna,
132
+ )
133
+ if normalize:
134
+ row_totals = table.sum(axis=1).replace(0, pd.NA)
135
+ table = table.div(row_totals, axis=0).mul(100.0).fillna(0.0)
136
+ return table
137
+
138
+
139
+ def override_site_zones(
140
+ df: pd.DataFrame,
141
+ overrides: dict[str, str] | pd.DataFrame | str | Path,
142
+ *,
143
+ site_col: str | None = None,
144
+ zone_col: str | None = None,
145
+ override_site_col: str | None = None,
146
+ override_zone_col: str | None = None,
147
+ on_unknown: Literal["ignore", "warn", "raise"] = "warn",
148
+ config: str | Path | Config | None = None,
149
+ ) -> pd.DataFrame:
150
+ """Manually assign or correct management zone/FMU values for specific sites.
151
+
152
+ Useful when site coordinates fall slightly outside a polygon boundary (e.g., coastal
153
+ sites or estuaries) or just across a watershed divide into the neighbouring FMU.
154
+
155
+ Args:
156
+ df: Input results DataFrame (not mutated).
157
+ overrides: Either:
158
+ - A ``dict`` mapping ``{site_id: zone_name}``,
159
+ - A ``DataFrame`` containing site and zone columns, or
160
+ - A path (``str`` or ``Path``) to a CSV/Excel override lookup file.
161
+ site_col: Site ID column in ``df``. Defaults to ``config.columns["site_id"]``.
162
+ zone_col: Target zone/FMU column in ``df`` (created if absent). Defaults to
163
+ ``config.columns["zone"]``.
164
+ override_site_col: Site column in ``overrides`` table (defaults to ``site_col``).
165
+ override_zone_col: Zone column in ``overrides`` table (defaults to ``zone_col``).
166
+ on_unknown: Behavior if an override key does not appear in ``df[site_col]``:
167
+ ``"ignore"``, ``"warn"`` (default), or ``"raise"``.
168
+ config: Optional Config object, preset name, or path to YAML/TOML config.
169
+
170
+ Returns:
171
+ Copy of ``df`` with manual zone overrides applied.
172
+ """
173
+ if on_unknown not in {"ignore", "warn", "raise"}:
174
+ raise ValueError(
175
+ f"Invalid on_unknown='{on_unknown}'. Expected one of: 'ignore', 'warn', 'raise'."
176
+ )
177
+
178
+ cfg = ensure_config(config)
179
+ df_site = resolve_column(site_col, cfg, "site_id")
180
+ out_zone = resolve_column(zone_col, cfg, "zone")
181
+ validate_columns(df, [df_site], context="override_site_zones(df)")
182
+
183
+ if isinstance(overrides, dict):
184
+ override_map = {str(k): v for k, v in overrides.items()}
185
+ else:
186
+ ov_df = read_results(overrides) if isinstance(overrides, (str, Path)) else overrides
187
+ ov_site = override_site_col if override_site_col is not None else df_site
188
+ ov_zone = override_zone_col if override_zone_col is not None else out_zone
189
+ validate_columns(ov_df, [ov_site, ov_zone], context="override_site_zones(overrides)")
190
+ dedup = ov_df[[ov_site, ov_zone]].drop_duplicates(subset=[ov_site], keep="last")
191
+ override_map = dict(zip(dedup[ov_site].astype(str), dedup[ov_zone], strict=True))
192
+
193
+ out = df.copy()
194
+ if out_zone not in out.columns:
195
+ out[out_zone] = pd.NA
196
+
197
+ present_sites = set(out[df_site].dropna().astype(str).unique())
198
+ unknown = sorted(k for k in override_map if k not in present_sites)
199
+ if unknown:
200
+ msg = f"Manual zone override(s) referenced site(s) not found in df: {unknown[:10]}"
201
+ if on_unknown == "raise":
202
+ raise ValueError(msg)
203
+ if on_unknown == "warn":
204
+ warnings.warn(msg, UserWarning, stacklevel=2)
205
+
206
+ site_str = out[df_site].astype(str)
207
+ for site_key, target_zone in override_map.items():
208
+ mask = site_str == site_key
209
+ if mask.any():
210
+ out.loc[mask, out_zone] = target_zone
211
+
212
+ return out
213
+
214
+
215
+ def assign_zones_spatial(
216
+ df: pd.DataFrame,
217
+ polygons: Any,
218
+ *,
219
+ polygon_zone_col: str,
220
+ x_col: str | None = None,
221
+ y_col: str | None = None,
222
+ crs: str | int | None = None,
223
+ site_col: str | None = None,
224
+ zone_col: str | None = None,
225
+ predicate: str = "intersects",
226
+ nearest_max_distance: float | None = None,
227
+ manual_overrides: dict[str, str] | pd.DataFrame | str | Path | None = None,
228
+ unmatched: str = "Unassigned",
229
+ on_missing: Literal["keep", "warn", "raise"] = "keep",
230
+ config: str | Path | Config | None = None,
231
+ ) -> pd.DataFrame:
232
+ """Assign sites in ``df`` to management zones/FMUs via spatial join against polygons.
233
+
234
+ Supports optional nearest-polygon snapping (``nearest_max_distance``, in CRS units
235
+ such as metres in ``EPSG:2193``) for coastal/boundary-edge sites, plus optional
236
+ ``manual_overrides`` for sites whose coordinates fall in the wrong polygon.
237
+
238
+ Args:
239
+ df: Results DataFrame with coordinate columns (not mutated).
240
+ polygons: ``GeoDataFrame``, local vector file path, REST GeoJSON URL, or named key
241
+ in ``config.spatial_sources`` (e.g., ``"horizons_fmu"``).
242
+ polygon_zone_col: Attribute column in ``polygons`` containing the zone/FMU name.
243
+ x_col: Easting/longitude column in ``df`` (defaults to ``config.columns["x"]``).
244
+ y_col: Northing/latitude column in ``df`` (defaults to ``config.columns["y"]``).
245
+ crs: CRS of ``x_col``/``y_col`` (defaults to ``config.columns["crs"]`` or ``"EPSG:2193"``).
246
+ site_col: Site ID column used for ``manual_overrides`` and warning messages.
247
+ zone_col: Output zone column name (defaults to ``config.columns["zone"]``).
248
+ predicate: Spatial predicate passed to ``geopandas.sjoin`` (default ``"intersects"``).
249
+ nearest_max_distance: Optional maximum distance (in CRS units, e.g., metres in
250
+ ``EPSG:2193``) to snap unmatched points to the nearest polygon.
251
+ manual_overrides: Optional manual site-to-zone overrides applied after the spatial
252
+ join (see :func:`override_site_zones`).
253
+ unmatched: Label assigned to remaining unmatched sites when ``on_missing`` is
254
+ ``"keep"`` or ``"warn"``.
255
+ on_missing: Behavior for unmatched sites: ``"keep"``, ``"warn"``, or ``"raise"``.
256
+ config: Optional Config object, preset name, or path to YAML/TOML config.
257
+
258
+ Returns:
259
+ Copy of ``df`` with ``zone_col`` populated.
260
+ """
261
+ if on_missing not in {"keep", "warn", "raise"}:
262
+ raise ValueError(
263
+ f"Invalid on_missing='{on_missing}'. Expected one of: 'keep', 'warn', 'raise'."
264
+ )
265
+
266
+ try:
267
+ import geopandas as gpd
268
+ except ImportError as exc:
269
+ raise ImportError(
270
+ 'Spatial zone assignment requires geopandas. Install with: pip install "stplot[geo]"'
271
+ ) from exc
272
+
273
+ cfg = ensure_config(config)
274
+ resolved_x = resolve_column(x_col, cfg, "x")
275
+ resolved_y = resolve_column(y_col, cfg, "y")
276
+ resolved_zone = resolve_column(zone_col, cfg, "zone")
277
+ resolved_crs = crs if crs is not None else cfg.columns.get("crs", "EPSG:2193")
278
+
279
+ validate_columns(df, [resolved_x, resolved_y], context="assign_zones_spatial(df)")
280
+
281
+ poly_gdf = (
282
+ read_spatial(polygons, crs=resolved_crs, config=cfg)
283
+ if isinstance(polygons, (str, Path))
284
+ else polygons.to_crs(resolved_crs)
285
+ if getattr(polygons, "crs", None) is not None
286
+ else polygons.set_crs(resolved_crs)
287
+ )
288
+ validate_columns(poly_gdf, [polygon_zone_col], context="assign_zones_spatial(polygons)")
289
+
290
+ out = df.copy()
291
+ valid_coords = out[resolved_x].notna() & out[resolved_y].notna()
292
+ assigned = pd.Series(pd.NA, index=out.index, dtype="object")
293
+
294
+ if valid_coords.any():
295
+ pts = gpd.GeoDataFrame(
296
+ {"_row_id": out.index[valid_coords]},
297
+ geometry=gpd.points_from_xy(
298
+ out.loc[valid_coords, resolved_x],
299
+ out.loc[valid_coords, resolved_y],
300
+ ),
301
+ crs=resolved_crs,
302
+ )
303
+ poly_subset = poly_gdf[[polygon_zone_col, "geometry"]].copy()
304
+ joined = gpd.sjoin(pts, poly_subset, how="left", predicate=predicate)
305
+ joined = joined.drop_duplicates(subset=["_row_id"], keep="first")
306
+ assigned.loc[joined["_row_id"].to_numpy()] = joined[polygon_zone_col].to_numpy()
307
+
308
+ # Optional nearest-polygon fallback for points slightly outside boundaries
309
+ if nearest_max_distance is not None:
310
+ still_missing_ids = assigned.loc[out.index[valid_coords]].isna()
311
+ unmatched_idx = still_missing_ids[still_missing_ids].index
312
+ if len(unmatched_idx) > 0:
313
+ rem_pts = pts[pts["_row_id"].isin(unmatched_idx)]
314
+ nearest = gpd.sjoin_nearest(
315
+ rem_pts,
316
+ poly_subset,
317
+ how="left",
318
+ max_distance=nearest_max_distance,
319
+ )
320
+ nearest = nearest.drop_duplicates(subset=["_row_id"], keep="first")
321
+ assigned.loc[nearest["_row_id"].to_numpy()] = nearest[polygon_zone_col].to_numpy()
322
+
323
+ out[resolved_zone] = assigned
324
+
325
+ # Apply manual site overrides before checking remaining unmatched rows
326
+ if manual_overrides is not None:
327
+ out = override_site_zones(
328
+ out,
329
+ manual_overrides,
330
+ site_col=site_col,
331
+ zone_col=resolved_zone,
332
+ config=cfg,
333
+ )
334
+
335
+ missing_mask = out[resolved_zone].isna()
336
+ if missing_mask.any():
337
+ resolved_site = site_col if site_col is not None else cfg.columns.get("site_id")
338
+ if resolved_site and resolved_site in out.columns:
339
+ missing_desc = sorted(
340
+ out.loc[missing_mask, resolved_site].dropna().astype(str).unique()
341
+ )
342
+ else:
343
+ missing_desc = [str(i) for i in out.index[missing_mask][:10]]
344
+ msg = (
345
+ f"{int(missing_mask.sum())} row(s) were not matched to any polygon in "
346
+ f"assign_zones_spatial: {missing_desc[:10]}"
347
+ )
348
+ if on_missing == "raise":
349
+ raise ValueError(msg)
350
+ if on_missing == "warn":
351
+ warnings.warn(msg, UserWarning, stacklevel=2)
352
+ out.loc[missing_mask, resolved_zone] = unmatched
353
+
354
+ return out
@@ -0,0 +1,235 @@
1
+ Metadata-Version: 2.5
2
+ Name: stplot
3
+ Version: 0.1.0
4
+ Summary: Post-processing and templated visualization helpers for environmental state and trends results.
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: matplotlib>=3.8
7
+ Requires-Dist: pandas>=2.0
8
+ Requires-Dist: pyyaml>=6.0
9
+ Requires-Dist: seaborn>=0.13
10
+ Requires-Dist: tomli>=2.0; python_version < '3.11'
11
+ Provides-Extra: all
12
+ Requires-Dist: docxtpl>=0.18; extra == 'all'
13
+ Requires-Dist: folium>=0.16; extra == 'all'
14
+ Requires-Dist: geopandas>=0.14; extra == 'all'
15
+ Requires-Dist: openpyxl>=3.1; extra == 'all'
16
+ Requires-Dist: plotly>=5.20; extra == 'all'
17
+ Requires-Dist: pyarrow>=15.0; extra == 'all'
18
+ Requires-Dist: python-docx>=1.1; extra == 'all'
19
+ Requires-Dist: shapely>=2.0; extra == 'all'
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8.0; extra == 'dev'
22
+ Requires-Dist: ruff>=0.6; extra == 'dev'
23
+ Provides-Extra: excel
24
+ Requires-Dist: openpyxl>=3.1; extra == 'excel'
25
+ Provides-Extra: geo
26
+ Requires-Dist: folium>=0.16; extra == 'geo'
27
+ Requires-Dist: geopandas>=0.14; extra == 'geo'
28
+ Requires-Dist: shapely>=2.0; extra == 'geo'
29
+ Provides-Extra: interactive
30
+ Requires-Dist: plotly>=5.20; extra == 'interactive'
31
+ Provides-Extra: parquet
32
+ Requires-Dist: pyarrow>=15.0; extra == 'parquet'
33
+ Provides-Extra: report
34
+ Requires-Dist: docxtpl>=0.18; extra == 'report'
35
+ Requires-Dist: python-docx>=1.1; extra == 'report'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # stplot
39
+
40
+ **State and Trends processing and templated plotting helpers in Python.**
41
+
42
+ `stplot` provides reusable Python functions for preparing pre-computed environmental state and trends results and generating publication-ready, visually consistent plots and maps across multiple plotting backends.
43
+
44
+ ## Scope
45
+
46
+ ### What `stplot` IS for
47
+ 1. **Processing results files** — Loading state and trends outputs (primarily CSV/Excel, plus optional shapefiles/GeoPackages or API lookups), standardizing column names, assigning sites to management zones or custom groupings, filtering, aggregating, and reshaping data for visualization.
48
+ 2. **Templated plotting** — Generating standardized static and interactive charts and maps with a consistent visual identity (palettes, category ordering, typography, annotations, and export settings).
49
+ 3. **Templated reporting (planned)** — Populating Word (`.docx`) report templates with pre-filled figures, captions, and summary tables so new regional/annual reports can be generated quickly and consistently.
50
+
51
+ ### What `stplot` is NOT for
52
+ - **Calculating state or trends** — Statistical calculations (e.g., percentiles, attribute grading/band assignment from raw time series, Mann-Kendall tests, Sen slopes) are performed upstream by dedicated tools. `stplot` consumes those results files.
53
+
54
+ ---
55
+
56
+ ## Key Design Principles
57
+
58
+ - **Hybrid configuration**: Project defaults (column name mappings, semantic color palettes, category orderings, typography, and figure dimensions) live in a YAML configuration file, while any function parameter can override those defaults at call time.
59
+ - **No hardcoded schemas**: Functions accept column mappings via config or explicit keyword arguments so different upstream result formats work without rewriting plotting code.
60
+ - **Consistent look across backends**: Shared theme tokens (colors, fonts, labels, legend layouts) are translated into backend-specific templates for:
61
+ - **Static charts**: `matplotlib`, `seaborn`
62
+ - **Interactive charts**: `plotly`
63
+ - **Static & interactive maps**: `geopandas`, `folium`
64
+ - **Composable transforms**: Preprocessing steps (zone assignment, grouping, renaming, category ordering) are pure, non-mutating functions that return tidy `pandas.DataFrame` / `geopandas.GeoDataFrame` objects ready for any plot template.
65
+
66
+ ---
67
+
68
+ ## Planned Project Structure
69
+
70
+ ```text
71
+ stplot/
72
+ ├── AGENTS.md # Guidelines for AI coding agents
73
+ ├── README.md
74
+ ├── pyproject.toml # Package metadata, dependencies, and tool config
75
+ ├── configs/
76
+ │ └── default.yaml # Default column mappings, palettes, and plot templates
77
+ ├── src/
78
+ │ └── stplot/
79
+ │ ├── __init__.py
80
+ │ ├── config/ # Config schema, YAML loader, and override resolution
81
+ │ ├── io/ # Readers for CSV/Excel, shapefiles/GeoPackage, and APIs
82
+ │ ├── transform/ # Zone assignment, site grouping, filtering, reshaping
83
+ │ ├── theme/ # Shared palettes, typography, and backend theme adapters
84
+ │ ├── plots/ # Templated plot & map functions (static, interactive, geo)
85
+ │ └── reporting/ # (Planned) Templated Word (.docx) report assembly
86
+ ├── tests/ # Pytest unit and smoke tests using synthetic fixtures
87
+ └── examples/ # Example configs, notebooks, and scripts
88
+ ```
89
+
90
+ ---
91
+
92
+ ## Configuration Model (Hybrid & Multi-Preset)
93
+
94
+ `stplot` ships with built-in YAML presets in [configs/](configs/) (and packaged in `stplot.config.presets`):
95
+
96
+ - **`default` / `npsfm_lawa`** ([configs/default.yaml](configs/default.yaml)) — NZ NPS-FM / LAWA state bands (`NOF_Grade`: `A`–`E`) and IPCC/LWP trend likelihoods (`DirectionConf`, `Improving_Confidence`, `AnnualSenSlope`), NZTM coordinates (`NZTM.X`, `NZTM.Y`, `EPSG:2193`), and FMU/subzone groupings.
97
+ - **`horizons_one_plan`** ([configs/horizons_one_plan.yaml](configs/horizons_one_plan.yaml)) — Horizons One Plan compliance reporting (`Site.Name`, `VarName`, `CriteriaName`, `SitePasses`, `nOK`, `Water.management.subzone.One.Plan`).
98
+
99
+ ```yaml
100
+ name: "npsfm_lawa"
101
+ columns:
102
+ site_id: "sID"
103
+ indicator: "npID"
104
+ state_band: "NOF_Grade"
105
+ trend_confidence: "DirectionConf"
106
+ zone: "Freshwater.Management.Unit.FMU"
107
+ x: "NZTM.X"
108
+ y: "NZTM.Y"
109
+ ```
110
+
111
+ Every processing and plotting function accepts an optional `config` (a preset name, YAML/TOML path, or `Config` object) plus explicit keyword overrides (e.g., `group_col="CatName"`, `band_col="NOF_Grade"`), resolving values in the order:
112
+
113
+ 1. Explicit function argument
114
+ 2. User-provided YAML/TOML config or named preset
115
+ 3. Built-in `stplot` default (`npsfm_lawa`)
116
+
117
+ ---
118
+
119
+ ## Usage Example
120
+
121
+ ```python
122
+ import stplot as stp
123
+
124
+ # Load a built-in preset ("npsfm_lawa" or "horizons_one_plan") or a custom YAML/TOML file
125
+ cfg = stp.load_config("npsfm_lawa")
126
+
127
+ # 1. Load and preprocess results
128
+ df = stp.io.read_results("data/NPSFM_State_Example.csv")
129
+ df = stp.transform.order_categories(df, config=cfg)
130
+
131
+ # 2. Generate templated plots (with optional per-call overrides)
132
+ fig, ax = stp.plots.state_band_bar(
133
+ df,
134
+ group_col="Freshwater.Management.Unit.FMU", # overrides config.columns["zone"] if needed
135
+ title="NPS-FM State by FMU",
136
+ config=cfg,
137
+ )
138
+ stp.plots.save_figure(fig, "outputs/state_by_fmu.png", config=cfg)
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Implemented Transforms & Plot Templates
144
+
145
+ ### Pre-Analysis (`stplot.transform`)
146
+ - `filter_sites(...)` — Filter by `site_type` (`River`/`Lake`/`Beach`/`Estuary`), `status` (`RepSite`/`Impact`), `fmu`, `catchment`, `zone`, `indicator`, `attribute`, `period`, and `valid_only=True` (`FilterOK` or `nOK == "OK"`).
147
+ - `split_by_site_group(...)` — Split results into separate DataFrames by site status or site type.
148
+ - `split_full_and_preliminary(...)` & `audit_results_data(...)` — Split full (`FilterOK=True` / `nOK="OK"`) vs preliminary/insufficient results without silently dropping records, and run pre-flight QA checks (duplicates, missing coords/FMUs, unmapped indicators).
149
+ - `merge_state_and_trends(...)` & `stplot.io.merge_period_files(...)` / `combine_period_dataframes(...)` — Join separate State & Trends tables (filtering to a target `trend_period`) and stack multiple historical period Excel/CSV files (e.g., One Plan `2015–2020`, `2020–2025`) with automatic filename period extraction.
150
+ - `derive_pass_fail(...)` — Derive `"Pass"` / `"Fail"` / `"Insufficient data"` labels from One Plan `SitePasses` + `nOK`.
151
+ - `derive_trend_direction_3level(...)` — Collapse IPCC/LWP 9-level confidence into `"Improving"` / `"Indeterminate"` / `"Degrading"`.
152
+ - `build_fmu_vs_region_table(...)` — Build `"XX.X% (n)"` FMU vs Whole Region summary tables.
153
+ - `assign_zones(...)` & `assign_zones_spatial(...)` — Assign sites to FMUs/zones via lookup table or `geopandas` spatial join (with optional nearest-boundary snapping).
154
+ - `override_site_zones(...)` — Manually assign or correct specific sites whose coordinates fall slightly outside a boundary or into the wrong FMU.
155
+ - `pair_upstream_downstream(...)` — Pair long-format `u/s` and `d/s` records into wide format for paired discharge plots.
156
+ - `order_categories(...)`, `summarise_by_group(...)`, `standardize_columns(...)`.
157
+
158
+ ### Plot, Map & Table Templates (`stplot.plots`)
159
+ - `state_band_bar(...)` (`matplotlib`) — Stacked state band counts or percentages by FMU/zone.
160
+ - `pass_fail_bar(...)` (`matplotlib`) — Horizons One Plan 100% stacked Pass/Fail bars by variable with `n = XX` totals and in-bar `%` labels.
161
+ - `pass_fail_donuts(...)` (`matplotlib`) — Small-multiple Pass/Fail donut grid with wrapped center labels and callouts.
162
+ - `compliance_dot_matrix(...)` (`matplotlib`) — Site × Indicator compliance dot matrix encoding Pass/Fail and Final/Interim.
163
+ - `horizontal_proportion_bar(...)` (`matplotlib`) — Sorted horizontal 100% stacked bar with `(n = XX)` labels (e.g., recreational swim traffic-light).
164
+ - `barbell_plot(...)` & `multi_node_barbell(...)` (`matplotlib`) — 2-node and multi-node over-time horizontal barbells.
165
+ - `slopegraph(...)` (`matplotlib`) — 2-period before/after slopegraph showing value and rank shifts.
166
+ - `state_distribution_plot(...)` (`matplotlib` / `seaborn`) — Box + strip distributions across FMUs overlaid on pastel NOF band shading.
167
+ - `trend_diverging_bar(...)` (`matplotlib`) — LAWA-style diverging trend stacked bars around 0%.
168
+ - `state_trend_quadrant(...)` (`matplotlib`) — 4-quadrant State vs Trend management prioritization scatter.
169
+ - `state_lollipop(...)` (`plotly`) — Sorted horizontal state value lollipop colored by `NOF_Grade`.
170
+ - `trend_lollipop(...)` (`plotly`) — Diverging horizontal trend lollipop (`Percent.annual.change`) colored by 3-level trend direction.
171
+ - `upstream_downstream_comparison(...)` (`matplotlib`) — Paired Upstream (`▲`) vs Downstream (`▼`) log-scale comparison grouped by district with NOF grades inside markers.
172
+ - `upstream_downstream_timeseries(...)` (`matplotlib`) — Rolling-period Upstream vs Downstream time series with pastel NOF band shading.
173
+ - `fmu_state_map(...)` (`folium`) — Interactive Esri greyscale map with automatic NZTM (`EPSG:2193`) → WGS84 reprojection, optional FMU boundary overlay, grade-colored markers, title badge, and legend.
174
+ - `static_fmu_map(...)` (`geopandas` / `matplotlib`) — 300-DPI static publication map (state circles or trend triangles) with north arrow and km scale bar.
175
+ - `grade_matrix(...)` (`plotly`) — Single-site or side-by-side faceted tile grid of NOF grades across attributes and rolling 5-year periods.
176
+ - `trend_timeseries(...)` (`plotly`) — Monitoring time series (with censored markers) overlaid with pre-computed Sen slope and CI lines.
177
+ - `grade_summary_over_time(...)` (`plotly`) — 100% stacked NOF grade proportions across rolling periods with total site counts above bars.
178
+ - `state_over_time(...)` & `state_over_time_comparison(...)` (`plotly`) — Single-site or multi-site rolling 5-year state trajectory over pastel NOF band zones with grade letters inside contrasting triangle markers (`▲` / `▼`).
179
+ - `style_summary_table(...)` (`pandas.Styler`) — Semantic color-coded FMU vs Whole Region HTML summary tables.
180
+ - `publication_map(...)`, `kpi_summary_cards(...)`, `grade_transition_sankey(...)`, `fmu_indicator_heatmap(...)`, `fmu_factsheet_panel(...)` — Editorial map and executive reporting templates.
181
+ - `catchment_profile_infographic(...)`, `site_report_card(...)`, `catchment_report_card(...)`, `waffle_infographic(...)`, `target_gauge_strip(...)`, `regional_infographic_poster(...)` — Publication-ready infographic & report card templates.
182
+ - `ecosystem_flower_plot(...)`, `water_quality_stripes(...)`, `bullet_scorecard(...)`, `beeswarm_nof_plot(...)`, `rank_bump_chart(...)`, `swim_season_calendar(...)`, `intervention_spotlight_card(...)` — Waterway flower/petal plots, river quality stripes, multi-metric bullet scorecards, NOF beeswarms, FMU rank bump charts, swim-season calendars, and intervention spotlight cards.
183
+ - `state_trend_butterfly(...)`, `state_trend_lollipop(...)`, `state_trend_map(...)`, `state_trend_risk_matrix(...)`, `state_trend_heatmap(...)`, `state_trend_sparktable(...)` — Combined State + Trend templates (paired butterfly, velocity-arrow lollipop, color+shape map, 2D risk triage matrix, state+trend overlay heatmap, and sparkline summary table).
184
+ - `domain_summary_strip(...)`, `discharge_impact_card(...)`, `lake_health_card(...)`, `estuary_coastal_card(...)` — Multi-domain reporting cards covering Rivers (SoE/Impact), Lakes (TLI), Estuaries, Coastal Bathing, and Consented Discharges.
185
+ - `save_figure(...)` & `batch_export_by_group(...)` — Unified export helpers for Matplotlib, Plotly, and Folium outputs.
186
+
187
+ ### Word & HTML Report Assembly (`stplot.reporting`)
188
+ - `create_npsfm_report_template(...)` & `create_one_plan_report_template(...)` — Production A4 Word (`.docx`) templates with Cover Page, Executive Summary, Regional Multi-Domain chapters (Rivers SoE/Impact, Lakes, Estuaries, Coastal, Discharges), dynamic `{%p for fmu in fmus %}` FMU/WMS chapters, and Appendices.
189
+ - `render_docx_report(...)` (`docxtpl` / `python-docx`) — Populate a Word (`.docx`) template with Jinja text variables, top-level & nested per-FMU PNG figures, and styled summary tables.
190
+ - `add_styled_table(...)` (`python-docx`) — Append color-coded FMU vs Whole Region summary tables with semantic hex cell shading.
191
+ - `build_html_companion(...)` — Build a self-contained, tabbed interactive HTML Companion Pack bundling `folium` maps, `plotly` charts, base64-inlined PNGs, QA tables, and separated Preliminary results.
192
+ - `CaptionTracker` & `generate_figure_caption(...)` — Automated sequential Figure/Table captions with macron-aware label resolution and data-derived site & preliminary counts.
193
+ - `build_network_summary_table(...)`, `build_data_sufficiency_table(...)`, `build_indicator_coverage_table(...)`, `build_exceedance_watchlist_table(...)`, `build_site_master_table(...)`, `build_grade_change_table(...)`, `build_top_movers_table(...)`, `select_top_bottom_sites(...)` (`stplot.transform`) — Monitoring network, data sufficiency, exceedance watchlist, site master appendix, grade shift, top movers, and Best/Worst *N* site selectors.
194
+ - `top_bottom_sites_plot(...)` (`stplot.plots`) — Best *N* & Worst *N* sites spotlight plot with Regional/FMU Median reference line and auto-detected indicator polarity.
195
+
196
+ Browse runnable scripts and rendered plot previews in the [Examples Gallery](examples/README.md).
197
+
198
+ ---
199
+
200
+ ## Getting Started (Setup)
201
+
202
+ `stplot` uses a standard `src/` layout with `pyproject.toml`, managed with [`uv`](https://docs.astral.sh/uv/) (recommended) or `pip`.
203
+
204
+ ### Using `uv` (recommended)
205
+
206
+ ```bash
207
+ # Create virtual environment and install in editable mode with dev dependencies
208
+ uv venv
209
+ uv pip install -e ".[dev]"
210
+
211
+ # Install optional geospatial and interactive plotting extras
212
+ uv pip install -e ".[geo,interactive,dev]"
213
+ ```
214
+
215
+ ### Using `pip`
216
+
217
+ ```bash
218
+ python -m venv .venv
219
+ source .venv/bin/activate # On Windows: .venv\Scripts\activate
220
+ pip install -e ".[dev]"
221
+ ```
222
+
223
+ ---
224
+
225
+ ## Development Workflow
226
+
227
+ Once scaffolding is in place:
228
+
229
+ - **Run tests**: `pytest`
230
+ - **Lint & format**: `ruff check .` and `ruff format .`
231
+ - **Adding a new plot template**:
232
+ 1. Reuse theme tokens from `stplot.theme` rather than hardcoding colors or fonts.
233
+ 2. Resolve all column names through `stplot.config` with keyword-argument override support.
234
+ 3. Add unit/smoke tests in `tests/` using small synthetic DataFrames (no private data files).
235
+ 4. Document expected columns and return type in the function docstring.
@@ -0,0 +1,49 @@
1
+ stplot/__init__.py,sha256=9WiY_Lh-zbMGo8If7VrWl2dmycLa6JH_StdqG_t9oPs,468
2
+ stplot/config/__init__.py,sha256=oXJT3-kxWt7Ux2omI1yX6l9qwNJGNXaPYd1lGeWQdqk,769
3
+ stplot/config/loader.py,sha256=5xlPL1caDBcSo_gTJywELA5B7BRLfCKfgXrYL4fqfPk,3455
4
+ stplot/config/models.py,sha256=uJhsP_FCDp_09jPX-MwUFZWrAVc6LhCV3cl7kgeT068,11517
5
+ stplot/config/presets/__init__.py,sha256=vToMbnuFmnvS1BczvBPRkP6UPzRqcb0058ix6BYXYiY,54
6
+ stplot/config/presets/default.yaml,sha256=K-De5LSSCRkJq4YjV3VoMBh-F06Kv7xCtdgXbBvGpco,5902
7
+ stplot/config/presets/horizons_one_plan.yaml,sha256=s5akr3J6kAL8pzCJuwSSaCKMFOvN1lJcmmVE-NhECw0,1746
8
+ stplot/io/__init__.py,sha256=IL9vZoCo-J7CwtZ220kQlVOPkq95vzVNMSt-qMWjNaA,245
9
+ stplot/io/spatial.py,sha256=oztUCOZvsE9UBQBVN5kIK6e4aSCwB0f3Pn6PYf2jS_8,2510
10
+ stplot/io/tabular.py,sha256=3nwGoPVPTaRu3sdVTlbwWumKVlg_iaZSCp8iIXG9z-E,5740
11
+ stplot/plots/__init__.py,sha256=zXS9jRG3K90oqol5ruHiUkwzkXlfQFc62pBoESGbaj0,3460
12
+ stplot/plots/barbell.py,sha256=LAY3KqwF7sFloJA2ZUnKkk47uh-A1M7JudClq1Zq5fs,14603
13
+ stplot/plots/batch.py,sha256=XOAUqeV1RCNjlwkN05wZd3rm4veMnKPYNe6lkP1Mvfo,5496
14
+ stplot/plots/domains.py,sha256=JgH2OqqKGrDoxyljqZhVvg3g7juyNEi62l1kQaTrmOU,36435
15
+ stplot/plots/executive.py,sha256=bNx39WT8hyDMcUWLugGIZmvbS2TRvZ4_cYK2QFuP-So,16656
16
+ stplot/plots/export.py,sha256=8bsV0Fu0r1Ui684saCNMCVWDeLAJHcZfAz_cjsuHbwU,2650
17
+ stplot/plots/infographics.py,sha256=OeKrgZzwsV8A18wg2nKbS9xVTzuKQdi-NVtEO87viKE,37693
18
+ stplot/plots/lollipop.py,sha256=SUmfB3yIzork2wPyrq9FjABIAnmTUUK5y9Nb49WUmYU,10040
19
+ stplot/plots/maps.py,sha256=EehSxnlH_wGOP-rWgY9w4UouOw9Bu4JMw5xwZ-0xmLc,27646
20
+ stplot/plots/matrix.py,sha256=nVMI1QTHSoUOLyFN1VTJAVhLuOKm7QRYibDYJT187TE,6652
21
+ stplot/plots/one_plan.py,sha256=4sKZ_YVBGqWsDT6qeVGflGYB4-nD3nDOVolOQw6tEkQ,21603
22
+ stplot/plots/paired.py,sha256=iecJvJy3QeJfr5xfSckLDeAymNB0Ja3yAog_e2LvKSU,16073
23
+ stplot/plots/scorecards.py,sha256=jpgItZKpjAgoUjZXk-rhveVdFx_jhGG_TNVSUbeTj6c,68237
24
+ stplot/plots/state.py,sha256=eutCoqY4Y2cPf7UYJBIYNvhaUekwxqMZK-Gdqe0n_dc,12797
25
+ stplot/plots/state_trends.py,sha256=xTQUd9idd6CyrcDen6cgXbhmOF-3nKsLxwnrcCGB1gg,48843
26
+ stplot/plots/tables.py,sha256=A2_fk1MhJDqLQgbdjKhdyWIlBQyrYWE49UHUuV2v1Hc,3690
27
+ stplot/plots/timeseries.py,sha256=t7hiKhVoR2bU89FkyuZMAWsls_8y5z8XWAfUQWW3LhI,22199
28
+ stplot/plots/trends.py,sha256=DVucQvm8giHpz3MsOPH2on6G2M3ysaTWA2jXJ781b5I,11745
29
+ stplot/reporting/__init__.py,sha256=Q5yL0riAUF9Wfh6GklSvh7dtFGsesP3NNi8RTz220W0,689
30
+ stplot/reporting/captions.py,sha256=Su1tvnAHQeKvRKvLecF_pTniHOgG054QCBzwTyWg1B0,6643
31
+ stplot/reporting/html_companion.py,sha256=o5BJqJv5IuFTx9oVNVREr4vVGgtv_W9X9BzAG2Lv2X8,13640
32
+ stplot/reporting/templates.py,sha256=NOPQXHug3OEaxO6hq1kPsMrM0WJaOIDpgvyiXSxWutE,19273
33
+ stplot/reporting/word.py,sha256=3wUMdqtRP5pewl4grMx_PWbtv8DggLWC-isXcnRc9BE,14202
34
+ stplot/theme/__init__.py,sha256=Lh7TjU_24hs-YV40BjeZEPepXd414lZ03dySCfa5vsw,639
35
+ stplot/theme/folium.py,sha256=OFEX5b3fJl5E6NtXZVlQZK7XtcuLTL72XVuLex1RrbE,2236
36
+ stplot/theme/mpl.py,sha256=8OQKBVQ_459F_OK1JWXtd8_87zpBKrO1IJQs8KeF99I,5836
37
+ stplot/theme/plotly.py,sha256=J-NKTGzuwr58UBDSKARPHBMtRKVQpXHLje5xJH5yaz4,4221
38
+ stplot/transform/__init__.py,sha256=9AJUBUsOxkktl46Z3UnQKVXLCMGp_CYqScnV_HvHQkE,1894
39
+ stplot/transform/categories.py,sha256=3Eq4m-Q0oO81O8FFOT220wVJHDTaElmfYhEkHxOQC54,1921
40
+ stplot/transform/columns.py,sha256=MveVZDKaIDDvlO7NwmBr1KcG9IxAd0j7yYY_PtT9N7Y,3259
41
+ stplot/transform/filters.py,sha256=t0kx3MB_ybc9yTyY2733pWJVueFBTbdtpnZDSX7C5PU,15597
42
+ stplot/transform/merge.py,sha256=HS4nEjWhQqC8UHZ5WfzZarqfjPntTuClJ2yJrF_awVE,7570
43
+ stplot/transform/pairing.py,sha256=_ob86rSHvZLEX57xuHNjmgEHJPl9Bw7cfRUq2l5hO0c,6406
44
+ stplot/transform/qa.py,sha256=0mNC7W5QT34oSpbTuKsrZQuIpXFmZFhQGedR-r2Xa40,11819
45
+ stplot/transform/tables.py,sha256=ADVtoUyeedvGvHrLvKYx_CpEGREjwtFmJ27mTx2Yk4w,23780
46
+ stplot/transform/zones.py,sha256=xDzc7knoiI-6OXkbP3XmLNlVrrZ1Op4f3n1AofGcwms,15019
47
+ stplot-0.1.0.dist-info/METADATA,sha256=_ZHcrc2pIpLU5NT-WmKOsdkXcDKDe7W7llSgZBVEuOM,16052
48
+ stplot-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
49
+ stplot-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any