mintfig 0.2.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.
- mintfig/__init__.py +162 -0
- mintfig/_explain/__init__.py +1 -0
- mintfig/_explain/change.py +392 -0
- mintfig/_explain/compare.py +1308 -0
- mintfig/_explain/compare_grouped.py +472 -0
- mintfig/_explain/core.py +2005 -0
- mintfig/_explain/distribution.py +1268 -0
- mintfig/_explain/flow.py +508 -0
- mintfig/_explain/layout.py +2012 -0
- mintfig/_explain/matrix.py +623 -0
- mintfig/_explain/relate.py +1318 -0
- mintfig/_explain/timeline.py +595 -0
- mintfig/_explain/trend.py +2557 -0
- mintfig/_explain/waterfall.py +459 -0
- mintfig/_table.py +691 -0
- mintfig/_tabular.py +738 -0
- mintfig/annotations.py +1165 -0
- mintfig/assets/AGENTS_SNIPPET.md +11 -0
- mintfig/assets/SKILL.md +143 -0
- mintfig/assets/__init__.py +1 -0
- mintfig/assets/references/publication.md +79 -0
- mintfig/assets/references/scientific_and_recipes.md +213 -0
- mintfig/audit.py +179 -0
- mintfig/brief.py +518 -0
- mintfig/bundle.py +333 -0
- mintfig/cli.py +1300 -0
- mintfig/edit.py +347 -0
- mintfig/epistemic.py +1083 -0
- mintfig/explainer.py +194 -0
- mintfig/export.py +247 -0
- mintfig/inspect_data.py +583 -0
- mintfig/interactive.py +1028 -0
- mintfig/palettes.py +233 -0
- mintfig/plate.py +784 -0
- mintfig/preflight.py +2398 -0
- mintfig/proof.py +627 -0
- mintfig/runner.py +403 -0
- mintfig/skill.py +167 -0
- mintfig/specs.py +291 -0
- mintfig/style.py +151 -0
- mintfig/terminal.py +785 -0
- mintfig/themes.py +660 -0
- mintfig-0.2.0.dist-info/METADATA +239 -0
- mintfig-0.2.0.dist-info/RECORD +47 -0
- mintfig-0.2.0.dist-info/WHEEL +4 -0
- mintfig-0.2.0.dist-info/entry_points.txt +2 -0
- mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,2012 @@
|
|
|
1
|
+
"""Layout engine, Explanation, Summary, explain(), load(), and JSON spec entry points."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import zlib
|
|
9
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from matplotlib import dates as mdates
|
|
15
|
+
from matplotlib.axes import Axes
|
|
16
|
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
|
17
|
+
from matplotlib.figure import Figure
|
|
18
|
+
from matplotlib.lines import Line2D
|
|
19
|
+
from matplotlib.ticker import (
|
|
20
|
+
FixedLocator,
|
|
21
|
+
FuncFormatter,
|
|
22
|
+
MaxNLocator,
|
|
23
|
+
)
|
|
24
|
+
from matplotlib.transforms import Bbox
|
|
25
|
+
|
|
26
|
+
from ..specs import JournalSpec, get_spec, mm_to_in
|
|
27
|
+
from ..themes import (
|
|
28
|
+
EXPLAIN_PALETTES,
|
|
29
|
+
MINTFIG_THEME,
|
|
30
|
+
THEME_ALIASES,
|
|
31
|
+
THEMES,
|
|
32
|
+
ExplainPalette,
|
|
33
|
+
Theme,
|
|
34
|
+
apply_accent,
|
|
35
|
+
apply_palette,
|
|
36
|
+
get_theme,
|
|
37
|
+
)
|
|
38
|
+
from .change import change
|
|
39
|
+
from .compare import compare, share
|
|
40
|
+
from .core import (
|
|
41
|
+
_ADJUSTMENTS,
|
|
42
|
+
_COL_GAP_MM,
|
|
43
|
+
_HAS_DIGIT,
|
|
44
|
+
_ILLUSTRATIVE_CUE,
|
|
45
|
+
_LINE,
|
|
46
|
+
_MARGIN_MM,
|
|
47
|
+
_ROW_GAP_MM,
|
|
48
|
+
_STRICT,
|
|
49
|
+
_TOPIC_TITLE,
|
|
50
|
+
_VISUAL_DEFECT_RULES,
|
|
51
|
+
COMFORTABLE_PANELS,
|
|
52
|
+
DISPLAY_WIDTH_PX,
|
|
53
|
+
KINDS,
|
|
54
|
+
MAX_PANELS,
|
|
55
|
+
MAX_TITLE_LINES,
|
|
56
|
+
MIN_TEXT_PX,
|
|
57
|
+
PT_TO_MM,
|
|
58
|
+
ExplainError,
|
|
59
|
+
Panel,
|
|
60
|
+
_cover_with_ticks,
|
|
61
|
+
_Ctx,
|
|
62
|
+
_date_formatter,
|
|
63
|
+
_fit_axes,
|
|
64
|
+
_glyph_issue,
|
|
65
|
+
_GlyphCapture,
|
|
66
|
+
_guarded,
|
|
67
|
+
_has_items,
|
|
68
|
+
_is_strict,
|
|
69
|
+
_issue,
|
|
70
|
+
_labels_collide,
|
|
71
|
+
_Measure,
|
|
72
|
+
_measure_text,
|
|
73
|
+
_missing_glyphs,
|
|
74
|
+
_pairs,
|
|
75
|
+
_plain,
|
|
76
|
+
_record_adjustment,
|
|
77
|
+
_Sizes,
|
|
78
|
+
_tick_label,
|
|
79
|
+
_tick_label_boxes,
|
|
80
|
+
_value_axis,
|
|
81
|
+
)
|
|
82
|
+
from .distribution import distribution, histogram
|
|
83
|
+
from .flow import flow
|
|
84
|
+
from .matrix import matrix
|
|
85
|
+
from .relate import relate
|
|
86
|
+
from .timeline import timeline
|
|
87
|
+
from .trend import trend
|
|
88
|
+
from .waterfall import waterfall
|
|
89
|
+
|
|
90
|
+
# --------------------------------------------------------------------------- #
|
|
91
|
+
# table
|
|
92
|
+
# --------------------------------------------------------------------------- #
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@_guarded("table")
|
|
96
|
+
def table(
|
|
97
|
+
rows: Sequence[Mapping[str, Any]] | Mapping[str, Sequence[Any]] | Sequence[Sequence[Any]],
|
|
98
|
+
*,
|
|
99
|
+
columns: Sequence[str] | None = None,
|
|
100
|
+
title: str | None = None,
|
|
101
|
+
label: str | None = None,
|
|
102
|
+
unit: str | None = None,
|
|
103
|
+
units: Mapping[str, str] | None = None,
|
|
104
|
+
highlight: str | Sequence[str] | None = None,
|
|
105
|
+
baseline: str | None = None,
|
|
106
|
+
bold_best: bool | str | Mapping[str, str] = False,
|
|
107
|
+
sort: str | None = None,
|
|
108
|
+
align: Mapping[str, str] | None = None,
|
|
109
|
+
fmt: str | Mapping[str, str] | None = None,
|
|
110
|
+
) -> Panel:
|
|
111
|
+
"""Exact lookup table or multi-metric scorecard with booktabs rules and aligned figures."""
|
|
112
|
+
from .._table import table as _build_table
|
|
113
|
+
|
|
114
|
+
return _build_table(
|
|
115
|
+
rows,
|
|
116
|
+
columns=columns,
|
|
117
|
+
title=title,
|
|
118
|
+
label=label,
|
|
119
|
+
unit=unit,
|
|
120
|
+
units=units,
|
|
121
|
+
highlight=highlight,
|
|
122
|
+
baseline=baseline,
|
|
123
|
+
bold_best=bold_best,
|
|
124
|
+
sort=sort,
|
|
125
|
+
align=align,
|
|
126
|
+
fmt=fmt,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# --------------------------------------------------------------------------- #
|
|
131
|
+
# custom
|
|
132
|
+
# --------------------------------------------------------------------------- #
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@_guarded("custom")
|
|
136
|
+
def custom(
|
|
137
|
+
draw: Callable[[Axes], None],
|
|
138
|
+
*,
|
|
139
|
+
title: str | None = None,
|
|
140
|
+
label: str | None = None,
|
|
141
|
+
unit: str | None = None,
|
|
142
|
+
height_mm: float = 48.0,
|
|
143
|
+
describe: str = "Custom panel",
|
|
144
|
+
) -> Panel:
|
|
145
|
+
"""Escape hatch: draw anything on a house-styled Axes when no form fits.
|
|
146
|
+
|
|
147
|
+
The built-in rules do not apply inside ``draw``; preflight still does.
|
|
148
|
+
"""
|
|
149
|
+
if not callable(draw):
|
|
150
|
+
raise ExplainError(
|
|
151
|
+
"custom(draw) must be a function taking an Axes.", fix_hint="Pass def draw(ax): ..."
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
def _draw(ctx: _Ctx, ax: Axes) -> None:
|
|
155
|
+
_value_axis(ax, ctx.sizes, ctx.theme)
|
|
156
|
+
draw(ax)
|
|
157
|
+
|
|
158
|
+
return Panel(
|
|
159
|
+
kind="custom",
|
|
160
|
+
title=title,
|
|
161
|
+
label=label,
|
|
162
|
+
unit=unit,
|
|
163
|
+
spec={"title": title, "label": label, "unit": unit},
|
|
164
|
+
facts=[],
|
|
165
|
+
describe=describe,
|
|
166
|
+
_height_mm=lambda _w, _m, _s, _t: float(height_mm),
|
|
167
|
+
stretch=True,
|
|
168
|
+
_draw=_draw,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# --------------------------------------------------------------------------- #
|
|
173
|
+
# Layout and the Explanation object
|
|
174
|
+
# --------------------------------------------------------------------------- #
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _auto_layout(keys: list[str]) -> list[list[str]]:
|
|
178
|
+
n = len(keys)
|
|
179
|
+
if n <= 2:
|
|
180
|
+
return [keys]
|
|
181
|
+
if n == 3:
|
|
182
|
+
return [[keys[0], keys[0]], [keys[1], keys[2]]]
|
|
183
|
+
if n % 2 == 0:
|
|
184
|
+
return [keys[i : i + 2] for i in range(0, n, 2)]
|
|
185
|
+
return [[keys[0], keys[0]], *[keys[i : i + 2] for i in range(1, n, 2)]]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _validate_layout(layout: Sequence[Sequence[str]], keys: list[str]) -> list[list[str]]:
|
|
189
|
+
rows = [[str(k) for k in row] for row in layout]
|
|
190
|
+
seen: list[str] = []
|
|
191
|
+
for row in rows:
|
|
192
|
+
if not row:
|
|
193
|
+
raise ExplainError(
|
|
194
|
+
"layout has an empty row.", fix_hint='e.g. layout=[["a"], ["b", "c"]].'
|
|
195
|
+
)
|
|
196
|
+
collapsed = [k for i, k in enumerate(row) if i == 0 or row[i - 1] != k]
|
|
197
|
+
if len(set(collapsed)) != len(collapsed):
|
|
198
|
+
raise ExplainError(
|
|
199
|
+
f"layout row {row!r} repeats a panel non-contiguously.",
|
|
200
|
+
fix_hint="Repeat a key only side by side to make that panel wider.",
|
|
201
|
+
)
|
|
202
|
+
for key in collapsed:
|
|
203
|
+
if key in seen:
|
|
204
|
+
raise ExplainError(
|
|
205
|
+
f"layout places panel {key!r} in more than one row.",
|
|
206
|
+
fix_hint="Each panel occupies one row; rows are stacked top to bottom.",
|
|
207
|
+
)
|
|
208
|
+
seen.append(key)
|
|
209
|
+
if sorted(seen) != sorted(keys):
|
|
210
|
+
raise ExplainError(
|
|
211
|
+
f"layout uses panels {sorted(seen)!r} but the figure has {sorted(keys)!r}.",
|
|
212
|
+
fix_hint="Panels are keyed a, b, c ... in the order passed; list each exactly once.",
|
|
213
|
+
)
|
|
214
|
+
return rows
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
#: Named colour slots for ``explain(colors=...)``: an index into the theme's validated
|
|
218
|
+
#: series palette, so a pinned colour stays colour-blind and grayscale safe in every style.
|
|
219
|
+
COLOR_SLOTS: dict[str, int] = {"blue": 0, "red": 1, "green": 2, "amber": 3}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _entity_key(name: object) -> str:
|
|
223
|
+
return str(name).strip()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _pinned_colors(colors: object, theme: Theme) -> dict[str, str]:
|
|
227
|
+
"""Read ``explain(colors={name: slot})`` into ``{name: hex}`` from the theme palette."""
|
|
228
|
+
if colors is None:
|
|
229
|
+
return {}
|
|
230
|
+
slots = ", ".join(f'"{s}"' for s in COLOR_SLOTS)
|
|
231
|
+
hint = (
|
|
232
|
+
f"Pass colors={{name: slot}} with slot one of {slots}, e.g. "
|
|
233
|
+
'colors={"no retrieval": "red", "full model": "blue"}. Slots resolve to the style\'s '
|
|
234
|
+
"validated palette (colour-blind and grayscale separated), so arbitrary colours are not "
|
|
235
|
+
"accepted."
|
|
236
|
+
)
|
|
237
|
+
if not _has_items(colors):
|
|
238
|
+
raise ExplainError(
|
|
239
|
+
f"explain(colors=...) must map names to colour slots, got {type(colors).__name__}.",
|
|
240
|
+
fix_hint=hint,
|
|
241
|
+
rule="bad_colors",
|
|
242
|
+
)
|
|
243
|
+
out: dict[str, str] = {}
|
|
244
|
+
used: dict[str, str] = {}
|
|
245
|
+
for name, slot in _pairs(colors):
|
|
246
|
+
key = _entity_key(name)
|
|
247
|
+
word = slot.strip().lower() if isinstance(slot, str) else None
|
|
248
|
+
if word not in COLOR_SLOTS:
|
|
249
|
+
raise ExplainError(
|
|
250
|
+
f"explain(colors[{key!r}]) = {slot!r} is not a colour slot.",
|
|
251
|
+
fix_hint=hint,
|
|
252
|
+
rule="bad_colors",
|
|
253
|
+
)
|
|
254
|
+
if word in used:
|
|
255
|
+
raise ExplainError(
|
|
256
|
+
f"explain(colors=...) gives {used[word]!r} and {key!r} the same slot {word!r}; "
|
|
257
|
+
"one colour must mean one thing.",
|
|
258
|
+
fix_hint=f"Give each pinned name its own slot ({slots}): at most "
|
|
259
|
+
f"{len(COLOR_SLOTS)} pinned names; leave the rest unpinned (they take the "
|
|
260
|
+
"figure's own colours).",
|
|
261
|
+
rule="bad_colors",
|
|
262
|
+
)
|
|
263
|
+
used[word] = key
|
|
264
|
+
out[key] = theme.series_colors[COLOR_SLOTS[word] % len(theme.series_colors)]
|
|
265
|
+
return out
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _colour_registry(
|
|
269
|
+
panels: Sequence[Panel], theme: Theme, pinned: Mapping[str, str]
|
|
270
|
+
) -> tuple[list[dict[str, str]], str, list[dict[str, Any]]]:
|
|
271
|
+
"""One colour per named entity across the whole figure.
|
|
272
|
+
|
|
273
|
+
Entities are the names a panel emphasises (highlighted items, then trend series and
|
|
274
|
+
relate groups that are coloured by default) plus ``pinned`` names, each group in
|
|
275
|
+
order of first appearance. Each gets one colour from one pool: the accent order when any panel has a
|
|
276
|
+
highlight, else the series order, with the uniform default colour moved last when some
|
|
277
|
+
panel still draws in it. Returns per-panel ``{name: colour}`` maps (keys are the
|
|
278
|
+
panel's own names), the uniform colour, and issues.
|
|
279
|
+
"""
|
|
280
|
+
# Highlighted names first (they are what the takeaway is about and get the warm
|
|
281
|
+
# accent), then names coloured by default (trend series, relate groups); each in
|
|
282
|
+
# order of first appearance across the panels.
|
|
283
|
+
# A baseline (control, "before") is drawn in ink wherever it appears, unless pinned:
|
|
284
|
+
# it never takes a palette colour, so a control is never the red one.
|
|
285
|
+
baselines = {
|
|
286
|
+
_entity_key(p.color_baseline)
|
|
287
|
+
for p in panels
|
|
288
|
+
if p.color_baseline and _entity_key(p.color_baseline) not in pinned
|
|
289
|
+
}
|
|
290
|
+
entities: list[str] = []
|
|
291
|
+
for modes in (("highlight",), ("series",)):
|
|
292
|
+
for panel in panels:
|
|
293
|
+
if panel.color_mode not in modes:
|
|
294
|
+
continue
|
|
295
|
+
for name in panel.color_focus:
|
|
296
|
+
key = _entity_key(name)
|
|
297
|
+
if key and key not in entities and key not in baselines:
|
|
298
|
+
entities.append(key)
|
|
299
|
+
known = set(entities) | set(pinned)
|
|
300
|
+
|
|
301
|
+
def _uniform(panel: Panel) -> bool:
|
|
302
|
+
if not panel.uses_default:
|
|
303
|
+
return False
|
|
304
|
+
if panel.color_mode == "series":
|
|
305
|
+
return True # an unnamed single series
|
|
306
|
+
return not any(_entity_key(nm) in known for nm in panel.color_items)
|
|
307
|
+
|
|
308
|
+
any_highlight = any(p.color_mode == "highlight" for p in panels)
|
|
309
|
+
base = list(theme.accent_colors) if any_highlight else list(theme.series_colors)
|
|
310
|
+
base += [c for c in theme.series_colors if c not in base]
|
|
311
|
+
default = theme.default_color
|
|
312
|
+
pool = [c for c in base if c not in pinned.values()]
|
|
313
|
+
if any(_uniform(p) for p in panels) and default in pool:
|
|
314
|
+
pool = [c for c in pool if c != default] + [default]
|
|
315
|
+
|
|
316
|
+
registry: dict[str, str] = dict(pinned)
|
|
317
|
+
registry.update({key: theme.ink for key in baselines})
|
|
318
|
+
known |= baselines
|
|
319
|
+
overflow: list[str] = []
|
|
320
|
+
for key in entities:
|
|
321
|
+
if key in registry:
|
|
322
|
+
continue
|
|
323
|
+
if pool:
|
|
324
|
+
registry[key] = pool.pop(0)
|
|
325
|
+
else:
|
|
326
|
+
overflow.append(key)
|
|
327
|
+
|
|
328
|
+
taken = set(registry.values())
|
|
329
|
+
uniform = default
|
|
330
|
+
if default in taken: # a pinned or fifth entity took it: use a free colour if one is left
|
|
331
|
+
uniform = next((c for c in base if c not in taken), default)
|
|
332
|
+
|
|
333
|
+
per_panel: list[dict[str, str]] = []
|
|
334
|
+
for panel in panels:
|
|
335
|
+
colours: dict[str, str] = {}
|
|
336
|
+
if panel.color_mode != "none":
|
|
337
|
+
wanted = (
|
|
338
|
+
list(panel.color_focus)
|
|
339
|
+
if panel.color_mode in {"highlight", "series"}
|
|
340
|
+
else [nm for nm in panel.color_items if _entity_key(nm) in known]
|
|
341
|
+
)
|
|
342
|
+
if panel.color_mode == "series":
|
|
343
|
+
# coloured by default: entities pinned elsewhere keep their colour too
|
|
344
|
+
wanted = list(dict.fromkeys(wanted))
|
|
345
|
+
if panel.color_baseline and panel.color_baseline not in wanted:
|
|
346
|
+
wanted.append(panel.color_baseline)
|
|
347
|
+
for name in wanted:
|
|
348
|
+
key = _entity_key(name)
|
|
349
|
+
if key in registry:
|
|
350
|
+
colours[name] = registry[key]
|
|
351
|
+
for name in wanted: # overflow: a colour not used elsewhere in this panel
|
|
352
|
+
if name not in colours and _entity_key(name):
|
|
353
|
+
free = [c for c in base if c not in colours.values()]
|
|
354
|
+
colours[name] = free[0] if free else base[0]
|
|
355
|
+
per_panel.append(colours)
|
|
356
|
+
|
|
357
|
+
issues: list[dict[str, Any]] = []
|
|
358
|
+
if overflow:
|
|
359
|
+
named = [*list(registry)[: len(base)], *overflow]
|
|
360
|
+
issues.append(
|
|
361
|
+
_issue(
|
|
362
|
+
"colour_reused_across_panels",
|
|
363
|
+
"warning",
|
|
364
|
+
f"{len(named)} names need colour across the panels "
|
|
365
|
+
f"({', '.join(map(repr, named[:8]))}) but the palette has {len(base)} "
|
|
366
|
+
f"colours; {', '.join(map(repr, overflow))} reuse a colour that means "
|
|
367
|
+
"something else in another panel.",
|
|
368
|
+
"Highlight fewer names (the ones the takeaway is about), or split the "
|
|
369
|
+
"argument into two figures.",
|
|
370
|
+
)
|
|
371
|
+
)
|
|
372
|
+
return per_panel, uniform, issues
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
#: Plot height cap (mm at scale 1) for a full-width trend/relate in a multi-row figure.
|
|
376
|
+
_FULL_ROW_STRETCH_MM = 44.0
|
|
377
|
+
#: How much a bar-like panel may grow to fill a row set by a taller neighbour.
|
|
378
|
+
_ROW_GROWTH = 1.3
|
|
379
|
+
#: Narrowest plot area (mm at scale 1) a panel may be left with after its labels fit.
|
|
380
|
+
_MIN_PLOT_MM = 20.0
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _check_plot_width(fig: Figure, panel: Panel, ax: Axes, rect: Bbox, scale: float) -> None:
|
|
384
|
+
"""Refuse a panel whose labels leave a sliver of plot (end labels in a narrow cell)."""
|
|
385
|
+
if panel.kind in {"matrix", "custom", "table"}:
|
|
386
|
+
return
|
|
387
|
+
px_per_mm = float(fig.dpi) / 25.4
|
|
388
|
+
plot_mm = ax.get_window_extent(fig.canvas.get_renderer()).width / px_per_mm
|
|
389
|
+
# Lines and scatters need room to show a shape; bars, dots and slopes less so.
|
|
390
|
+
least = _MIN_PLOT_MM if panel.stretch or panel.kind == "trend" else 0.4 * _MIN_PLOT_MM
|
|
391
|
+
floor = min(least * scale, 0.42 * rect.width / px_per_mm)
|
|
392
|
+
if plot_mm + 0.05 < floor:
|
|
393
|
+
hint = 'Use fewer columns (e.g. layout=[["a", "a"], ["b", "c"]] gives one panel the full width), shorten the item or series names'
|
|
394
|
+
if panel.kind == "trend":
|
|
395
|
+
hint += ", or pass end_values=False to drop the numbers at the line ends"
|
|
396
|
+
raise ExplainError(
|
|
397
|
+
f"The labels leave only {plot_mm:.0f} mm of plot area (at least {floor:.0f} mm is "
|
|
398
|
+
"needed to read the data).",
|
|
399
|
+
fix_hint=hint + ".",
|
|
400
|
+
rule="panel_too_small",
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _fit_ticks(fig: Figure, ax: Axes, which: str = "xy") -> None:
|
|
405
|
+
"""Thin tick labels that would touch ("8001,200 1,600") on every axis of ``ax``.
|
|
406
|
+
|
|
407
|
+
Runs after layout, so the decision uses the measured label widths and the final
|
|
408
|
+
axes size. A "nice number" locator gets fewer bins; a date locator fewer ticks;
|
|
409
|
+
fixed ticks (log decades, measured x positions, categories) keep a greedy subset
|
|
410
|
+
counted back from the last label, so the end of the range stays labelled.
|
|
411
|
+
"""
|
|
412
|
+
renderer = fig.canvas.get_renderer()
|
|
413
|
+
for axis, horizontal in ((ax.xaxis, True), (ax.yaxis, False)):
|
|
414
|
+
if not axis.get_visible() or axis.axis_name not in which:
|
|
415
|
+
continue
|
|
416
|
+
size = max((t.label1.get_fontsize() for t in axis.get_major_ticks()[:1]), default=8.0)
|
|
417
|
+
gap = 0.55 * size * fig.dpi / 72.0
|
|
418
|
+
for _ in range(8):
|
|
419
|
+
boxes = _tick_label_boxes(axis, renderer)
|
|
420
|
+
if len(boxes) < 2 or not _labels_collide(boxes, horizontal, gap):
|
|
421
|
+
break
|
|
422
|
+
locator = axis.get_major_locator()
|
|
423
|
+
if isinstance(locator, MaxNLocator) and len(boxes) > 2:
|
|
424
|
+
nbins = locator._nbins if isinstance(locator._nbins, int) else len(boxes)
|
|
425
|
+
# Fewer bins on round steps keep both ends labelled ("0 1,000 2,000").
|
|
426
|
+
locator.set_params(nbins=max(1, min(nbins, len(boxes)) - 1), steps=[1, 2, 5, 10])
|
|
427
|
+
continue
|
|
428
|
+
if isinstance(locator, mdates.AutoDateLocator) and len(boxes) > 2:
|
|
429
|
+
fewer = mdates.AutoDateLocator(minticks=2, maxticks=max(2, len(boxes) - 1))
|
|
430
|
+
fewer.set_axis(axis)
|
|
431
|
+
lo_v, hi_v = sorted(axis.get_view_interval())
|
|
432
|
+
# Day-of-month labels ("15 Sep") are wide: when the locator cannot go below
|
|
433
|
+
# the current count, fall through to the greedy subset instead of looping.
|
|
434
|
+
if len(fewer.tick_values(mdates.num2date(lo_v), mdates.num2date(hi_v))) < len(
|
|
435
|
+
boxes
|
|
436
|
+
):
|
|
437
|
+
axis.set_major_locator(fewer)
|
|
438
|
+
axis.set_major_formatter(_date_formatter(fewer))
|
|
439
|
+
continue
|
|
440
|
+
# Greedy subset from the end: keep a label when it clears the last one kept.
|
|
441
|
+
ordered = sorted(boxes, key=lambda lb: lb[1].x0 if horizontal else lb[1].y0)
|
|
442
|
+
kept: list[tuple[float, Bbox]] = [ordered[-1]]
|
|
443
|
+
for loc, box in reversed(ordered[:-1]):
|
|
444
|
+
prev = kept[-1][1]
|
|
445
|
+
room = (prev.x0 - box.x1) if horizontal else (prev.y0 - box.y1)
|
|
446
|
+
if room >= gap:
|
|
447
|
+
kept.append((loc, box))
|
|
448
|
+
keep = [loc for loc, _ in kept]
|
|
449
|
+
old = axis.get_major_formatter()
|
|
450
|
+
span = abs(float(np.diff(axis.get_view_interval())[0])) or 1.0
|
|
451
|
+
# A formatter that labels ticks as a set (concise dates) keeps the labels it
|
|
452
|
+
# gave in context; called one value at a time it would print a bare year.
|
|
453
|
+
shown: dict[float, str] = {}
|
|
454
|
+
if isinstance(old, mdates.ConciseDateFormatter):
|
|
455
|
+
locs = [float(v) for v in axis.get_majorticklocs()]
|
|
456
|
+
shown = dict(zip(locs, old.format_ticks(locs), strict=True))
|
|
457
|
+
|
|
458
|
+
def _subset(
|
|
459
|
+
v: float,
|
|
460
|
+
pos: Any,
|
|
461
|
+
old: Any = old,
|
|
462
|
+
keep: list[float] = keep,
|
|
463
|
+
span: float = span,
|
|
464
|
+
shown: dict[float, str] = shown,
|
|
465
|
+
) -> str:
|
|
466
|
+
for k in keep:
|
|
467
|
+
if abs(v - k) <= 1e-9 * max(abs(k), span):
|
|
468
|
+
return shown.get(k) or old(v, pos)
|
|
469
|
+
return ""
|
|
470
|
+
|
|
471
|
+
axis.set_major_formatter(FuncFormatter(_subset))
|
|
472
|
+
break
|
|
473
|
+
cover = getattr(ax, "_mintfig_cover", None)
|
|
474
|
+
bracket = getattr(ax, "_mintfig_bracket", None)
|
|
475
|
+
if (
|
|
476
|
+
bracket is not None
|
|
477
|
+
and horizontal
|
|
478
|
+
and axis.get_scale() == "linear"
|
|
479
|
+
and _bracket_with_ticks(fig, axis, *bracket)
|
|
480
|
+
):
|
|
481
|
+
continue
|
|
482
|
+
if cover is not None and horizontal and axis.get_scale() == "linear":
|
|
483
|
+
_cover_with_ticks(axis, *cover)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _bracket_with_ticks(
|
|
487
|
+
fig: Figure, axis: Any, lo: float, hi: float, max_ticks: int, minus: str
|
|
488
|
+
) -> bool:
|
|
489
|
+
"""Round ticks that bracket [lo, hi]: at least three, the lowest at or below every
|
|
490
|
+
observation and the highest at or above it, on the finest nice step whose labels
|
|
491
|
+
fit (so the axis is widened as little as possible). Returns False when no step
|
|
492
|
+
fits, leaving the caller's fallback in charge."""
|
|
493
|
+
span = (hi - lo) or abs(hi) or 1.0
|
|
494
|
+
renderer = fig.canvas.get_renderer()
|
|
495
|
+
size = max((t.label1.get_fontsize() for t in axis.get_major_ticks()[:1]), default=8.0)
|
|
496
|
+
gap = 0.55 * size * fig.dpi / 72.0
|
|
497
|
+
base = 10.0 ** math.floor(math.log10(span / max_ticks))
|
|
498
|
+
steps = [m * base * 10**k for k in (-1, 0, 1, 2) for m in (1, 2, 2.5, 5)]
|
|
499
|
+
set_lim = axis.axes.set_xlim if axis.axis_name == "x" else axis.axes.set_ylim
|
|
500
|
+
old_lim = axis.get_view_interval()
|
|
501
|
+
old_locator, old_formatter = axis.get_major_locator(), axis.get_major_formatter()
|
|
502
|
+
for step in sorted(steps):
|
|
503
|
+
k0 = math.floor(lo / step + 1e-9)
|
|
504
|
+
k1 = math.ceil(hi / step - 1e-9)
|
|
505
|
+
if k1 - k0 + 1 > max_ticks:
|
|
506
|
+
continue
|
|
507
|
+
while k1 - k0 + 1 < 3: # one more round tick on the side with the less widening
|
|
508
|
+
if (lo - k0 * step) <= (k1 * step - hi) or (k0 - 1) * step < 0 <= lo:
|
|
509
|
+
k1 += 1
|
|
510
|
+
else:
|
|
511
|
+
k0 -= 1
|
|
512
|
+
count = k1 - k0 + 1
|
|
513
|
+
ticks = [float(f"{k * step:.12g}") for k in range(k0, k1 + 1)]
|
|
514
|
+
axis.set_major_locator(FixedLocator(ticks))
|
|
515
|
+
axis.set_major_formatter(
|
|
516
|
+
FuncFormatter(lambda v, _p, m=minus, a=axis: _tick_label(v, m, a))
|
|
517
|
+
)
|
|
518
|
+
# Dots on an end tick stay whole: the view reaches 3% of the span past the data.
|
|
519
|
+
margin = 0.03 * span
|
|
520
|
+
set_lim(min(ticks[0], lo - margin), max(ticks[-1], hi + margin))
|
|
521
|
+
boxes = _tick_label_boxes(axis, renderer)
|
|
522
|
+
if len(boxes) == count and not _labels_collide(boxes, True, gap):
|
|
523
|
+
return True
|
|
524
|
+
axis.set_major_locator(old_locator)
|
|
525
|
+
axis.set_major_formatter(old_formatter)
|
|
526
|
+
set_lim(*old_lim)
|
|
527
|
+
return False
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
#: Which tick labels of each form are numbers or dates that may be thinned (never names).
|
|
531
|
+
_TICK_AXES = {
|
|
532
|
+
"trend": "xy",
|
|
533
|
+
"relate": "xy",
|
|
534
|
+
"distribution": "x",
|
|
535
|
+
"compare": "x",
|
|
536
|
+
"timeline": "x",
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
#: Mathtext draws a superscript or subscript at this fraction of its parent's size.
|
|
541
|
+
_SCRIPT_SHRINK = 0.7
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _script_depth(text: str) -> int:
|
|
545
|
+
"""Deepest superscript/subscript nesting inside the ``$...$`` parts of ``text``.
|
|
546
|
+
|
|
547
|
+
``"µm$^{2}$"`` is 1, ``"$e^{x^{2}}$"`` is 2, plain text (or escaped ``\\$``) is 0.
|
|
548
|
+
"""
|
|
549
|
+
parts = re.split(r"(?<!\\)\$", text)
|
|
550
|
+
deepest = 0
|
|
551
|
+
for math_part in parts[1::2]:
|
|
552
|
+
stack: list[int] = [] # depth of each open brace group
|
|
553
|
+
depth = 0
|
|
554
|
+
pending = False # the next token or group is a script
|
|
555
|
+
for ch in math_part:
|
|
556
|
+
if ch in "^_":
|
|
557
|
+
pending = True
|
|
558
|
+
continue
|
|
559
|
+
if ch == "{":
|
|
560
|
+
stack.append(depth)
|
|
561
|
+
if pending:
|
|
562
|
+
depth += 1
|
|
563
|
+
deepest = max(deepest, depth)
|
|
564
|
+
pending = False
|
|
565
|
+
continue
|
|
566
|
+
if ch == "}":
|
|
567
|
+
depth = stack.pop() if stack else 0
|
|
568
|
+
continue
|
|
569
|
+
if pending and not ch.isspace():
|
|
570
|
+
deepest = max(deepest, depth + 1)
|
|
571
|
+
pending = False
|
|
572
|
+
return deepest
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
class Summary(dict): # type: ignore[type-arg]
|
|
576
|
+
"""What :meth:`Explanation.save` returns: a plain dict that prints as indented JSON.
|
|
577
|
+
|
|
578
|
+
Keys: ``schema_version``, ``ok``, ``style``, ``path``, ``size_px``, ``size_mm``,
|
|
579
|
+
``display``, ``takeaway``, ``panels`` (key, kind, title, facts), ``narrative``
|
|
580
|
+
(L1–L4 semantic narrative), ``alt_text``, ``colors``, ``issues`` and ``rendered``. ``display`` holds ``width_px`` (the chat
|
|
581
|
+
width the sizes refer to), ``min_text_px`` (smallest font size at that width,
|
|
582
|
+
counting each text at its own size) and ``min_script_px``: the smallest
|
|
583
|
+
mathtext superscript or subscript at that width (drawn at about 70% of its
|
|
584
|
+
label's size, 49% when nested), or ``None`` when the figure has no scripts.
|
|
585
|
+
The ``min_text_px`` floor does not apply to scripts.
|
|
586
|
+
"""
|
|
587
|
+
|
|
588
|
+
def __str__(self) -> str:
|
|
589
|
+
return json.dumps(self, indent=2, ensure_ascii=False)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
#: Target display width (CSS px) when rendering for a narrow IDE sidebar (Cursor / VS Code).
|
|
593
|
+
NARROW_DISPLAY_WIDTH_PX = 450
|
|
594
|
+
#: Target display width (CSS px) when rendering a presentation / blog-hero slide.
|
|
595
|
+
SLIDE_DISPLAY_WIDTH_PX = 1280
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
class Explanation:
|
|
599
|
+
"""A rendered message-first figure plus what an agent needs to hand it over."""
|
|
600
|
+
|
|
601
|
+
def __init__(
|
|
602
|
+
self,
|
|
603
|
+
*,
|
|
604
|
+
fig: Figure,
|
|
605
|
+
spec: JournalSpec,
|
|
606
|
+
theme: Theme = MINTFIG_THEME,
|
|
607
|
+
palette: str | None = None,
|
|
608
|
+
accent: str | None = None,
|
|
609
|
+
takeaway: str,
|
|
610
|
+
subtitle: str | None,
|
|
611
|
+
source: str | None,
|
|
612
|
+
note: str | None,
|
|
613
|
+
panels: dict[str, Panel],
|
|
614
|
+
axes: dict[str, Axes],
|
|
615
|
+
layout: list[list[str]],
|
|
616
|
+
width: str | float,
|
|
617
|
+
issues: list[dict[str, Any]],
|
|
618
|
+
colors: dict[str, str] | None = None,
|
|
619
|
+
strict: bool = True,
|
|
620
|
+
adjustments: Sequence[str] = (),
|
|
621
|
+
advisories: Sequence[dict[str, Any]] = (),
|
|
622
|
+
) -> None:
|
|
623
|
+
self.fig = fig
|
|
624
|
+
self.colors = colors
|
|
625
|
+
#: Colour slot of every named entity in the figure ({"no retrieval": "red"}); pass
|
|
626
|
+
#: it as ``colors=`` to the next figure to keep the same colours.
|
|
627
|
+
self.entity_colors: dict[str, str] = {}
|
|
628
|
+
self.spec = spec
|
|
629
|
+
self.theme = theme
|
|
630
|
+
self.palette = palette
|
|
631
|
+
self.accent = accent
|
|
632
|
+
self.takeaway = takeaway
|
|
633
|
+
self.subtitle = subtitle
|
|
634
|
+
self.source = source
|
|
635
|
+
self.note = note
|
|
636
|
+
self.panels = panels
|
|
637
|
+
self.axes = axes
|
|
638
|
+
self.layout = layout
|
|
639
|
+
self.width = width
|
|
640
|
+
self.issues = issues
|
|
641
|
+
self.strict = strict
|
|
642
|
+
self.adjustments = list(adjustments)
|
|
643
|
+
self.advisories = list(advisories)
|
|
644
|
+
self.saved_path: Path | None = None
|
|
645
|
+
self.saved_px: tuple[int, int] | None = None
|
|
646
|
+
|
|
647
|
+
@property
|
|
648
|
+
def display_width_px(self) -> int:
|
|
649
|
+
w = self.width.strip().lower() if isinstance(self.width, str) else ""
|
|
650
|
+
if w == "slide":
|
|
651
|
+
return SLIDE_DISPLAY_WIDTH_PX
|
|
652
|
+
if w == "narrow":
|
|
653
|
+
return NARROW_DISPLAY_WIDTH_PX
|
|
654
|
+
return DISPLAY_WIDTH_PX
|
|
655
|
+
|
|
656
|
+
def __getitem__(self, key: str) -> Axes:
|
|
657
|
+
return self.axes[key]
|
|
658
|
+
|
|
659
|
+
@property
|
|
660
|
+
def width_mm(self) -> float:
|
|
661
|
+
return float(self.fig.get_figwidth()) * 25.4
|
|
662
|
+
|
|
663
|
+
@property
|
|
664
|
+
def height_mm(self) -> float:
|
|
665
|
+
return float(self.fig.get_figheight()) * 25.4
|
|
666
|
+
|
|
667
|
+
@property
|
|
668
|
+
def ok(self) -> bool:
|
|
669
|
+
return not any(issue["severity"] == "error" for issue in self.issues)
|
|
670
|
+
|
|
671
|
+
@property
|
|
672
|
+
def ship(self) -> bool:
|
|
673
|
+
"""True when the figure has no errors and no visual/legibility defects.
|
|
674
|
+
|
|
675
|
+
Advisory polish warnings (e.g. ``many_items``, ``too_tall``,
|
|
676
|
+
``fit_on_weak_relationship``) do not block ``ship``.
|
|
677
|
+
"""
|
|
678
|
+
return self.ok and not any(issue["rule"] in _VISUAL_DEFECT_RULES for issue in self.issues)
|
|
679
|
+
|
|
680
|
+
@property
|
|
681
|
+
def min_text_px(self) -> float:
|
|
682
|
+
"""Smallest text height in pixels when the figure is shown at ``display_width_px``."""
|
|
683
|
+
from matplotlib.text import Text
|
|
684
|
+
|
|
685
|
+
sizes = [
|
|
686
|
+
float(t.get_fontsize())
|
|
687
|
+
for t in self.fig.findobj(Text)
|
|
688
|
+
if t.get_visible() and t.get_text().strip()
|
|
689
|
+
]
|
|
690
|
+
px_per_pt = self.display_width_px / (float(self.fig.get_figwidth()) * 72.0)
|
|
691
|
+
return round(min(sizes, default=0.0) * px_per_pt, 1)
|
|
692
|
+
|
|
693
|
+
@property
|
|
694
|
+
def min_script_px(self) -> float | None:
|
|
695
|
+
"""Smallest mathtext superscript/subscript height in pixels at display width."""
|
|
696
|
+
from matplotlib.text import Text
|
|
697
|
+
|
|
698
|
+
sizes = [
|
|
699
|
+
float(t.get_fontsize()) * _SCRIPT_SHRINK**depth
|
|
700
|
+
for t in self.fig.findobj(Text)
|
|
701
|
+
if t.get_visible() and (depth := _script_depth(t.get_text()))
|
|
702
|
+
]
|
|
703
|
+
if not sizes:
|
|
704
|
+
return None
|
|
705
|
+
px_per_pt = self.display_width_px / (float(self.fig.get_figwidth()) * 72.0)
|
|
706
|
+
return round(min(sizes) * px_per_pt, 1)
|
|
707
|
+
|
|
708
|
+
@property
|
|
709
|
+
def alt_text(self) -> str:
|
|
710
|
+
parts = [self.takeaway.rstrip(".") + "."]
|
|
711
|
+
for key, panel in self.panels.items():
|
|
712
|
+
lead = f"Panel {key}: " if len(self.panels) > 1 else ""
|
|
713
|
+
body = panel.describe
|
|
714
|
+
if panel.title:
|
|
715
|
+
body = f"{panel.title.rstrip('.')}. {body}"
|
|
716
|
+
said = panel.alt_facts if panel.alt_facts is not None else panel.facts[:1]
|
|
717
|
+
if said:
|
|
718
|
+
body += "".join(f". {fact}" for fact in said)
|
|
719
|
+
parts.append(f"{lead}{body}.")
|
|
720
|
+
if self.source:
|
|
721
|
+
parts.append(f"Source: {self.source.rstrip('.')}.")
|
|
722
|
+
return " ".join(parts)
|
|
723
|
+
|
|
724
|
+
def to_spec(self) -> dict[str, Any]:
|
|
725
|
+
"""JSON-serialisable spec that ``mintfig explain`` renders back to the same figure."""
|
|
726
|
+
out: dict[str, Any] = {"takeaway": self.takeaway}
|
|
727
|
+
for key in ("subtitle", "source", "note"):
|
|
728
|
+
if getattr(self, key):
|
|
729
|
+
out[key] = getattr(self, key)
|
|
730
|
+
if self.theme.name != "mintfig":
|
|
731
|
+
out["style"] = self.theme.name
|
|
732
|
+
if self.palette:
|
|
733
|
+
out["palette"] = self.palette
|
|
734
|
+
if self.accent:
|
|
735
|
+
out["accent"] = self.accent
|
|
736
|
+
if self.spec.name != "screen":
|
|
737
|
+
out["target"] = self.spec.name
|
|
738
|
+
if self.width != "chat":
|
|
739
|
+
out["width"] = self.width
|
|
740
|
+
if self.colors:
|
|
741
|
+
out["colors"] = dict(self.colors)
|
|
742
|
+
out["layout"] = self.layout
|
|
743
|
+
out["panels"] = [panel.to_spec() for panel in self.panels.values()]
|
|
744
|
+
return out
|
|
745
|
+
|
|
746
|
+
def summary(self) -> Summary:
|
|
747
|
+
"""What to check before showing the figure: facts to verify the claim, and issues to fix."""
|
|
748
|
+
from ..epistemic import build_narrative
|
|
749
|
+
|
|
750
|
+
out: dict[str, Any] = {
|
|
751
|
+
"schema_version": "0.2",
|
|
752
|
+
"ok": self.ok,
|
|
753
|
+
"ship": self.ship,
|
|
754
|
+
"style": self.theme.name,
|
|
755
|
+
"palette": self.palette or "default",
|
|
756
|
+
"path": str(self.saved_path) if self.saved_path else None,
|
|
757
|
+
"size_px": list(self.saved_px) if self.saved_px else None,
|
|
758
|
+
"size_mm": [round(self.width_mm, 1), round(self.height_mm, 1)],
|
|
759
|
+
"display": {
|
|
760
|
+
"width_px": self.display_width_px,
|
|
761
|
+
"min_text_px": self.min_text_px,
|
|
762
|
+
"min_script_px": self.min_script_px,
|
|
763
|
+
},
|
|
764
|
+
"takeaway": self.takeaway,
|
|
765
|
+
"panels": [
|
|
766
|
+
{"key": key, "kind": p.kind, "title": p.title, "facts": p.facts}
|
|
767
|
+
for key, p in self.panels.items()
|
|
768
|
+
],
|
|
769
|
+
"narrative": build_narrative(
|
|
770
|
+
self.takeaway,
|
|
771
|
+
self.panels,
|
|
772
|
+
subtitle=self.subtitle,
|
|
773
|
+
source=self.source,
|
|
774
|
+
),
|
|
775
|
+
"alt_text": self.alt_text,
|
|
776
|
+
"colors": dict(self.entity_colors),
|
|
777
|
+
"issues": self.issues,
|
|
778
|
+
"rendered": self.saved_path is not None,
|
|
779
|
+
}
|
|
780
|
+
if not self.strict:
|
|
781
|
+
out["strict"] = False
|
|
782
|
+
out["adjustments"] = list(self.adjustments)
|
|
783
|
+
out["advisories"] = list(self.advisories)
|
|
784
|
+
return Summary(out)
|
|
785
|
+
|
|
786
|
+
def save(
|
|
787
|
+
self,
|
|
788
|
+
path: str | Path,
|
|
789
|
+
*,
|
|
790
|
+
scale: float = 2.0,
|
|
791
|
+
write_spec: bool = False,
|
|
792
|
+
embed: bool = True,
|
|
793
|
+
) -> Summary:
|
|
794
|
+
"""Write the figure (PNG, SVG or PDF by suffix) and return :meth:`summary`.
|
|
795
|
+
|
|
796
|
+
PNGs for the screen target are ``DISPLAY_WIDTH_PX * scale`` pixels wide
|
|
797
|
+
(1400 px by default: crisp on high-density displays at chat width).
|
|
798
|
+
``write_spec=True`` also writes ``<name>.json``, the reproducible spec.
|
|
799
|
+
A PNG carries its own spec, takeaway and alt text as text chunks
|
|
800
|
+
(``mintfig:spec``, ``mintfig:takeaway``, ``mintfig:alt_text``) so
|
|
801
|
+
:func:`load` can rebuild it later; ``embed=False`` leaves them out.
|
|
802
|
+
The figure is written even when ``ok`` is false (``rendered`` says so).
|
|
803
|
+
"""
|
|
804
|
+
from ..export import save_figure
|
|
805
|
+
|
|
806
|
+
out = Path(path)
|
|
807
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
808
|
+
if out.suffix.lower() in {".html", ".htm"}:
|
|
809
|
+
out.write_text(self.to_html(interactive=True), encoding="utf-8")
|
|
810
|
+
self.saved_path = out.resolve()
|
|
811
|
+
self.saved_px = None
|
|
812
|
+
if write_spec:
|
|
813
|
+
out.with_suffix(".json").write_text(
|
|
814
|
+
json.dumps(self.to_spec(), indent=2, ensure_ascii=False) + "\n",
|
|
815
|
+
encoding="utf-8",
|
|
816
|
+
)
|
|
817
|
+
return self.summary()
|
|
818
|
+
if self.spec.name == "screen":
|
|
819
|
+
dpi = round(self.display_width_px * float(scale) / float(self.fig.get_figwidth()))
|
|
820
|
+
else:
|
|
821
|
+
dpi = int(self.spec.dpi_combo)
|
|
822
|
+
with self.theme.rc_context(self.spec), _GlyphCapture() as glyph_log:
|
|
823
|
+
save_figure(self.fig, out, journal=self.spec, dpi=dpi)
|
|
824
|
+
late = glyph_log.missing()
|
|
825
|
+
if late and not any(i["rule"] == "glyph_missing" for i in self.issues):
|
|
826
|
+
self.issues.append(_glyph_issue(late))
|
|
827
|
+
self.saved_path = out.resolve()
|
|
828
|
+
if out.suffix.lower() == ".png":
|
|
829
|
+
self.saved_px = (
|
|
830
|
+
round(self.fig.get_figwidth() * dpi),
|
|
831
|
+
round(self.fig.get_figheight() * dpi),
|
|
832
|
+
)
|
|
833
|
+
if embed:
|
|
834
|
+
_embed_png_text(
|
|
835
|
+
out,
|
|
836
|
+
{
|
|
837
|
+
"mintfig:spec": json.dumps(self.to_spec(), ensure_ascii=False),
|
|
838
|
+
"mintfig:takeaway": self.takeaway,
|
|
839
|
+
"mintfig:alt_text": self.alt_text,
|
|
840
|
+
},
|
|
841
|
+
)
|
|
842
|
+
else:
|
|
843
|
+
self.saved_px = None
|
|
844
|
+
if write_spec:
|
|
845
|
+
out.with_suffix(".json").write_text(
|
|
846
|
+
json.dumps(self.to_spec(), indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
|
847
|
+
)
|
|
848
|
+
return self.summary()
|
|
849
|
+
|
|
850
|
+
def preflight(self) -> Any:
|
|
851
|
+
"""Run mintfig's full preflight on the figure under the target's style."""
|
|
852
|
+
from ..preflight import preflight_figure
|
|
853
|
+
|
|
854
|
+
with self.theme.rc_context(self.spec), _GlyphCapture():
|
|
855
|
+
return preflight_figure(self.fig, self.spec)
|
|
856
|
+
|
|
857
|
+
def bundle(self, out_dir: str | Path, **kwargs: Any) -> Any:
|
|
858
|
+
"""Export the full manuscript bundle (PDF, SVG, proof sheet, sidecar) for this figure."""
|
|
859
|
+
from ..bundle import bundle_figure
|
|
860
|
+
|
|
861
|
+
kwargs.setdefault("takeaway", self.takeaway)
|
|
862
|
+
kwargs.setdefault("takeaway_subtitle", self.subtitle)
|
|
863
|
+
kwargs.setdefault(
|
|
864
|
+
"panel_notes", {k: p.title for k, p in self.panels.items() if p.title} or None
|
|
865
|
+
)
|
|
866
|
+
kwargs.setdefault("caption", self.alt_text)
|
|
867
|
+
with self.theme.rc_context(self.spec):
|
|
868
|
+
return bundle_figure(self.fig, out_dir, journal=self.spec, **kwargs)
|
|
869
|
+
|
|
870
|
+
def to_html(self, interactive: bool = True) -> str:
|
|
871
|
+
"""Render a self-contained interactive HTML document for this figure."""
|
|
872
|
+
from ..interactive import render_html
|
|
873
|
+
|
|
874
|
+
return render_html(self, interactive=interactive)
|
|
875
|
+
|
|
876
|
+
def to_terminal(
|
|
877
|
+
self,
|
|
878
|
+
width: int = 78,
|
|
879
|
+
color: bool = True,
|
|
880
|
+
ascii_only: bool = False,
|
|
881
|
+
) -> str:
|
|
882
|
+
"""Render a terminal-friendly Unicode or ASCII view of this figure."""
|
|
883
|
+
from ..terminal import render_terminal
|
|
884
|
+
|
|
885
|
+
return render_terminal(self, width=width, color=color, ascii_only=ascii_only)
|
|
886
|
+
|
|
887
|
+
def _repr_html_(self) -> str:
|
|
888
|
+
"""Rich interactive HTML fragment for Jupyter and notebook outputs."""
|
|
889
|
+
from ..interactive import render_html_fragment
|
|
890
|
+
|
|
891
|
+
return render_html_fragment(self)
|
|
892
|
+
|
|
893
|
+
def _repr_png_(self) -> bytes:
|
|
894
|
+
import io
|
|
895
|
+
|
|
896
|
+
buffer = io.BytesIO()
|
|
897
|
+
with self.theme.rc_context(self.spec), _GlyphCapture():
|
|
898
|
+
self.fig.savefig(buffer, format="png", dpi=160)
|
|
899
|
+
return buffer.getvalue()
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
#: Preflight checks phrase their hints for the publication path (Plate, rcParams).
|
|
903
|
+
#: On an explain figure the agent can only change explain arguments, so say those.
|
|
904
|
+
_EXPLAIN_PREFLIGHT_HINTS: dict[str, str] = {
|
|
905
|
+
"font_sizes": "Text sizes are fixed by mint.explain; this comes from a custom() panel: set "
|
|
906
|
+
"fontsize >= 7 in its draw function, or use a built-in form.",
|
|
907
|
+
"font_family": "Fonts come from style=; use the default style='mintfig', or set the "
|
|
908
|
+
"fontfamily inside a custom() panel to a sans-serif font.",
|
|
909
|
+
"text_overlaps": "Two labels in this panel touch. Shorten the item names, end labels or "
|
|
910
|
+
"event text (end_values=False drops the numbers at line ends); show fewer items or "
|
|
911
|
+
'series; give the panel a full-width row with layout=[["a"], ["b", "c"]]; or drop a panel '
|
|
912
|
+
"and move it to a second figure.",
|
|
913
|
+
"canvas_clipping": "Text runs off the image edge. Shorten the longest name or label (or "
|
|
914
|
+
'end_values=False on a trend); give the panel a full-width row with layout=[["a"], ["b"]]; '
|
|
915
|
+
"or drop a panel so the rest get more width.",
|
|
916
|
+
"hairline_strokes": "This comes from a custom() panel: draw lines at linewidth >= 0.5.",
|
|
917
|
+
"colormaps": "Use matrix() for a heat table, or a perceptual colormap such as 'viridis' "
|
|
918
|
+
"inside custom().",
|
|
919
|
+
"layout_collapse": "Give the panel more room: a full-width row via layout=, fewer panels, "
|
|
920
|
+
"or shorter names.",
|
|
921
|
+
"color_separation": "Name fewer series in highlight= (others turn grey), or pass facet=True.",
|
|
922
|
+
"clarity_metadata": "Name what is measured with label= and unit= (and x_label= on trend), "
|
|
923
|
+
'e.g. label="p99 latency", unit="ms".',
|
|
924
|
+
"bar_baseline_nonzero": "Bars must start at zero: use compare() (zero=True), or zero=False "
|
|
925
|
+
"for a dot plot.",
|
|
926
|
+
"chartjunk_hints": "Built-in forms label the data directly; remove legends, frames and 3-D "
|
|
927
|
+
"effects from custom() panels.",
|
|
928
|
+
"text_on_data": "Shorten labels, name fewer items in highlight=, or give the panel a "
|
|
929
|
+
'full-width row with layout=[["a"], ["b"]].',
|
|
930
|
+
"vector_fonts": "Save as .png for chat; for print use target= with a journal name.",
|
|
931
|
+
"file_size": "Save as .png for chat; reduce points in custom() panels.",
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
def _png_chunks(data: bytes) -> list[tuple[bytes, bytes]]:
|
|
939
|
+
if not data.startswith(_PNG_SIGNATURE):
|
|
940
|
+
raise ExplainError(
|
|
941
|
+
"The file is not a PNG.",
|
|
942
|
+
fix_hint="Pass a PNG written by Explanation.save(), or a .json spec.",
|
|
943
|
+
)
|
|
944
|
+
chunks: list[tuple[bytes, bytes]] = []
|
|
945
|
+
pos = len(_PNG_SIGNATURE)
|
|
946
|
+
while pos + 8 <= len(data):
|
|
947
|
+
length = int.from_bytes(data[pos : pos + 4], "big")
|
|
948
|
+
kind = data[pos + 4 : pos + 8]
|
|
949
|
+
chunks.append((kind, data[pos + 8 : pos + 8 + length]))
|
|
950
|
+
pos += 12 + length
|
|
951
|
+
if kind == b"IEND":
|
|
952
|
+
break
|
|
953
|
+
return chunks
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def _embed_png_text(path: Path, entries: Mapping[str, str]) -> None:
|
|
957
|
+
"""Insert uncompressed iTXt chunks before IEND; image data (IDAT) is left byte-identical."""
|
|
958
|
+
data = path.read_bytes()
|
|
959
|
+
end = data.rfind(b"IEND") - 4
|
|
960
|
+
if end < len(_PNG_SIGNATURE):
|
|
961
|
+
return
|
|
962
|
+
extra = b""
|
|
963
|
+
for key, text in entries.items():
|
|
964
|
+
body = key.encode("latin-1") + b"\x00\x00\x00" + b"\x00" + b"\x00" + text.encode("utf-8")
|
|
965
|
+
chunk_type = b"iTXt"
|
|
966
|
+
crc = zlib.crc32(chunk_type + body) & 0xFFFFFFFF
|
|
967
|
+
extra += len(body).to_bytes(4, "big") + chunk_type + body + crc.to_bytes(4, "big")
|
|
968
|
+
path.write_bytes(data[:end] + extra + data[end:])
|
|
969
|
+
|
|
970
|
+
|
|
971
|
+
def read_png_text(path: str | Path) -> dict[str, str]:
|
|
972
|
+
"""The ``mintfig:*`` text chunks of a PNG written by :meth:`Explanation.save`."""
|
|
973
|
+
out: dict[str, str] = {}
|
|
974
|
+
for kind, body in _png_chunks(Path(path).read_bytes()):
|
|
975
|
+
if kind == b"iTXt":
|
|
976
|
+
key, _, rest = body.partition(b"\x00")
|
|
977
|
+
# compression flag, method, then language tag and translated keyword (NUL-ended)
|
|
978
|
+
flag = rest[0:1]
|
|
979
|
+
rest = rest[2:]
|
|
980
|
+
_lang, _, rest = rest.partition(b"\x00")
|
|
981
|
+
_tkey, _, text = rest.partition(b"\x00")
|
|
982
|
+
if flag == b"\x01":
|
|
983
|
+
text = zlib.decompress(text)
|
|
984
|
+
out[key.decode("latin-1")] = text.decode("utf-8")
|
|
985
|
+
elif kind == b"tEXt":
|
|
986
|
+
key, _, text = body.partition(b"\x00")
|
|
987
|
+
out[key.decode("latin-1")] = text.decode("latin-1")
|
|
988
|
+
return {k: v for k, v in out.items() if k.startswith("mintfig:")}
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def load(path: str | Path) -> Explanation:
|
|
992
|
+
"""Rebuild an :class:`Explanation` from a PNG saved by mintfig or from a ``.json`` spec."""
|
|
993
|
+
source = Path(path)
|
|
994
|
+
if not source.exists():
|
|
995
|
+
raise ExplainError(
|
|
996
|
+
f"{source} does not exist.",
|
|
997
|
+
fix_hint="Pass the path of a PNG written by Explanation.save() or a .json spec.",
|
|
998
|
+
)
|
|
999
|
+
if source.suffix.lower() == ".json":
|
|
1000
|
+
try:
|
|
1001
|
+
spec = json.loads(source.read_text("utf-8"))
|
|
1002
|
+
except json.JSONDecodeError as exc:
|
|
1003
|
+
raise ExplainError(
|
|
1004
|
+
f"{source} is not valid JSON ({exc}).",
|
|
1005
|
+
fix_hint="Fix the JSON, or pass the PNG the figure was saved as.",
|
|
1006
|
+
) from exc
|
|
1007
|
+
return explain_from_spec(spec)
|
|
1008
|
+
text = read_png_text(source)
|
|
1009
|
+
if "mintfig:spec" not in text:
|
|
1010
|
+
raise ExplainError(
|
|
1011
|
+
f"{source.name} carries no mintfig spec.",
|
|
1012
|
+
fix_hint="Only PNGs written by Explanation.save() (embed=True, the default) carry "
|
|
1013
|
+
"their spec; otherwise load the .json written with save(..., write_spec=True).",
|
|
1014
|
+
)
|
|
1015
|
+
return explain_from_spec(json.loads(text["mintfig:spec"]))
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
_LATEX_DOLLAR = re.compile(r"\$[^$\n]*(?:\\[A-Za-z]+|[\^_])[^$\n]*\$")
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
def _latex_issues(
|
|
1022
|
+
texts: Sequence[str | None], panel_map: Mapping[str, Panel]
|
|
1023
|
+
) -> list[dict[str, Any]]:
|
|
1024
|
+
"""Warn when caller text contains Matplotlib-style $...$ LaTeX markup."""
|
|
1025
|
+
hits: list[str] = []
|
|
1026
|
+
for text in texts:
|
|
1027
|
+
if isinstance(text, str):
|
|
1028
|
+
hits.extend(_LATEX_DOLLAR.findall(text))
|
|
1029
|
+
for panel in panel_map.values():
|
|
1030
|
+
for val in (
|
|
1031
|
+
panel.title,
|
|
1032
|
+
panel.label,
|
|
1033
|
+
panel.unit,
|
|
1034
|
+
panel.spec.get("x_label"),
|
|
1035
|
+
panel.spec.get("y_label"),
|
|
1036
|
+
):
|
|
1037
|
+
if isinstance(val, str):
|
|
1038
|
+
hits.extend(_LATEX_DOLLAR.findall(val))
|
|
1039
|
+
if not hits:
|
|
1040
|
+
return []
|
|
1041
|
+
shown = ", ".join(repr(h) for h in list(dict.fromkeys(hits))[:3])
|
|
1042
|
+
return [
|
|
1043
|
+
_issue(
|
|
1044
|
+
"latex_markup",
|
|
1045
|
+
"warning",
|
|
1046
|
+
f"Literal LaTeX math ({shown}) is drawn as plain characters in mint.explain.",
|
|
1047
|
+
"Write Unicode directly (e.g. R², µm, ×10⁻³, °C, χ²); $...$ is not parsed as math.",
|
|
1048
|
+
)
|
|
1049
|
+
]
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
def _takeaway_issues(takeaway: str) -> list[dict[str, Any]]:
|
|
1053
|
+
words = takeaway.split()
|
|
1054
|
+
if len(words) < 4 or (_TOPIC_TITLE.search(takeaway) and not _HAS_DIGIT.search(takeaway)):
|
|
1055
|
+
return [
|
|
1056
|
+
_issue(
|
|
1057
|
+
"takeaway_is_a_topic",
|
|
1058
|
+
"warning",
|
|
1059
|
+
f"The takeaway {takeaway!r} reads like a topic, not a conclusion.",
|
|
1060
|
+
'State what the reader should conclude, with the number: "Checkout p99 tripled '
|
|
1061
|
+
'after the v2.3 deploy", not "Latency by service".',
|
|
1062
|
+
)
|
|
1063
|
+
]
|
|
1064
|
+
return []
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def _too_tall_issue(
|
|
1068
|
+
row_plans: Sequence[Mapping[str, Any]],
|
|
1069
|
+
panel_map: Mapping[str, Panel],
|
|
1070
|
+
height_mm: float,
|
|
1071
|
+
min_mm: float,
|
|
1072
|
+
width_mm: float,
|
|
1073
|
+
spec: JournalSpec,
|
|
1074
|
+
) -> dict[str, Any]:
|
|
1075
|
+
"""The ``too_tall`` warning: the tallest panel, and one concrete way to fit."""
|
|
1076
|
+
px = DISPLAY_WIDTH_PX / width_mm
|
|
1077
|
+
heights = {
|
|
1078
|
+
c["key"]: (plan["head_mm"] + c["plot_mm"], plan["head_mm"] + c["min_mm"])
|
|
1079
|
+
for plan in row_plans
|
|
1080
|
+
for c in plan["cells"]
|
|
1081
|
+
}
|
|
1082
|
+
tallest = max(heights, key=lambda k: heights[k][0])
|
|
1083
|
+
kind = panel_map[tallest].kind
|
|
1084
|
+
over = min_mm - spec.max_height_mm
|
|
1085
|
+
message = (
|
|
1086
|
+
f"The figure is {height_mm:.0f} mm tall (about {height_mm * px:.0f} px at chat width); "
|
|
1087
|
+
f"even with every panel at its minimum readable height it needs {min_mm:.0f} mm, "
|
|
1088
|
+
f"more than fits on one screen ({spec.max_height_mm:.0f} mm). The tallest is panel "
|
|
1089
|
+
f"{tallest} ({kind}), {heights[tallest][0]:.0f} mm."
|
|
1090
|
+
)
|
|
1091
|
+
keys = [[c["key"] for c in plan["cells"]] for plan in row_plans]
|
|
1092
|
+
layout_now = [list(row) for row in keys]
|
|
1093
|
+
options: list[str] = []
|
|
1094
|
+
# Two stacked single-panel rows side by side save the shorter one's height.
|
|
1095
|
+
pairs = [
|
|
1096
|
+
(min(heights[keys[i][0]][1], heights[keys[i + 1][0]][1]), i)
|
|
1097
|
+
for i in range(len(keys) - 1)
|
|
1098
|
+
if len(keys[i]) == 1 and len(keys[i + 1]) == 1
|
|
1099
|
+
]
|
|
1100
|
+
if pairs:
|
|
1101
|
+
saved, i = max(pairs)
|
|
1102
|
+
if saved >= over:
|
|
1103
|
+
merged = [*layout_now[:i], [keys[i][0], keys[i + 1][0]], *layout_now[i + 2 :]]
|
|
1104
|
+
options.append(f"put panels {keys[i][0]} and {keys[i + 1][0]} side by side: layout={merged!r}")
|
|
1105
|
+
if len(panel_map) > 1:
|
|
1106
|
+
options.append(
|
|
1107
|
+
f"drop panel {tallest} and state its key numbers in note=, or split the figure "
|
|
1108
|
+
"into two, each with its own takeaway (e.g. "
|
|
1109
|
+
+ ", ".join(k for k in panel_map if k != tallest)
|
|
1110
|
+
+ f" in one, {tallest} in the other)"
|
|
1111
|
+
)
|
|
1112
|
+
else:
|
|
1113
|
+
options.append(
|
|
1114
|
+
"shorten it: fewer items or rows, a shorter takeaway, subtitle and note, or show the "
|
|
1115
|
+
"top 10 and say so in the title"
|
|
1116
|
+
)
|
|
1117
|
+
hint = "; or ".join(options)
|
|
1118
|
+
return _issue("too_tall", "warning", message, hint[0].upper() + hint[1:] + ".")
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
@_guarded("explain")
|
|
1122
|
+
def explain(
|
|
1123
|
+
takeaway: str,
|
|
1124
|
+
*panels: Panel | Mapping[str, Any],
|
|
1125
|
+
subtitle: str | None = None,
|
|
1126
|
+
source: str | None = None,
|
|
1127
|
+
note: str | None = None,
|
|
1128
|
+
layout: Sequence[Sequence[str]] | None = None,
|
|
1129
|
+
target: str | JournalSpec = "screen",
|
|
1130
|
+
width: str | float = "chat",
|
|
1131
|
+
style: str | Theme = "mintfig",
|
|
1132
|
+
palette: str | ExplainPalette | None = None,
|
|
1133
|
+
accent: str | None = None,
|
|
1134
|
+
colors: Mapping[str, str] | None = None,
|
|
1135
|
+
strict: bool = True,
|
|
1136
|
+
out: str | Path | None = None,
|
|
1137
|
+
) -> Explanation:
|
|
1138
|
+
"""Build a message-first figure: one takeaway sentence and the panels that prove it.
|
|
1139
|
+
|
|
1140
|
+
Parameters
|
|
1141
|
+
----------
|
|
1142
|
+
takeaway:
|
|
1143
|
+
The conclusion, as a sentence, ideally with its number. It becomes the title.
|
|
1144
|
+
panels:
|
|
1145
|
+
One to six panels from :func:`compare`, :func:`trend`, :func:`change`,
|
|
1146
|
+
:func:`distribution`, :func:`relate`, :func:`share`, :func:`matrix` or
|
|
1147
|
+
:func:`custom` (or their dict specs). Use several only when the argument
|
|
1148
|
+
has steps; panels are keyed ``a``, ``b``, ``c`` in order.
|
|
1149
|
+
subtitle:
|
|
1150
|
+
Optional context line under the title (scope, period, population).
|
|
1151
|
+
source, note:
|
|
1152
|
+
Footer lines: where the numbers came from, and any caveat (synthetic,
|
|
1153
|
+
estimated, n, what an interval means).
|
|
1154
|
+
layout:
|
|
1155
|
+
Rows of panel keys, e.g. ``[["a"], ["b", "c"]]``; repeat a key within a
|
|
1156
|
+
row to widen it. Defaults: two panels side by side, three as one wide
|
|
1157
|
+
row above two, four as a 2x2.
|
|
1158
|
+
target, width:
|
|
1159
|
+
Spec and width preset. The default (``"screen"``, ``"chat"``) is sized
|
|
1160
|
+
for a ~700 px chat column; pass a journal name for print.
|
|
1161
|
+
style:
|
|
1162
|
+
Visual surface theme: ``"mintfig"`` (default), ``"bold"``, ``"editorial"``, ``"sketch"``,
|
|
1163
|
+
or a custom :class:`Theme`. Changes surface aesthetics only, never rules.
|
|
1164
|
+
colors:
|
|
1165
|
+
Pin a name to a colour slot so it keeps its colour across figures in one
|
|
1166
|
+
conversation: ``{"no retrieval": "red"}``. Slots are ``"blue"``, ``"red"``,
|
|
1167
|
+
``"green"`` and ``"amber"``, resolved from the style's validated palette.
|
|
1168
|
+
Within one figure a name always has one colour; pinned names are fixed
|
|
1169
|
+
entries of that registry.
|
|
1170
|
+
out:
|
|
1171
|
+
If given, the figure is saved there immediately.
|
|
1172
|
+
"""
|
|
1173
|
+
effective_strict = bool(strict) and _is_strict()
|
|
1174
|
+
local_adjustments: list[str] = list(_ADJUSTMENTS.get() or [])
|
|
1175
|
+
if not effective_strict:
|
|
1176
|
+
tok_s = _STRICT.set(False)
|
|
1177
|
+
tok_a = _ADJUSTMENTS.set(local_adjustments)
|
|
1178
|
+
try:
|
|
1179
|
+
return _explain_impl(
|
|
1180
|
+
takeaway,
|
|
1181
|
+
*panels,
|
|
1182
|
+
subtitle=subtitle,
|
|
1183
|
+
source=source,
|
|
1184
|
+
note=note,
|
|
1185
|
+
layout=layout,
|
|
1186
|
+
target=target,
|
|
1187
|
+
width=width,
|
|
1188
|
+
style=style,
|
|
1189
|
+
palette=palette,
|
|
1190
|
+
accent=accent,
|
|
1191
|
+
colors=colors,
|
|
1192
|
+
strict=False,
|
|
1193
|
+
adjustments=local_adjustments,
|
|
1194
|
+
out=out,
|
|
1195
|
+
)
|
|
1196
|
+
finally:
|
|
1197
|
+
_STRICT.reset(tok_s)
|
|
1198
|
+
_ADJUSTMENTS.reset(tok_a)
|
|
1199
|
+
return _explain_impl(
|
|
1200
|
+
takeaway,
|
|
1201
|
+
*panels,
|
|
1202
|
+
subtitle=subtitle,
|
|
1203
|
+
source=source,
|
|
1204
|
+
note=note,
|
|
1205
|
+
layout=layout,
|
|
1206
|
+
target=target,
|
|
1207
|
+
width=width,
|
|
1208
|
+
style=style,
|
|
1209
|
+
palette=palette,
|
|
1210
|
+
accent=accent,
|
|
1211
|
+
colors=colors,
|
|
1212
|
+
strict=True,
|
|
1213
|
+
adjustments=local_adjustments,
|
|
1214
|
+
out=out,
|
|
1215
|
+
)
|
|
1216
|
+
|
|
1217
|
+
|
|
1218
|
+
def _explain_impl(
|
|
1219
|
+
takeaway: str,
|
|
1220
|
+
*panels: Panel | Mapping[str, Any],
|
|
1221
|
+
subtitle: str | None = None,
|
|
1222
|
+
source: str | None = None,
|
|
1223
|
+
note: str | None = None,
|
|
1224
|
+
layout: Sequence[Sequence[str]] | None = None,
|
|
1225
|
+
target: str | JournalSpec = "screen",
|
|
1226
|
+
width: str | float = "chat",
|
|
1227
|
+
style: str | Theme = "mintfig",
|
|
1228
|
+
palette: str | ExplainPalette | None = None,
|
|
1229
|
+
accent: str | None = None,
|
|
1230
|
+
colors: Mapping[str, str] | None = None,
|
|
1231
|
+
strict: bool = True,
|
|
1232
|
+
adjustments: list[str] | None = None,
|
|
1233
|
+
out: str | Path | None = None,
|
|
1234
|
+
) -> Explanation:
|
|
1235
|
+
adj = adjustments if adjustments is not None else []
|
|
1236
|
+
try:
|
|
1237
|
+
theme = get_theme(style)
|
|
1238
|
+
except (TypeError, ValueError) as exc:
|
|
1239
|
+
if not strict:
|
|
1240
|
+
theme = MINTFIG_THEME
|
|
1241
|
+
_record_adjustment(f"explain(style={style!r}): fell back to 'mintfig'")
|
|
1242
|
+
else:
|
|
1243
|
+
aliases = ", ".join(sorted(THEME_ALIASES))
|
|
1244
|
+
raise ExplainError(
|
|
1245
|
+
str(exc),
|
|
1246
|
+
fix_hint=f"Use one of: {', '.join(THEMES)} (aliases: {aliases}).",
|
|
1247
|
+
rule="unknown_style",
|
|
1248
|
+
) from exc
|
|
1249
|
+
try:
|
|
1250
|
+
theme, palette_name = apply_palette(theme, palette)
|
|
1251
|
+
except (TypeError, ValueError) as exc:
|
|
1252
|
+
if not strict:
|
|
1253
|
+
palette_name = None
|
|
1254
|
+
_record_adjustment(f"explain(palette={palette!r}): fell back to 'default'")
|
|
1255
|
+
else:
|
|
1256
|
+
raise ExplainError(
|
|
1257
|
+
str(exc),
|
|
1258
|
+
fix_hint=f"Use one of: {', '.join(EXPLAIN_PALETTES)}.",
|
|
1259
|
+
rule="unknown_palette",
|
|
1260
|
+
) from exc
|
|
1261
|
+
try:
|
|
1262
|
+
theme, accent_hex = apply_accent(theme, accent)
|
|
1263
|
+
except ValueError as exc:
|
|
1264
|
+
if not strict:
|
|
1265
|
+
accent_hex = None
|
|
1266
|
+
_record_adjustment(f"explain(accent={accent!r}): ignored invalid accent color")
|
|
1267
|
+
else:
|
|
1268
|
+
raise ExplainError(
|
|
1269
|
+
str(exc),
|
|
1270
|
+
fix_hint="Pass a valid hex/CSS color string such as accent='#D97757'.",
|
|
1271
|
+
rule="invalid_accent",
|
|
1272
|
+
) from exc
|
|
1273
|
+
|
|
1274
|
+
built: list[Panel] = []
|
|
1275
|
+
for item in panels:
|
|
1276
|
+
if isinstance(item, Panel):
|
|
1277
|
+
built.append(item)
|
|
1278
|
+
elif isinstance(item, Mapping):
|
|
1279
|
+
built.append(panel_from_spec(item))
|
|
1280
|
+
else:
|
|
1281
|
+
raise ExplainError(
|
|
1282
|
+
f"explain() panels must come from mint.compare/trend/..., got {type(item).__name__}.",
|
|
1283
|
+
fix_hint="e.g. mint.explain('...', mint.compare({...}), mint.trend(x, {...})).",
|
|
1284
|
+
)
|
|
1285
|
+
if not built:
|
|
1286
|
+
raise ExplainError(
|
|
1287
|
+
"explain() needs at least one panel.",
|
|
1288
|
+
fix_hint="Add evidence, e.g. mint.compare({'a': 3, 'b': 1}).",
|
|
1289
|
+
)
|
|
1290
|
+
if len(built) > MAX_PANELS:
|
|
1291
|
+
if not strict:
|
|
1292
|
+
_record_adjustment(f"explain(): trimmed {len(built)} panels to first {MAX_PANELS}")
|
|
1293
|
+
built = built[:MAX_PANELS]
|
|
1294
|
+
else:
|
|
1295
|
+
raise ExplainError(
|
|
1296
|
+
f"explain() got {len(built)} panels; more than {MAX_PANELS} cannot be read in one figure.",
|
|
1297
|
+
fix_hint=f"explain() takes at most {MAX_PANELS} panels ({COMFORTABLE_PANELS} read "
|
|
1298
|
+
"comfortably): split the argument into two figures, each with its own takeaway, or "
|
|
1299
|
+
"fold related panels into one (trend(facet=True), a matrix()).",
|
|
1300
|
+
rule="too_many_panels",
|
|
1301
|
+
)
|
|
1302
|
+
if not isinstance(takeaway, str) or not takeaway.strip():
|
|
1303
|
+
if not strict:
|
|
1304
|
+
fallback = next(
|
|
1305
|
+
(p.title for p in built if p.title),
|
|
1306
|
+
next((p.facts[0] for p in built if p.facts), "Summary"),
|
|
1307
|
+
)
|
|
1308
|
+
takeaway = str(fallback)
|
|
1309
|
+
_record_adjustment("explain(): used first panel title/fact as takeaway")
|
|
1310
|
+
else:
|
|
1311
|
+
raise ExplainError(
|
|
1312
|
+
"explain() needs a takeaway sentence as its first argument.",
|
|
1313
|
+
fix_hint="Write the one thing the reader should conclude, then choose panels that show it.",
|
|
1314
|
+
rule="takeaway_missing",
|
|
1315
|
+
)
|
|
1316
|
+
takeaway = " ".join(takeaway.split())
|
|
1317
|
+
|
|
1318
|
+
pinned = _pinned_colors(colors, theme)
|
|
1319
|
+
panel_colors, uniform_color, colour_issues = _colour_registry(built, theme, pinned)
|
|
1320
|
+
|
|
1321
|
+
spec = get_spec(target)
|
|
1322
|
+
keys = [chr(ord("a") + i) for i in range(len(built))]
|
|
1323
|
+
panel_map = dict(zip(keys, built, strict=True))
|
|
1324
|
+
is_narrow = isinstance(width, str) and width.strip().lower() == "narrow"
|
|
1325
|
+
if layout is not None:
|
|
1326
|
+
rows = _validate_layout(layout, keys)
|
|
1327
|
+
elif is_narrow and len(keys) > 1:
|
|
1328
|
+
rows = [[k] for k in keys]
|
|
1329
|
+
else:
|
|
1330
|
+
rows = _auto_layout(keys)
|
|
1331
|
+
|
|
1332
|
+
issues: list[dict[str, Any]] = list(_takeaway_issues(takeaway))
|
|
1333
|
+
issues.extend(_latex_issues((takeaway, subtitle, source, note), panel_map))
|
|
1334
|
+
issues.extend(colour_issues)
|
|
1335
|
+
if len(built) > COMFORTABLE_PANELS:
|
|
1336
|
+
issues.append(
|
|
1337
|
+
_issue(
|
|
1338
|
+
"many_panels",
|
|
1339
|
+
"warning",
|
|
1340
|
+
f"{len(built)} panels is a lot for one glance in a conversation.",
|
|
1341
|
+
"Keep the panels the takeaway needs; move the rest to a follow-up figure.",
|
|
1342
|
+
)
|
|
1343
|
+
)
|
|
1344
|
+
if theme.warn_unless_illustrative:
|
|
1345
|
+
provenance = " ".join(t for t in (source, note) if t)
|
|
1346
|
+
if not _ILLUSTRATIVE_CUE.search(provenance):
|
|
1347
|
+
issues.append(
|
|
1348
|
+
_issue(
|
|
1349
|
+
"sketch_on_measured_data",
|
|
1350
|
+
"warning",
|
|
1351
|
+
"style='sketch' signals a conceptual sketch, but source/note does not mark "
|
|
1352
|
+
"these numbers as illustrative or synthetic.",
|
|
1353
|
+
"Use style='mintfig', 'editorial', or 'bold' for measured data, or note in "
|
|
1354
|
+
"source=/note= that the values are illustrative or synthetic.",
|
|
1355
|
+
)
|
|
1356
|
+
)
|
|
1357
|
+
|
|
1358
|
+
with theme.rc_context(spec), _GlyphCapture() as glyph_log:
|
|
1359
|
+
sizes = _Sizes.from_spec(spec, theme)
|
|
1360
|
+
if is_narrow and spec.name == "screen":
|
|
1361
|
+
# Keep smallest text >= 12 px at 450 px sidebar width while tightening
|
|
1362
|
+
# the headline slightly so takeaways wrap cleanly within 92 mm.
|
|
1363
|
+
sizes = _Sizes(
|
|
1364
|
+
scale=sizes.scale,
|
|
1365
|
+
title=min(sizes.title, max(sizes.body + 1.5, round(sizes.title * 0.92, 1))),
|
|
1366
|
+
body=sizes.body,
|
|
1367
|
+
small=sizes.small,
|
|
1368
|
+
foot=max(sizes.foot, 7.0),
|
|
1369
|
+
)
|
|
1370
|
+
s = sizes.scale
|
|
1371
|
+
measure = _Measure(theme)
|
|
1372
|
+
width_mm = float(spec.resolve_width_mm(width))
|
|
1373
|
+
margin = _MARGIN_MM * s
|
|
1374
|
+
content_mm = width_mm - 2 * margin
|
|
1375
|
+
content_pt = content_mm / PT_TO_MM
|
|
1376
|
+
|
|
1377
|
+
def _line_mm(size: float) -> float:
|
|
1378
|
+
return size * _LINE * PT_TO_MM
|
|
1379
|
+
|
|
1380
|
+
title_lines = measure.wrap(
|
|
1381
|
+
takeaway,
|
|
1382
|
+
content_pt,
|
|
1383
|
+
sizes.title,
|
|
1384
|
+
theme.title_weight,
|
|
1385
|
+
family=theme.title_family,
|
|
1386
|
+
)
|
|
1387
|
+
if len(title_lines) > MAX_TITLE_LINES:
|
|
1388
|
+
if not strict:
|
|
1389
|
+
if len(title_lines) > MAX_TITLE_LINES + 2:
|
|
1390
|
+
ell = theme.ellipsis
|
|
1391
|
+
title_lines = [*title_lines[: MAX_TITLE_LINES + 1], title_lines[MAX_TITLE_LINES + 1] + ell]
|
|
1392
|
+
_record_adjustment(
|
|
1393
|
+
f"explain(): wrapped long takeaway onto {len(title_lines)} lines"
|
|
1394
|
+
)
|
|
1395
|
+
else:
|
|
1396
|
+
raise ExplainError(
|
|
1397
|
+
f"The takeaway is {len(takeaway)} characters and wraps to {len(title_lines)} lines.",
|
|
1398
|
+
fix_hint=f"The takeaway may wrap to at most {MAX_TITLE_LINES} lines: cut it to "
|
|
1399
|
+
"one sentence (about 100 characters); move scope and caveats to subtitle= and "
|
|
1400
|
+
"note=.",
|
|
1401
|
+
rule="takeaway_too_long",
|
|
1402
|
+
)
|
|
1403
|
+
subtitle_lines = measure.wrap(subtitle, content_pt, sizes.body) if subtitle else []
|
|
1404
|
+
footer_text = [t for t in (note, f"Source: {source}" if source else None) if t]
|
|
1405
|
+
footer_lines = [ln for t in footer_text for ln in measure.wrap(t, content_pt, sizes.foot)]
|
|
1406
|
+
|
|
1407
|
+
top_rule_pad = 2.2 * s if theme.top_rule else 0.0
|
|
1408
|
+
header_mm = (
|
|
1409
|
+
top_rule_pad
|
|
1410
|
+
+ len(title_lines) * _line_mm(sizes.title)
|
|
1411
|
+
+ len(subtitle_lines) * _line_mm(sizes.body)
|
|
1412
|
+
)
|
|
1413
|
+
header_gap = 4.0 * s
|
|
1414
|
+
footer_rule_pad = 2.0 * s if (theme.footer_rule and footer_lines) else 0.0
|
|
1415
|
+
footer_mm = footer_rule_pad + len(footer_lines) * _line_mm(sizes.foot)
|
|
1416
|
+
footer_gap = 3.5 * s if footer_lines else 0.0
|
|
1417
|
+
|
|
1418
|
+
multi = len(built) > 1
|
|
1419
|
+
letter_pt = measure.width_pt("a", sizes.body, "bold") + sizes.body * 0.75 if multi else 0.0
|
|
1420
|
+
|
|
1421
|
+
# Per-row geometry (mm)
|
|
1422
|
+
row_plans: list[dict[str, Any]] = []
|
|
1423
|
+
for row in rows:
|
|
1424
|
+
order = [k for i, k in enumerate(row) if i == 0 or row[i - 1] != k]
|
|
1425
|
+
unit_mm = (content_mm - _COL_GAP_MM * s * (len(row) - 1)) / len(row)
|
|
1426
|
+
cells: list[dict[str, Any]] = []
|
|
1427
|
+
x_mm = margin
|
|
1428
|
+
for key in order:
|
|
1429
|
+
span = row.count(key)
|
|
1430
|
+
cell_w = unit_mm * span + _COL_GAP_MM * s * (span - 1)
|
|
1431
|
+
panel = panel_map[key]
|
|
1432
|
+
head_lines = (
|
|
1433
|
+
measure.wrap(panel.title, cell_w / PT_TO_MM - letter_pt, sizes.body, "bold")
|
|
1434
|
+
if panel.title
|
|
1435
|
+
else ([""] if multi else [])
|
|
1436
|
+
)
|
|
1437
|
+
inline_unit_panel = (
|
|
1438
|
+
theme.inline_y_ticks
|
|
1439
|
+
and panel.kind == "trend"
|
|
1440
|
+
and not panel.spec.get("facet")
|
|
1441
|
+
and not panel.spec.get("log")
|
|
1442
|
+
and bool(panel.unit)
|
|
1443
|
+
)
|
|
1444
|
+
measure_text = (
|
|
1445
|
+
panel.label if inline_unit_panel else _measure_text(panel.label, panel.unit)
|
|
1446
|
+
)
|
|
1447
|
+
if panel.measure_note:
|
|
1448
|
+
measure_text = (
|
|
1449
|
+
f"{measure_text}; {panel.measure_note}"
|
|
1450
|
+
if measure_text
|
|
1451
|
+
else panel.measure_note
|
|
1452
|
+
)
|
|
1453
|
+
measure_lines = (
|
|
1454
|
+
measure.wrap(measure_text, cell_w / PT_TO_MM - letter_pt, sizes.small)
|
|
1455
|
+
if measure_text
|
|
1456
|
+
else []
|
|
1457
|
+
)
|
|
1458
|
+
head_mm = len(head_lines) * _line_mm(sizes.body) + len(measure_lines) * _line_mm(
|
|
1459
|
+
sizes.small
|
|
1460
|
+
)
|
|
1461
|
+
if head_mm:
|
|
1462
|
+
head_mm += 2.2 * s
|
|
1463
|
+
cells.append(
|
|
1464
|
+
{
|
|
1465
|
+
"key": key,
|
|
1466
|
+
"x": x_mm,
|
|
1467
|
+
"w": cell_w,
|
|
1468
|
+
"head_lines": head_lines,
|
|
1469
|
+
"measure_lines": measure_lines,
|
|
1470
|
+
"head_mm": head_mm,
|
|
1471
|
+
"plot_mm": panel._height_mm(cell_w / s, measure, sizes, theme) * s,
|
|
1472
|
+
}
|
|
1473
|
+
)
|
|
1474
|
+
floor = panel._min_height_mm
|
|
1475
|
+
cells[-1]["min_mm"] = min(
|
|
1476
|
+
cells[-1]["plot_mm"],
|
|
1477
|
+
floor(cell_w / s, measure, sizes, theme) * s if floor else cells[-1]["plot_mm"],
|
|
1478
|
+
)
|
|
1479
|
+
x_mm += cell_w + _COL_GAP_MM * s
|
|
1480
|
+
if len(rows) > 1 and len(cells) == 1 and panel_map[cells[0]["key"]].stretch:
|
|
1481
|
+
# A full-width line or scatter panel in a multi-row figure would set the
|
|
1482
|
+
# tallest row of the figure; cap it so three panels stay on one screen.
|
|
1483
|
+
cells[0]["plot_mm"] = min(cells[0]["plot_mm"], _FULL_ROW_STRETCH_MM * s)
|
|
1484
|
+
cells[0]["min_mm"] = min(cells[0]["min_mm"], cells[0]["plot_mm"])
|
|
1485
|
+
row_plans.append(
|
|
1486
|
+
{
|
|
1487
|
+
"cells": cells,
|
|
1488
|
+
"head_mm": max(c["head_mm"] for c in cells),
|
|
1489
|
+
"plot_mm": max(c["plot_mm"] for c in cells),
|
|
1490
|
+
}
|
|
1491
|
+
)
|
|
1492
|
+
|
|
1493
|
+
def _height_at(squeeze: float) -> float:
|
|
1494
|
+
"""Figure height with every panel ``squeeze`` (0..1) of the way to its minimum."""
|
|
1495
|
+
body = sum(
|
|
1496
|
+
r["head_mm"]
|
|
1497
|
+
+ max(c["plot_mm"] - squeeze * (c["plot_mm"] - c["min_mm"]) for c in r["cells"])
|
|
1498
|
+
for r in row_plans
|
|
1499
|
+
) + _ROW_GAP_MM * s * (len(row_plans) - 1)
|
|
1500
|
+
return margin + header_mm + header_gap + body + footer_gap + footer_mm + margin
|
|
1501
|
+
|
|
1502
|
+
natural_mm = _height_at(0.0)
|
|
1503
|
+
height_mm = natural_mm
|
|
1504
|
+
squeeze = 0.0
|
|
1505
|
+
limit_mm = spec.max_height_mm
|
|
1506
|
+
if natural_mm > limit_mm + 0.5 and _height_at(1.0) <= limit_mm + 0.5:
|
|
1507
|
+
# Too tall for one screen at natural size, but it fits with the panels nearer
|
|
1508
|
+
# their minimum readable height: compress just enough, not a warning.
|
|
1509
|
+
lo, hi = 0.0, 1.0
|
|
1510
|
+
for _ in range(24):
|
|
1511
|
+
mid = 0.5 * (lo + hi)
|
|
1512
|
+
lo, hi = (lo, mid) if _height_at(mid) <= limit_mm else (mid, hi)
|
|
1513
|
+
squeeze = hi
|
|
1514
|
+
for plan in row_plans:
|
|
1515
|
+
for cell in plan["cells"]:
|
|
1516
|
+
cell["plot_mm"] -= squeeze * (cell["plot_mm"] - cell["min_mm"])
|
|
1517
|
+
plan["plot_mm"] = max(c["plot_mm"] for c in plan["cells"])
|
|
1518
|
+
height_mm = _height_at(0.0)
|
|
1519
|
+
|
|
1520
|
+
fig = Figure(
|
|
1521
|
+
figsize=(mm_to_in(width_mm), mm_to_in(height_mm)),
|
|
1522
|
+
dpi=150,
|
|
1523
|
+
facecolor=theme.background,
|
|
1524
|
+
)
|
|
1525
|
+
FigureCanvasAgg(fig)
|
|
1526
|
+
fig._mintfig_journal = spec.name # type: ignore[attr-defined]
|
|
1527
|
+
px_per_mm = float(fig.dpi) / 25.4
|
|
1528
|
+
|
|
1529
|
+
def _fx(mm: float) -> float:
|
|
1530
|
+
return mm / width_mm
|
|
1531
|
+
|
|
1532
|
+
def _fy(mm_from_top: float) -> float:
|
|
1533
|
+
return 1.0 - mm_from_top / height_mm
|
|
1534
|
+
|
|
1535
|
+
cursor = margin
|
|
1536
|
+
if theme.top_rule:
|
|
1537
|
+
rule_y = _fy(cursor + 0.3 * s)
|
|
1538
|
+
fig.add_artist(
|
|
1539
|
+
Line2D(
|
|
1540
|
+
[_fx(margin), _fx(width_mm - margin)],
|
|
1541
|
+
[rule_y, rule_y],
|
|
1542
|
+
transform=fig.transFigure,
|
|
1543
|
+
color=theme.top_rule_color or theme.ink,
|
|
1544
|
+
linewidth=theme.top_rule_lw * s,
|
|
1545
|
+
solid_capstyle="butt",
|
|
1546
|
+
)
|
|
1547
|
+
)
|
|
1548
|
+
cursor += top_rule_pad
|
|
1549
|
+
|
|
1550
|
+
for line in title_lines:
|
|
1551
|
+
title_kw: dict[str, Any] = {
|
|
1552
|
+
"ha": "left",
|
|
1553
|
+
"va": "top",
|
|
1554
|
+
"fontsize": sizes.title,
|
|
1555
|
+
"fontweight": theme.title_weight,
|
|
1556
|
+
"color": theme.ink,
|
|
1557
|
+
}
|
|
1558
|
+
if theme.title_family is not None:
|
|
1559
|
+
title_kw["fontfamily"] = list(theme.title_family)
|
|
1560
|
+
t_art = fig.text(_fx(margin), _fy(cursor), _plain(line, theme), **title_kw)
|
|
1561
|
+
if theme.allow_serif_title:
|
|
1562
|
+
t_art._mintfig_allow_serif = True # type: ignore[attr-defined]
|
|
1563
|
+
cursor += _line_mm(sizes.title)
|
|
1564
|
+
for line in subtitle_lines:
|
|
1565
|
+
fig.text(
|
|
1566
|
+
_fx(margin),
|
|
1567
|
+
_fy(cursor + 0.3 * s),
|
|
1568
|
+
_plain(line, theme),
|
|
1569
|
+
ha="left",
|
|
1570
|
+
va="top",
|
|
1571
|
+
fontsize=sizes.body,
|
|
1572
|
+
color=theme.muted,
|
|
1573
|
+
)
|
|
1574
|
+
cursor += _line_mm(sizes.body)
|
|
1575
|
+
cursor += header_gap
|
|
1576
|
+
|
|
1577
|
+
axes: dict[str, Axes] = {}
|
|
1578
|
+
finishers: list[tuple[str, Panel, Callable[[], None]]] = []
|
|
1579
|
+
tick_axes: list[tuple[Axes, str]] = []
|
|
1580
|
+
contexts: list[tuple[str, _Ctx, int]] = []
|
|
1581
|
+
for plan in row_plans:
|
|
1582
|
+
row_top = cursor
|
|
1583
|
+
for cell in plan["cells"]:
|
|
1584
|
+
key = cell["key"]
|
|
1585
|
+
panel = panel_map[key]
|
|
1586
|
+
text_x = cell["x"] + letter_pt * PT_TO_MM
|
|
1587
|
+
y_mm = row_top
|
|
1588
|
+
if multi:
|
|
1589
|
+
tag = fig.text(
|
|
1590
|
+
_fx(cell["x"]),
|
|
1591
|
+
_fy(y_mm),
|
|
1592
|
+
key,
|
|
1593
|
+
ha="left",
|
|
1594
|
+
va="top",
|
|
1595
|
+
fontsize=sizes.body,
|
|
1596
|
+
fontweight="bold",
|
|
1597
|
+
color=theme.resolved_panel_tag_color,
|
|
1598
|
+
)
|
|
1599
|
+
tag._mintfig_panel_label = True # type: ignore[attr-defined]
|
|
1600
|
+
for line in cell["head_lines"]:
|
|
1601
|
+
if line:
|
|
1602
|
+
fig.text(
|
|
1603
|
+
_fx(text_x),
|
|
1604
|
+
_fy(y_mm),
|
|
1605
|
+
_plain(line, theme),
|
|
1606
|
+
ha="left",
|
|
1607
|
+
va="top",
|
|
1608
|
+
fontsize=sizes.body,
|
|
1609
|
+
fontweight="bold",
|
|
1610
|
+
color=theme.ink,
|
|
1611
|
+
)
|
|
1612
|
+
y_mm += _line_mm(sizes.body)
|
|
1613
|
+
for line in cell["measure_lines"]:
|
|
1614
|
+
fig.text(
|
|
1615
|
+
_fx(text_x),
|
|
1616
|
+
_fy(y_mm + 0.2 * s),
|
|
1617
|
+
_plain(line, theme),
|
|
1618
|
+
ha="left",
|
|
1619
|
+
va="top",
|
|
1620
|
+
fontsize=sizes.small,
|
|
1621
|
+
color=theme.muted,
|
|
1622
|
+
)
|
|
1623
|
+
y_mm += _line_mm(sizes.small)
|
|
1624
|
+
|
|
1625
|
+
plot_top = row_top + plan["head_mm"]
|
|
1626
|
+
# Bar-like panels keep their own pitch instead of fattening to
|
|
1627
|
+
# match a taller neighbour in the same row.
|
|
1628
|
+
plot_mm = (
|
|
1629
|
+
plan["plot_mm"]
|
|
1630
|
+
if panel.stretch
|
|
1631
|
+
else min(plan["plot_mm"], cell["plot_mm"] * _ROW_GROWTH)
|
|
1632
|
+
)
|
|
1633
|
+
rect = Bbox.from_extents(
|
|
1634
|
+
cell["x"] * px_per_mm,
|
|
1635
|
+
(height_mm - plot_top - plot_mm) * px_per_mm,
|
|
1636
|
+
(cell["x"] + cell["w"]) * px_per_mm,
|
|
1637
|
+
(height_mm - plot_top) * px_per_mm,
|
|
1638
|
+
)
|
|
1639
|
+
ctx = _Ctx(
|
|
1640
|
+
fig=fig,
|
|
1641
|
+
sizes=sizes,
|
|
1642
|
+
key=key,
|
|
1643
|
+
cell_width_mm=cell["w"] / s,
|
|
1644
|
+
measure=measure,
|
|
1645
|
+
theme=theme,
|
|
1646
|
+
measure_label=_measure_text(panel.label, panel.unit) or "(see measure_unnamed)",
|
|
1647
|
+
colors=panel_colors[keys.index(key)],
|
|
1648
|
+
uniform_color=uniform_color,
|
|
1649
|
+
)
|
|
1650
|
+
ax = ctx.tag(fig.add_axes([0.1, 0.1, 0.5, 0.5]))
|
|
1651
|
+
_fit_axes(fig, ax, rect)
|
|
1652
|
+
try:
|
|
1653
|
+
finish = panel._draw(ctx, ax)
|
|
1654
|
+
frames = panel._frames(ctx, ax, rect) if panel._frames else [(ax, rect)]
|
|
1655
|
+
for frame_ax, frame_rect in frames:
|
|
1656
|
+
_fit_axes(fig, frame_ax, frame_rect)
|
|
1657
|
+
_check_plot_width(fig, panel, frame_ax, frame_rect, s)
|
|
1658
|
+
except ExplainError as exc:
|
|
1659
|
+
if (
|
|
1660
|
+
not strict
|
|
1661
|
+
and layout is None
|
|
1662
|
+
and len(built) > 1
|
|
1663
|
+
and rows != [[k] for k in keys]
|
|
1664
|
+
and exc.rule in {"panel_too_small", "matrix_cells_too_small", "table_too_wide"}
|
|
1665
|
+
):
|
|
1666
|
+
_record_adjustment(
|
|
1667
|
+
"layout: stacked panels into full-width rows so every label fits"
|
|
1668
|
+
)
|
|
1669
|
+
return _explain_impl(
|
|
1670
|
+
takeaway,
|
|
1671
|
+
*built,
|
|
1672
|
+
subtitle=subtitle,
|
|
1673
|
+
source=source,
|
|
1674
|
+
note=note,
|
|
1675
|
+
layout=[[k] for k in keys],
|
|
1676
|
+
target=target,
|
|
1677
|
+
width=width,
|
|
1678
|
+
style=style,
|
|
1679
|
+
palette=palette,
|
|
1680
|
+
accent=accent,
|
|
1681
|
+
colors=colors,
|
|
1682
|
+
strict=False,
|
|
1683
|
+
adjustments=adj,
|
|
1684
|
+
out=out,
|
|
1685
|
+
)
|
|
1686
|
+
raise ExplainError(
|
|
1687
|
+
f"Panel {key} ({panel.kind}): {exc.message}",
|
|
1688
|
+
fix_hint=exc.fix_hint,
|
|
1689
|
+
rule=exc.rule,
|
|
1690
|
+
) from exc
|
|
1691
|
+
which = _TICK_AXES.get(panel.kind, "")
|
|
1692
|
+
if which:
|
|
1693
|
+
tick_axes.extend((frame_ax, which) for frame_ax, _ in frames)
|
|
1694
|
+
if callable(finish):
|
|
1695
|
+
finishers.append((key, panel, finish))
|
|
1696
|
+
finishers.extend((key, panel, extra) for extra in ctx.finishers)
|
|
1697
|
+
issues.extend({**issue, "panel": key} for issue in (*panel.issues, *ctx.issues))
|
|
1698
|
+
contexts.append((key, ctx, len(ctx.issues)))
|
|
1699
|
+
has_measure = bool(
|
|
1700
|
+
panel.label
|
|
1701
|
+
or panel.unit
|
|
1702
|
+
or (
|
|
1703
|
+
panel.kind == "timeline"
|
|
1704
|
+
and (panel.spec.get("x_label") or panel.spec.get("unit"))
|
|
1705
|
+
)
|
|
1706
|
+
)
|
|
1707
|
+
if panel.kind in KINDS and panel.kind != "table" and not has_measure:
|
|
1708
|
+
issues.append(
|
|
1709
|
+
_issue(
|
|
1710
|
+
"measure_unnamed",
|
|
1711
|
+
"warning",
|
|
1712
|
+
f"Panel {key} ({panel.kind}) does not say what is measured.",
|
|
1713
|
+
'Pass label= and unit=, e.g. label="p99 latency", unit="ms".',
|
|
1714
|
+
panel=key,
|
|
1715
|
+
)
|
|
1716
|
+
)
|
|
1717
|
+
axes[key] = frames[0][0]
|
|
1718
|
+
cursor = row_top + plan["head_mm"] + plan["plot_mm"] + _ROW_GAP_MM * s
|
|
1719
|
+
|
|
1720
|
+
y_mm = height_mm - margin - footer_mm
|
|
1721
|
+
if theme.footer_rule and footer_lines:
|
|
1722
|
+
frule_y = _fy(y_mm + 0.3 * s)
|
|
1723
|
+
fig.add_artist(
|
|
1724
|
+
Line2D(
|
|
1725
|
+
[_fx(margin), _fx(width_mm - margin)],
|
|
1726
|
+
[frule_y, frule_y],
|
|
1727
|
+
transform=fig.transFigure,
|
|
1728
|
+
color=theme.footer_rule_color or theme.grid,
|
|
1729
|
+
linewidth=theme.footer_rule_lw * s,
|
|
1730
|
+
solid_capstyle="butt",
|
|
1731
|
+
)
|
|
1732
|
+
)
|
|
1733
|
+
y_mm += footer_rule_pad
|
|
1734
|
+
for line in footer_lines:
|
|
1735
|
+
fig.text(
|
|
1736
|
+
_fx(margin),
|
|
1737
|
+
_fy(y_mm),
|
|
1738
|
+
_plain(line, theme),
|
|
1739
|
+
ha="left",
|
|
1740
|
+
va="top",
|
|
1741
|
+
fontsize=sizes.foot,
|
|
1742
|
+
color=theme.muted,
|
|
1743
|
+
)
|
|
1744
|
+
y_mm += _line_mm(sizes.foot)
|
|
1745
|
+
|
|
1746
|
+
for key, panel, finish in finishers:
|
|
1747
|
+
try:
|
|
1748
|
+
finish()
|
|
1749
|
+
except ExplainError as exc:
|
|
1750
|
+
if (
|
|
1751
|
+
not strict
|
|
1752
|
+
and layout is None
|
|
1753
|
+
and len(built) > 1
|
|
1754
|
+
and rows != [[k] for k in keys]
|
|
1755
|
+
and exc.rule in {"panel_too_small", "matrix_cells_too_small", "table_too_wide"}
|
|
1756
|
+
):
|
|
1757
|
+
_record_adjustment(
|
|
1758
|
+
"layout: stacked panels into full-width rows so every label fits"
|
|
1759
|
+
)
|
|
1760
|
+
return _explain_impl(
|
|
1761
|
+
takeaway,
|
|
1762
|
+
*built,
|
|
1763
|
+
subtitle=subtitle,
|
|
1764
|
+
source=source,
|
|
1765
|
+
note=note,
|
|
1766
|
+
layout=[[k] for k in keys],
|
|
1767
|
+
target=target,
|
|
1768
|
+
width=width,
|
|
1769
|
+
style=style,
|
|
1770
|
+
palette=palette,
|
|
1771
|
+
accent=accent,
|
|
1772
|
+
colors=colors,
|
|
1773
|
+
strict=False,
|
|
1774
|
+
adjustments=adj,
|
|
1775
|
+
out=out,
|
|
1776
|
+
)
|
|
1777
|
+
raise ExplainError(
|
|
1778
|
+
f"Panel {key} ({panel.kind}): {exc.message}",
|
|
1779
|
+
fix_hint=exc.fix_hint,
|
|
1780
|
+
rule=exc.rule,
|
|
1781
|
+
) from exc
|
|
1782
|
+
for tick_ax, which in tick_axes:
|
|
1783
|
+
_fit_ticks(fig, tick_ax, which)
|
|
1784
|
+
for key, ctx, seen in contexts: # warnings raised while finishing the layout
|
|
1785
|
+
issues.extend({**issue, "panel": key} for issue in ctx.issues[seen:])
|
|
1786
|
+
|
|
1787
|
+
result = Explanation(
|
|
1788
|
+
fig=fig,
|
|
1789
|
+
spec=spec,
|
|
1790
|
+
theme=theme,
|
|
1791
|
+
palette=palette_name,
|
|
1792
|
+
accent=accent_hex,
|
|
1793
|
+
takeaway=takeaway,
|
|
1794
|
+
subtitle=subtitle,
|
|
1795
|
+
source=source,
|
|
1796
|
+
note=note,
|
|
1797
|
+
panels=panel_map,
|
|
1798
|
+
axes=axes,
|
|
1799
|
+
layout=rows,
|
|
1800
|
+
width=width,
|
|
1801
|
+
issues=issues,
|
|
1802
|
+
colors={k: str(v) for k, v in _pairs(colors)} if colors else None,
|
|
1803
|
+
strict=strict,
|
|
1804
|
+
adjustments=adj,
|
|
1805
|
+
)
|
|
1806
|
+
slot_of = {theme.series_colors[i]: slot for slot, i in COLOR_SLOTS.items()}
|
|
1807
|
+
for panel_map_colors in panel_colors:
|
|
1808
|
+
for name, col in panel_map_colors.items():
|
|
1809
|
+
key = _entity_key(name)
|
|
1810
|
+
used = set(result.entity_colors.values())
|
|
1811
|
+
if col in slot_of and key not in result.entity_colors and slot_of[col] not in used:
|
|
1812
|
+
result.entity_colors[key] = slot_of[col] # overflow reuse is left out
|
|
1813
|
+
|
|
1814
|
+
if height_mm > spec.max_height_mm + 0.5:
|
|
1815
|
+
issues.append(
|
|
1816
|
+
_too_tall_issue(row_plans, panel_map, height_mm, _height_at(1.0), width_mm, spec)
|
|
1817
|
+
)
|
|
1818
|
+
if spec.name == "screen" and result.min_text_px < MIN_TEXT_PX:
|
|
1819
|
+
issues.append(
|
|
1820
|
+
_issue(
|
|
1821
|
+
"small_at_chat_size",
|
|
1822
|
+
"warning",
|
|
1823
|
+
f"The smallest text is {result.min_text_px:.1f} px when shown "
|
|
1824
|
+
f"{result.display_width_px} px wide (floor {MIN_TEXT_PX:.0f} px).",
|
|
1825
|
+
'Use width="chat" for a 700 px chat column, width="narrow" for a 450 px IDE sidebar, or width="slide" for a 1280 px presentation/blog hero.',
|
|
1826
|
+
)
|
|
1827
|
+
)
|
|
1828
|
+
|
|
1829
|
+
missing = _missing_glyphs(fig)
|
|
1830
|
+
for ch in glyph_log.missing():
|
|
1831
|
+
missing.setdefault(ch, "")
|
|
1832
|
+
if missing:
|
|
1833
|
+
issues.append(_glyph_issue(missing))
|
|
1834
|
+
|
|
1835
|
+
from ..audit import audit_figure, audit_to_issues
|
|
1836
|
+
from ..preflight import preflight_figure
|
|
1837
|
+
|
|
1838
|
+
report = preflight_figure(fig, spec)
|
|
1839
|
+
for check in report.issues:
|
|
1840
|
+
if check.rule == "dimensions":
|
|
1841
|
+
continue # height is reported above as too_tall, in chat terms
|
|
1842
|
+
issues.append(
|
|
1843
|
+
{
|
|
1844
|
+
"rule": check.rule,
|
|
1845
|
+
"severity": "error" if check.status == "fail" else "warning",
|
|
1846
|
+
"panel": check.panel,
|
|
1847
|
+
"message": check.message,
|
|
1848
|
+
"fix_hint": _EXPLAIN_PREFLIGHT_HINTS.get(check.rule, check.fix_hint),
|
|
1849
|
+
}
|
|
1850
|
+
)
|
|
1851
|
+
audit = audit_figure(fig, allow_ascii_minus=(theme.minus_sign == "-"))
|
|
1852
|
+
existing_rules = {str(i.get("rule", "")) for i in issues}
|
|
1853
|
+
issues.extend(audit_to_issues(audit, existing_rules=existing_rules))
|
|
1854
|
+
|
|
1855
|
+
from ..epistemic import audit_epistemic
|
|
1856
|
+
|
|
1857
|
+
issues.extend(audit_epistemic(takeaway, panel_map))
|
|
1858
|
+
if not strict:
|
|
1859
|
+
actionable = [
|
|
1860
|
+
i
|
|
1861
|
+
for i in issues
|
|
1862
|
+
if i["severity"] == "error" or i["rule"] in _VISUAL_DEFECT_RULES
|
|
1863
|
+
]
|
|
1864
|
+
advisory = [i for i in issues if i not in actionable]
|
|
1865
|
+
result.issues = actionable
|
|
1866
|
+
result.advisories = advisory
|
|
1867
|
+
|
|
1868
|
+
if out is not None:
|
|
1869
|
+
result.save(out)
|
|
1870
|
+
return result
|
|
1871
|
+
|
|
1872
|
+
|
|
1873
|
+
# --------------------------------------------------------------------------- #
|
|
1874
|
+
# JSON spec entry points
|
|
1875
|
+
# --------------------------------------------------------------------------- #
|
|
1876
|
+
|
|
1877
|
+
_BUILDERS: dict[str, Callable[..., Panel]] = {
|
|
1878
|
+
"compare": compare,
|
|
1879
|
+
"trend": trend,
|
|
1880
|
+
"change": change,
|
|
1881
|
+
"distribution": distribution,
|
|
1882
|
+
"histogram": histogram,
|
|
1883
|
+
"relate": relate,
|
|
1884
|
+
"share": share,
|
|
1885
|
+
"matrix": matrix,
|
|
1886
|
+
"table": table,
|
|
1887
|
+
"waterfall": waterfall,
|
|
1888
|
+
"timeline": timeline,
|
|
1889
|
+
"flow": flow,
|
|
1890
|
+
}
|
|
1891
|
+
_POSITIONAL: dict[str, tuple[str, ...]] = {
|
|
1892
|
+
"compare": ("values",),
|
|
1893
|
+
"trend": ("x",), # series may be replaced by points=
|
|
1894
|
+
"change": ("before", "after"),
|
|
1895
|
+
"distribution": ("groups",),
|
|
1896
|
+
"histogram": ("values",),
|
|
1897
|
+
"relate": ("x", "y"),
|
|
1898
|
+
"share": ("parts",),
|
|
1899
|
+
"matrix": ("values",),
|
|
1900
|
+
"table": ("rows",),
|
|
1901
|
+
"waterfall": ("steps",),
|
|
1902
|
+
"timeline": ("spans",),
|
|
1903
|
+
"flow": ("stages",),
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
|
|
1907
|
+
def panel_from_spec(spec: Mapping[str, Any]) -> Panel:
|
|
1908
|
+
"""Build one panel from its dict form, e.g. ``{"kind": "compare", "values": {...}}``."""
|
|
1909
|
+
options = dict(spec)
|
|
1910
|
+
kind = options.pop("kind", None)
|
|
1911
|
+
if kind == "histogram" and "values" not in options and "groups" in options:
|
|
1912
|
+
options["values"] = options.pop("groups")
|
|
1913
|
+
if kind not in _BUILDERS:
|
|
1914
|
+
raise ExplainError(
|
|
1915
|
+
f"Unknown panel kind {kind!r}.",
|
|
1916
|
+
fix_hint=f"Use one of: {', '.join(KINDS)}.",
|
|
1917
|
+
)
|
|
1918
|
+
missing = [name for name in _POSITIONAL[kind] if name not in options]
|
|
1919
|
+
if missing:
|
|
1920
|
+
raise ExplainError(
|
|
1921
|
+
f"A {kind} panel needs {', '.join(map(repr, missing))}.",
|
|
1922
|
+
fix_hint=f"Required keys for {kind}: {', '.join(_POSITIONAL[kind])}.",
|
|
1923
|
+
)
|
|
1924
|
+
try:
|
|
1925
|
+
return _BUILDERS[kind](**options)
|
|
1926
|
+
except TypeError as exc:
|
|
1927
|
+
raise ExplainError(
|
|
1928
|
+
f"Invalid options for a {kind} panel: {exc}.",
|
|
1929
|
+
fix_hint=f"See `mintfig explain --example` or help(mintfig.{kind}).",
|
|
1930
|
+
) from exc
|
|
1931
|
+
|
|
1932
|
+
|
|
1933
|
+
def explain_from_spec(
|
|
1934
|
+
spec: Mapping[str, Any],
|
|
1935
|
+
*,
|
|
1936
|
+
out: str | Path | None = None,
|
|
1937
|
+
strict: bool = True,
|
|
1938
|
+
) -> Explanation:
|
|
1939
|
+
"""Render a whole figure from its JSON spec (the inverse of :meth:`Explanation.to_spec`)."""
|
|
1940
|
+
options = dict(spec)
|
|
1941
|
+
takeaway = options.pop("takeaway", "")
|
|
1942
|
+
panels = options.pop("panels", None)
|
|
1943
|
+
if not isinstance(panels, Sequence) or isinstance(panels, (str, bytes)) or not panels:
|
|
1944
|
+
raise ExplainError(
|
|
1945
|
+
'The spec needs a "panels" list.',
|
|
1946
|
+
fix_hint='e.g. {"takeaway": "...", "panels": [{"kind": "compare", "values": {...}}]}.',
|
|
1947
|
+
)
|
|
1948
|
+
allowed = {
|
|
1949
|
+
"subtitle",
|
|
1950
|
+
"source",
|
|
1951
|
+
"note",
|
|
1952
|
+
"layout",
|
|
1953
|
+
"target",
|
|
1954
|
+
"width",
|
|
1955
|
+
"style",
|
|
1956
|
+
"palette",
|
|
1957
|
+
"accent",
|
|
1958
|
+
"colors",
|
|
1959
|
+
"strict",
|
|
1960
|
+
}
|
|
1961
|
+
unknown = sorted(set(options) - allowed)
|
|
1962
|
+
if unknown:
|
|
1963
|
+
if not (strict and _is_strict()):
|
|
1964
|
+
for k in unknown:
|
|
1965
|
+
options.pop(k, None)
|
|
1966
|
+
else:
|
|
1967
|
+
raise ExplainError(
|
|
1968
|
+
f"Unknown top-level key(s) {unknown!r}.",
|
|
1969
|
+
fix_hint=f"Allowed: takeaway, panels, {', '.join(sorted(allowed))}.",
|
|
1970
|
+
)
|
|
1971
|
+
spec_strict = options.pop("strict", strict)
|
|
1972
|
+
effective_strict = bool(spec_strict) and bool(strict) and _is_strict()
|
|
1973
|
+
return explain(takeaway, *panels, out=out, strict=effective_strict, **options)
|
|
1974
|
+
|
|
1975
|
+
|
|
1976
|
+
EXAMPLE_SPEC: dict[str, Any] = {
|
|
1977
|
+
"takeaway": "Checkout is the slow service: its p99 is 4x the next worst",
|
|
1978
|
+
"subtitle": "API p99 latency by service, week of 16 Nov",
|
|
1979
|
+
"source": "synthetic example data",
|
|
1980
|
+
"panels": [
|
|
1981
|
+
{
|
|
1982
|
+
"kind": "compare",
|
|
1983
|
+
"title": "Checkout stands alone",
|
|
1984
|
+
"label": "p99 latency",
|
|
1985
|
+
"unit": "ms",
|
|
1986
|
+
"values": {
|
|
1987
|
+
"checkout": 1840,
|
|
1988
|
+
"search": 460,
|
|
1989
|
+
"auth": 310,
|
|
1990
|
+
"catalog": 280,
|
|
1991
|
+
"cart": 240,
|
|
1992
|
+
"profile": 120,
|
|
1993
|
+
},
|
|
1994
|
+
"highlight": "checkout",
|
|
1995
|
+
},
|
|
1996
|
+
{
|
|
1997
|
+
"kind": "trend",
|
|
1998
|
+
"title": "It regressed after the v2.3 deploy",
|
|
1999
|
+
"label": "p99 latency",
|
|
2000
|
+
"unit": "ms",
|
|
2001
|
+
"x_label": "Week",
|
|
2002
|
+
"x": [1, 2, 3, 4, 5, 6, 7, 8],
|
|
2003
|
+
"series": {
|
|
2004
|
+
"checkout": [540, 560, 550, 570, 980, 1400, 1700, 1840],
|
|
2005
|
+
"search": [450, 470, 455, 465, 460, 450, 470, 460],
|
|
2006
|
+
"auth": [300, 310, 305, 315, 300, 320, 305, 310],
|
|
2007
|
+
},
|
|
2008
|
+
"highlight": "checkout",
|
|
2009
|
+
"events": {"4": "v2.3 deploy"},
|
|
2010
|
+
},
|
|
2011
|
+
],
|
|
2012
|
+
}
|