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,1143 @@
1
+ """Multi-domain infographic templates (Rivers, Lakes, Estuaries, Coastal, Discharges)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import matplotlib.colors as mcolors
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ import pandas as pd
12
+ from matplotlib.axes import Axes
13
+ from matplotlib.figure import Figure
14
+ from matplotlib.patches import FancyBboxPatch, Polygon, Rectangle
15
+
16
+ from stplot.config import (
17
+ Config,
18
+ ensure_config,
19
+ resolve_category_order,
20
+ resolve_column,
21
+ resolve_label,
22
+ resolve_palette,
23
+ )
24
+ from stplot.theme.mpl import mpl_theme
25
+ from stplot.transform.columns import validate_columns
26
+
27
+
28
+ def _contrast_text(hex_color: str) -> str:
29
+ cleaned = str(hex_color).lstrip("#")
30
+ if len(cleaned) != 6:
31
+ return "#1e2a38"
32
+ r, g, b = int(cleaned[0:2], 16), int(cleaned[2:4], 16), int(cleaned[4:6], 16)
33
+ return "#111111" if (0.299 * r + 0.587 * g + 0.114 * b) > 150 else "#ffffff"
34
+
35
+
36
+ def domain_summary_strip(
37
+ domains: list[dict[str, Any]],
38
+ *,
39
+ palette: dict[str, str] | None = None,
40
+ palette_name: str = "state_bands",
41
+ title: str = "Regional Water Quality — Multi-Domain Overview",
42
+ subtitle: str | None = None,
43
+ figsize: tuple[float, float] | None = None,
44
+ config: str | Path | Config | None = None,
45
+ ) -> tuple[Figure, Axes]:
46
+ """Render a horizontal strip of domain cards (Rivers SoE/Impact, Lakes, Estuaries, etc.).
47
+
48
+ Each dict in ``domains`` supports:
49
+ - ``name`` (str): Domain title (e.g., ``"Rivers (SoE)"``, ``"Lakes"``, ``"Discharges"``)
50
+ - ``headline`` (str): Bold KPI value (e.g., ``"74%"`` or ``"Band B"``)
51
+ - ``headline_label`` (str): Short KPI subtitle (e.g., ``"Band A/B"`` or ``"Passing"``)
52
+ - ``n_sites`` (int): Number of monitored sites
53
+ - ``proportions`` (dict[str, float]): Category -> percentage (sums to ~100) for mini bar
54
+ - ``trend`` (str, optional): ``"Improving"``, ``"Indeterminate"``, or ``"Degrading"``
55
+ - ``accent`` (str, optional): Optional top-bar hex color override
56
+
57
+ Returns:
58
+ Tuple of ``(fig, ax)``.
59
+ """
60
+ if not domains:
61
+ raise ValueError("domain_summary_strip: 'domains' list cannot be empty.")
62
+
63
+ cfg = ensure_config(config)
64
+ resolved_pal = resolve_palette(palette, cfg, palette_name)
65
+ trend_pal = resolve_palette(None, cfg, "trend_directions")
66
+ trend_sym = {
67
+ "Improving": "↗ Improving",
68
+ "Indeterminate": "→ Stable",
69
+ "Degrading": "↘ Degrading",
70
+ }
71
+
72
+ n = len(domains)
73
+ n_cols = min(n, 6)
74
+ n_rows = int(np.ceil(n / n_cols))
75
+
76
+ with mpl_theme(cfg):
77
+ fig_w = max(11.0, 2.25 * n_cols + 0.8)
78
+ fig_h = 3.2 * n_rows + (1.1 if subtitle else 0.85)
79
+ fig = plt.figure(figsize=figsize or (fig_w, fig_h), facecolor="#ffffff")
80
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
81
+ ax.set_xlim(0, n_cols * 2.2 + 0.3)
82
+ ax.set_ylim(0, n_rows * 2.9 + 1.1)
83
+ ax.axis("off")
84
+
85
+ top_y = n_rows * 2.9 + 0.72
86
+ ax.text(
87
+ 0.25,
88
+ top_y,
89
+ title,
90
+ ha="left",
91
+ va="center",
92
+ fontsize=cfg.theme.title_size + 1.5,
93
+ fontweight="bold",
94
+ color=cfg.theme.text_color,
95
+ )
96
+ if subtitle:
97
+ ax.text(
98
+ 0.25,
99
+ top_y - 0.36,
100
+ subtitle,
101
+ ha="left",
102
+ va="center",
103
+ fontsize=cfg.theme.subtitle_size,
104
+ color=cfg.theme.caption_color,
105
+ )
106
+
107
+ order = (
108
+ resolve_category_order(None, cfg, palette_name)
109
+ if palette_name in cfg.category_orders
110
+ else list(resolved_pal.keys())
111
+ )
112
+ card_w = 1.98
113
+ card_h = 2.48
114
+ x_gap = 0.22
115
+ y_gap = 0.38
116
+
117
+ for idx, item in enumerate(domains):
118
+ r = idx // n_cols
119
+ c = idx % n_cols
120
+ x0 = 0.25 + c * (card_w + x_gap)
121
+ y0 = (n_rows - 1 - r) * (card_h + y_gap) + 0.18
122
+ accent = item.get("accent") or cfg.theme.accent_color
123
+
124
+ # Card body
125
+ ax.add_patch(
126
+ FancyBboxPatch(
127
+ (x0, y0),
128
+ card_w,
129
+ card_h,
130
+ boxstyle="round,pad=0.02,rounding_size=0.14",
131
+ facecolor="#f9fbfd",
132
+ edgecolor="#d7e0ea",
133
+ linewidth=1.3,
134
+ zorder=1,
135
+ )
136
+ )
137
+ # Top accent bar
138
+ ax.add_patch(
139
+ FancyBboxPatch(
140
+ (x0, y0 + card_h - 0.42),
141
+ card_w,
142
+ 0.42,
143
+ boxstyle="round,pad=0.02,rounding_size=0.12",
144
+ facecolor=accent,
145
+ edgecolor="none",
146
+ zorder=2,
147
+ )
148
+ )
149
+ ax.text(
150
+ x0 + card_w / 2.0,
151
+ y0 + card_h - 0.21,
152
+ str(item["name"]),
153
+ ha="center",
154
+ va="center",
155
+ fontsize=cfg.theme.tick_size,
156
+ fontweight="bold",
157
+ color=_contrast_text(accent),
158
+ zorder=3,
159
+ )
160
+
161
+ # Headline KPI
162
+ ax.text(
163
+ x0 + card_w / 2.0,
164
+ y0 + 1.56,
165
+ str(item.get("headline", "—")),
166
+ ha="center",
167
+ va="center",
168
+ fontsize=20,
169
+ fontweight="bold",
170
+ color=cfg.theme.text_color,
171
+ zorder=3,
172
+ )
173
+ ax.text(
174
+ x0 + card_w / 2.0,
175
+ y0 + 1.18,
176
+ str(item.get("headline_label", "")),
177
+ ha="center",
178
+ va="center",
179
+ fontsize=cfg.theme.caption_size - 0.5,
180
+ color=cfg.theme.caption_color,
181
+ zorder=3,
182
+ )
183
+ if "n_sites" in item:
184
+ ax.text(
185
+ x0 + card_w / 2.0,
186
+ y0 + 0.94,
187
+ f"n = {item['n_sites']} sites",
188
+ ha="center",
189
+ va="center",
190
+ fontsize=cfg.theme.caption_size - 1.0,
191
+ fontweight="bold",
192
+ color="#475569",
193
+ zorder=3,
194
+ )
195
+
196
+ # Mini 100% stacked proportion bar
197
+ props = item.get("proportions", {})
198
+ if props:
199
+ bar_x = x0 + 0.14
200
+ bar_w = card_w - 0.28
201
+ bar_y = y0 + 0.54
202
+ bar_h = 0.22
203
+ tot = sum(max(float(v), 0.0) for v in props.values()) or 1.0
204
+ cats = [k for k in order if k in props] + [k for k in props if k not in order]
205
+ curr = bar_x
206
+ for cat in cats:
207
+ seg_w = bar_w * (max(float(props[cat]), 0.0) / tot)
208
+ if seg_w <= 0:
209
+ continue
210
+ ax.add_patch(
211
+ Rectangle(
212
+ (curr, bar_y),
213
+ seg_w,
214
+ bar_h,
215
+ facecolor=resolved_pal.get(cat, "#cbd5e1"),
216
+ edgecolor="#ffffff",
217
+ linewidth=0.5,
218
+ zorder=3,
219
+ )
220
+ )
221
+ curr += seg_w
222
+
223
+ # Optional trend pill
224
+ tr = item.get("trend")
225
+ if tr:
226
+ t_col = trend_pal.get(str(tr), "#cbd5e1")
227
+ ax.add_patch(
228
+ FancyBboxPatch(
229
+ (x0 + 0.24, y0 + 0.14),
230
+ card_w - 0.48,
231
+ 0.28,
232
+ boxstyle="round,pad=0.02,rounding_size=0.08",
233
+ facecolor=t_col,
234
+ edgecolor="none",
235
+ alpha=0.90,
236
+ zorder=3,
237
+ )
238
+ )
239
+ ax.text(
240
+ x0 + card_w / 2.0,
241
+ y0 + 0.28,
242
+ trend_sym.get(str(tr), str(tr)),
243
+ ha="center",
244
+ va="center",
245
+ fontsize=cfg.theme.caption_size - 1.2,
246
+ fontweight="bold",
247
+ color=_contrast_text(t_col),
248
+ zorder=4,
249
+ )
250
+
251
+ return fig, ax
252
+
253
+
254
+ def discharge_impact_card(
255
+ df: pd.DataFrame,
256
+ *,
257
+ discharge_name: str,
258
+ receiving_water: str,
259
+ compliance_status: str = "Compliant",
260
+ indicator_col: str | None = None,
261
+ upstream_grade_col: str = "Upstream_Grade",
262
+ downstream_grade_col: str = "Downstream_Grade",
263
+ upstream_value_col: str = "Upstream_Value",
264
+ downstream_value_col: str = "Downstream_Value",
265
+ unit_col: str | None = "Unit",
266
+ palette: dict[str, str] | None = None,
267
+ palette_name: str = "state_bands",
268
+ summary_note: str | None = None,
269
+ figsize: tuple[float, float] | None = None,
270
+ config: str | Path | Config | None = None,
271
+ ) -> tuple[Figure, Axes]:
272
+ """Render a point-source Discharge Impact Card comparing Upstream (u/s) vs Downstream (d/s).
273
+
274
+ Displays a compliance status header banner and one row per indicator showing:
275
+ - Indicator label
276
+ - Upstream NOF Grade / Pass badge -> Downstream badge
277
+ - Numeric u/s vs d/s values and `% change` callout bar
278
+
279
+ Returns:
280
+ Tuple of ``(fig, ax)``.
281
+ """
282
+ cfg = ensure_config(config)
283
+ r_ind = resolve_column(indicator_col, cfg, "indicator")
284
+ validate_columns(
285
+ df,
286
+ [r_ind, upstream_grade_col, downstream_grade_col, upstream_value_col, downstream_value_col],
287
+ context="discharge_impact_card",
288
+ )
289
+
290
+ work = df.copy().reset_index(drop=True)
291
+ if work.empty:
292
+ raise ValueError("discharge_impact_card: Input DataFrame is empty.")
293
+
294
+ pal = resolve_palette(palette, cfg, palette_name)
295
+ n = len(work)
296
+
297
+ status_lower = compliance_status.strip().lower()
298
+ if "non" in status_lower or "fail" in status_lower or "breach" in status_lower:
299
+ header_col = "#c62828"
300
+ elif "partial" in status_lower or "caution" in status_lower:
301
+ header_col = "#d97706"
302
+ else:
303
+ header_col = "#2e7d32"
304
+
305
+ with mpl_theme(cfg):
306
+ fig_h = max(4.0, 0.72 * n + 2.3)
307
+ fig = plt.figure(figsize=figsize or (10.6, fig_h), facecolor="#ffffff")
308
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
309
+ ax.set_xlim(0, 10)
310
+ ax.set_ylim(0, n + 2.5)
311
+ ax.axis("off")
312
+
313
+ # Outer card frame
314
+ ax.add_patch(
315
+ FancyBboxPatch(
316
+ (0.15, 0.15),
317
+ 9.7,
318
+ n + 2.2,
319
+ boxstyle="round,pad=0.02,rounding_size=0.16",
320
+ facecolor="#f9fbfd",
321
+ edgecolor="#d7e0ea",
322
+ linewidth=1.4,
323
+ zorder=1,
324
+ )
325
+ )
326
+
327
+ # Header banner
328
+ ax.add_patch(
329
+ FancyBboxPatch(
330
+ (0.15, n + 1.35),
331
+ 9.7,
332
+ 1.0,
333
+ boxstyle="round,pad=0.02,rounding_size=0.16",
334
+ facecolor="#1e2a38",
335
+ edgecolor="none",
336
+ zorder=2,
337
+ )
338
+ )
339
+ ax.text(
340
+ 0.45,
341
+ n + 2.00,
342
+ discharge_name,
343
+ ha="left",
344
+ va="center",
345
+ fontsize=cfg.theme.title_size + 1,
346
+ fontweight="bold",
347
+ color="#ffffff",
348
+ zorder=3,
349
+ )
350
+ ax.text(
351
+ 0.45,
352
+ n + 1.62,
353
+ f"Receiving water: {receiving_water}",
354
+ ha="left",
355
+ va="center",
356
+ fontsize=cfg.theme.subtitle_size - 0.5,
357
+ color="#cbd5e1",
358
+ zorder=3,
359
+ )
360
+ # Compliance pill
361
+ ax.add_patch(
362
+ FancyBboxPatch(
363
+ (7.45, n + 1.58),
364
+ 2.15,
365
+ 0.52,
366
+ boxstyle="round,pad=0.02,rounding_size=0.12",
367
+ facecolor=header_col,
368
+ edgecolor="#ffffff",
369
+ linewidth=1.2,
370
+ zorder=3,
371
+ )
372
+ )
373
+ ax.text(
374
+ 8.525,
375
+ n + 1.84,
376
+ compliance_status,
377
+ ha="center",
378
+ va="center",
379
+ fontsize=cfg.theme.tick_size,
380
+ fontweight="bold",
381
+ color="#ffffff",
382
+ zorder=4,
383
+ )
384
+
385
+ # Column headers
386
+ hy = n + 1.02
387
+ for hx, htxt, ha in [
388
+ (0.45, "Parameter", "left"),
389
+ (3.75, "Upstream (u/s)", "center"),
390
+ (5.55, "Downstream (d/s)", "center"),
391
+ (8.25, "Downstream Change", "center"),
392
+ ]:
393
+ ax.text(
394
+ hx,
395
+ hy,
396
+ htxt,
397
+ ha=ha,
398
+ va="center",
399
+ fontsize=cfg.theme.caption_size,
400
+ fontweight="bold",
401
+ color=cfg.theme.caption_color,
402
+ zorder=3,
403
+ )
404
+ ax.plot([0.35, 9.65], [hy - 0.24, hy - 0.24], color="#d7e0ea", linewidth=1.0, zorder=2)
405
+
406
+ for idx, row in work.iterrows():
407
+ y = n + 0.36 - idx * 0.92
408
+ ind = resolve_label(str(row[r_ind]), cfg)
409
+ ug = str(row[upstream_grade_col])
410
+ dg = str(row[downstream_grade_col])
411
+ uv = float(row[upstream_value_col])
412
+ dv = float(row[downstream_value_col])
413
+ unit = (
414
+ str(row[unit_col])
415
+ if (unit_col and unit_col in work.columns and pd.notna(row[unit_col]))
416
+ else ""
417
+ )
418
+ pct = 100.0 * (dv - uv) / abs(uv) if uv != 0 else 0.0
419
+
420
+ ax.plot([0.35, 9.65], [y - 0.44, y - 0.44], color="#e2e8f0", linewidth=0.7, zorder=2)
421
+ ax.text(
422
+ 0.45,
423
+ y,
424
+ ind,
425
+ ha="left",
426
+ va="center",
427
+ fontsize=cfg.theme.tick_size,
428
+ fontweight="bold",
429
+ color=cfg.theme.text_color,
430
+ zorder=3,
431
+ )
432
+
433
+ # Upstream badge + value
434
+ u_col = pal.get(ug, "#bdbdbd")
435
+ ax.add_patch(
436
+ FancyBboxPatch(
437
+ (3.15, y - 0.22),
438
+ 0.50,
439
+ 0.44,
440
+ boxstyle="round,pad=0.02,rounding_size=0.08",
441
+ facecolor=u_col,
442
+ edgecolor="#ffffff",
443
+ zorder=3,
444
+ )
445
+ )
446
+ ax.text(
447
+ 3.40,
448
+ y,
449
+ ug,
450
+ ha="center",
451
+ va="center",
452
+ fontsize=cfg.theme.tick_size - 0.5,
453
+ fontweight="bold",
454
+ color=_contrast_text(u_col),
455
+ zorder=4,
456
+ )
457
+ ax.text(
458
+ 3.76,
459
+ y,
460
+ f"{uv:g} {unit}".strip(),
461
+ ha="left",
462
+ va="center",
463
+ fontsize=cfg.theme.caption_size - 0.5,
464
+ color=cfg.theme.text_color,
465
+ zorder=3,
466
+ )
467
+
468
+ # Arrow u/s -> d/s
469
+ ax.annotate(
470
+ "",
471
+ xy=(5.02, y),
472
+ xytext=(4.62, y),
473
+ arrowprops={"arrowstyle": "-|>", "color": "#64748b", "lw": 1.6},
474
+ zorder=3,
475
+ )
476
+
477
+ # Downstream badge + value
478
+ d_col = pal.get(dg, "#bdbdbd")
479
+ ax.add_patch(
480
+ FancyBboxPatch(
481
+ (5.10, y - 0.22),
482
+ 0.50,
483
+ 0.44,
484
+ boxstyle="round,pad=0.02,rounding_size=0.08",
485
+ facecolor=d_col,
486
+ edgecolor="#ffffff",
487
+ zorder=3,
488
+ )
489
+ )
490
+ ax.text(
491
+ 5.35,
492
+ y,
493
+ dg,
494
+ ha="center",
495
+ va="center",
496
+ fontsize=cfg.theme.tick_size - 0.5,
497
+ fontweight="bold",
498
+ color=_contrast_text(d_col),
499
+ zorder=4,
500
+ )
501
+ ax.text(
502
+ 5.72,
503
+ y,
504
+ f"{dv:g} {unit}".strip(),
505
+ ha="left",
506
+ va="center",
507
+ fontsize=cfg.theme.caption_size - 0.5,
508
+ color=cfg.theme.text_color,
509
+ zorder=3,
510
+ )
511
+
512
+ # Mini delta bar + % label
513
+ bar_x0 = 7.35
514
+ bar_max_w = 1.35
515
+ bar_w = bar_max_w * min(abs(pct) / 100.0, 1.0)
516
+ bar_col = "#c62828" if pct > 10 else ("#2e7d32" if pct < -5 else "#64748b")
517
+ ax.add_patch(
518
+ Rectangle(
519
+ (bar_x0, y - 0.13),
520
+ bar_max_w,
521
+ 0.26,
522
+ facecolor="#e5e9f0",
523
+ edgecolor="none",
524
+ zorder=2,
525
+ )
526
+ )
527
+ ax.add_patch(
528
+ Rectangle(
529
+ (bar_x0, y - 0.13), bar_w, 0.26, facecolor=bar_col, edgecolor="none", zorder=3
530
+ )
531
+ )
532
+ ax.text(
533
+ bar_x0 + bar_max_w + 0.12,
534
+ y,
535
+ f"{pct:+.0f}%",
536
+ ha="left",
537
+ va="center",
538
+ fontsize=cfg.theme.caption_size,
539
+ fontweight="bold",
540
+ color=bar_col,
541
+ zorder=4,
542
+ )
543
+
544
+ if summary_note:
545
+ ax.text(
546
+ 0.45,
547
+ 0.45,
548
+ summary_note,
549
+ ha="left",
550
+ va="center",
551
+ fontsize=cfg.theme.caption_size,
552
+ style="italic",
553
+ color=cfg.theme.caption_color,
554
+ zorder=3,
555
+ )
556
+
557
+ return fig, ax
558
+
559
+
560
+ def lake_health_card(
561
+ attributes_df: pd.DataFrame,
562
+ *,
563
+ lake_name: str,
564
+ fmu_name: str | None = None,
565
+ tli_score: float,
566
+ period: str = "2021–2025",
567
+ indicator_col: str | None = None,
568
+ band_col: str | None = None,
569
+ value_col: str | None = None,
570
+ trend_col: str | None = None,
571
+ palette: dict[str, str] | None = None,
572
+ summary_note: str | None = None,
573
+ figsize: tuple[float, float] = (10.6, 5.2),
574
+ config: str | Path | Config | None = None,
575
+ ) -> tuple[Figure, Axes]:
576
+ """Render a Lake Health & Trophic Level Index (TLI) infographic card.
577
+
578
+ Combines an Oligotrophic -> Hypertrophic TLI gradient gauge bar with NPS-FM lake
579
+ attribute badges (e.g., ``Chl-a``, ``TN``, ``TP``, ``Cyanobacteria``, ``E. coli``)
580
+ and optional trend pills.
581
+
582
+ Returns:
583
+ Tuple of ``(fig, ax)``.
584
+ """
585
+ cfg = ensure_config(config)
586
+ r_ind = resolve_column(indicator_col, cfg, "indicator")
587
+ r_band = resolve_column(band_col, cfg, "state_band")
588
+ validate_columns(attributes_df, [r_ind, r_band], context="lake_health_card")
589
+
590
+ work = attributes_df.copy().reset_index(drop=True)
591
+ if work.empty:
592
+ raise ValueError("lake_health_card: attributes_df is empty.")
593
+
594
+ pal = resolve_palette(palette, cfg, "state_bands")
595
+ t_pal = resolve_palette(None, cfg, "trend_directions")
596
+ trend_sym = {"Improving": "↗", "Indeterminate": "→", "Degrading": "↘"}
597
+
598
+ # Classify TLI (NZ Burns et al. / LAWA bands)
599
+ if tli_score < 2.0:
600
+ tli_class = "Microtrophic"
601
+ elif tli_score < 3.0:
602
+ tli_class = "Oligotrophic"
603
+ elif tli_score < 4.0:
604
+ tli_class = "Mesotrophic"
605
+ elif tli_score < 5.0:
606
+ tli_class = "Eutrophic"
607
+ elif tli_score < 6.0:
608
+ tli_class = "Supertrophic"
609
+ else:
610
+ tli_class = "Hypertrophic"
611
+
612
+ with mpl_theme(cfg):
613
+ fig = plt.figure(figsize=figsize, facecolor="#ffffff")
614
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
615
+ ax.set_xlim(0, 10)
616
+ ax.set_ylim(0, 5.6)
617
+ ax.axis("off")
618
+
619
+ # Card frame
620
+ ax.add_patch(
621
+ FancyBboxPatch(
622
+ (0.15, 0.15),
623
+ 9.7,
624
+ 5.3,
625
+ boxstyle="round,pad=0.02,rounding_size=0.16",
626
+ facecolor="#f9fbfd",
627
+ edgecolor="#d7e0ea",
628
+ linewidth=1.4,
629
+ zorder=1,
630
+ )
631
+ )
632
+ # Header banner
633
+ ax.add_patch(
634
+ FancyBboxPatch(
635
+ (0.15, 4.45),
636
+ 9.7,
637
+ 1.0,
638
+ boxstyle="round,pad=0.02,rounding_size=0.16",
639
+ facecolor="#005f83",
640
+ edgecolor="none",
641
+ zorder=2,
642
+ )
643
+ )
644
+ ax.text(
645
+ 0.45,
646
+ 5.10,
647
+ lake_name,
648
+ ha="left",
649
+ va="center",
650
+ fontsize=cfg.theme.title_size + 1.5,
651
+ fontweight="bold",
652
+ color="#ffffff",
653
+ zorder=3,
654
+ )
655
+ sub_txt = f"{fmu_name} FMU • {period}" if fmu_name else period
656
+ ax.text(
657
+ 0.45,
658
+ 4.72,
659
+ sub_txt,
660
+ ha="left",
661
+ va="center",
662
+ fontsize=cfg.theme.subtitle_size - 0.5,
663
+ color="#d6eef8",
664
+ zorder=3,
665
+ )
666
+
667
+ # TLI headline badge on right of header
668
+ ax.add_patch(
669
+ FancyBboxPatch(
670
+ (7.45, 4.62),
671
+ 2.15,
672
+ 0.66,
673
+ boxstyle="round,pad=0.02,rounding_size=0.12",
674
+ facecolor="#ffffff",
675
+ edgecolor="none",
676
+ zorder=3,
677
+ )
678
+ )
679
+ ax.text(
680
+ 8.525,
681
+ 5.06,
682
+ f"TLI {tli_score:.1f}",
683
+ ha="center",
684
+ va="center",
685
+ fontsize=13,
686
+ fontweight="bold",
687
+ color="#005f83",
688
+ zorder=4,
689
+ )
690
+ ax.text(
691
+ 8.525,
692
+ 4.76,
693
+ tli_class,
694
+ ha="center",
695
+ va="center",
696
+ fontsize=cfg.theme.caption_size - 0.5,
697
+ fontweight="bold",
698
+ color="#475569",
699
+ zorder=4,
700
+ )
701
+
702
+ # Trophic Level Index (TLI) gradient bar (1.0 -> 7.0)
703
+ bar_x0, bar_w, bar_y, bar_h = 0.55, 8.9, 3.35, 0.38
704
+ tli_segments = [
705
+ (1.0, 2.0, "#29b6f6", "Microtrophic"),
706
+ (2.0, 3.0, "#66bb6a", "Oligotrophic"),
707
+ (3.0, 4.0, "#d4e157", "Mesotrophic"),
708
+ (4.0, 5.0, "#ffa726", "Eutrophic"),
709
+ (5.0, 6.0, "#ef5350", "Supertrophic"),
710
+ (6.0, 7.0, "#8e24aa", "Hypertrophic"),
711
+ ]
712
+ ax.text(
713
+ bar_x0,
714
+ bar_y + 0.62,
715
+ "Trophic Level Index (TLI) Scale",
716
+ ha="left",
717
+ va="center",
718
+ fontsize=cfg.theme.tick_size,
719
+ fontweight="bold",
720
+ color=cfg.theme.text_color,
721
+ zorder=3,
722
+ )
723
+ for low, high, col, lbl in tli_segments:
724
+ sx = bar_x0 + bar_w * ((low - 1.0) / 6.0)
725
+ sw = bar_w * ((high - low) / 6.0)
726
+ ax.add_patch(
727
+ Rectangle(
728
+ (sx, bar_y), sw, bar_h, facecolor=col, edgecolor="#ffffff", lw=1.0, zorder=2
729
+ )
730
+ )
731
+ ax.text(
732
+ sx + sw / 2.0,
733
+ bar_y + bar_h / 2.0,
734
+ lbl,
735
+ ha="center",
736
+ va="center",
737
+ fontsize=cfg.theme.caption_size - 1.3,
738
+ fontweight="bold",
739
+ color=_contrast_text(col),
740
+ zorder=3,
741
+ )
742
+
743
+ # Pointer triangle at tli_score
744
+ clamped = float(np.clip(tli_score, 1.0, 7.0))
745
+ px = bar_x0 + bar_w * ((clamped - 1.0) / 6.0)
746
+ tri = Polygon(
747
+ [
748
+ (px, bar_y + bar_h + 0.02),
749
+ (px - 0.14, bar_y + bar_h + 0.25),
750
+ (px + 0.14, bar_y + bar_h + 0.25),
751
+ ],
752
+ closed=True,
753
+ facecolor="#111827",
754
+ edgecolor="#ffffff",
755
+ lw=0.8,
756
+ zorder=5,
757
+ )
758
+ ax.add_patch(tri)
759
+
760
+ # Attribute grade badge cards along the bottom
761
+ n_attr = len(work)
762
+ card_gap = 0.22
763
+ total_w = 8.9
764
+ cw = (total_w - card_gap * (n_attr - 1)) / n_attr
765
+ cy0, ch = 0.88, 1.95
766
+
767
+ for i, row in work.iterrows():
768
+ cx0 = 0.55 + i * (cw + card_gap)
769
+ ind_lbl = resolve_label(str(row[r_ind]), cfg)
770
+ grade = str(row[r_band])
771
+ g_col = pal.get(grade, "#bdbdbd")
772
+
773
+ ax.add_patch(
774
+ FancyBboxPatch(
775
+ (cx0, cy0),
776
+ cw,
777
+ ch,
778
+ boxstyle="round,pad=0.02,rounding_size=0.12",
779
+ facecolor="#ffffff",
780
+ edgecolor="#d7e0ea",
781
+ linewidth=1.1,
782
+ zorder=2,
783
+ )
784
+ )
785
+ ax.text(
786
+ cx0 + cw / 2.0,
787
+ cy0 + ch - 0.28,
788
+ ind_lbl,
789
+ ha="center",
790
+ va="center",
791
+ fontsize=cfg.theme.caption_size,
792
+ fontweight="bold",
793
+ color=cfg.theme.text_color,
794
+ zorder=3,
795
+ )
796
+ ax.add_patch(
797
+ FancyBboxPatch(
798
+ (cx0 + cw / 2.0 - 0.34, cy0 + 0.78),
799
+ 0.68,
800
+ 0.68,
801
+ boxstyle="round,pad=0.02,rounding_size=0.10",
802
+ facecolor=g_col,
803
+ edgecolor="#ffffff",
804
+ lw=1.2,
805
+ zorder=3,
806
+ )
807
+ )
808
+ ax.text(
809
+ cx0 + cw / 2.0,
810
+ cy0 + 1.12,
811
+ grade,
812
+ ha="center",
813
+ va="center",
814
+ fontsize=16,
815
+ fontweight="bold",
816
+ color=_contrast_text(g_col),
817
+ zorder=4,
818
+ )
819
+ if value_col and value_col in work.columns and pd.notna(row[value_col]):
820
+ ax.text(
821
+ cx0 + cw / 2.0,
822
+ cy0 + 0.52,
823
+ f"{row[value_col]}",
824
+ ha="center",
825
+ va="center",
826
+ fontsize=cfg.theme.caption_size - 0.5,
827
+ color=cfg.theme.caption_color,
828
+ zorder=3,
829
+ )
830
+ if trend_col and trend_col in work.columns and pd.notna(row[trend_col]):
831
+ tr = str(row[trend_col])
832
+ tc = t_pal.get(tr, "#cbd5e1")
833
+ ax.add_patch(
834
+ FancyBboxPatch(
835
+ (cx0 + 0.14, cy0 + 0.12),
836
+ cw - 0.28,
837
+ 0.28,
838
+ boxstyle="round,pad=0.02,rounding_size=0.07",
839
+ facecolor=tc,
840
+ edgecolor="none",
841
+ zorder=3,
842
+ )
843
+ )
844
+ ax.text(
845
+ cx0 + cw / 2.0,
846
+ cy0 + 0.26,
847
+ f"{trend_sym.get(tr, '')} {tr}".strip(),
848
+ ha="center",
849
+ va="center",
850
+ fontsize=cfg.theme.caption_size - 1.5,
851
+ fontweight="bold",
852
+ color=_contrast_text(tc),
853
+ zorder=4,
854
+ )
855
+
856
+ if summary_note:
857
+ ax.text(
858
+ 0.55,
859
+ 0.42,
860
+ summary_note,
861
+ ha="left",
862
+ va="center",
863
+ fontsize=cfg.theme.caption_size,
864
+ style="italic",
865
+ color=cfg.theme.caption_color,
866
+ zorder=3,
867
+ )
868
+
869
+ return fig, ax
870
+
871
+
872
+ def estuary_coastal_card(
873
+ metrics_df: pd.DataFrame,
874
+ *,
875
+ site_name: str,
876
+ domain_type: str = "Estuary",
877
+ overall_grade: str = "B",
878
+ period: str = "2021–2025",
879
+ metric_col: str = "Metric",
880
+ score_col: str = "Score",
881
+ grade_col: str = "Grade",
882
+ swim_months: dict[str, str] | None = None,
883
+ palette: dict[str, str] | None = None,
884
+ summary_note: str | None = None,
885
+ figsize: tuple[float, float] = (10.6, 5.0),
886
+ config: str | Path | Config | None = None,
887
+ ) -> tuple[Figure, Axes]:
888
+ """Render an Estuary / Coastal Health Dashboard Card with indicator bars & swim strip.
889
+
890
+ Pairs an overall estuary/coastal grade badge, horizontal ecological indicator score bars
891
+ (e.g., Mud/Sedimentation, Macroalgae, Nutrients, Dissolved Oxygen), and an optional
892
+ summer bathing suitability strip (``Nov``–``Mar`` colored by LAWA Green/Amber/Red).
893
+
894
+ Returns:
895
+ Tuple of ``(fig, ax)``.
896
+ """
897
+ cfg = ensure_config(config)
898
+ validate_columns(metrics_df, [metric_col, score_col], context="estuary_coastal_card")
899
+
900
+ work = metrics_df.copy().reset_index(drop=True)
901
+ if work.empty:
902
+ raise ValueError("estuary_coastal_card: metrics_df is empty.")
903
+
904
+ pal = resolve_palette(palette, cfg, "state_bands")
905
+ swim_pal = resolve_palette(None, cfg, "recreational_swim")
906
+ overall_col = pal.get(overall_grade, cfg.theme.accent_color)
907
+
908
+ with mpl_theme(cfg):
909
+ fig = plt.figure(figsize=figsize, facecolor="#ffffff")
910
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
911
+ ax.set_xlim(0, 10)
912
+ ax.set_ylim(0, 5.4)
913
+ ax.axis("off")
914
+
915
+ # Card frame
916
+ ax.add_patch(
917
+ FancyBboxPatch(
918
+ (0.15, 0.15),
919
+ 9.7,
920
+ 5.1,
921
+ boxstyle="round,pad=0.02,rounding_size=0.16",
922
+ facecolor="#f9fbfd",
923
+ edgecolor="#d7e0ea",
924
+ linewidth=1.4,
925
+ zorder=1,
926
+ )
927
+ )
928
+ # Header banner
929
+ ax.add_patch(
930
+ FancyBboxPatch(
931
+ (0.15, 4.25),
932
+ 9.7,
933
+ 1.0,
934
+ boxstyle="round,pad=0.02,rounding_size=0.16",
935
+ facecolor="#0d5c63",
936
+ edgecolor="none",
937
+ zorder=2,
938
+ )
939
+ )
940
+ ax.text(
941
+ 0.45,
942
+ 4.90,
943
+ site_name,
944
+ ha="left",
945
+ va="center",
946
+ fontsize=cfg.theme.title_size + 1.5,
947
+ fontweight="bold",
948
+ color="#ffffff",
949
+ zorder=3,
950
+ )
951
+ ax.text(
952
+ 0.45,
953
+ 4.52,
954
+ f"{domain_type} Ecological & Recreational Health • {period}",
955
+ ha="left",
956
+ va="center",
957
+ fontsize=cfg.theme.subtitle_size - 0.5,
958
+ color="#ccebea",
959
+ zorder=3,
960
+ )
961
+
962
+ # Overall grade badge
963
+ ax.add_patch(
964
+ FancyBboxPatch(
965
+ (8.25, 4.40),
966
+ 1.32,
967
+ 0.70,
968
+ boxstyle="round,pad=0.02,rounding_size=0.12",
969
+ facecolor=overall_col,
970
+ edgecolor="#ffffff",
971
+ linewidth=1.6,
972
+ zorder=3,
973
+ )
974
+ )
975
+ ax.text(
976
+ 8.91,
977
+ 4.75,
978
+ f"Grade {overall_grade}",
979
+ ha="center",
980
+ va="center",
981
+ fontsize=cfg.theme.tick_size + 1,
982
+ fontweight="bold",
983
+ color=_contrast_text(overall_col),
984
+ zorder=4,
985
+ )
986
+
987
+ # Left/center: Horizontal ecological indicator bars
988
+ ax.text(
989
+ 0.45,
990
+ 3.92,
991
+ "Ecological Health Indicators (0–100)",
992
+ ha="left",
993
+ va="center",
994
+ fontsize=cfg.theme.tick_size,
995
+ fontweight="bold",
996
+ color=cfg.theme.text_color,
997
+ zorder=3,
998
+ )
999
+ n_m = len(work)
1000
+ bar_x0 = 2.65
1001
+ bar_w = 3.25 if swim_months else 6.1
1002
+ y_top = 3.45
1003
+ step_y = min(0.58, 2.35 / max(n_m, 1))
1004
+
1005
+ cmap = mcolors.LinearSegmentedColormap.from_list(
1006
+ "stplot_estuary", ["#ef5350", "#ffa726", "#e6e600", "#81c784", "#29b6f6"]
1007
+ )
1008
+ for idx, row in work.iterrows():
1009
+ y = y_top - idx * step_y
1010
+ m_name = resolve_label(str(row[metric_col]), cfg)
1011
+ sc = float(np.clip(float(row[score_col]), 0.0, 100.0))
1012
+ if grade_col in work.columns and pd.notna(row[grade_col]):
1013
+ gr = str(row[grade_col])
1014
+ fill = pal.get(gr, mcolors.to_hex(cmap(sc / 100.0)))
1015
+ lbl_right = f"{sc:.0f} ({gr})"
1016
+ else:
1017
+ fill = mcolors.to_hex(cmap(sc / 100.0))
1018
+ lbl_right = f"{sc:.0f}%"
1019
+
1020
+ ax.text(
1021
+ bar_x0 - 0.14,
1022
+ y,
1023
+ m_name,
1024
+ ha="right",
1025
+ va="center",
1026
+ fontsize=cfg.theme.caption_size,
1027
+ fontweight="bold",
1028
+ color=cfg.theme.text_color,
1029
+ zorder=3,
1030
+ )
1031
+ ax.add_patch(
1032
+ FancyBboxPatch(
1033
+ (bar_x0, y - 0.14),
1034
+ bar_w,
1035
+ 0.28,
1036
+ boxstyle="round,pad=0.01,rounding_size=0.06",
1037
+ facecolor="#e5e9f0",
1038
+ edgecolor="none",
1039
+ zorder=2,
1040
+ )
1041
+ )
1042
+ ax.add_patch(
1043
+ FancyBboxPatch(
1044
+ (bar_x0, y - 0.14),
1045
+ max(0.08, bar_w * sc / 100.0),
1046
+ 0.28,
1047
+ boxstyle="round,pad=0.01,rounding_size=0.06",
1048
+ facecolor=fill,
1049
+ edgecolor="none",
1050
+ zorder=3,
1051
+ )
1052
+ )
1053
+ ax.text(
1054
+ bar_x0 + bar_w + 0.12,
1055
+ y,
1056
+ lbl_right,
1057
+ ha="left",
1058
+ va="center",
1059
+ fontsize=cfg.theme.caption_size - 0.5,
1060
+ fontweight="bold",
1061
+ color=cfg.theme.text_color,
1062
+ zorder=3,
1063
+ )
1064
+
1065
+ # Right panel: Summer bathing suitability strip
1066
+ if swim_months:
1067
+ sx0 = 6.95
1068
+ ax.add_patch(
1069
+ FancyBboxPatch(
1070
+ (sx0 - 0.15, 1.05),
1071
+ 2.80,
1072
+ 2.98,
1073
+ boxstyle="round,pad=0.02,rounding_size=0.12",
1074
+ facecolor="#ffffff",
1075
+ edgecolor="#d7e0ea",
1076
+ linewidth=1.0,
1077
+ zorder=2,
1078
+ )
1079
+ )
1080
+ ax.text(
1081
+ sx0 + 1.25,
1082
+ 3.78,
1083
+ "Summer Swim Suitability",
1084
+ ha="center",
1085
+ va="center",
1086
+ fontsize=cfg.theme.caption_size,
1087
+ fontweight="bold",
1088
+ color=cfg.theme.text_color,
1089
+ zorder=3,
1090
+ )
1091
+ items = list(swim_months.items())
1092
+ m_step = min(0.48, 2.30 / max(len(items), 1))
1093
+ for m_idx, (mon, st) in enumerate(items):
1094
+ my = 3.30 - m_idx * m_step
1095
+ scol = swim_pal.get(str(st), "#cbd5e1")
1096
+ ax.text(
1097
+ sx0 + 0.10,
1098
+ my,
1099
+ str(mon),
1100
+ ha="left",
1101
+ va="center",
1102
+ fontsize=cfg.theme.caption_size,
1103
+ fontweight="bold",
1104
+ color=cfg.theme.text_color,
1105
+ zorder=3,
1106
+ )
1107
+ ax.add_patch(
1108
+ FancyBboxPatch(
1109
+ (sx0 + 0.85, my - 0.15),
1110
+ 1.55,
1111
+ 0.30,
1112
+ boxstyle="round,pad=0.02,rounding_size=0.08",
1113
+ facecolor=scol,
1114
+ edgecolor="none",
1115
+ zorder=3,
1116
+ )
1117
+ )
1118
+ ax.text(
1119
+ sx0 + 1.625,
1120
+ my,
1121
+ str(st),
1122
+ ha="center",
1123
+ va="center",
1124
+ fontsize=cfg.theme.caption_size - 0.8,
1125
+ fontweight="bold",
1126
+ color=_contrast_text(scol),
1127
+ zorder=4,
1128
+ )
1129
+
1130
+ if summary_note:
1131
+ ax.text(
1132
+ 0.45,
1133
+ 0.45,
1134
+ summary_note,
1135
+ ha="left",
1136
+ va="center",
1137
+ fontsize=cfg.theme.caption_size,
1138
+ style="italic",
1139
+ color=cfg.theme.caption_color,
1140
+ zorder=3,
1141
+ )
1142
+
1143
+ return fig, ax