stplot 0.1.0__tar.gz
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.
- stplot-0.1.0/.gitignore +39 -0
- stplot-0.1.0/PKG-INFO +235 -0
- stplot-0.1.0/README.md +198 -0
- stplot-0.1.0/configs/default.yaml +208 -0
- stplot-0.1.0/configs/horizons_one_plan.yaml +59 -0
- stplot-0.1.0/pyproject.toml +70 -0
- stplot-0.1.0/src/stplot/__init__.py +21 -0
- stplot-0.1.0/src/stplot/config/__init__.py +33 -0
- stplot-0.1.0/src/stplot/config/loader.py +106 -0
- stplot-0.1.0/src/stplot/config/models.py +328 -0
- stplot-0.1.0/src/stplot/config/presets/__init__.py +1 -0
- stplot-0.1.0/src/stplot/config/presets/default.yaml +208 -0
- stplot-0.1.0/src/stplot/config/presets/horizons_one_plan.yaml +59 -0
- stplot-0.1.0/src/stplot/io/__init__.py +6 -0
- stplot-0.1.0/src/stplot/io/spatial.py +72 -0
- stplot-0.1.0/src/stplot/io/tabular.py +154 -0
- stplot-0.1.0/src/stplot/plots/__init__.py +122 -0
- stplot-0.1.0/src/stplot/plots/barbell.py +400 -0
- stplot-0.1.0/src/stplot/plots/batch.py +135 -0
- stplot-0.1.0/src/stplot/plots/domains.py +1143 -0
- stplot-0.1.0/src/stplot/plots/executive.py +474 -0
- stplot-0.1.0/src/stplot/plots/export.py +74 -0
- stplot-0.1.0/src/stplot/plots/infographics.py +1118 -0
- stplot-0.1.0/src/stplot/plots/lollipop.py +285 -0
- stplot-0.1.0/src/stplot/plots/maps.py +738 -0
- stplot-0.1.0/src/stplot/plots/matrix.py +190 -0
- stplot-0.1.0/src/stplot/plots/one_plan.py +642 -0
- stplot-0.1.0/src/stplot/plots/paired.py +437 -0
- stplot-0.1.0/src/stplot/plots/scorecards.py +1940 -0
- stplot-0.1.0/src/stplot/plots/state.py +373 -0
- stplot-0.1.0/src/stplot/plots/state_trends.py +1413 -0
- stplot-0.1.0/src/stplot/plots/tables.py +107 -0
- stplot-0.1.0/src/stplot/plots/timeseries.py +607 -0
- stplot-0.1.0/src/stplot/plots/trends.py +305 -0
- stplot-0.1.0/src/stplot/reporting/__init__.py +24 -0
- stplot-0.1.0/src/stplot/reporting/captions.py +177 -0
- stplot-0.1.0/src/stplot/reporting/html_companion.py +339 -0
- stplot-0.1.0/src/stplot/reporting/templates.py +485 -0
- stplot-0.1.0/src/stplot/reporting/word.py +369 -0
- stplot-0.1.0/src/stplot/theme/__init__.py +25 -0
- stplot-0.1.0/src/stplot/theme/folium.py +62 -0
- stplot-0.1.0/src/stplot/theme/mpl.py +181 -0
- stplot-0.1.0/src/stplot/theme/plotly.py +130 -0
- stplot-0.1.0/src/stplot/transform/__init__.py +60 -0
- stplot-0.1.0/src/stplot/transform/categories.py +51 -0
- stplot-0.1.0/src/stplot/transform/columns.py +103 -0
- stplot-0.1.0/src/stplot/transform/filters.py +385 -0
- stplot-0.1.0/src/stplot/transform/merge.py +173 -0
- stplot-0.1.0/src/stplot/transform/pairing.py +154 -0
- stplot-0.1.0/src/stplot/transform/qa.py +297 -0
- stplot-0.1.0/src/stplot/transform/tables.py +573 -0
- stplot-0.1.0/src/stplot/transform/zones.py +354 -0
- stplot-0.1.0/templates/horizons_one_plan_report_template.docx +0 -0
- stplot-0.1.0/templates/npsfm_state_trends_report_template.docx +0 -0
- stplot-0.1.0/templates/state_trends_report_template.docx +0 -0
- stplot-0.1.0/tests/conftest.py +78 -0
- stplot-0.1.0/tests/test_batch_and_heatmap.py +113 -0
- stplot-0.1.0/tests/test_captions_and_tables.py +92 -0
- stplot-0.1.0/tests/test_config.py +125 -0
- stplot-0.1.0/tests/test_domains.py +136 -0
- stplot-0.1.0/tests/test_executive_and_maps.py +170 -0
- stplot-0.1.0/tests/test_extended_plots.py +186 -0
- stplot-0.1.0/tests/test_filters.py +104 -0
- stplot-0.1.0/tests/test_indicator_directions.py +121 -0
- stplot-0.1.0/tests/test_infographics_and_labels.py +181 -0
- stplot-0.1.0/tests/test_io.py +32 -0
- stplot-0.1.0/tests/test_log_axes.py +92 -0
- stplot-0.1.0/tests/test_merge_files.py +106 -0
- stplot-0.1.0/tests/test_plots.py +256 -0
- stplot-0.1.0/tests/test_qa_and_html.py +167 -0
- stplot-0.1.0/tests/test_report_tables_and_top_bottom.py +159 -0
- stplot-0.1.0/tests/test_reporting.py +96 -0
- stplot-0.1.0/tests/test_reporting_templates.py +320 -0
- stplot-0.1.0/tests/test_scorecards.py +339 -0
- stplot-0.1.0/tests/test_spatial_and_pairing.py +151 -0
- stplot-0.1.0/tests/test_state_over_time.py +69 -0
- stplot-0.1.0/tests/test_state_trends.py +258 -0
- stplot-0.1.0/tests/test_theme.py +48 -0
- stplot-0.1.0/tests/test_transform.py +86 -0
stplot-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# Distribution / packaging
|
|
7
|
+
build/
|
|
8
|
+
dist/
|
|
9
|
+
*.egg-info/
|
|
10
|
+
.eggs/
|
|
11
|
+
|
|
12
|
+
# Virtual environments
|
|
13
|
+
.venv/
|
|
14
|
+
venv/
|
|
15
|
+
ENV/
|
|
16
|
+
|
|
17
|
+
# Testing & linting caches
|
|
18
|
+
.pytest_cache/
|
|
19
|
+
.ruff_cache/
|
|
20
|
+
.mypy_cache/
|
|
21
|
+
.coverage
|
|
22
|
+
htmlcov/
|
|
23
|
+
|
|
24
|
+
# Jupyter
|
|
25
|
+
.ipynb_checkpoints/
|
|
26
|
+
|
|
27
|
+
# Local data & generated outputs
|
|
28
|
+
data/
|
|
29
|
+
outputs/
|
|
30
|
+
*.png
|
|
31
|
+
*.pdf
|
|
32
|
+
*.html
|
|
33
|
+
!examples/**/*.png
|
|
34
|
+
!examples/**/*.html
|
|
35
|
+
|
|
36
|
+
# OS / IDE
|
|
37
|
+
.DS_Store
|
|
38
|
+
.vscode/
|
|
39
|
+
.idea/
|
stplot-0.1.0/PKG-INFO
ADDED
|
@@ -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.
|
stplot-0.1.0/README.md
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# stplot
|
|
2
|
+
|
|
3
|
+
**State and Trends processing and templated plotting helpers in Python.**
|
|
4
|
+
|
|
5
|
+
`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.
|
|
6
|
+
|
|
7
|
+
## Scope
|
|
8
|
+
|
|
9
|
+
### What `stplot` IS for
|
|
10
|
+
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.
|
|
11
|
+
2. **Templated plotting** — Generating standardized static and interactive charts and maps with a consistent visual identity (palettes, category ordering, typography, annotations, and export settings).
|
|
12
|
+
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.
|
|
13
|
+
|
|
14
|
+
### What `stplot` is NOT for
|
|
15
|
+
- **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.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Key Design Principles
|
|
20
|
+
|
|
21
|
+
- **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.
|
|
22
|
+
- **No hardcoded schemas**: Functions accept column mappings via config or explicit keyword arguments so different upstream result formats work without rewriting plotting code.
|
|
23
|
+
- **Consistent look across backends**: Shared theme tokens (colors, fonts, labels, legend layouts) are translated into backend-specific templates for:
|
|
24
|
+
- **Static charts**: `matplotlib`, `seaborn`
|
|
25
|
+
- **Interactive charts**: `plotly`
|
|
26
|
+
- **Static & interactive maps**: `geopandas`, `folium`
|
|
27
|
+
- **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.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Planned Project Structure
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
stplot/
|
|
35
|
+
├── AGENTS.md # Guidelines for AI coding agents
|
|
36
|
+
├── README.md
|
|
37
|
+
├── pyproject.toml # Package metadata, dependencies, and tool config
|
|
38
|
+
├── configs/
|
|
39
|
+
│ └── default.yaml # Default column mappings, palettes, and plot templates
|
|
40
|
+
├── src/
|
|
41
|
+
│ └── stplot/
|
|
42
|
+
│ ├── __init__.py
|
|
43
|
+
│ ├── config/ # Config schema, YAML loader, and override resolution
|
|
44
|
+
│ ├── io/ # Readers for CSV/Excel, shapefiles/GeoPackage, and APIs
|
|
45
|
+
│ ├── transform/ # Zone assignment, site grouping, filtering, reshaping
|
|
46
|
+
│ ├── theme/ # Shared palettes, typography, and backend theme adapters
|
|
47
|
+
│ ├── plots/ # Templated plot & map functions (static, interactive, geo)
|
|
48
|
+
│ └── reporting/ # (Planned) Templated Word (.docx) report assembly
|
|
49
|
+
├── tests/ # Pytest unit and smoke tests using synthetic fixtures
|
|
50
|
+
└── examples/ # Example configs, notebooks, and scripts
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Configuration Model (Hybrid & Multi-Preset)
|
|
56
|
+
|
|
57
|
+
`stplot` ships with built-in YAML presets in [configs/](configs/) (and packaged in `stplot.config.presets`):
|
|
58
|
+
|
|
59
|
+
- **`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.
|
|
60
|
+
- **`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`).
|
|
61
|
+
|
|
62
|
+
```yaml
|
|
63
|
+
name: "npsfm_lawa"
|
|
64
|
+
columns:
|
|
65
|
+
site_id: "sID"
|
|
66
|
+
indicator: "npID"
|
|
67
|
+
state_band: "NOF_Grade"
|
|
68
|
+
trend_confidence: "DirectionConf"
|
|
69
|
+
zone: "Freshwater.Management.Unit.FMU"
|
|
70
|
+
x: "NZTM.X"
|
|
71
|
+
y: "NZTM.Y"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
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:
|
|
75
|
+
|
|
76
|
+
1. Explicit function argument
|
|
77
|
+
2. User-provided YAML/TOML config or named preset
|
|
78
|
+
3. Built-in `stplot` default (`npsfm_lawa`)
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## Usage Example
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import stplot as stp
|
|
86
|
+
|
|
87
|
+
# Load a built-in preset ("npsfm_lawa" or "horizons_one_plan") or a custom YAML/TOML file
|
|
88
|
+
cfg = stp.load_config("npsfm_lawa")
|
|
89
|
+
|
|
90
|
+
# 1. Load and preprocess results
|
|
91
|
+
df = stp.io.read_results("data/NPSFM_State_Example.csv")
|
|
92
|
+
df = stp.transform.order_categories(df, config=cfg)
|
|
93
|
+
|
|
94
|
+
# 2. Generate templated plots (with optional per-call overrides)
|
|
95
|
+
fig, ax = stp.plots.state_band_bar(
|
|
96
|
+
df,
|
|
97
|
+
group_col="Freshwater.Management.Unit.FMU", # overrides config.columns["zone"] if needed
|
|
98
|
+
title="NPS-FM State by FMU",
|
|
99
|
+
config=cfg,
|
|
100
|
+
)
|
|
101
|
+
stp.plots.save_figure(fig, "outputs/state_by_fmu.png", config=cfg)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## Implemented Transforms & Plot Templates
|
|
107
|
+
|
|
108
|
+
### Pre-Analysis (`stplot.transform`)
|
|
109
|
+
- `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"`).
|
|
110
|
+
- `split_by_site_group(...)` — Split results into separate DataFrames by site status or site type.
|
|
111
|
+
- `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).
|
|
112
|
+
- `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.
|
|
113
|
+
- `derive_pass_fail(...)` — Derive `"Pass"` / `"Fail"` / `"Insufficient data"` labels from One Plan `SitePasses` + `nOK`.
|
|
114
|
+
- `derive_trend_direction_3level(...)` — Collapse IPCC/LWP 9-level confidence into `"Improving"` / `"Indeterminate"` / `"Degrading"`.
|
|
115
|
+
- `build_fmu_vs_region_table(...)` — Build `"XX.X% (n)"` FMU vs Whole Region summary tables.
|
|
116
|
+
- `assign_zones(...)` & `assign_zones_spatial(...)` — Assign sites to FMUs/zones via lookup table or `geopandas` spatial join (with optional nearest-boundary snapping).
|
|
117
|
+
- `override_site_zones(...)` — Manually assign or correct specific sites whose coordinates fall slightly outside a boundary or into the wrong FMU.
|
|
118
|
+
- `pair_upstream_downstream(...)` — Pair long-format `u/s` and `d/s` records into wide format for paired discharge plots.
|
|
119
|
+
- `order_categories(...)`, `summarise_by_group(...)`, `standardize_columns(...)`.
|
|
120
|
+
|
|
121
|
+
### Plot, Map & Table Templates (`stplot.plots`)
|
|
122
|
+
- `state_band_bar(...)` (`matplotlib`) — Stacked state band counts or percentages by FMU/zone.
|
|
123
|
+
- `pass_fail_bar(...)` (`matplotlib`) — Horizons One Plan 100% stacked Pass/Fail bars by variable with `n = XX` totals and in-bar `%` labels.
|
|
124
|
+
- `pass_fail_donuts(...)` (`matplotlib`) — Small-multiple Pass/Fail donut grid with wrapped center labels and callouts.
|
|
125
|
+
- `compliance_dot_matrix(...)` (`matplotlib`) — Site × Indicator compliance dot matrix encoding Pass/Fail and Final/Interim.
|
|
126
|
+
- `horizontal_proportion_bar(...)` (`matplotlib`) — Sorted horizontal 100% stacked bar with `(n = XX)` labels (e.g., recreational swim traffic-light).
|
|
127
|
+
- `barbell_plot(...)` & `multi_node_barbell(...)` (`matplotlib`) — 2-node and multi-node over-time horizontal barbells.
|
|
128
|
+
- `slopegraph(...)` (`matplotlib`) — 2-period before/after slopegraph showing value and rank shifts.
|
|
129
|
+
- `state_distribution_plot(...)` (`matplotlib` / `seaborn`) — Box + strip distributions across FMUs overlaid on pastel NOF band shading.
|
|
130
|
+
- `trend_diverging_bar(...)` (`matplotlib`) — LAWA-style diverging trend stacked bars around 0%.
|
|
131
|
+
- `state_trend_quadrant(...)` (`matplotlib`) — 4-quadrant State vs Trend management prioritization scatter.
|
|
132
|
+
- `state_lollipop(...)` (`plotly`) — Sorted horizontal state value lollipop colored by `NOF_Grade`.
|
|
133
|
+
- `trend_lollipop(...)` (`plotly`) — Diverging horizontal trend lollipop (`Percent.annual.change`) colored by 3-level trend direction.
|
|
134
|
+
- `upstream_downstream_comparison(...)` (`matplotlib`) — Paired Upstream (`▲`) vs Downstream (`▼`) log-scale comparison grouped by district with NOF grades inside markers.
|
|
135
|
+
- `upstream_downstream_timeseries(...)` (`matplotlib`) — Rolling-period Upstream vs Downstream time series with pastel NOF band shading.
|
|
136
|
+
- `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.
|
|
137
|
+
- `static_fmu_map(...)` (`geopandas` / `matplotlib`) — 300-DPI static publication map (state circles or trend triangles) with north arrow and km scale bar.
|
|
138
|
+
- `grade_matrix(...)` (`plotly`) — Single-site or side-by-side faceted tile grid of NOF grades across attributes and rolling 5-year periods.
|
|
139
|
+
- `trend_timeseries(...)` (`plotly`) — Monitoring time series (with censored markers) overlaid with pre-computed Sen slope and CI lines.
|
|
140
|
+
- `grade_summary_over_time(...)` (`plotly`) — 100% stacked NOF grade proportions across rolling periods with total site counts above bars.
|
|
141
|
+
- `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 (`▲` / `▼`).
|
|
142
|
+
- `style_summary_table(...)` (`pandas.Styler`) — Semantic color-coded FMU vs Whole Region HTML summary tables.
|
|
143
|
+
- `publication_map(...)`, `kpi_summary_cards(...)`, `grade_transition_sankey(...)`, `fmu_indicator_heatmap(...)`, `fmu_factsheet_panel(...)` — Editorial map and executive reporting templates.
|
|
144
|
+
- `catchment_profile_infographic(...)`, `site_report_card(...)`, `catchment_report_card(...)`, `waffle_infographic(...)`, `target_gauge_strip(...)`, `regional_infographic_poster(...)` — Publication-ready infographic & report card templates.
|
|
145
|
+
- `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.
|
|
146
|
+
- `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).
|
|
147
|
+
- `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.
|
|
148
|
+
- `save_figure(...)` & `batch_export_by_group(...)` — Unified export helpers for Matplotlib, Plotly, and Folium outputs.
|
|
149
|
+
|
|
150
|
+
### Word & HTML Report Assembly (`stplot.reporting`)
|
|
151
|
+
- `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.
|
|
152
|
+
- `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.
|
|
153
|
+
- `add_styled_table(...)` (`python-docx`) — Append color-coded FMU vs Whole Region summary tables with semantic hex cell shading.
|
|
154
|
+
- `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.
|
|
155
|
+
- `CaptionTracker` & `generate_figure_caption(...)` — Automated sequential Figure/Table captions with macron-aware label resolution and data-derived site & preliminary counts.
|
|
156
|
+
- `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.
|
|
157
|
+
- `top_bottom_sites_plot(...)` (`stplot.plots`) — Best *N* & Worst *N* sites spotlight plot with Regional/FMU Median reference line and auto-detected indicator polarity.
|
|
158
|
+
|
|
159
|
+
Browse runnable scripts and rendered plot previews in the [Examples Gallery](examples/README.md).
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## Getting Started (Setup)
|
|
164
|
+
|
|
165
|
+
`stplot` uses a standard `src/` layout with `pyproject.toml`, managed with [`uv`](https://docs.astral.sh/uv/) (recommended) or `pip`.
|
|
166
|
+
|
|
167
|
+
### Using `uv` (recommended)
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
# Create virtual environment and install in editable mode with dev dependencies
|
|
171
|
+
uv venv
|
|
172
|
+
uv pip install -e ".[dev]"
|
|
173
|
+
|
|
174
|
+
# Install optional geospatial and interactive plotting extras
|
|
175
|
+
uv pip install -e ".[geo,interactive,dev]"
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Using `pip`
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
python -m venv .venv
|
|
182
|
+
source .venv/bin/activate # On Windows: .venv\Scripts\activate
|
|
183
|
+
pip install -e ".[dev]"
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
## Development Workflow
|
|
189
|
+
|
|
190
|
+
Once scaffolding is in place:
|
|
191
|
+
|
|
192
|
+
- **Run tests**: `pytest`
|
|
193
|
+
- **Lint & format**: `ruff check .` and `ruff format .`
|
|
194
|
+
- **Adding a new plot template**:
|
|
195
|
+
1. Reuse theme tokens from `stplot.theme` rather than hardcoding colors or fonts.
|
|
196
|
+
2. Resolve all column names through `stplot.config` with keyword-argument override support.
|
|
197
|
+
3. Add unit/smoke tests in `tests/` using small synthetic DataFrames (no private data files).
|
|
198
|
+
4. Document expected columns and return type in the function docstring.
|