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,59 @@
1
+ # Horizons One Plan preset
2
+ # Tailored to Horizons One Plan State Excel outputs (sheet: "One Plan").
3
+ # Inherits unspecified settings (e.g., theme, export, trend settings) from `default.yaml`.
4
+
5
+ name: "horizons_one_plan"
6
+ description: "Horizons Regional Council One Plan compliance and state reporting preset."
7
+
8
+ columns:
9
+ site_id: "Site.Name"
10
+ indicator: "VarName"
11
+ attribute: "CriteriaName"
12
+ attribute_label: "Nice_CriteriaName"
13
+ state_band: "SitePasses"
14
+ state_value: "TestStat"
15
+ criteria_value: "CriteriaValue"
16
+ filter_ok: "nOK"
17
+ season: "Season"
18
+ site_type: "SiteType"
19
+ site_status: "Status"
20
+ zone: "Water.management.subzone.One.Plan"
21
+ fmu: "Freshwater.Management.Unit.FMU"
22
+ subzone: "Water.management.subzone.One.Plan"
23
+ catchment: "CatName"
24
+ x: "NZTM.X"
25
+ y: "NZTM.Y"
26
+ crs: "EPSG:2193"
27
+
28
+ category_orders:
29
+ state_bands:
30
+ - "Pass"
31
+ - "Fail"
32
+ - "Insufficient data"
33
+ - "Insufficient FLOW data"
34
+
35
+ palettes:
36
+ state_bands:
37
+ Pass: "#2e8b57"
38
+ Fail: "#d95f59"
39
+ Insufficient data: "#bdbdbd"
40
+ Insufficient FLOW data: "#d9d9d9"
41
+ one_plan_report:
42
+ Pass: "#009ec2"
43
+ Fail: "#263742"
44
+ Insufficient data: "#bdbdbd"
45
+
46
+ spatial_sources:
47
+ horizons_fmu: "https://services1.arcgis.com/VuN78wcRdq1Oj69W/arcgis/rest/services/FMU_20210122/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=geojson"
48
+ horizons_wms: "https://maps.horizons.govt.nz/arcgis/rest/services/LocalMapsPublic/Public_OnePlan/MapServer/3/query?where=1=1&outFields=*&returnGeometry=true&outSR=4326&f=geojson"
49
+
50
+ theme:
51
+ background_color: "#ffffff"
52
+ axes_facecolor: "#ffffff"
53
+ grid_color: "#e6eaee"
54
+ grid_width: 0.8
55
+ text_color: "#22303c"
56
+ caption_color: "#4a5a68"
57
+ spine_color: "#c5cfd6"
58
+ accent_color: "#009ec2"
59
+ title_weight: "bold"
stplot/io/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Input/output loaders for tabular and spatial state & trends data."""
2
+
3
+ from stplot.io.spatial import read_spatial
4
+ from stplot.io.tabular import merge_period_files, read_results
5
+
6
+ __all__ = ["merge_period_files", "read_results", "read_spatial"]
stplot/io/spatial.py ADDED
@@ -0,0 +1,72 @@
1
+ """Spatial data readers for local vector files and REST GeoJSON endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from stplot.config import Config, ensure_config
9
+
10
+
11
+ def _is_url(value: str) -> bool:
12
+ return value.startswith(("http://", "https://"))
13
+
14
+
15
+ def read_spatial(
16
+ source: str | Path,
17
+ *,
18
+ layer: str | None = None,
19
+ crs: str | int | None = None,
20
+ config: str | Path | Config | None = None,
21
+ **kwargs: Any,
22
+ ) -> Any:
23
+ """Read a vector spatial dataset from a local file, REST GeoJSON URL, or config key.
24
+
25
+ Args:
26
+ source: One of:
27
+ - A local path to a vector file (``.shp``, ``.gpkg``, ``.geojson``).
28
+ - An HTTP/HTTPS URL returning GeoJSON (e.g., an ArcGIS REST FeatureServer query).
29
+ - A named key in ``config.spatial_sources`` (e.g., ``"nz_regional_councils"`` or
30
+ ``"horizons_fmu"``).
31
+ layer: Optional layer name for multi-layer formats such as GeoPackage.
32
+ crs: Optional target CRS (e.g., ``"EPSG:2193"`` or ``4326``) to reproject into.
33
+ config: Optional Config object, preset name, or path to YAML/TOML config used to
34
+ resolve named ``spatial_sources`` keys.
35
+ **kwargs: Additional keyword arguments forwarded to ``geopandas.read_file``.
36
+
37
+ Returns:
38
+ ``geopandas.GeoDataFrame`` containing the loaded geometries and attributes.
39
+
40
+ Raises:
41
+ ImportError: If ``geopandas`` is not installed.
42
+ FileNotFoundError: If ``source`` is a local file path that does not exist.
43
+ """
44
+ try:
45
+ import geopandas as gpd
46
+ except ImportError as exc:
47
+ raise ImportError(
48
+ 'Spatial I/O requires geopandas. Install with: pip install "stplot[geo]"'
49
+ ) from exc
50
+
51
+ target: str | Path = source
52
+ if isinstance(source, str) and not _is_url(source):
53
+ cfg = ensure_config(config)
54
+ if source in cfg.spatial_sources:
55
+ target = cfg.spatial_sources[source]
56
+
57
+ if isinstance(target, str) and _is_url(target):
58
+ read_target: str | Path = target
59
+ else:
60
+ file_path = Path(target)
61
+ if not file_path.exists():
62
+ raise FileNotFoundError(f"Spatial file not found: {file_path}")
63
+ read_target = file_path
64
+
65
+ read_kwargs = dict(kwargs)
66
+ if layer is not None:
67
+ read_kwargs["layer"] = layer
68
+
69
+ gdf = gpd.read_file(read_target, **read_kwargs)
70
+ if crs is not None and gdf.crs is not None:
71
+ gdf = gdf.to_crs(crs)
72
+ return gdf
stplot/io/tabular.py ADDED
@@ -0,0 +1,154 @@
1
+ """Tabular result readers for CSV, Excel, and Parquet files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import pandas as pd
9
+
10
+
11
+ def read_results(
12
+ path: str | Path,
13
+ *,
14
+ sheet_name: str | int = 0,
15
+ **kwargs: Any,
16
+ ) -> pd.DataFrame:
17
+ """Read pre-computed state or trends results from a tabular file.
18
+
19
+ Supports ``.csv``, ``.tsv``, ``.xlsx``, ``.xls``, and ``.parquet`` files.
20
+
21
+ Args:
22
+ path: Path to the input results file.
23
+ sheet_name: Worksheet name or index when reading Excel files (ignored for CSV/Parquet).
24
+ **kwargs: Additional keyword arguments forwarded to the underlying ``pandas`` reader.
25
+
26
+ Returns:
27
+ DataFrame containing the loaded results.
28
+
29
+ Raises:
30
+ FileNotFoundError: If ``path`` does not exist.
31
+ ImportError: If an optional dependency (``openpyxl`` or ``pyarrow``) is required
32
+ but missing.
33
+ ValueError: If the file extension is not supported.
34
+ """
35
+ file_path = Path(path)
36
+ if not file_path.exists():
37
+ raise FileNotFoundError(f"Results file not found: {file_path}")
38
+
39
+ suffix = file_path.suffix.lower()
40
+
41
+ if suffix == ".csv":
42
+ return pd.read_csv(file_path, **kwargs)
43
+ if suffix == ".tsv":
44
+ kwargs.setdefault("sep", "\t")
45
+ return pd.read_csv(file_path, **kwargs)
46
+ if suffix in {".xlsx", ".xls"}:
47
+ try:
48
+ import openpyxl # noqa: F401
49
+ except ImportError as exc:
50
+ raise ImportError(
51
+ 'Reading Excel files requires openpyxl. Install with: pip install "stplot[excel]"'
52
+ ) from exc
53
+ return pd.read_excel(file_path, sheet_name=sheet_name, **kwargs)
54
+ if suffix == ".parquet":
55
+ try:
56
+ import pyarrow # noqa: F401
57
+ except ImportError as exc:
58
+ raise ImportError(
59
+ "Reading Parquet files requires pyarrow. "
60
+ 'Install with: pip install "stplot[parquet]"'
61
+ ) from exc
62
+ return pd.read_parquet(file_path, **kwargs)
63
+
64
+ raise ValueError(
65
+ f"Unsupported tabular file format '{suffix}' for {file_path}. "
66
+ "Supported formats: .csv, .tsv, .xlsx, .xls, .parquet."
67
+ )
68
+
69
+
70
+ def _extract_period_from_filename(path: Path, pattern: str) -> str:
71
+ import re
72
+
73
+ match = re.search(pattern, path.stem)
74
+ if not match:
75
+ raise ValueError(
76
+ f"merge_period_files: Could not infer period label from filename '{path.name}' "
77
+ f"using pattern r'{pattern}'. Pass a dict mapping {{period_label: path}} instead."
78
+ )
79
+ if match.lastindex and match.lastindex >= 2:
80
+ return f"{match.group(1)}–{match.group(2)}"
81
+ return match.group(0)
82
+
83
+
84
+ def merge_period_files(
85
+ sources: dict[str, str | Path | pd.DataFrame] | list[str | Path] | tuple[str | Path, ...],
86
+ *,
87
+ period_col: str | None = None,
88
+ sheet_name: str | int = 0,
89
+ period_pattern: str = r"(\d{4})\s*[-–_]\s*(\d{4})",
90
+ sort_periods: bool = True,
91
+ source_file_col: str | None = None,
92
+ config: str | Path | Any | None = None,
93
+ **read_kwargs: Any,
94
+ ) -> pd.DataFrame:
95
+ """Load and stack multiple historical period State files (e.g., One Plan Excel/CSV).
96
+
97
+ Supports two convenient input styles:
98
+ 1. **Explicit mapping**: ``{"2015–2020": "OnePlan_2015_2020.xlsx", ...}``
99
+ 2. **List of file paths**: ``["OnePlan_2015-2020.xlsx", "OnePlan_2020-2025.xlsx"]``
100
+ (automatically extracts ``YYYY–YYYY`` period labels from filenames).
101
+
102
+ Args:
103
+ sources: Dict of ``{period_label: path_or_df}`` or list/tuple of file paths.
104
+ period_col: Target period column name (defaults to ``config.columns["period"]``).
105
+ sheet_name: Excel worksheet name or index (e.g., ``"One Plan"``).
106
+ period_pattern: Regex used to extract period labels when ``sources`` is a list of paths.
107
+ sort_periods: If True (default), sort periods chronologically and use ordered Categorical.
108
+ source_file_col: Optional provenance column name (e.g., ``"SourceFile"``) storing
109
+ each file's basename.
110
+ config: Optional Config object, preset name, or path to YAML/TOML config.
111
+ **read_kwargs: Extra keyword arguments forwarded to :func:`read_results`.
112
+
113
+ Returns:
114
+ Combined multi-period ``pd.DataFrame``.
115
+ """
116
+ from stplot.transform.merge import combine_period_dataframes
117
+
118
+ if not sources:
119
+ raise ValueError("merge_period_files: 'sources' cannot be empty.")
120
+
121
+ period_dfs: dict[str, pd.DataFrame] = {}
122
+
123
+ if isinstance(sources, dict):
124
+ for label, src in sources.items():
125
+ if isinstance(src, pd.DataFrame):
126
+ df = src.copy()
127
+ fname = None
128
+ else:
129
+ p = Path(src)
130
+ df = read_results(p, sheet_name=sheet_name, **read_kwargs)
131
+ fname = p.name
132
+ if source_file_col and fname is not None:
133
+ df[source_file_col] = fname
134
+ period_dfs[str(label)] = df
135
+ else:
136
+ for src in sources:
137
+ p = Path(src)
138
+ label = _extract_period_from_filename(p, period_pattern)
139
+ if label in period_dfs:
140
+ raise ValueError(
141
+ f"merge_period_files: Duplicate period '{label}' inferred from '{p.name}'. "
142
+ "Pass an explicit dict mapping if two files share a period."
143
+ )
144
+ df = read_results(p, sheet_name=sheet_name, **read_kwargs)
145
+ if source_file_col:
146
+ df[source_file_col] = p.name
147
+ period_dfs[label] = df
148
+
149
+ return combine_period_dataframes(
150
+ period_dfs,
151
+ period_col=period_col,
152
+ sort_periods=sort_periods,
153
+ config=config,
154
+ )
@@ -0,0 +1,122 @@
1
+ """Templated visualization, map, infographic, summary table, and export helpers."""
2
+
3
+ from stplot.plots.barbell import barbell_plot, multi_node_barbell, slopegraph
4
+ from stplot.plots.batch import batch_export_by_group, slugify
5
+ from stplot.plots.domains import (
6
+ discharge_impact_card,
7
+ domain_summary_strip,
8
+ estuary_coastal_card,
9
+ lake_health_card,
10
+ )
11
+ from stplot.plots.executive import (
12
+ fmu_factsheet_panel,
13
+ fmu_indicator_heatmap,
14
+ grade_transition_sankey,
15
+ kpi_summary_cards,
16
+ )
17
+ from stplot.plots.export import save_figure
18
+ from stplot.plots.infographics import (
19
+ catchment_profile_infographic,
20
+ catchment_report_card,
21
+ regional_infographic_poster,
22
+ site_report_card,
23
+ target_gauge_strip,
24
+ waffle_infographic,
25
+ )
26
+ from stplot.plots.lollipop import state_lollipop, trend_lollipop
27
+ from stplot.plots.maps import fmu_state_map, publication_map, static_fmu_map
28
+ from stplot.plots.matrix import grade_matrix
29
+ from stplot.plots.one_plan import compliance_dot_matrix, pass_fail_bar, pass_fail_donuts
30
+ from stplot.plots.paired import (
31
+ upstream_downstream_comparison,
32
+ upstream_downstream_timeseries,
33
+ )
34
+ from stplot.plots.scorecards import (
35
+ beeswarm_nof_plot,
36
+ bullet_scorecard,
37
+ ecosystem_flower_plot,
38
+ intervention_spotlight_card,
39
+ rank_bump_chart,
40
+ swim_season_calendar,
41
+ top_bottom_sites_plot,
42
+ water_quality_stripes,
43
+ )
44
+ from stplot.plots.state import (
45
+ horizontal_proportion_bar,
46
+ state_band_bar,
47
+ state_distribution_plot,
48
+ )
49
+ from stplot.plots.state_trends import (
50
+ state_trend_butterfly,
51
+ state_trend_heatmap,
52
+ state_trend_lollipop,
53
+ state_trend_map,
54
+ state_trend_risk_matrix,
55
+ state_trend_sparktable,
56
+ )
57
+ from stplot.plots.tables import style_summary_table
58
+ from stplot.plots.timeseries import (
59
+ grade_summary_over_time,
60
+ state_over_time,
61
+ state_over_time_comparison,
62
+ trend_timeseries,
63
+ )
64
+ from stplot.plots.trends import state_trend_quadrant, trend_diverging_bar
65
+
66
+ __all__ = [
67
+ "barbell_plot",
68
+ "batch_export_by_group",
69
+ "beeswarm_nof_plot",
70
+ "bullet_scorecard",
71
+ "catchment_profile_infographic",
72
+ "catchment_report_card",
73
+ "compliance_dot_matrix",
74
+ "discharge_impact_card",
75
+ "domain_summary_strip",
76
+ "ecosystem_flower_plot",
77
+ "estuary_coastal_card",
78
+ "fmu_factsheet_panel",
79
+ "fmu_indicator_heatmap",
80
+ "fmu_state_map",
81
+ "grade_matrix",
82
+ "grade_summary_over_time",
83
+ "grade_transition_sankey",
84
+ "horizontal_proportion_bar",
85
+ "intervention_spotlight_card",
86
+ "kpi_summary_cards",
87
+ "lake_health_card",
88
+ "multi_node_barbell",
89
+ "pass_fail_bar",
90
+ "pass_fail_donuts",
91
+ "publication_map",
92
+ "rank_bump_chart",
93
+ "regional_infographic_poster",
94
+ "save_figure",
95
+ "site_report_card",
96
+ "slopegraph",
97
+ "slugify",
98
+ "state_band_bar",
99
+ "state_distribution_plot",
100
+ "state_lollipop",
101
+ "state_over_time",
102
+ "state_over_time_comparison",
103
+ "state_trend_butterfly",
104
+ "state_trend_heatmap",
105
+ "state_trend_lollipop",
106
+ "state_trend_map",
107
+ "state_trend_quadrant",
108
+ "state_trend_risk_matrix",
109
+ "state_trend_sparktable",
110
+ "static_fmu_map",
111
+ "style_summary_table",
112
+ "swim_season_calendar",
113
+ "target_gauge_strip",
114
+ "top_bottom_sites_plot",
115
+ "trend_diverging_bar",
116
+ "trend_lollipop",
117
+ "trend_timeseries",
118
+ "upstream_downstream_comparison",
119
+ "upstream_downstream_timeseries",
120
+ "waffle_infographic",
121
+ "water_quality_stripes",
122
+ ]