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
stplot/theme/plotly.py ADDED
@@ -0,0 +1,130 @@
1
+ """Plotly theme template builder."""
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 build_plotly_template(config: str | Path | Config | None = None) -> dict[str, Any]:
12
+ """Build a reusable Plotly template dictionary from ``config.theme``.
13
+
14
+ The returned dictionary can be passed directly to ``fig.update_layout(template=...)``
15
+ or registered with ``plotly.io.templates``.
16
+
17
+ Args:
18
+ config: Optional Config object, preset name, or path to YAML/TOML config.
19
+
20
+ Returns:
21
+ Plotly template dictionary with a ``"layout"`` specification.
22
+ """
23
+ cfg = ensure_config(config)
24
+ t = cfg.theme
25
+ return {
26
+ "layout": {
27
+ "font": {
28
+ "family": t.font_family,
29
+ "size": t.label_size,
30
+ "color": t.text_color,
31
+ },
32
+ "title": {
33
+ "font": {
34
+ "family": t.font_family,
35
+ "size": t.title_size,
36
+ "color": t.text_color,
37
+ },
38
+ "x": 0.0,
39
+ "xanchor": "left",
40
+ },
41
+ "paper_bgcolor": t.background_color,
42
+ "plot_bgcolor": t.axes_facecolor,
43
+ "xaxis": {
44
+ "showgrid": t.show_grid,
45
+ "gridcolor": t.grid_color,
46
+ "gridwidth": t.grid_width,
47
+ "linecolor": t.spine_color,
48
+ "tickfont": {"size": t.tick_size, "color": t.text_color},
49
+ },
50
+ "yaxis": {
51
+ "showgrid": t.show_grid,
52
+ "gridcolor": t.grid_color,
53
+ "gridwidth": t.grid_width,
54
+ "linecolor": t.spine_color,
55
+ "tickfont": {"size": t.tick_size, "color": t.text_color},
56
+ },
57
+ "legend": {
58
+ "font": {"size": t.legend_size, "color": t.text_color},
59
+ },
60
+ }
61
+ }
62
+
63
+
64
+ def build_plotly_log_axis(
65
+ values: Any = None,
66
+ *,
67
+ title: str | None = None,
68
+ showgrid: bool = True,
69
+ gridcolor: str | None = None,
70
+ gridwidth: float | None = None,
71
+ min_val: float | None = None,
72
+ max_val: float | None = None,
73
+ ) -> dict[str, Any]:
74
+ """Build a Plotly log-axis layout dict with clean plain-number decade ticks.
75
+
76
+ Avoids Plotly's awkward ``10k`` / ``2`` / ``5`` / ``1e-3`` log ticks by generating
77
+ explicit ``tickvals`` and plain ``ticktext`` (e.g., ``0.001``, ``0.01``, ``0.1``,
78
+ ``1``, ``10``, ``100``, ``1,000``). Adds ``2×`` and ``5×`` intermediate ticks when
79
+ the data spans fewer than 2 orders of magnitude.
80
+ """
81
+ import math
82
+
83
+ import numpy as np
84
+
85
+ from stplot.theme.mpl import format_log_value
86
+
87
+ cfg_axis: dict[str, Any] = {
88
+ "type": "log",
89
+ "showgrid": showgrid,
90
+ "zeroline": False,
91
+ "minor": {"ticks": "outside", "showgrid": False},
92
+ }
93
+ if title is not None:
94
+ cfg_axis["title"] = title
95
+ if gridcolor is not None:
96
+ cfg_axis["gridcolor"] = gridcolor
97
+ if gridwidth is not None:
98
+ cfg_axis["gridwidth"] = gridwidth
99
+
100
+ pos_vals: list[float] = []
101
+ if values is not None:
102
+ arr = np.asarray(values, dtype=float)
103
+ arr = arr[np.isfinite(arr) & (arr > 0)]
104
+ pos_vals.extend(arr.tolist())
105
+ if min_val is not None and min_val > 0:
106
+ pos_vals.append(float(min_val))
107
+ if max_val is not None and max_val > 0:
108
+ pos_vals.append(float(max_val))
109
+
110
+ if pos_vals:
111
+ lo = min(pos_vals)
112
+ hi = max(pos_vals)
113
+ d_lo = math.floor(math.log10(lo))
114
+ d_hi = math.ceil(math.log10(hi))
115
+ span = d_hi - d_lo
116
+ subs = (1.0, 2.0, 5.0) if span <= 2 else (1.0,)
117
+ tickvals: list[float] = []
118
+ for exp in range(d_lo, d_hi + 1):
119
+ base = 10.0**exp
120
+ for s in subs:
121
+ v = base * s
122
+ if lo * 0.5 <= v <= hi * 2.0:
123
+ tickvals.append(v)
124
+ if not tickvals:
125
+ tickvals = [10.0**exp for exp in range(d_lo, d_hi + 1)]
126
+ cfg_axis["tickmode"] = "array"
127
+ cfg_axis["tickvals"] = tickvals
128
+ cfg_axis["ticktext"] = [format_log_value(v) for v in tickvals]
129
+
130
+ return cfg_axis
@@ -0,0 +1,60 @@
1
+ """Pure DataFrame preprocessing, spatial zone assignment, pairing, and grouping helpers."""
2
+
3
+ from stplot.transform.categories import order_categories
4
+ from stplot.transform.columns import apply_display_labels, standardize_columns, validate_columns
5
+ from stplot.transform.filters import (
6
+ build_fmu_vs_region_table,
7
+ derive_pass_fail,
8
+ derive_trend_direction_3level,
9
+ filter_sites,
10
+ split_by_site_group,
11
+ )
12
+ from stplot.transform.merge import combine_period_dataframes, merge_state_and_trends
13
+ from stplot.transform.pairing import pair_upstream_downstream
14
+ from stplot.transform.qa import AuditReport, audit_results_data, split_full_and_preliminary
15
+ from stplot.transform.tables import (
16
+ build_data_sufficiency_table,
17
+ build_exceedance_watchlist_table,
18
+ build_grade_change_table,
19
+ build_indicator_coverage_table,
20
+ build_network_summary_table,
21
+ build_site_master_table,
22
+ build_top_movers_table,
23
+ select_top_bottom_sites,
24
+ )
25
+ from stplot.transform.zones import (
26
+ assign_zones,
27
+ assign_zones_spatial,
28
+ override_site_zones,
29
+ summarise_by_group,
30
+ )
31
+
32
+ __all__ = [
33
+ "AuditReport",
34
+ "apply_display_labels",
35
+ "assign_zones",
36
+ "assign_zones_spatial",
37
+ "audit_results_data",
38
+ "build_data_sufficiency_table",
39
+ "build_exceedance_watchlist_table",
40
+ "build_fmu_vs_region_table",
41
+ "build_grade_change_table",
42
+ "build_indicator_coverage_table",
43
+ "build_network_summary_table",
44
+ "build_site_master_table",
45
+ "build_top_movers_table",
46
+ "combine_period_dataframes",
47
+ "derive_pass_fail",
48
+ "derive_trend_direction_3level",
49
+ "filter_sites",
50
+ "merge_state_and_trends",
51
+ "order_categories",
52
+ "override_site_zones",
53
+ "pair_upstream_downstream",
54
+ "select_top_bottom_sites",
55
+ "split_by_site_group",
56
+ "split_full_and_preliminary",
57
+ "standardize_columns",
58
+ "summarise_by_group",
59
+ "validate_columns",
60
+ ]
@@ -0,0 +1,51 @@
1
+ """Category ordering helpers for state bands and trend classifications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pandas as pd
8
+
9
+ from stplot.config import Config, ensure_config, resolve_category_order, resolve_column
10
+ from stplot.transform.columns import validate_columns
11
+
12
+
13
+ def order_categories(
14
+ df: pd.DataFrame,
15
+ *,
16
+ col: str | None = None,
17
+ col_key: str = "state_band",
18
+ order: list[str] | None = None,
19
+ order_key: str = "state_bands",
20
+ include_extras: bool = True,
21
+ config: str | Path | Config | None = None,
22
+ ) -> pd.DataFrame:
23
+ """Convert a classification column into an ordered ``pandas.Categorical``.
24
+
25
+ Args:
26
+ df: Input DataFrame (not mutated).
27
+ col: Explicit column name override. Defaults to ``config.columns[col_key]``.
28
+ col_key: Logical column key in ``config.columns``.
29
+ order: Explicit ordered list of category labels. Defaults to
30
+ ``config.category_orders[order_key]``.
31
+ order_key: Logical order key in ``config.category_orders``.
32
+ include_extras: If True, any non-null values present in ``df[col]`` that are not in
33
+ ``order`` are appended to the category list instead of becoming ``NaN``.
34
+ config: Optional Config object, preset name, or path to YAML/TOML config.
35
+
36
+ Returns:
37
+ Copy of ``df`` with the target column cast to an ordered ``Categorical``.
38
+ """
39
+ cfg = ensure_config(config)
40
+ target_col = resolve_column(col, cfg, col_key)
41
+ validate_columns(df, [target_col], context="order_categories")
42
+
43
+ categories = resolve_category_order(order, cfg, order_key)
44
+
45
+ out = df.copy()
46
+ if include_extras:
47
+ present = [v for v in out[target_col].dropna().unique().tolist() if v not in categories]
48
+ categories = [*categories, *present]
49
+
50
+ out[target_col] = pd.Categorical(out[target_col], categories=categories, ordered=True)
51
+ return out
@@ -0,0 +1,103 @@
1
+ """Column validation and standardization helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+
10
+ from stplot.config import Config, ensure_config
11
+
12
+
13
+ def validate_columns(
14
+ df: pd.DataFrame,
15
+ required: Iterable[str],
16
+ *,
17
+ context: str = "",
18
+ ) -> None:
19
+ """Validate that all required columns exist in ``df``.
20
+
21
+ Args:
22
+ df: Input DataFrame to validate.
23
+ required: Iterable of required column names.
24
+ context: Optional function or operation name included in the error message.
25
+
26
+ Raises:
27
+ KeyError: If one or more required columns are missing from ``df``.
28
+ """
29
+ required_list = list(required)
30
+ missing = [col for col in required_list if col not in df.columns]
31
+ if missing:
32
+ prefix = f"{context}: " if context else ""
33
+ available = list(df.columns)
34
+ raise KeyError(
35
+ f"{prefix}Missing required column(s): {missing}. "
36
+ f"Available columns: {available}."
37
+ )
38
+
39
+
40
+ def standardize_columns(
41
+ df: pd.DataFrame,
42
+ rename_map: dict[str, str],
43
+ *,
44
+ strict: bool = False,
45
+ ) -> pd.DataFrame:
46
+ """Return a copy of ``df`` with columns renamed according to ``rename_map``.
47
+
48
+ Args:
49
+ df: Input DataFrame (not mutated).
50
+ rename_map: Mapping of ``{source_column: target_column}``.
51
+ strict: If True, raise ``KeyError`` if any key in ``rename_map`` is missing.
52
+
53
+ Returns:
54
+ Copy of ``df`` with renamed columns.
55
+ """
56
+ if strict:
57
+ validate_columns(df, rename_map.keys(), context="standardize_columns")
58
+ out = df.copy()
59
+ existing_map = {src: dst for src, dst in rename_map.items() if src in out.columns}
60
+ return out.rename(columns=existing_map)
61
+
62
+
63
+ def apply_display_labels(
64
+ df: pd.DataFrame,
65
+ *,
66
+ cols: Iterable[str] | None = None,
67
+ labels: dict[str, str] | None = None,
68
+ config: str | Path | Config | None = None,
69
+ ) -> pd.DataFrame:
70
+ """Replace raw indicator/place codes with clean display labels (including macrons).
71
+
72
+ Uses ``config.labels`` merged with any explicit ``labels`` overrides. By default
73
+ applies to indicator, FMU, zone, and catchment columns present in ``df``.
74
+
75
+ Args:
76
+ df: Input DataFrame (not mutated).
77
+ cols: Specific column names to transform. If omitted, transforms any present
78
+ columns matching ``indicator``, ``fmu``, ``zone``, or ``catchment`` in config.
79
+ labels: Optional explicit ``{raw_value: display_label}`` overrides.
80
+ config: Optional Config object, preset name, or path to YAML/TOML config.
81
+
82
+ Returns:
83
+ Copy of ``df`` with display labels applied.
84
+ """
85
+ cfg = ensure_config(config)
86
+ label_map = {**cfg.labels, **(labels or {})}
87
+ if not label_map:
88
+ return df.copy()
89
+
90
+ if cols is not None:
91
+ target_cols = [c for c in cols if c in df.columns]
92
+ else:
93
+ default_keys = ("indicator", "fmu", "zone", "catchment")
94
+ target_cols = [
95
+ cfg.columns[k]
96
+ for k in default_keys
97
+ if k in cfg.columns and cfg.columns[k] in df.columns
98
+ ]
99
+
100
+ out = df.copy()
101
+ for col in dict.fromkeys(target_cols):
102
+ out[col] = out[col].replace(label_map)
103
+ return out