Metadata-Version: 2.5
Name: stplot
Version: 0.1.0
Summary: Post-processing and templated visualization helpers for environmental state and trends results.
Requires-Python: >=3.10
Requires-Dist: matplotlib>=3.8
Requires-Dist: pandas>=2.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: seaborn>=0.13
Requires-Dist: tomli>=2.0; python_version < '3.11'
Provides-Extra: all
Requires-Dist: docxtpl>=0.18; extra == 'all'
Requires-Dist: folium>=0.16; extra == 'all'
Requires-Dist: geopandas>=0.14; extra == 'all'
Requires-Dist: openpyxl>=3.1; extra == 'all'
Requires-Dist: plotly>=5.20; extra == 'all'
Requires-Dist: pyarrow>=15.0; extra == 'all'
Requires-Dist: python-docx>=1.1; extra == 'all'
Requires-Dist: shapely>=2.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: excel
Requires-Dist: openpyxl>=3.1; extra == 'excel'
Provides-Extra: geo
Requires-Dist: folium>=0.16; extra == 'geo'
Requires-Dist: geopandas>=0.14; extra == 'geo'
Requires-Dist: shapely>=2.0; extra == 'geo'
Provides-Extra: interactive
Requires-Dist: plotly>=5.20; extra == 'interactive'
Provides-Extra: parquet
Requires-Dist: pyarrow>=15.0; extra == 'parquet'
Provides-Extra: report
Requires-Dist: docxtpl>=0.18; extra == 'report'
Requires-Dist: python-docx>=1.1; extra == 'report'
Description-Content-Type: text/markdown

# stplot

**State and Trends processing and templated plotting helpers in Python.**

`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.

## Scope

### What `stplot` IS for
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.
2. **Templated plotting** — Generating standardized static and interactive charts and maps with a consistent visual identity (palettes, category ordering, typography, annotations, and export settings).
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.

### What `stplot` is NOT for
- **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.

---

## Key Design Principles

- **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.
- **No hardcoded schemas**: Functions accept column mappings via config or explicit keyword arguments so different upstream result formats work without rewriting plotting code.
- **Consistent look across backends**: Shared theme tokens (colors, fonts, labels, legend layouts) are translated into backend-specific templates for:
  - **Static charts**: `matplotlib`, `seaborn`
  - **Interactive charts**: `plotly`
  - **Static & interactive maps**: `geopandas`, `folium`
- **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.

---

## Planned Project Structure

```text
stplot/
├── AGENTS.md                 # Guidelines for AI coding agents
├── README.md
├── pyproject.toml            # Package metadata, dependencies, and tool config
├── configs/
│   └── default.yaml          # Default column mappings, palettes, and plot templates
├── src/
│   └── stplot/
│       ├── __init__.py
│       ├── config/           # Config schema, YAML loader, and override resolution
│       ├── io/               # Readers for CSV/Excel, shapefiles/GeoPackage, and APIs
│       ├── transform/        # Zone assignment, site grouping, filtering, reshaping
│       ├── theme/            # Shared palettes, typography, and backend theme adapters
│       ├── plots/            # Templated plot & map functions (static, interactive, geo)
│       └── reporting/        # (Planned) Templated Word (.docx) report assembly
├── tests/                    # Pytest unit and smoke tests using synthetic fixtures
└── examples/                 # Example configs, notebooks, and scripts
```

---

## Configuration Model (Hybrid & Multi-Preset)

`stplot` ships with built-in YAML presets in [configs/](configs/) (and packaged in `stplot.config.presets`):

- **`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.
- **`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`).

```yaml
name: "npsfm_lawa"
columns:
  site_id: "sID"
  indicator: "npID"
  state_band: "NOF_Grade"
  trend_confidence: "DirectionConf"
  zone: "Freshwater.Management.Unit.FMU"
  x: "NZTM.X"
  y: "NZTM.Y"
```

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:

1. Explicit function argument
2. User-provided YAML/TOML config or named preset
3. Built-in `stplot` default (`npsfm_lawa`)

---

## Usage Example

```python
import stplot as stp

# Load a built-in preset ("npsfm_lawa" or "horizons_one_plan") or a custom YAML/TOML file
cfg = stp.load_config("npsfm_lawa")

# 1. Load and preprocess results
df = stp.io.read_results("data/NPSFM_State_Example.csv")
df = stp.transform.order_categories(df, config=cfg)

# 2. Generate templated plots (with optional per-call overrides)
fig, ax = stp.plots.state_band_bar(
    df,
    group_col="Freshwater.Management.Unit.FMU",  # overrides config.columns["zone"] if needed
    title="NPS-FM State by FMU",
    config=cfg,
)
stp.plots.save_figure(fig, "outputs/state_by_fmu.png", config=cfg)
```

---

## Implemented Transforms & Plot Templates

### Pre-Analysis (`stplot.transform`)
- `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"`).
- `split_by_site_group(...)` — Split results into separate DataFrames by site status or site type.
- `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).
- `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.
- `derive_pass_fail(...)` — Derive `"Pass"` / `"Fail"` / `"Insufficient data"` labels from One Plan `SitePasses` + `nOK`.
- `derive_trend_direction_3level(...)` — Collapse IPCC/LWP 9-level confidence into `"Improving"` / `"Indeterminate"` / `"Degrading"`.
- `build_fmu_vs_region_table(...)` — Build `"XX.X% (n)"` FMU vs Whole Region summary tables.
- `assign_zones(...)` & `assign_zones_spatial(...)` — Assign sites to FMUs/zones via lookup table or `geopandas` spatial join (with optional nearest-boundary snapping).
- `override_site_zones(...)` — Manually assign or correct specific sites whose coordinates fall slightly outside a boundary or into the wrong FMU.
- `pair_upstream_downstream(...)` — Pair long-format `u/s` and `d/s` records into wide format for paired discharge plots.
- `order_categories(...)`, `summarise_by_group(...)`, `standardize_columns(...)`.

