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
stplot/reporting/word.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""Templated Word (.docx) report assembly with pre-filled figures and styled summary tables."""
|
|
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
|
+
from stplot.config import Config, ensure_config, resolve_palette
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _import_docx() -> tuple[Any, Any, Any, Any]:
|
|
14
|
+
try:
|
|
15
|
+
from docx import Document
|
|
16
|
+
from docx.oxml import OxmlElement
|
|
17
|
+
from docx.oxml.ns import qn
|
|
18
|
+
from docx.shared import Mm, RGBColor
|
|
19
|
+
except ImportError as exc:
|
|
20
|
+
raise ImportError(
|
|
21
|
+
"Word report assembly requires python-docx and docxtpl. "
|
|
22
|
+
'Install with: pip install "stplot[report]"'
|
|
23
|
+
) from exc
|
|
24
|
+
return Document, (OxmlElement, qn), Mm, RGBColor
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _import_docxtpl() -> tuple[Any, Any]:
|
|
28
|
+
try:
|
|
29
|
+
from docxtpl import DocxTemplate, InlineImage
|
|
30
|
+
except ImportError as exc:
|
|
31
|
+
raise ImportError(
|
|
32
|
+
"Templated Word (.docx) rendering requires docxtpl. "
|
|
33
|
+
'Install with: pip install "stplot[report]"'
|
|
34
|
+
) from exc
|
|
35
|
+
return DocxTemplate, InlineImage
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _contrast_rgb(hex_color: str) -> tuple[int, int, int]:
|
|
39
|
+
cleaned = hex_color.lstrip("#")
|
|
40
|
+
if len(cleaned) != 6:
|
|
41
|
+
return (34, 34, 34)
|
|
42
|
+
r, g, b = int(cleaned[0:2], 16), int(cleaned[2:4], 16), int(cleaned[4:6], 16)
|
|
43
|
+
luminance = 0.299 * r + 0.587 * g + 0.114 * b
|
|
44
|
+
return (17, 17, 17) if luminance > 140 else (255, 255, 255)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _set_cell_shading(cell: Any, hex_color: str, xml_helpers: tuple[Any, Any]) -> None:
|
|
48
|
+
oxml_element, qn = xml_helpers
|
|
49
|
+
tc_pr = cell._tc.get_or_add_tcPr()
|
|
50
|
+
shd = oxml_element("w:shd")
|
|
51
|
+
shd.set(qn("w:fill"), hex_color.lstrip("#").upper())
|
|
52
|
+
tc_pr.append(shd)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def add_styled_table(
|
|
56
|
+
doc: Any,
|
|
57
|
+
table: pd.DataFrame,
|
|
58
|
+
*,
|
|
59
|
+
palette_key: str = "state_bands",
|
|
60
|
+
palette: dict[str, str] | None = None,
|
|
61
|
+
index_name: str | None = None,
|
|
62
|
+
caption: str | None = None,
|
|
63
|
+
config: str | Path | Config | None = None,
|
|
64
|
+
) -> Any:
|
|
65
|
+
"""Append a color-coded summary table (e.g., FMU vs Whole Region) to a Word document.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
doc: An open ``python-docx`` ``Document`` instance.
|
|
69
|
+
table: Summary DataFrame whose columns correspond to semantic palette keys
|
|
70
|
+
(such as ``A``–``E`` or ``Improving`` / ``Indeterminate`` / ``Degrading``).
|
|
71
|
+
palette_key: Key in ``config.palettes`` (default ``"state_bands"``).
|
|
72
|
+
palette: Optional explicit category-to-hex color mapping override.
|
|
73
|
+
index_name: Top-left corner header label (defaults to ``table.index.name`` or ``""``).
|
|
74
|
+
caption: Optional paragraph heading/caption inserted above the table.
|
|
75
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
Created ``python-docx`` ``Table`` object.
|
|
79
|
+
"""
|
|
80
|
+
_, xml_helpers, _, rgb_color = _import_docx()
|
|
81
|
+
cfg = ensure_config(config)
|
|
82
|
+
resolved_palette = resolve_palette(palette, cfg, palette_key)
|
|
83
|
+
|
|
84
|
+
if caption:
|
|
85
|
+
p = doc.add_paragraph()
|
|
86
|
+
run = p.add_run(caption)
|
|
87
|
+
run.bold = True
|
|
88
|
+
|
|
89
|
+
n_rows = len(table) + 1
|
|
90
|
+
n_cols = len(table.columns) + 1
|
|
91
|
+
word_table = doc.add_table(rows=n_rows, cols=n_cols)
|
|
92
|
+
|
|
93
|
+
# Header row
|
|
94
|
+
corner_label = index_name if index_name is not None else (str(table.index.name or ""))
|
|
95
|
+
hdr_cells = word_table.rows[0].cells
|
|
96
|
+
hdr_cells[0].text = corner_label
|
|
97
|
+
_set_cell_shading(hdr_cells[0], "#f3f5f7", xml_helpers)
|
|
98
|
+
for run in hdr_cells[0].paragraphs[0].runs:
|
|
99
|
+
run.bold = True
|
|
100
|
+
|
|
101
|
+
for col_idx, col_name in enumerate(table.columns, start=1):
|
|
102
|
+
cell = hdr_cells[col_idx]
|
|
103
|
+
cell.text = str(col_name)
|
|
104
|
+
bg = resolved_palette.get(str(col_name), "#f3f5f7")
|
|
105
|
+
_set_cell_shading(cell, bg, xml_helpers)
|
|
106
|
+
r, g, b = _contrast_rgb(bg)
|
|
107
|
+
for run in cell.paragraphs[0].runs:
|
|
108
|
+
run.bold = True
|
|
109
|
+
run.font.color.rgb = rgb_color(r, g, b)
|
|
110
|
+
|
|
111
|
+
# Data rows
|
|
112
|
+
for row_idx, (idx_label, row) in enumerate(table.iterrows(), start=1):
|
|
113
|
+
row_cells = word_table.rows[row_idx].cells
|
|
114
|
+
row_cells[0].text = str(idx_label)
|
|
115
|
+
_set_cell_shading(row_cells[0], "#f7f7f7", xml_helpers)
|
|
116
|
+
for col_idx, col_name in enumerate(table.columns, start=1):
|
|
117
|
+
cell = row_cells[col_idx]
|
|
118
|
+
cell.text = str(row[col_name])
|
|
119
|
+
bg = resolved_palette.get(str(col_name), "#ffffff")
|
|
120
|
+
_set_cell_shading(cell, bg, xml_helpers)
|
|
121
|
+
r, g, b = _contrast_rgb(bg)
|
|
122
|
+
for run in cell.paragraphs[0].runs:
|
|
123
|
+
run.font.color.rgb = rgb_color(r, g, b)
|
|
124
|
+
|
|
125
|
+
return word_table
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def render_docx_report(
|
|
129
|
+
template_path: str | Path,
|
|
130
|
+
output_path: str | Path,
|
|
131
|
+
*,
|
|
132
|
+
context: dict[str, Any] | None = None,
|
|
133
|
+
figures: dict[str, str | Path] | None = None,
|
|
134
|
+
figure_widths_mm: dict[str, float] | None = None,
|
|
135
|
+
default_figure_width_mm: float = 155.0,
|
|
136
|
+
tables: list[dict[str, Any]] | None = None,
|
|
137
|
+
config: str | Path | Config | None = None,
|
|
138
|
+
) -> Path:
|
|
139
|
+
"""Populate a Word (``.docx``) report template with text, pre-generated figures, and tables.
|
|
140
|
+
|
|
141
|
+
Uses ``docxtpl`` Jinja2 placeholders inside ``template_path`` (e.g., ``{{ report_title }}``
|
|
142
|
+
for text and ``{{ state_bar_fig }}`` for inline images from ``figures``). Optional
|
|
143
|
+
styled summary tables (e.g., from :func:`stplot.transform.build_fmu_vs_region_table`)
|
|
144
|
+
can also be appended cleanly with semantic cell shading.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
template_path: Path to the input ``.docx`` template file.
|
|
148
|
+
output_path: Destination path for the rendered ``.docx`` report.
|
|
149
|
+
context: Dictionary of template variables (strings, numbers, lists, etc.).
|
|
150
|
+
figures: Mapping of ``{placeholder_name: image_file_path}`` inserted as inline images.
|
|
151
|
+
figure_widths_mm: Optional per-figure width overrides in millimetres.
|
|
152
|
+
default_figure_width_mm: Default inline image width in millimetres (default ``155.0``).
|
|
153
|
+
tables: Optional list of table specification dicts passed to :func:`add_styled_table`
|
|
154
|
+
(each dict must include ``"df"`` and may include ``"caption"``, ``"palette_key"``,
|
|
155
|
+
``"index_name"``, and ``"palette"``).
|
|
156
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
Resolved :class:`pathlib.Path` to the generated ``.docx`` file.
|
|
160
|
+
"""
|
|
161
|
+
Document, _, Mm, _ = _import_docx()
|
|
162
|
+
DocxTemplate, InlineImage = _import_docxtpl()
|
|
163
|
+
|
|
164
|
+
tpl_path = Path(template_path)
|
|
165
|
+
if not tpl_path.exists():
|
|
166
|
+
raise FileNotFoundError(f"Word report template not found: {tpl_path}")
|
|
167
|
+
|
|
168
|
+
out_path = Path(output_path)
|
|
169
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
|
|
171
|
+
tpl = DocxTemplate(str(tpl_path))
|
|
172
|
+
widths = figure_widths_mm or {}
|
|
173
|
+
|
|
174
|
+
def _resolve_inline_images(obj: Any, key_hint: str = "") -> Any:
|
|
175
|
+
if isinstance(obj, Path):
|
|
176
|
+
if not obj.exists():
|
|
177
|
+
raise FileNotFoundError(f"Figure image for '{key_hint}' not found: {obj}")
|
|
178
|
+
w_mm = float(widths.get(key_hint, default_figure_width_mm))
|
|
179
|
+
return InlineImage(tpl, str(obj), width=Mm(w_mm))
|
|
180
|
+
if isinstance(obj, dict):
|
|
181
|
+
resolved: dict[str, Any] = {}
|
|
182
|
+
for k, v in obj.items():
|
|
183
|
+
if isinstance(v, (str, Path)) and str(k).endswith("_fig") and str(v).strip():
|
|
184
|
+
img_p = Path(v)
|
|
185
|
+
if not img_p.exists():
|
|
186
|
+
raise FileNotFoundError(
|
|
187
|
+
f"Figure image for placeholder '{k}' not found: {img_p}"
|
|
188
|
+
)
|
|
189
|
+
w_mm = float(widths.get(k, default_figure_width_mm))
|
|
190
|
+
resolved[k] = InlineImage(tpl, str(img_p), width=Mm(w_mm))
|
|
191
|
+
else:
|
|
192
|
+
resolved[k] = _resolve_inline_images(v, key_hint=str(k))
|
|
193
|
+
return resolved
|
|
194
|
+
if isinstance(obj, list):
|
|
195
|
+
return [_resolve_inline_images(item, key_hint=key_hint) for item in obj]
|
|
196
|
+
return obj
|
|
197
|
+
|
|
198
|
+
render_ctx: dict[str, Any] = _resolve_inline_images(dict(context or {}))
|
|
199
|
+
|
|
200
|
+
for key, img_path in (figures or {}).items():
|
|
201
|
+
img_file = Path(img_path)
|
|
202
|
+
if not img_file.exists():
|
|
203
|
+
raise FileNotFoundError(f"Figure image for placeholder '{key}' not found: {img_file}")
|
|
204
|
+
width_mm = float(widths.get(key, default_figure_width_mm))
|
|
205
|
+
render_ctx[key] = InlineImage(tpl, str(img_file), width=Mm(width_mm))
|
|
206
|
+
|
|
207
|
+
tpl.render(render_ctx, autoescape=True)
|
|
208
|
+
tpl.save(str(out_path))
|
|
209
|
+
|
|
210
|
+
if tables:
|
|
211
|
+
cfg = ensure_config(config)
|
|
212
|
+
doc = Document(str(out_path))
|
|
213
|
+
for spec in tables:
|
|
214
|
+
add_styled_table(
|
|
215
|
+
doc,
|
|
216
|
+
spec["df"],
|
|
217
|
+
palette_key=spec.get("palette_key", "state_bands"),
|
|
218
|
+
palette=spec.get("palette"),
|
|
219
|
+
index_name=spec.get("index_name"),
|
|
220
|
+
caption=spec.get("caption"),
|
|
221
|
+
config=cfg,
|
|
222
|
+
)
|
|
223
|
+
doc.save(str(out_path))
|
|
224
|
+
|
|
225
|
+
return out_path
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def create_starter_docx_template(
|
|
229
|
+
output_path: str | Path,
|
|
230
|
+
*,
|
|
231
|
+
config: str | Path | Config | None = None,
|
|
232
|
+
) -> Path:
|
|
233
|
+
"""Generate a clean, ready-to-customize A4 Word (``.docx``) report template.
|
|
234
|
+
|
|
235
|
+
The created template contains Jinja2 placeholders compatible with
|
|
236
|
+
:func:`render_docx_report`:
|
|
237
|
+
|
|
238
|
+
- **Cover / Header**: ``{{ report_title }}``, ``{{ subtitle }}``,
|
|
239
|
+
``{{ reporting_period }}``, ``{{ author }}``
|
|
240
|
+
- **Executive Summary**: ``{{ executive_summary }}``
|
|
241
|
+
- **Spatial Overview**: ``{{ fmu_map_fig }}``, ``{{ fmu_map_caption }}``
|
|
242
|
+
- **State Results**: ``{{ state_bar_fig }}``, ``{{ state_bar_caption }}``,
|
|
243
|
+
``{{ state_commentary }}``
|
|
244
|
+
- **Trend Evaluation**: ``{{ trend_bar_fig }}``, ``{{ trend_bar_caption }}``,
|
|
245
|
+
``{{ trend_commentary }}``
|
|
246
|
+
- **One Plan Compliance**: ``{{ one_plan_fig }}``, ``{{ one_plan_caption }}``
|
|
247
|
+
|
|
248
|
+
Open the generated ``.docx`` in Microsoft Word to apply your council's logo, fonts,
|
|
249
|
+
and brand styles while keeping the ``{{ ... }}`` placeholders intact.
|
|
250
|
+
|
|
251
|
+
Args:
|
|
252
|
+
output_path: Destination path for the starter ``.docx`` template.
|
|
253
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
Resolved :class:`pathlib.Path` to the written template file.
|
|
257
|
+
"""
|
|
258
|
+
Document, _, Mm, rgb_color = _import_docx()
|
|
259
|
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
|
260
|
+
from docx.shared import Pt
|
|
261
|
+
|
|
262
|
+
cfg = ensure_config(config)
|
|
263
|
+
out_path = Path(output_path)
|
|
264
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
265
|
+
|
|
266
|
+
doc = Document()
|
|
267
|
+
|
|
268
|
+
# Configure A4 page with clean 22 mm margins
|
|
269
|
+
for section in doc.sections:
|
|
270
|
+
section.page_width = Mm(210)
|
|
271
|
+
section.page_height = Mm(297)
|
|
272
|
+
section.top_margin = Mm(22)
|
|
273
|
+
section.bottom_margin = Mm(22)
|
|
274
|
+
section.left_margin = Mm(22)
|
|
275
|
+
section.right_margin = Mm(22)
|
|
276
|
+
|
|
277
|
+
header_p = section.header.paragraphs[0]
|
|
278
|
+
header_p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
|
279
|
+
h_run = header_p.add_run("{{ report_title }} | {{ reporting_period }}")
|
|
280
|
+
h_run.font.size = Pt(8.5)
|
|
281
|
+
h_run.font.color.rgb = rgb_color(100, 110, 120)
|
|
282
|
+
|
|
283
|
+
footer_p = section.footer.paragraphs[0]
|
|
284
|
+
footer_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
285
|
+
f_run = footer_p.add_run("Generated with stplot — {{ author }}")
|
|
286
|
+
f_run.font.size = Pt(8.5)
|
|
287
|
+
f_run.font.color.rgb = rgb_color(120, 130, 140)
|
|
288
|
+
|
|
289
|
+
# Parse accent & text colors from active preset theme
|
|
290
|
+
accent_hex = cfg.theme.accent_color.lstrip("#")
|
|
291
|
+
accent_rgb = rgb_color(
|
|
292
|
+
int(accent_hex[0:2], 16),
|
|
293
|
+
int(accent_hex[2:4], 16),
|
|
294
|
+
int(accent_hex[4:6], 16),
|
|
295
|
+
)
|
|
296
|
+
text_hex = cfg.theme.text_color.lstrip("#")
|
|
297
|
+
text_rgb = rgb_color(
|
|
298
|
+
int(text_hex[0:2], 16),
|
|
299
|
+
int(text_hex[2:4], 16),
|
|
300
|
+
int(text_hex[4:6], 16),
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
normal_style = doc.styles["Normal"]
|
|
304
|
+
normal_style.font.name = "Calibri"
|
|
305
|
+
normal_style.font.size = Pt(10.5)
|
|
306
|
+
normal_style.font.color.rgb = text_rgb
|
|
307
|
+
|
|
308
|
+
def _add_section_heading(text: str) -> None:
|
|
309
|
+
h = doc.add_heading(text, level=1)
|
|
310
|
+
for run in h.runs:
|
|
311
|
+
run.font.color.rgb = accent_rgb
|
|
312
|
+
|
|
313
|
+
def _add_figure_block(fig_placeholder: str, caption_placeholder: str) -> None:
|
|
314
|
+
p_img = doc.add_paragraph()
|
|
315
|
+
p_img.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
316
|
+
p_img.add_run(fig_placeholder)
|
|
317
|
+
p_cap = doc.add_paragraph()
|
|
318
|
+
p_cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
319
|
+
cap_run = p_cap.add_run(caption_placeholder)
|
|
320
|
+
cap_run.italic = True
|
|
321
|
+
cap_run.font.size = Pt(9.5)
|
|
322
|
+
cap_run.font.color.rgb = rgb_color(90, 100, 110)
|
|
323
|
+
|
|
324
|
+
# Title block
|
|
325
|
+
title_p = doc.add_paragraph()
|
|
326
|
+
t_run = title_p.add_run("{{ report_title }}")
|
|
327
|
+
t_run.bold = True
|
|
328
|
+
t_run.font.size = Pt(22)
|
|
329
|
+
t_run.font.color.rgb = accent_rgb
|
|
330
|
+
|
|
331
|
+
sub_p = doc.add_paragraph()
|
|
332
|
+
s_run = sub_p.add_run("{{ subtitle }}")
|
|
333
|
+
s_run.font.size = Pt(13)
|
|
334
|
+
s_run.font.color.rgb = text_rgb
|
|
335
|
+
|
|
336
|
+
meta_p = doc.add_paragraph()
|
|
337
|
+
m_run = meta_p.add_run(
|
|
338
|
+
"Reporting Period: {{ reporting_period }} | Prepared by: {{ author }}"
|
|
339
|
+
)
|
|
340
|
+
m_run.font.size = Pt(9.5)
|
|
341
|
+
m_run.font.color.rgb = rgb_color(95, 105, 115)
|
|
342
|
+
|
|
343
|
+
# Section 1: Executive Summary
|
|
344
|
+
_add_section_heading("1. Executive Summary")
|
|
345
|
+
doc.add_paragraph("{{ executive_summary }}")
|
|
346
|
+
|
|
347
|
+
# Section 2: Spatial Overview
|
|
348
|
+
_add_section_heading("2. Spatial Overview")
|
|
349
|
+
_add_figure_block("{{ fmu_map_fig }}", "{{ fmu_map_caption }}")
|
|
350
|
+
|
|
351
|
+
# Section 3: State Results
|
|
352
|
+
_add_section_heading("3. State Results")
|
|
353
|
+
doc.add_paragraph("{{ state_commentary }}")
|
|
354
|
+
_add_figure_block("{{ state_bar_fig }}", "{{ state_bar_caption }}")
|
|
355
|
+
|
|
356
|
+
# Section 4: Trend Evaluation
|
|
357
|
+
_add_section_heading("4. Trend Evaluation")
|
|
358
|
+
doc.add_paragraph("{{ trend_commentary }}")
|
|
359
|
+
_add_figure_block("{{ trend_bar_fig }}", "{{ trend_bar_caption }}")
|
|
360
|
+
|
|
361
|
+
# Section 5: One Plan Compliance
|
|
362
|
+
_add_section_heading("5. One Plan Compliance")
|
|
363
|
+
_add_figure_block("{{ one_plan_fig }}", "{{ one_plan_caption }}")
|
|
364
|
+
|
|
365
|
+
# Section 6: Summary Tables (appended dynamically via render_docx_report(..., tables=[...]))
|
|
366
|
+
_add_section_heading("6. Summary Tables")
|
|
367
|
+
|
|
368
|
+
doc.save(str(out_path))
|
|
369
|
+
return out_path
|
stplot/theme/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Shared visual theme adapters for Matplotlib, Seaborn, Plotly, and Folium."""
|
|
2
|
+
|
|
3
|
+
from stplot.theme.folium import build_legend_html, get_folium_color_map
|
|
4
|
+
from stplot.theme.mpl import (
|
|
5
|
+
apply_mpl_theme,
|
|
6
|
+
build_mpl_rcparams,
|
|
7
|
+
format_log_axis,
|
|
8
|
+
format_log_value,
|
|
9
|
+
mpl_theme,
|
|
10
|
+
style_axes,
|
|
11
|
+
)
|
|
12
|
+
from stplot.theme.plotly import build_plotly_log_axis, build_plotly_template
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"apply_mpl_theme",
|
|
16
|
+
"build_legend_html",
|
|
17
|
+
"build_mpl_rcparams",
|
|
18
|
+
"build_plotly_log_axis",
|
|
19
|
+
"build_plotly_template",
|
|
20
|
+
"format_log_axis",
|
|
21
|
+
"format_log_value",
|
|
22
|
+
"get_folium_color_map",
|
|
23
|
+
"mpl_theme",
|
|
24
|
+
"style_axes",
|
|
25
|
+
]
|
stplot/theme/folium.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Folium color-mapping and HTML legend helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from html import escape
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from stplot.config import Config, ensure_config, resolve_palette
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_folium_color_map(
|
|
12
|
+
palette_key: str = "state_bands",
|
|
13
|
+
*,
|
|
14
|
+
palette: dict[str, str] | None = None,
|
|
15
|
+
config: str | Path | Config | None = None,
|
|
16
|
+
) -> dict[str, str]:
|
|
17
|
+
"""Return a category-to-hex color mapping for Folium layers."""
|
|
18
|
+
cfg = ensure_config(config)
|
|
19
|
+
return resolve_palette(palette, cfg, palette_key)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_legend_html(
|
|
23
|
+
title: str,
|
|
24
|
+
palette: dict[str, str],
|
|
25
|
+
*,
|
|
26
|
+
order: list[str] | None = None,
|
|
27
|
+
config: str | Path | Config | None = None,
|
|
28
|
+
) -> str:
|
|
29
|
+
"""Build a theme-consistent HTML legend snippet for a Folium map.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
title: Legend heading text.
|
|
33
|
+
palette: Mapping of category labels to CSS/hex color strings.
|
|
34
|
+
order: Optional display order for legend items. Defaults to ``palette`` key order.
|
|
35
|
+
config: Optional Config object, preset name, or path to YAML/TOML config.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
HTML string suitable for embedding via ``folium.Element`` / ``branca.element.MacroElement``.
|
|
39
|
+
"""
|
|
40
|
+
cfg = ensure_config(config)
|
|
41
|
+
t = cfg.theme
|
|
42
|
+
keys = [k for k in order if k in palette] if order is not None else list(palette.keys())
|
|
43
|
+
|
|
44
|
+
items_html = "\n".join(
|
|
45
|
+
f'<div style="display:flex;align-items:center;margin:3px 0;">'
|
|
46
|
+
f'<span style="display:inline-block;width:12px;height:12px;margin-right:6px;'
|
|
47
|
+
f'background:{escape(palette[k])};border:1px solid {escape(t.spine_color)};"></span>'
|
|
48
|
+
f"<span>{escape(str(k))}</span>"
|
|
49
|
+
f"</div>"
|
|
50
|
+
for k in keys
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
return (
|
|
54
|
+
f'<div style="position:fixed;bottom:30px;left:30px;z-index:9999;'
|
|
55
|
+
f"background:{escape(t.background_color)};color:{escape(t.text_color)};"
|
|
56
|
+
f"font-family:{escape(t.font_family)},sans-serif;font-size:{int(t.legend_size)}px;"
|
|
57
|
+
f"padding:10px 12px;border:1px solid {escape(t.spine_color)};border-radius:4px;"
|
|
58
|
+
f'box-shadow:0 1px 4px rgba(0,0,0,0.15);">'
|
|
59
|
+
f'<div style="font-weight:600;margin-bottom:6px;">{escape(title)}</div>'
|
|
60
|
+
f"{items_html}"
|
|
61
|
+
f"</div>"
|
|
62
|
+
)
|
stplot/theme/mpl.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Matplotlib and Seaborn theme adapters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import matplotlib.pyplot as plt
|
|
11
|
+
from matplotlib.axes import Axes
|
|
12
|
+
|
|
13
|
+
from stplot.config import Config, ensure_config
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build_mpl_rcparams(config: str | Path | Config | None = None) -> dict[str, Any]:
|
|
17
|
+
"""Translate ``config.theme`` tokens into a Matplotlib ``rcParams`` dictionary."""
|
|
18
|
+
cfg = ensure_config(config)
|
|
19
|
+
t = cfg.theme
|
|
20
|
+
return {
|
|
21
|
+
"font.family": t.font_family,
|
|
22
|
+
"axes.titlesize": t.title_size,
|
|
23
|
+
"axes.labelsize": t.label_size,
|
|
24
|
+
"xtick.labelsize": t.tick_size,
|
|
25
|
+
"ytick.labelsize": t.tick_size,
|
|
26
|
+
"legend.fontsize": t.legend_size,
|
|
27
|
+
"figure.dpi": t.figure_dpi,
|
|
28
|
+
"figure.figsize": t.default_figsize,
|
|
29
|
+
"figure.facecolor": t.background_color,
|
|
30
|
+
"axes.facecolor": t.axes_facecolor,
|
|
31
|
+
"axes.edgecolor": t.spine_color,
|
|
32
|
+
"axes.labelcolor": t.text_color,
|
|
33
|
+
"text.color": t.text_color,
|
|
34
|
+
"xtick.color": t.text_color,
|
|
35
|
+
"ytick.color": t.text_color,
|
|
36
|
+
"grid.color": t.grid_color,
|
|
37
|
+
"grid.linewidth": t.grid_width,
|
|
38
|
+
"axes.grid": t.show_grid,
|
|
39
|
+
"axes.axisbelow": True,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def apply_mpl_theme(config: str | Path | Config | None = None) -> None:
|
|
44
|
+
"""Apply the stplot theme globally to Matplotlib ``rcParams``."""
|
|
45
|
+
plt.rcParams.update(build_mpl_rcparams(config))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@contextmanager
|
|
49
|
+
def mpl_theme(config: str | Path | Config | None = None) -> Iterator[Config]:
|
|
50
|
+
"""Context manager that temporarily applies stplot's Matplotlib theme."""
|
|
51
|
+
cfg = ensure_config(config)
|
|
52
|
+
with plt.rc_context(build_mpl_rcparams(cfg)):
|
|
53
|
+
yield cfg
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def style_axes(
|
|
57
|
+
ax: Axes,
|
|
58
|
+
*,
|
|
59
|
+
title: str | None = None,
|
|
60
|
+
xlabel: str | None = None,
|
|
61
|
+
ylabel: str | None = None,
|
|
62
|
+
config: str | Path | Config | None = None,
|
|
63
|
+
) -> Axes:
|
|
64
|
+
"""Apply consistent axis labels, title, grid, and spine styling to a Matplotlib Axes."""
|
|
65
|
+
cfg = ensure_config(config)
|
|
66
|
+
t = cfg.theme
|
|
67
|
+
|
|
68
|
+
ax.set_facecolor(t.axes_facecolor)
|
|
69
|
+
|
|
70
|
+
if title is not None:
|
|
71
|
+
ax.set_title(
|
|
72
|
+
title,
|
|
73
|
+
fontsize=t.title_size,
|
|
74
|
+
color=t.text_color,
|
|
75
|
+
fontweight=t.title_weight,
|
|
76
|
+
pad=10,
|
|
77
|
+
)
|
|
78
|
+
if xlabel is not None:
|
|
79
|
+
ax.set_xlabel(xlabel, fontsize=t.label_size, color=t.text_color)
|
|
80
|
+
if ylabel is not None:
|
|
81
|
+
ax.set_ylabel(ylabel, fontsize=t.label_size, color=t.text_color)
|
|
82
|
+
|
|
83
|
+
if t.despine:
|
|
84
|
+
ax.spines["top"].set_visible(False)
|
|
85
|
+
ax.spines["right"].set_visible(False)
|
|
86
|
+
for spine in ("left", "bottom"):
|
|
87
|
+
ax.spines[spine].set_color(t.spine_color)
|
|
88
|
+
|
|
89
|
+
if t.show_grid:
|
|
90
|
+
ax.grid(True, color=t.grid_color, linestyle="-", linewidth=t.grid_width, alpha=0.9)
|
|
91
|
+
else:
|
|
92
|
+
ax.grid(False)
|
|
93
|
+
|
|
94
|
+
ax.set_axisbelow(True)
|
|
95
|
+
return ax
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def format_log_value(val: float, _pos: int | None = None) -> str:
|
|
99
|
+
"""Format a positive log-axis tick value as a clean human-readable number.
|
|
100
|
+
|
|
101
|
+
Examples:
|
|
102
|
+
- ``0.001`` -> ``"0.001"``
|
|
103
|
+
- ``0.01`` -> ``"0.01"``
|
|
104
|
+
- ``1.0`` -> ``"1"``
|
|
105
|
+
- ``100.0`` -> ``"100"``
|
|
106
|
+
- ``1000.0`` -> ``"1,000"``
|
|
107
|
+
- ``10000.0`` -> ``"10,000"``
|
|
108
|
+
"""
|
|
109
|
+
import math
|
|
110
|
+
|
|
111
|
+
if val <= 0 or math.isnan(val):
|
|
112
|
+
return ""
|
|
113
|
+
if val >= 1000:
|
|
114
|
+
if abs(val - round(val)) < 1e-6:
|
|
115
|
+
return f"{int(round(val)):,}"
|
|
116
|
+
return f"{val:,.2g}"
|
|
117
|
+
if val >= 1:
|
|
118
|
+
if abs(val - round(val)) < 1e-6:
|
|
119
|
+
return f"{int(round(val))}"
|
|
120
|
+
return f"{val:g}"
|
|
121
|
+
# Sub-1 values: avoid scientific notation down to 1e-5
|
|
122
|
+
if val >= 1e-5:
|
|
123
|
+
formatted = f"{val:.6f}".rstrip("0").rstrip(".")
|
|
124
|
+
return formatted
|
|
125
|
+
return f"{val:.1e}"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def format_log_axis(
|
|
129
|
+
ax: Axes,
|
|
130
|
+
axis: str = "y",
|
|
131
|
+
*,
|
|
132
|
+
show_minor_ticks: bool = True,
|
|
133
|
+
show_minor_grid: bool = False,
|
|
134
|
+
style: str = "plain",
|
|
135
|
+
) -> Axes:
|
|
136
|
+
"""Apply clean, publication-ready base-10 logarithmic scaling and tick labels to an Axes.
|
|
137
|
+
|
|
138
|
+
Replaces scientific ``10^x`` / ``1e-03`` Matplotlib defaults with clean plain numbers
|
|
139
|
+
(``0.001``, ``0.01``, ``0.1``, ``1``, ``10``, ``100``, ``1,000``) plus crisp unlabeled
|
|
140
|
+
minor log ticks at 2–9× decades.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
ax: Target Matplotlib Axes.
|
|
144
|
+
axis: ``"x"``, ``"y"``, or ``"both"``.
|
|
145
|
+
show_minor_ticks: If True (default), display unlabeled minor log ticks at 2..9.
|
|
146
|
+
show_minor_grid: If True, draw subtle dotted minor gridlines.
|
|
147
|
+
style: ``"plain"`` (default, human-readable numbers) or ``"scientific"``.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
The styled Axes.
|
|
151
|
+
"""
|
|
152
|
+
import numpy as np
|
|
153
|
+
from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter
|
|
154
|
+
|
|
155
|
+
targets = ["x", "y"] if axis == "both" else [axis.lower()]
|
|
156
|
+
for target in targets:
|
|
157
|
+
if target == "x":
|
|
158
|
+
ax.set_xscale("log")
|
|
159
|
+
ax_obj = ax.xaxis
|
|
160
|
+
elif target == "y":
|
|
161
|
+
ax.set_yscale("log")
|
|
162
|
+
ax_obj = ax.yaxis
|
|
163
|
+
else:
|
|
164
|
+
raise ValueError(f"format_log_axis: axis must be 'x', 'y', or 'both', got '{axis}'.")
|
|
165
|
+
|
|
166
|
+
ax_obj.set_major_locator(LogLocator(base=10.0, numticks=12))
|
|
167
|
+
if style == "plain":
|
|
168
|
+
ax_obj.set_major_formatter(FuncFormatter(format_log_value))
|
|
169
|
+
|
|
170
|
+
if show_minor_ticks:
|
|
171
|
+
ax_obj.set_minor_locator(
|
|
172
|
+
LogLocator(base=10.0, subs=np.arange(2, 10) * 0.1, numticks=100)
|
|
173
|
+
)
|
|
174
|
+
ax_obj.set_minor_formatter(NullFormatter())
|
|
175
|
+
if show_minor_grid:
|
|
176
|
+
ax.grid(True, which="minor", axis=target, linestyle=":", linewidth=0.4, alpha=0.45)
|
|
177
|
+
else:
|
|
178
|
+
ax_obj.set_minor_formatter(NullFormatter())
|
|
179
|
+
ax.tick_params(axis=target, which="minor", length=0)
|
|
180
|
+
|
|
181
|
+
return ax
|