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.
- stplot/__init__.py +21 -0
- stplot/config/__init__.py +33 -0
- stplot/config/loader.py +106 -0
- stplot/config/models.py +328 -0
- stplot/config/presets/__init__.py +1 -0
- stplot/config/presets/default.yaml +208 -0
- stplot/config/presets/horizons_one_plan.yaml +59 -0
- stplot/io/__init__.py +6 -0
- stplot/io/spatial.py +72 -0
- stplot/io/tabular.py +154 -0
- stplot/plots/__init__.py +122 -0
- stplot/plots/barbell.py +400 -0
- stplot/plots/batch.py +135 -0
- stplot/plots/domains.py +1143 -0
- stplot/plots/executive.py +474 -0
- stplot/plots/export.py +74 -0
- stplot/plots/infographics.py +1118 -0
- stplot/plots/lollipop.py +285 -0
- stplot/plots/maps.py +738 -0
- stplot/plots/matrix.py +190 -0
- stplot/plots/one_plan.py +642 -0
- stplot/plots/paired.py +437 -0
- stplot/plots/scorecards.py +1940 -0
- stplot/plots/state.py +373 -0
- stplot/plots/state_trends.py +1413 -0
- stplot/plots/tables.py +107 -0
- stplot/plots/timeseries.py +607 -0
- stplot/plots/trends.py +305 -0
- stplot/reporting/__init__.py +24 -0
- stplot/reporting/captions.py +177 -0
- stplot/reporting/html_companion.py +339 -0
- stplot/reporting/templates.py +485 -0
- stplot/reporting/word.py +369 -0
- stplot/theme/__init__.py +25 -0
- stplot/theme/folium.py +62 -0
- stplot/theme/mpl.py +181 -0
- stplot/theme/plotly.py +130 -0
- stplot/transform/__init__.py +60 -0
- stplot/transform/categories.py +51 -0
- stplot/transform/columns.py +103 -0
- stplot/transform/filters.py +385 -0
- stplot/transform/merge.py +173 -0
- stplot/transform/pairing.py +154 -0
- stplot/transform/qa.py +297 -0
- stplot/transform/tables.py +573 -0
- stplot/transform/zones.py +354 -0
- stplot-0.1.0.dist-info/METADATA +235 -0
- stplot-0.1.0.dist-info/RECORD +49 -0
- stplot-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
"""Pre-analysis site filtering, splitting, derived reporting labels, and summary tables."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from stplot.config import (
|
|
11
|
+
Config,
|
|
12
|
+
ensure_config,
|
|
13
|
+
resolve_category_order,
|
|
14
|
+
resolve_column,
|
|
15
|
+
resolve_indicator_direction,
|
|
16
|
+
)
|
|
17
|
+
from stplot.transform.columns import validate_columns
|
|
18
|
+
|
|
19
|
+
_IMPROVING_CONF = {
|
|
20
|
+
"virtually certain",
|
|
21
|
+
"extremely likely",
|
|
22
|
+
"very likely",
|
|
23
|
+
"likely",
|
|
24
|
+
}
|
|
25
|
+
_DEGRADING_CONF = {
|
|
26
|
+
"unlikely",
|
|
27
|
+
"very unlikely",
|
|
28
|
+
"extremely unlikely",
|
|
29
|
+
"exceptionally unlikely",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _as_list(value: str | int | Sequence[str | int]) -> list[str | int]:
|
|
34
|
+
if isinstance(value, (str, int)):
|
|
35
|
+
return [value]
|
|
36
|
+
return list(value)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def filter_sites(
|
|
40
|
+
df: pd.DataFrame,
|
|
41
|
+
*,
|
|
42
|
+
site_type: str | Sequence[str] | None = None,
|
|
43
|
+
status: str | Sequence[str] | None = None,
|
|
44
|
+
fmu: str | Sequence[str] | None = None,
|
|
45
|
+
catchment: str | Sequence[str] | None = None,
|
|
46
|
+
zone: str | Sequence[str] | None = None,
|
|
47
|
+
indicator: str | Sequence[str] | None = None,
|
|
48
|
+
attribute: str | Sequence[str] | None = None,
|
|
49
|
+
period: str | int | Sequence[str | int] | None = None,
|
|
50
|
+
valid_only: bool = False,
|
|
51
|
+
site_type_col: str | None = None,
|
|
52
|
+
status_col: str | None = None,
|
|
53
|
+
fmu_col: str | None = None,
|
|
54
|
+
catchment_col: str | None = None,
|
|
55
|
+
zone_col: str | None = None,
|
|
56
|
+
indicator_col: str | None = None,
|
|
57
|
+
attribute_col: str | None = None,
|
|
58
|
+
period_col: str | None = None,
|
|
59
|
+
filter_ok_col: str | None = None,
|
|
60
|
+
config: str | Path | Config | None = None,
|
|
61
|
+
) -> pd.DataFrame:
|
|
62
|
+
"""Filter state or trends results by site type, status, spatial group, indicator, and validity.
|
|
63
|
+
|
|
64
|
+
All filter criteria accept either a single value or a sequence of values. Unspecified
|
|
65
|
+
filters are ignored.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
df: Input DataFrame (not mutated).
|
|
69
|
+
site_type: Filter by site type (e.g., ``"River"``, ``"Lake"``, ``"Beach"``).
|
|
70
|
+
status: Filter by site status (e.g., ``"RepSite"``, ``"Impact"``).
|
|
71
|
+
fmu: Filter by Freshwater Management Unit (e.g., ``"Manawatu"``).
|
|
72
|
+
catchment: Filter by catchment name.
|
|
73
|
+
zone: Filter by management zone / subzone.
|
|
74
|
+
indicator: Filter by indicator / analyte (e.g., ``"ECOLI"``, ``"DRP"``).
|
|
75
|
+
attribute: Filter by attribute / criteria name (e.g., ``"NOF.DRP.Med"``).
|
|
76
|
+
period: Filter by reporting period (e.g., ``"1990 - 1994"`` or ``5``).
|
|
77
|
+
valid_only: If True, keep only rows passing data-sufficiency checks
|
|
78
|
+
(``True`` for boolean ``FilterOK`` columns, or ``"OK"`` for ``nOK`` string columns).
|
|
79
|
+
site_type_col: Override for ``config.columns["site_type"]``.
|
|
80
|
+
status_col: Override for ``config.columns["site_status"]``.
|
|
81
|
+
fmu_col: Override for ``config.columns["fmu"]``.
|
|
82
|
+
catchment_col: Override for ``config.columns["catchment"]``.
|
|
83
|
+
zone_col: Override for ``config.columns["zone"]``.
|
|
84
|
+
indicator_col: Override for ``config.columns["indicator"]``.
|
|
85
|
+
attribute_col: Override for ``config.columns["attribute"]``.
|
|
86
|
+
period_col: Override for ``config.columns["period"]``.
|
|
87
|
+
filter_ok_col: Override for ``config.columns["filter_ok"]``.
|
|
88
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
Filtered copy of ``df``.
|
|
92
|
+
"""
|
|
93
|
+
cfg = ensure_config(config)
|
|
94
|
+
mask = pd.Series(True, index=df.index)
|
|
95
|
+
|
|
96
|
+
criteria: list[tuple[str | int | Sequence[str | int] | None, str | None, str]] = [
|
|
97
|
+
(site_type, site_type_col, "site_type"),
|
|
98
|
+
(status, status_col, "site_status"),
|
|
99
|
+
(fmu, fmu_col, "fmu"),
|
|
100
|
+
(catchment, catchment_col, "catchment"),
|
|
101
|
+
(zone, zone_col, "zone"),
|
|
102
|
+
(indicator, indicator_col, "indicator"),
|
|
103
|
+
(attribute, attribute_col, "attribute"),
|
|
104
|
+
(period, period_col, "period"),
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
for value, col_override, key in criteria:
|
|
108
|
+
if value is not None:
|
|
109
|
+
col = resolve_column(col_override, cfg, key)
|
|
110
|
+
validate_columns(df, [col], context="filter_sites")
|
|
111
|
+
mask &= df[col].isin(_as_list(value))
|
|
112
|
+
|
|
113
|
+
if valid_only:
|
|
114
|
+
ok_col = resolve_column(filter_ok_col, cfg, "filter_ok")
|
|
115
|
+
validate_columns(df, [ok_col], context="filter_sites(valid_only)")
|
|
116
|
+
series = df[ok_col]
|
|
117
|
+
if pd.api.types.is_bool_dtype(series):
|
|
118
|
+
mask &= series.fillna(False)
|
|
119
|
+
else:
|
|
120
|
+
mask &= series.astype(str).str.strip().str.upper().isin({"OK", "TRUE", "1"})
|
|
121
|
+
|
|
122
|
+
return df.loc[mask].copy()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def split_by_site_group(
|
|
126
|
+
df: pd.DataFrame,
|
|
127
|
+
*,
|
|
128
|
+
col: str | None = None,
|
|
129
|
+
col_key: str = "site_status",
|
|
130
|
+
dropna: bool = True,
|
|
131
|
+
config: str | Path | Config | None = None,
|
|
132
|
+
) -> dict[str, pd.DataFrame]:
|
|
133
|
+
"""Split a results DataFrame into a dict of DataFrames keyed by site group.
|
|
134
|
+
|
|
135
|
+
Useful for separating ``RepSite`` vs ``Impact`` or ``River`` vs ``Lake`` vs ``Beach``.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
df: Input DataFrame (not mutated).
|
|
139
|
+
col: Explicit grouping column override. Defaults to ``config.columns[col_key]``.
|
|
140
|
+
col_key: Config column key (e.g., ``"site_status"`` or ``"site_type"``).
|
|
141
|
+
dropna: If True, exclude rows with missing group values.
|
|
142
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
Dictionary mapping group labels (as strings) to copied DataFrames.
|
|
146
|
+
"""
|
|
147
|
+
cfg = ensure_config(config)
|
|
148
|
+
group_col = resolve_column(col, cfg, col_key)
|
|
149
|
+
validate_columns(df, [group_col], context="split_by_site_group")
|
|
150
|
+
|
|
151
|
+
result: dict[str, pd.DataFrame] = {}
|
|
152
|
+
for key, sub_df in df.groupby(group_col, dropna=dropna, observed=False):
|
|
153
|
+
result[str(key)] = sub_df.copy()
|
|
154
|
+
return result
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def derive_pass_fail(
|
|
158
|
+
df: pd.DataFrame,
|
|
159
|
+
*,
|
|
160
|
+
passes_col: str | None = None,
|
|
161
|
+
ok_col: str | None = None,
|
|
162
|
+
out_col: str = "ComplianceResult",
|
|
163
|
+
pass_label: str = "Pass",
|
|
164
|
+
fail_label: str = "Fail",
|
|
165
|
+
include_insufficient: bool = True,
|
|
166
|
+
config: str | Path | Config | None = None,
|
|
167
|
+
) -> pd.DataFrame:
|
|
168
|
+
"""Derive human-readable Pass/Fail compliance labels from One Plan results.
|
|
169
|
+
|
|
170
|
+
Combines boolean ``SitePasses`` with data-sufficiency flags (``nOK``) so rows with
|
|
171
|
+
insufficient data are explicitly labelled rather than misclassified as Pass/Fail.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
df: Input One Plan DataFrame (not mutated).
|
|
175
|
+
passes_col: Boolean pass/fail column. Defaults to ``config.columns["state_band"]``.
|
|
176
|
+
ok_col: Data sufficiency column. Defaults to ``config.columns["filter_ok"]``.
|
|
177
|
+
out_col: Name of the output label column.
|
|
178
|
+
pass_label: Label for passing sites (default ``"Pass"``).
|
|
179
|
+
fail_label: Label for failing sites (default ``"Fail"``).
|
|
180
|
+
include_insufficient: If True, preserve non-``"OK"`` values from ``ok_col``
|
|
181
|
+
(e.g., ``"Insufficient data"``); if False, set them to ``pd.NA``.
|
|
182
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
Copy of ``df`` with ``out_col`` added.
|
|
186
|
+
"""
|
|
187
|
+
cfg = ensure_config(config)
|
|
188
|
+
p_col = resolve_column(passes_col, cfg, "state_band")
|
|
189
|
+
validate_columns(df, [p_col], context="derive_pass_fail")
|
|
190
|
+
|
|
191
|
+
out = df.copy()
|
|
192
|
+
labels = out[p_col].map({True: pass_label, False: fail_label}).astype("object")
|
|
193
|
+
|
|
194
|
+
resolved_ok = resolve_column(ok_col, cfg, "filter_ok")
|
|
195
|
+
if resolved_ok in out.columns:
|
|
196
|
+
ok_series = out[resolved_ok]
|
|
197
|
+
not_ok_mask = ok_series.astype(str).str.strip().str.upper() != "OK"
|
|
198
|
+
if include_insufficient:
|
|
199
|
+
labels = labels.where(~not_ok_mask, ok_series.astype(str))
|
|
200
|
+
else:
|
|
201
|
+
labels = labels.where(~not_ok_mask, pd.NA)
|
|
202
|
+
|
|
203
|
+
out[out_col] = labels
|
|
204
|
+
return out
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def derive_trend_direction_3level(
|
|
208
|
+
df: pd.DataFrame,
|
|
209
|
+
*,
|
|
210
|
+
confidence_col: str | None = None,
|
|
211
|
+
category_col: str | None = None,
|
|
212
|
+
indicator_col: str | None = None,
|
|
213
|
+
indicator: str | None = None,
|
|
214
|
+
indicator_directions: dict[str, str] | None = None,
|
|
215
|
+
out_col: str = "TrendSummary",
|
|
216
|
+
config: str | Path | Config | None = None,
|
|
217
|
+
) -> pd.DataFrame:
|
|
218
|
+
"""Collapse IPCC/LWP 9-band trend likelihoods into 3-level Improving/Indeterminate/Degrading.
|
|
219
|
+
|
|
220
|
+
- For pre-oriented LWP labels (e.g., ``"Very likely improving"``, ``"Likely"``):
|
|
221
|
+
``Virtually certain``–``Likely`` -> ``"Improving"``; ``As likely as not`` ->
|
|
222
|
+
``"Indeterminate"``; ``Unlikely``–``Exceptionally unlikely`` -> ``"Degrading"``.
|
|
223
|
+
- For raw directional labels (``"... increasing"`` / ``"... decreasing"``):
|
|
224
|
+
uses ``indicator_directions`` (explicit dict > ``config.indicator_directions`` >
|
|
225
|
+
``"lower_is_better"``) so increasing Clarity/MCI maps to ``"Improving"`` while
|
|
226
|
+
increasing DRP/E. coli maps to ``"Degrading"``.
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
df: Input trends DataFrame (not mutated).
|
|
230
|
+
confidence_col: Column containing IPCC likelihood labels (defaults to
|
|
231
|
+
``config.columns["trend_confidence"]``).
|
|
232
|
+
category_col: Optional fallback column (e.g., ``Improving_Confidence``) used if
|
|
233
|
+
``confidence_col`` is absent.
|
|
234
|
+
indicator_col: Optional indicator column (defaults to ``config.columns["indicator"]``
|
|
235
|
+
when present in ``df``) used to resolve per-row polarity.
|
|
236
|
+
indicator: Optional single indicator name override when ``df`` has no indicator column.
|
|
237
|
+
indicator_directions: Optional per-call mapping overriding ``config.indicator_directions``
|
|
238
|
+
(e.g., ``{"MY_METRIC": "higher_is_better"}``).
|
|
239
|
+
out_col: Output column name (default ``"TrendSummary"``).
|
|
240
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
Copy of ``df`` with ``out_col`` added.
|
|
244
|
+
"""
|
|
245
|
+
cfg = ensure_config(config)
|
|
246
|
+
conf = resolve_column(confidence_col, cfg, "trend_confidence")
|
|
247
|
+
cat = resolve_column(category_col, cfg, "trend_category")
|
|
248
|
+
r_ind = indicator_col if indicator_col is not None else cfg.columns.get("indicator")
|
|
249
|
+
|
|
250
|
+
source_col = conf if conf in df.columns else cat
|
|
251
|
+
validate_columns(df, [source_col], context="derive_trend_direction_3level")
|
|
252
|
+
|
|
253
|
+
def _classify(val: object, ind_name: str | None) -> str:
|
|
254
|
+
if pd.isna(val):
|
|
255
|
+
return "Not Analysed"
|
|
256
|
+
text = str(val).strip().lower()
|
|
257
|
+
if text in {"improving", "degrading", "indeterminate"}:
|
|
258
|
+
return text.capitalize()
|
|
259
|
+
|
|
260
|
+
# Detect raw increasing/decreasing polarity suffixes
|
|
261
|
+
raw_dir: str | None = None
|
|
262
|
+
if text == "increasing" or text.endswith(" increasing"):
|
|
263
|
+
raw_dir = "increasing"
|
|
264
|
+
text = text[: -len("increasing")].strip()
|
|
265
|
+
elif text == "decreasing" or text.endswith(" decreasing"):
|
|
266
|
+
raw_dir = "decreasing"
|
|
267
|
+
text = text[: -len("decreasing")].strip()
|
|
268
|
+
elif text.endswith(" improving"):
|
|
269
|
+
text = text[: -len(" improving")].strip()
|
|
270
|
+
elif text.endswith(" degrading"):
|
|
271
|
+
text = text[: -len(" degrading")].strip()
|
|
272
|
+
# "Likely degrading" -> Degrading; "Unlikely degrading" -> Improving
|
|
273
|
+
if text in _IMPROVING_CONF:
|
|
274
|
+
return "Degrading"
|
|
275
|
+
if text in _DEGRADING_CONF:
|
|
276
|
+
return "Improving"
|
|
277
|
+
if text == "as likely as not":
|
|
278
|
+
return "Indeterminate"
|
|
279
|
+
return "Not Analysed"
|
|
280
|
+
|
|
281
|
+
if text in {"as likely as not", "indeterminate"}:
|
|
282
|
+
return "Indeterminate"
|
|
283
|
+
|
|
284
|
+
if raw_dir is not None:
|
|
285
|
+
direction = resolve_indicator_direction(
|
|
286
|
+
ind_name,
|
|
287
|
+
cfg,
|
|
288
|
+
overrides=indicator_directions,
|
|
289
|
+
)
|
|
290
|
+
higher_good = direction == "higher_is_better"
|
|
291
|
+
is_inc = raw_dir == "increasing"
|
|
292
|
+
positive_means_improving = is_inc == higher_good
|
|
293
|
+
if text == "" or text in _IMPROVING_CONF:
|
|
294
|
+
return "Improving" if positive_means_improving else "Degrading"
|
|
295
|
+
if text in _DEGRADING_CONF:
|
|
296
|
+
return "Degrading" if positive_means_improving else "Improving"
|
|
297
|
+
return "Not Analysed"
|
|
298
|
+
|
|
299
|
+
if text in _IMPROVING_CONF:
|
|
300
|
+
return "Improving"
|
|
301
|
+
if text in _DEGRADING_CONF:
|
|
302
|
+
return "Degrading"
|
|
303
|
+
return "Not Analysed"
|
|
304
|
+
|
|
305
|
+
out = df.copy()
|
|
306
|
+
has_ind_col = r_ind is not None and r_ind in out.columns
|
|
307
|
+
if has_ind_col:
|
|
308
|
+
out[out_col] = [
|
|
309
|
+
_classify(v, str(i) if pd.notna(i) else indicator)
|
|
310
|
+
for v, i in zip(out[source_col], out[r_ind], strict=True)
|
|
311
|
+
]
|
|
312
|
+
else:
|
|
313
|
+
out[out_col] = [_classify(v, indicator) for v in out[source_col]]
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def build_fmu_vs_region_table(
|
|
318
|
+
df: pd.DataFrame,
|
|
319
|
+
*,
|
|
320
|
+
fmu: str,
|
|
321
|
+
fmu_col: str | None = None,
|
|
322
|
+
category_col: str | None = None,
|
|
323
|
+
category_key: str = "state_band",
|
|
324
|
+
order: list[str] | None = None,
|
|
325
|
+
order_key: str = "state_bands",
|
|
326
|
+
fmu_label: str | None = None,
|
|
327
|
+
region_label: str = "Whole Region",
|
|
328
|
+
decimals: int = 1,
|
|
329
|
+
include_empty_categories: bool = False,
|
|
330
|
+
config: str | Path | Config | None = None,
|
|
331
|
+
) -> pd.DataFrame:
|
|
332
|
+
"""Build a 2-row summary table comparing an FMU against the Whole Region as ``"% (n)"``.
|
|
333
|
+
|
|
334
|
+
Args:
|
|
335
|
+
df: Input results DataFrame (pre-filtered for the desired indicator/period).
|
|
336
|
+
fmu: Name of the target FMU in ``fmu_col``.
|
|
337
|
+
fmu_col: FMU column override. Defaults to ``config.columns["fmu"]``.
|
|
338
|
+
category_col: Category column override. Defaults to ``config.columns[category_key]``.
|
|
339
|
+
category_key: Config column key when ``category_col`` is None (e.g., ``"state_band"``
|
|
340
|
+
or ``"trend_direction"``).
|
|
341
|
+
order: Explicit display order for columns. Defaults to
|
|
342
|
+
``config.category_orders[order_key]``.
|
|
343
|
+
order_key: Config category order key when ``order`` is None.
|
|
344
|
+
fmu_label: Display label for the FMU row. Defaults to ``f"{fmu} FMU"``.
|
|
345
|
+
region_label: Display label for the whole-region row.
|
|
346
|
+
decimals: Number of decimal places for percentages (e.g., ``1`` -> ``"7.5% (4)"``).
|
|
347
|
+
include_empty_categories: If True, keep all categories in ``order`` even if count is 0.
|
|
348
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
349
|
+
|
|
350
|
+
Returns:
|
|
351
|
+
DataFrame with two rows (``fmu_label`` and ``region_label``) and columns for each
|
|
352
|
+
category, formatted as ``"XX.X% (n)"``.
|
|
353
|
+
"""
|
|
354
|
+
cfg = ensure_config(config)
|
|
355
|
+
resolved_fmu = resolve_column(fmu_col, cfg, "fmu")
|
|
356
|
+
resolved_cat = resolve_column(category_col, cfg, category_key)
|
|
357
|
+
validate_columns(df, [resolved_fmu, resolved_cat], context="build_fmu_vs_region_table")
|
|
358
|
+
|
|
359
|
+
categories = resolve_category_order(order, cfg, order_key)
|
|
360
|
+
if not include_empty_categories:
|
|
361
|
+
present = set(df[resolved_cat].dropna().astype(str).unique())
|
|
362
|
+
active = [c for c in categories if c in present]
|
|
363
|
+
if active:
|
|
364
|
+
categories = active
|
|
365
|
+
|
|
366
|
+
fmu_df = df[df[resolved_fmu] == fmu]
|
|
367
|
+
|
|
368
|
+
def _format_row(sub: pd.DataFrame) -> dict[str, str]:
|
|
369
|
+
counts = sub[resolved_cat].astype(str).value_counts()
|
|
370
|
+
total = int(sum(counts.get(c, 0) for c in categories))
|
|
371
|
+
row: dict[str, str] = {}
|
|
372
|
+
for c in categories:
|
|
373
|
+
n = int(counts.get(c, 0))
|
|
374
|
+
pct = (100.0 * n / total) if total > 0 else 0.0
|
|
375
|
+
row[c] = f"{pct:.{decimals}f}% ({n})"
|
|
376
|
+
return row
|
|
377
|
+
|
|
378
|
+
row_label = fmu_label if fmu_label is not None else f"{fmu} FMU"
|
|
379
|
+
return pd.DataFrame.from_dict(
|
|
380
|
+
{
|
|
381
|
+
row_label: _format_row(fmu_df),
|
|
382
|
+
region_label: _format_row(df),
|
|
383
|
+
},
|
|
384
|
+
orient="index",
|
|
385
|
+
)
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Pure DataFrame merging helpers for State + Trends and multi-period historical files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from stplot.config import Config, ensure_config, resolve_column
|
|
11
|
+
from stplot.transform.columns import validate_columns
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def merge_state_and_trends(
|
|
15
|
+
state_df: pd.DataFrame,
|
|
16
|
+
trend_df: pd.DataFrame,
|
|
17
|
+
*,
|
|
18
|
+
on: list[str] | tuple[str, ...] | None = None,
|
|
19
|
+
site_col: str | None = None,
|
|
20
|
+
indicator_col: str | None = None,
|
|
21
|
+
period_col: str | None = None,
|
|
22
|
+
trend_period_col: str | None = None,
|
|
23
|
+
trend_period: str | None = None,
|
|
24
|
+
state_period: str | None = None,
|
|
25
|
+
how: str = "left",
|
|
26
|
+
drop_duplicate_cols: bool = True,
|
|
27
|
+
suffixes: tuple[str, str] = ("_state", "_trend"),
|
|
28
|
+
config: str | Path | Config | None = None,
|
|
29
|
+
) -> pd.DataFrame:
|
|
30
|
+
"""Merge a State results DataFrame with a separate Trends results DataFrame.
|
|
31
|
+
|
|
32
|
+
Automatically resolves join keys from ``config`` (``site_id`` + ``indicator``, plus
|
|
33
|
+
``period`` when matching across both tables unless ``state_period`` / ``trend_period``
|
|
34
|
+
filtering is used). Prevents Cartesian row multiplication when ``trend_df`` contains
|
|
35
|
+
multiple trend windows (e.g., 10-yr, 20-yr, 30-yr) by letting you filter via
|
|
36
|
+
``trend_period=...``.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
state_df: Pre-computed State DataFrame (not mutated).
|
|
40
|
+
trend_df: Pre-computed Trends DataFrame (not mutated).
|
|
41
|
+
on: Optional explicit list of join columns (overrides auto-resolved keys).
|
|
42
|
+
site_col: Site identifier column override (defaults to ``config.columns["site_id"]``).
|
|
43
|
+
indicator_col: Indicator column override (defaults to ``config.columns["indicator"]``).
|
|
44
|
+
period_col: Rolling period column override (defaults to ``config.columns["period"]``).
|
|
45
|
+
trend_period_col: Trend window column override (defaults to
|
|
46
|
+
``config.columns["trend_period"]``).
|
|
47
|
+
trend_period: Optional filter applied to ``trend_df`` before merging (e.g., ``"10 year"``
|
|
48
|
+
or ``"2015-2025"``) to select a single trend window.
|
|
49
|
+
state_period: Optional filter applied to ``state_df`` before merging (e.g., ``"2021-2025"``)
|
|
50
|
+
to select the latest 5-year state window.
|
|
51
|
+
how: Pandas merge type (default ``"left"`` so all state sites are preserved).
|
|
52
|
+
drop_duplicate_cols: If True (default), drop non-key columns from ``trend_df`` that
|
|
53
|
+
already exist in ``state_df`` (e.g., ``FMU``, ``NZTM.X``, ``NZTM.Y``) so the
|
|
54
|
+
merged DataFrame stays clean without ``_state``/``_trend`` duplicates.
|
|
55
|
+
suffixes: Suffixes applied if ``drop_duplicate_cols=False``.
|
|
56
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Merged ``pd.DataFrame`` ready for combined State + Trend plots.
|
|
60
|
+
"""
|
|
61
|
+
cfg = ensure_config(config)
|
|
62
|
+
s_work = state_df.copy()
|
|
63
|
+
t_work = trend_df.copy()
|
|
64
|
+
|
|
65
|
+
r_site = resolve_column(site_col, cfg, "site_id")
|
|
66
|
+
r_ind = indicator_col if indicator_col is not None else cfg.columns.get("indicator")
|
|
67
|
+
r_period = period_col if period_col is not None else cfg.columns.get("period")
|
|
68
|
+
r_tperiod = (
|
|
69
|
+
trend_period_col if trend_period_col is not None else cfg.columns.get("trend_period")
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
if state_period is not None:
|
|
73
|
+
if not r_period or r_period not in s_work.columns:
|
|
74
|
+
raise KeyError(
|
|
75
|
+
f"merge_state_and_trends: Cannot filter state_period='{state_period}'; "
|
|
76
|
+
f"period column '{r_period}' not found in state_df."
|
|
77
|
+
)
|
|
78
|
+
s_work = s_work[s_work[r_period].astype(str) == str(state_period)].copy()
|
|
79
|
+
|
|
80
|
+
if trend_period is not None:
|
|
81
|
+
tp_target = (
|
|
82
|
+
r_tperiod
|
|
83
|
+
if (r_tperiod and r_tperiod in t_work.columns)
|
|
84
|
+
else (r_period if (r_period and r_period in t_work.columns) else None)
|
|
85
|
+
)
|
|
86
|
+
if tp_target is None:
|
|
87
|
+
raise KeyError(
|
|
88
|
+
f"merge_state_and_trends: Cannot filter trend_period='{trend_period}'; "
|
|
89
|
+
f"neither '{r_tperiod}' nor '{r_period}' found in trend_df."
|
|
90
|
+
)
|
|
91
|
+
t_work = t_work[t_work[tp_target].astype(str) == str(trend_period)].copy()
|
|
92
|
+
|
|
93
|
+
if on is not None:
|
|
94
|
+
join_cols = list(on)
|
|
95
|
+
else:
|
|
96
|
+
join_cols = [r_site]
|
|
97
|
+
if r_ind and r_ind in s_work.columns and r_ind in t_work.columns:
|
|
98
|
+
join_cols.append(r_ind)
|
|
99
|
+
# Include period in join keys only if present in both AND neither was pre-filtered
|
|
100
|
+
if (
|
|
101
|
+
state_period is None
|
|
102
|
+
and trend_period is None
|
|
103
|
+
and r_period
|
|
104
|
+
and r_period in s_work.columns
|
|
105
|
+
and r_period in t_work.columns
|
|
106
|
+
):
|
|
107
|
+
s_vals = set(s_work[r_period].dropna().astype(str))
|
|
108
|
+
t_vals = set(t_work[r_period].dropna().astype(str))
|
|
109
|
+
if s_vals & t_vals:
|
|
110
|
+
join_cols.append(r_period)
|
|
111
|
+
|
|
112
|
+
validate_columns(s_work, join_cols, context="merge_state_and_trends (state_df)")
|
|
113
|
+
validate_columns(t_work, join_cols, context="merge_state_and_trends (trend_df)")
|
|
114
|
+
|
|
115
|
+
if drop_duplicate_cols:
|
|
116
|
+
keep_t_cols = join_cols + [
|
|
117
|
+
c for c in t_work.columns if c not in s_work.columns and c not in join_cols
|
|
118
|
+
]
|
|
119
|
+
t_work = t_work[keep_t_cols]
|
|
120
|
+
|
|
121
|
+
merged = pd.merge(s_work, t_work, on=join_cols, how=how, suffixes=suffixes)
|
|
122
|
+
return merged.reset_index(drop=True)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def combine_period_dataframes(
|
|
126
|
+
period_dfs: Mapping[str, pd.DataFrame],
|
|
127
|
+
*,
|
|
128
|
+
period_col: str | None = None,
|
|
129
|
+
sort_periods: bool = True,
|
|
130
|
+
overwrite_period: bool = True,
|
|
131
|
+
config: str | Path | Config | None = None,
|
|
132
|
+
) -> pd.DataFrame:
|
|
133
|
+
"""Stack multiple period-specific DataFrames into one tidy multi-period DataFrame.
|
|
134
|
+
|
|
135
|
+
Ideal for combining separate historical One Plan or NPS-FM state exports (e.g.,
|
|
136
|
+
``{"2015–2020": df_15_20, "2020–2025": df_20_25}``) into a single DataFrame with
|
|
137
|
+
a canonical period column ready for ``state_over_time``, ``water_quality_stripes``,
|
|
138
|
+
``slopegraph``, ``grade_transition_sankey``, and ``build_grade_change_table``.
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
period_dfs: Mapping of ``{period_label: DataFrame}``.
|
|
142
|
+
period_col: Target period column name (defaults to ``config.columns["period"]``).
|
|
143
|
+
sort_periods: If True, sort period labels chronologically/lexicographically before
|
|
144
|
+
concatenating and set an ordered categorical dtype on ``period_col``.
|
|
145
|
+
overwrite_period: If True (default), always set ``period_col`` to the mapping key
|
|
146
|
+
even if the column already exists in a DataFrame.
|
|
147
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
Combined ``pd.DataFrame`` with all periods stacked cleanly.
|
|
151
|
+
"""
|
|
152
|
+
if not period_dfs:
|
|
153
|
+
raise ValueError("combine_period_dataframes: 'period_dfs' mapping cannot be empty.")
|
|
154
|
+
|
|
155
|
+
cfg = ensure_config(config)
|
|
156
|
+
r_period = resolve_column(period_col, cfg, "period")
|
|
157
|
+
|
|
158
|
+
labels = sorted(period_dfs.keys()) if sort_periods else list(period_dfs.keys())
|
|
159
|
+
frames: list[pd.DataFrame] = []
|
|
160
|
+
for label in labels:
|
|
161
|
+
part = period_dfs[label].copy()
|
|
162
|
+
if overwrite_period or r_period not in part.columns:
|
|
163
|
+
part[r_period] = str(label)
|
|
164
|
+
frames.append(part)
|
|
165
|
+
|
|
166
|
+
combined = pd.concat(frames, ignore_index=True, sort=False)
|
|
167
|
+
if sort_periods:
|
|
168
|
+
combined[r_period] = pd.Categorical(
|
|
169
|
+
combined[r_period].astype(str),
|
|
170
|
+
categories=[str(lbl) for lbl in labels],
|
|
171
|
+
ordered=True,
|
|
172
|
+
)
|
|
173
|
+
return combined
|