### Plot, Map & Table Templates (`stplot.plots`)
- `state_band_bar(...)` (`matplotlib`) — Stacked state band counts or percentages by FMU/zone.
- `pass_fail_bar(...)` (`matplotlib`) — Horizons One Plan 100% stacked Pass/Fail bars by variable with `n = XX` totals and in-bar `%` labels.
- `pass_fail_donuts(...)` (`matplotlib`) — Small-multiple Pass/Fail donut grid with wrapped center labels and callouts.
- `compliance_dot_matrix(...)` (`matplotlib`) — Site × Indicator compliance dot matrix encoding Pass/Fail and Final/Interim.
- `horizontal_proportion_bar(...)` (`matplotlib`) — Sorted horizontal 100% stacked bar with `(n = XX)` labels (e.g., recreational swim traffic-light).
- `barbell_plot(...)` & `multi_node_barbell(...)` (`matplotlib`) — 2-node and multi-node over-time horizontal barbells.
- `slopegraph(...)` (`matplotlib`) — 2-period before/after slopegraph showing value and rank shifts.
- `state_distribution_plot(...)` (`matplotlib` / `seaborn`) — Box + strip distributions across FMUs overlaid on pastel NOF band shading.
- `trend_diverging_bar(...)` (`matplotlib`) — LAWA-style diverging trend stacked bars around 0%.
- `state_trend_quadrant(...)` (`matplotlib`) — 4-quadrant State vs Trend management prioritization scatter.
- `state_lollipop(...)` (`plotly`) — Sorted horizontal state value lollipop colored by `NOF_Grade`.
- `trend_lollipop(...)` (`plotly`) — Diverging horizontal trend lollipop (`Percent.annual.change`) colored by 3-level trend direction.
- `upstream_downstream_comparison(...)` (`matplotlib`) — Paired Upstream (`▲`) vs Downstream (`▼`) log-scale comparison grouped by district with NOF grades inside markers.
- `upstream_downstream_timeseries(...)` (`matplotlib`) — Rolling-period Upstream vs Downstream time series with pastel NOF band shading.
- `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.
- `static_fmu_map(...)` (`geopandas` / `matplotlib`) — 300-DPI static publication map (state circles or trend triangles) with north arrow and km scale bar.
- `grade_matrix(...)` (`plotly`) — Single-site or side-by-side faceted tile grid of NOF grades across attributes and rolling 5-year periods.
- `trend_timeseries(...)` (`plotly`) — Monitoring time series (with censored markers) overlaid with pre-computed Sen slope and CI lines.
- `grade_summary_over_time(...)` (`plotly`) — 100% stacked NOF grade proportions across rolling periods with total site counts above bars.
- `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 (`▲` / `▼`).
- `style_summary_table(...)` (`pandas.Styler`) — Semantic color-coded FMU vs Whole Region HTML summary tables.
- `publication_map(...)`, `kpi_summary_cards(...)`, `grade_transition_sankey(...)`, `fmu_indicator_heatmap(...)`, `fmu_factsheet_panel(...)` — Editorial map and executive reporting templates.
- `catchment_profile_infographic(...)`, `site_report_card(...)`, `catchment_report_card(...)`, `waffle_infographic(...)`, `target_gauge_strip(...)`, `regional_infographic_poster(...)` — Publication-ready infographic & report card templates.
- `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.
- `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).
- `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.
- `save_figure(...)` & `batch_export_by_group(...)` — Unified export helpers for Matplotlib, Plotly, and Folium outputs.

### Word & HTML Report Assembly (`stplot.reporting`)
- `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.
- `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.
- `add_styled_table(...)` (`python-docx`) — Append color-coded FMU vs Whole Region summary tables with semantic hex cell shading.
- `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.
- `CaptionTracker` & `generate_figure_caption(...)` — Automated sequential Figure/Table captions with macron-aware label resolution and data-derived site & preliminary counts.
- `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.
- `top_bottom_sites_plot(...)` (`stplot.plots`) — Best *N* & Worst *N* sites spotlight plot with Regional/FMU Median reference line and auto-detected indicator polarity.

Browse runnable scripts and rendered plot previews in the [Examples Gallery](examples/README.md).

---

## Getting Started (Setup)

`stplot` uses a standard `src/` layout with `pyproject.toml`, managed with [`uv`](https://docs.astral.sh/uv/) (recommended) or `pip`.

### Using `uv` (recommended)

```bash
# Create virtual environment and install in editable mode with dev dependencies
uv venv
uv pip install -e ".[dev]"

# Install optional geospatial and interactive plotting extras
uv pip install -e ".[geo,interactive,dev]"
```

### Using `pip`

```bash
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -e ".[dev]"
```

---

## Development Workflow

Once scaffolding is in place:

- **Run tests**: `pytest`
- **Lint & format**: `ruff check .` and `ruff format .`
- **Adding a new plot template**:
  1. Reuse theme tokens from `stplot.theme` rather than hardcoding colors or fonts.
  2. Resolve all column names through `stplot.config` with keyword-argument override support.
  3. Add unit/smoke tests in `tests/` using small synthetic DataFrames (no private data files).
  4. Document expected columns and return type in the function docstring.
