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.
Files changed (47) hide show
  1. mintfig/__init__.py +162 -0
  2. mintfig/_explain/__init__.py +1 -0
  3. mintfig/_explain/change.py +392 -0
  4. mintfig/_explain/compare.py +1308 -0
  5. mintfig/_explain/compare_grouped.py +472 -0
  6. mintfig/_explain/core.py +2005 -0
  7. mintfig/_explain/distribution.py +1268 -0
  8. mintfig/_explain/flow.py +508 -0
  9. mintfig/_explain/layout.py +2012 -0
  10. mintfig/_explain/matrix.py +623 -0
  11. mintfig/_explain/relate.py +1318 -0
  12. mintfig/_explain/timeline.py +595 -0
  13. mintfig/_explain/trend.py +2557 -0
  14. mintfig/_explain/waterfall.py +459 -0
  15. mintfig/_table.py +691 -0
  16. mintfig/_tabular.py +738 -0
  17. mintfig/annotations.py +1165 -0
  18. mintfig/assets/AGENTS_SNIPPET.md +11 -0
  19. mintfig/assets/SKILL.md +143 -0
  20. mintfig/assets/__init__.py +1 -0
  21. mintfig/assets/references/publication.md +79 -0
  22. mintfig/assets/references/scientific_and_recipes.md +213 -0
  23. mintfig/audit.py +179 -0
  24. mintfig/brief.py +518 -0
  25. mintfig/bundle.py +333 -0
  26. mintfig/cli.py +1300 -0
  27. mintfig/edit.py +347 -0
  28. mintfig/epistemic.py +1083 -0
  29. mintfig/explainer.py +194 -0
  30. mintfig/export.py +247 -0
  31. mintfig/inspect_data.py +583 -0
  32. mintfig/interactive.py +1028 -0
  33. mintfig/palettes.py +233 -0
  34. mintfig/plate.py +784 -0
  35. mintfig/preflight.py +2398 -0
  36. mintfig/proof.py +627 -0
  37. mintfig/runner.py +403 -0
  38. mintfig/skill.py +167 -0
  39. mintfig/specs.py +291 -0
  40. mintfig/style.py +151 -0
  41. mintfig/terminal.py +785 -0
  42. mintfig/themes.py +660 -0
  43. mintfig-0.2.0.dist-info/METADATA +239 -0
  44. mintfig-0.2.0.dist-info/RECORD +47 -0
  45. mintfig-0.2.0.dist-info/WHEEL +4 -0
  46. mintfig-0.2.0.dist-info/entry_points.txt +2 -0
  47. mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,2005 @@
1
+ """Core constants, formatting, glyph handling, argument guards, and Panel primitives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import contextvars
7
+ import difflib
8
+ import functools
9
+ import inspect
10
+ import itertools
11
+ import math
12
+ import numbers
13
+ import re
14
+ import unicodedata
15
+ from collections.abc import Callable, Iterator, Mapping, Sequence
16
+ from dataclasses import dataclass, field
17
+ from datetime import date, datetime, timezone
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+ from matplotlib import dates as mdates
22
+ from matplotlib import patheffects
23
+ from matplotlib.axes import Axes
24
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
25
+ from matplotlib.colors import to_rgb
26
+ from matplotlib.figure import Figure
27
+ from matplotlib.font_manager import FontProperties
28
+ from matplotlib.ticker import (
29
+ FixedLocator,
30
+ FuncFormatter,
31
+ LogLocator,
32
+ MaxNLocator,
33
+ NullFormatter,
34
+ NullLocator,
35
+ )
36
+ from matplotlib.transforms import Bbox
37
+
38
+ from ..specs import JournalSpec
39
+ from ..themes import (
40
+ MINTFIG_THEME,
41
+ Theme,
42
+ contrast_ratio,
43
+ relative_luminance,
44
+ )
45
+
46
+ # --------------------------------------------------------------------------- #
47
+ # House constants (sourced from the default theme for backwards compatibility)
48
+ # --------------------------------------------------------------------------- #
49
+
50
+ INK = MINTFIG_THEME.ink
51
+ MUTED = MINTFIG_THEME.muted
52
+ AXIS = MINTFIG_THEME.axis
53
+ GRID = MINTFIG_THEME.grid
54
+ CONTEXT_LINE = MINTFIG_THEME.context_line
55
+ CONTEXT_FILL = MINTFIG_THEME.context_fill
56
+ # Fixed categorical order (blue, vermilion, teal, amber), never cycled past four.
57
+ # Every pair is separated in hue under deuteranopia/protanopia *and* in
58
+ # lightness, so the lines stay distinct in a grayscale print.
59
+ SERIES_COLORS: tuple[str, ...] = MINTFIG_THEME.series_colors
60
+ # Highlights lead with the warm accent so the focus pops against grey context.
61
+ ACCENT_COLORS: tuple[str, ...] = MINTFIG_THEME.accent_colors
62
+ DEFAULT_COLOR = MINTFIG_THEME.default_color
63
+
64
+ MAX_HIGHLIGHTS = 3
65
+ MAX_COLORED_SERIES = 4
66
+ MAX_PANELS = 6
67
+ COMFORTABLE_PANELS = 4
68
+ MAX_COMPARE_ITEMS = 20
69
+ COMFORTABLE_COMPARE_ITEMS = 12
70
+ MAX_GROUPS = 8
71
+ MAX_TITLE_LINES = 3
72
+ MAX_FACETS = 12
73
+ MAX_CHANGE_ITEMS = 14
74
+ MAX_MATRIX_ROWS = 16
75
+ MAX_MATRIX_COLS = 12
76
+
77
+ #: Width, in CSS pixels, at which chat clients typically show an inline image.
78
+ DISPLAY_WIDTH_PX = 700
79
+ #: Smallest text height (px at display width) still comfortable to read.
80
+ MIN_TEXT_PX = 11.0
81
+
82
+ PT_TO_MM = 25.4 / 72.0
83
+ _MARGIN_MM = 4.0
84
+ _COL_GAP_MM = 8.0
85
+ _ROW_GAP_MM = 6.5
86
+ _LINE = 1.26 # line height as a multiple of font size
87
+
88
+ _ISO_DATE = re.compile(r"^\d{4}-\d{2}(-\d{2})?([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?$")
89
+ _TOPIC_TITLE = re.compile(
90
+ r"^(overview|comparison|analysis|summary|results|plot|chart|figure|graph|breakdown)\b"
91
+ r"|\b(vs\.?|versus)\b",
92
+ re.IGNORECASE,
93
+ )
94
+ _HAS_DIGIT = re.compile(r"\d")
95
+
96
+ KINDS: tuple[str, ...] = (
97
+ "compare",
98
+ "trend",
99
+ "change",
100
+ "distribution",
101
+ "relate",
102
+ "share",
103
+ "matrix",
104
+ "table",
105
+ "waterfall",
106
+ "timeline",
107
+ "flow",
108
+ )
109
+
110
+
111
+ class ExplainError(ValueError):
112
+ """A rule the figure must satisfy was violated; ``fix_hint`` says how to repair it."""
113
+
114
+ def __init__(self, message: str, *, fix_hint: str, rule: str = "explain_spec") -> None:
115
+ super().__init__(f"{message} Fix: {fix_hint}")
116
+ self.message = message
117
+ self.fix_hint = fix_hint
118
+ self.rule = rule
119
+
120
+
121
+ # --------------------------------------------------------------------------- #
122
+ # Small helpers
123
+ # --------------------------------------------------------------------------- #
124
+
125
+
126
+ _ILLUSTRATIVE_CUE = re.compile(
127
+ r"\b(synthetic|illustrative|sketch|concept|conceptual|example|hypothetical|"
128
+ r"estimate|estimated|schematic|stylized|toy|mock|demo|approximate|approx)\b",
129
+ re.IGNORECASE,
130
+ )
131
+
132
+
133
+ #: An ASCII hyphen used as a sign: at the start, or after a space or one of
134
+ #: ( [ = : ^ , /, and before a digit ("-3 °C", "Δ = -0.4", "10^-3"). Dates
135
+ #: ("2026-01-31"), ranges ("43-53 nm") and words ("1C-rate") keep their hyphen.
136
+ _SIGN_HYPHEN = re.compile(r"(?<![^\s(\[=:^,/])-(?=\d)")
137
+
138
+
139
+ def _minus_signs(text: str) -> str:
140
+ """Caller text with sign hyphens drawn as a true minus ("−3 °C")."""
141
+ return _SIGN_HYPHEN.sub("\N{MINUS SIGN}", text)
142
+
143
+
144
+ def _plain(text: object, theme: Theme | None = None) -> str:
145
+ """Escape ``$`` so user text is never parsed as mathtext ("from $5M to $8M").
146
+
147
+ An ASCII hyphen used as a sign becomes a minus (:func:`_minus_signs`).
148
+ When ``theme`` defines ASCII glyph substitutes (e.g. ``sketch``), replaces
149
+ Unicode minus, en-dash, and ellipsis on the rendered text artist.
150
+ """
151
+ out = _minus_signs(str(text)).replace(r"\$", "$").replace("$", r"\$")
152
+ if theme is not None:
153
+ if theme.minus_sign != "\N{MINUS SIGN}":
154
+ out = _ascii_sci(out).replace("\N{MINUS SIGN}", theme.minus_sign)
155
+ if theme.en_dash != "\N{EN DASH}":
156
+ out = out.replace("\N{EN DASH}", theme.en_dash)
157
+ if theme.ellipsis != "\N{HORIZONTAL ELLIPSIS}":
158
+ out = out.replace("\N{HORIZONTAL ELLIPSIS}", theme.ellipsis)
159
+ return _glyphs(out, ascii_only=theme is not None and theme.minus_sign == "-")
160
+
161
+
162
+ # --------------------------------------------------------------------------- #
163
+ # Scientific symbols: draw-time normalisation and missing-glyph detection
164
+ # --------------------------------------------------------------------------- #
165
+
166
+ _SUPER_CHARS = "⁰¹²³⁴⁵⁶⁷⁸⁹⁻⁺⁼⁽⁾ⁿⁱ"
167
+ _SUB_CHARS = "₀₁₂₃₄₅₆₇₈₉₋₊₌₍₎ₐₑₒₓₕₖₗₘₙₚₛₜ"
168
+ _SUPER_PLAIN = str.maketrans(_SUPER_CHARS, "0123456789-+=()ni")
169
+ _SUB_PLAIN = str.maketrans(_SUB_CHARS, "0123456789-+=()aeoxhklmnpst")
170
+ _SCRIPT_RUN = re.compile(f"([{_SUPER_CHARS}]+)|([{_SUB_CHARS}]+)")
171
+ #: Look-alikes that system fonts draw wrongly: Helvetica's MICRO SIGN is a slanted
172
+ #: italic mu, while its GREEK SMALL LETTER MU is upright like the surrounding text.
173
+ _GLYPH_SWAPS = str.maketrans({"\N{MICRO SIGN}": "\N{GREEK SMALL LETTER MU}"})
174
+ _MATH_WRAPPER = re.compile(r"\\math(?:regular|rm)\{|[{}^_$]|\\")
175
+
176
+
177
+ def _script(run: str, table: dict[int, int]) -> str:
178
+ """A super/subscript run as upright body-font text ("{-}" keeps a sign unspaced)."""
179
+ plain = run.translate(table)
180
+ return r"\mathregular{" + "".join("{" + c + "}" if c in "-+=" else c for c in plain) + "}"
181
+
182
+
183
+ @functools.lru_cache(maxsize=64)
184
+ def _charmap(path: str) -> frozenset[int]:
185
+ from matplotlib.font_manager import get_font
186
+
187
+ try:
188
+ return frozenset(get_font(path).get_charmap())
189
+ except (OSError, RuntimeError, ValueError):
190
+ return frozenset()
191
+
192
+
193
+ @functools.lru_cache(maxsize=64)
194
+ def _coverage_for(
195
+ families: tuple[str, ...], weight: Any, style: str, rc_key: tuple[Any, ...]
196
+ ) -> frozenset[int]:
197
+ from matplotlib import font_manager
198
+
199
+ prop = FontProperties(family=list(families), weight=weight, style=style)
200
+ covered: set[int] = set()
201
+ for path in font_manager.fontManager._find_fonts_by_props(prop):
202
+ covered |= _charmap(str(path))
203
+ return frozenset(covered)
204
+
205
+
206
+ def _coverage(prop: FontProperties) -> frozenset[int]:
207
+ """Code points the font fallback chain of ``prop`` can draw (under the active rcParams)."""
208
+ import matplotlib as mpl
209
+
210
+ rc_key = tuple(tuple(mpl.rcParams[k]) for k in ("font.sans-serif", "font.serif", "font.family"))
211
+ return _coverage_for(tuple(prop.get_family()), prop.get_weight(), prop.get_style(), rc_key)
212
+
213
+
214
+ def _body_coverage() -> frozenset[int]:
215
+ """What the body font itself (no fallback) can draw."""
216
+ return _coverage(FontProperties(family=["sans-serif"]))
217
+
218
+
219
+ def _glyphs(text: str, *, ascii_only: bool = False) -> str:
220
+ """Draw-time symbol normalisation for already-escaped text.
221
+
222
+ * MICRO SIGN -> Greek mu (upright in every body font).
223
+ * A run of Unicode superscripts or subscripts ("×10¹⁷", "cm⁻³", "H₂O") is drawn
224
+ as one mathtext script in the body font, so the run has one size, weight and
225
+ baseline (fonts mix Latin-1 ¹²³ with the superscript block, often from
226
+ different faces). ASCII-glyph styles write superscripts as "^-3" instead.
227
+ * Inside such a string, characters the body font lacks are wrapped in
228
+ ``\\mathrm{}`` so mathtext's fallback font draws them (non-math text in a
229
+ mathtext string has no fallback of its own).
230
+ """
231
+ out = text.translate(_GLYPH_SWAPS)
232
+ if not _SCRIPT_RUN.search(out):
233
+ return out
234
+
235
+ def _sub(m: re.Match[str]) -> str:
236
+ if m.group(1):
237
+ if ascii_only:
238
+ return "^" + m.group(1).translate(_SUPER_PLAIN)
239
+ return "$^{" + _script(m.group(1), _SUPER_PLAIN) + "}$"
240
+ return "$_{" + _script(m.group(2), _SUB_PLAIN) + "}$"
241
+
242
+ pieces = _SCRIPT_RUN.split(out)
243
+ has_math = any(
244
+ (i % 3 == 2 and p) or (i % 3 == 1 and p and not ascii_only) for i, p in enumerate(pieces)
245
+ )
246
+ if not has_math:
247
+ return _SCRIPT_RUN.sub(_sub, out)
248
+ body = _body_coverage()
249
+ rebuilt: list[str] = []
250
+ for i, piece in enumerate(pieces):
251
+ if piece is None or piece == "":
252
+ continue
253
+ kind = i % 3
254
+ if kind == 0:
255
+ rebuilt.append(
256
+ "".join(
257
+ c if (ord(c) in body or c.isspace() or not body) else "$\\mathrm{" + c + "}$"
258
+ for c in piece
259
+ )
260
+ )
261
+ else:
262
+ rebuilt.append(_SCRIPT_RUN.sub(_sub, piece))
263
+ return "".join(rebuilt)
264
+
265
+
266
+ _TO_SUPER = {plain: sup for sup, plain in zip(_SUPER_CHARS, "0123456789-+=()ni", strict=True)}
267
+ _TO_SUB = {plain: sub for sub, plain in zip(_SUB_CHARS, "0123456789-+=()aeoxhklmnpst", strict=True)}
268
+ _DRAWN_SCRIPT = re.compile(r"\$([\^_])\{\\mathregular\{(.*?)\}\}\$")
269
+ _DRAWN_FALLBACK = re.compile(r"\$\\mathrm\{(.)\}\$")
270
+
271
+
272
+ def _reader_text(text: str) -> str:
273
+ """Inverse of :func:`_plain` for drawn text: what the reader sees, as Unicode."""
274
+
275
+ def _back(m: re.Match[str]) -> str:
276
+ table = _TO_SUPER if m.group(1) == "^" else _TO_SUB
277
+ return "".join(table.get(c, c) for c in m.group(2).replace("{", "").replace("}", ""))
278
+
279
+ out = _DRAWN_FALLBACK.sub(lambda m: m.group(1), _DRAWN_SCRIPT.sub(_back, text))
280
+ return out.replace(r"\$", "$")
281
+
282
+
283
+ def _logical_text(text: str) -> str:
284
+ """The characters a reader sees, with mintfig's mathtext wrappers removed."""
285
+ from matplotlib import cbook
286
+
287
+ if not cbook.is_math_text(text):
288
+ return text
289
+ return _MATH_WRAPPER.sub("", text.replace(r"\$", "\x00")).replace("\x00", "$")
290
+
291
+
292
+ def _missing_glyphs(fig: Figure) -> dict[str, str]:
293
+ """Characters of visible text that no font in the artist's fallback chain can draw."""
294
+ from matplotlib import cbook
295
+ from matplotlib.text import Text
296
+
297
+ missing: dict[str, str] = {}
298
+ stix: frozenset[int] | None = None
299
+ for artist in fig.findobj(Text):
300
+ raw = artist.get_text()
301
+ if not artist.get_visible() or not raw.strip():
302
+ continue
303
+ covered = _coverage(artist.get_fontproperties())
304
+ if cbook.is_math_text(raw):
305
+ if stix is None:
306
+ stix = _coverage(FontProperties(family=["STIXGeneral", "DejaVu Sans"]))
307
+ covered = covered | stix
308
+ for ch in _logical_text(raw):
309
+ if ch.isspace() or unicodedata.category(ch).startswith("C"):
310
+ continue
311
+ if ord(ch) not in covered and ch not in missing:
312
+ missing[ch] = raw
313
+ return missing
314
+
315
+
316
+ class _GlyphCapture:
317
+ """Collect Matplotlib's missing-glyph warnings (and mathtext's log lines) instead of
318
+ letting them reach stderr, where the agent never sees them."""
319
+
320
+ _WARNING = re.compile(r"Glyph (\d+)")
321
+ _LOG = re.compile(r"\[U\+([0-9a-fA-F]+)\]")
322
+
323
+ def __init__(self) -> None:
324
+ self.chars: set[str] = set()
325
+ self._warnings: Any = None
326
+ self._records: list[Any] = []
327
+ self._others: list[Any] = []
328
+
329
+ def _filter(self, record: Any) -> bool:
330
+ match = self._LOG.search(record.getMessage())
331
+ if match and "glyph" in record.getMessage():
332
+ self.chars.add(chr(int(match.group(1), 16)))
333
+ return False
334
+ return True
335
+
336
+ def __enter__(self) -> Any:
337
+ import logging
338
+ import warnings
339
+
340
+ self._warnings = warnings.catch_warnings(record=True)
341
+ self._records = self._warnings.__enter__()
342
+ warnings.simplefilter("always")
343
+ logging.getLogger("matplotlib.mathtext").addFilter(self._filter)
344
+ logging.getLogger("matplotlib._mathtext").addFilter(self._filter)
345
+ return self
346
+
347
+ def __exit__(self, *exc: object) -> None:
348
+ import logging
349
+ import warnings
350
+
351
+ logging.getLogger("matplotlib.mathtext").removeFilter(self._filter)
352
+ logging.getLogger("matplotlib._mathtext").removeFilter(self._filter)
353
+ self.missing()
354
+ others = list(self._others)
355
+ self._warnings.__exit__(*exc)
356
+ for w in others: # not ours to swallow
357
+ warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
358
+
359
+ def missing(self) -> set[str]:
360
+ """Characters reported missing so far (warnings are consumed as they are read)."""
361
+ while self._records:
362
+ w = self._records.pop(0)
363
+ match = self._WARNING.search(str(w.message))
364
+ if match and "missing from" in str(w.message):
365
+ self.chars.add(chr(int(match.group(1))))
366
+ else:
367
+ self._others.append(w)
368
+ return set(self.chars)
369
+
370
+
371
+ def _glyph_issue(chars: Mapping[str, str] | set[str]) -> dict[str, Any]:
372
+ listed = sorted(chars)
373
+ named = ", ".join(
374
+ f"{ch!r} (U+{ord(ch):04X} {unicodedata.name(ch, 'unnamed').lower()})" for ch in listed[:6]
375
+ )
376
+ return _issue(
377
+ "glyph_missing",
378
+ "warning",
379
+ f"{len(listed)} character(s) cannot be drawn in this style's fonts and show as empty "
380
+ f"boxes: {named}.",
381
+ "Replace each with a plain-text equivalent (e.g. 'hbar' for ℏ, 'deg' for a missing "
382
+ "degree sign, a Latin name for a symbol), or use a character from the same Unicode "
383
+ "block that the figure already draws.",
384
+ )
385
+
386
+
387
+ _FROM_SUPERSCRIPT = str.maketrans("⁰¹²³⁴⁵⁶⁷⁸⁹⁻⁺", "0123456789-+")
388
+ _SCI_SUPERSCRIPT = re.compile("\N{MULTIPLICATION SIGN}10([⁻⁺]?[⁰¹²³⁴⁵⁶⁷⁸⁹]+)")
389
+
390
+
391
+ def _ascii_sci(text: str) -> str:
392
+ """For ASCII-glyph styles: "1.3×10⁻⁷" -> "1.3x10^-7" and "4.0×" -> "4.0x"."""
393
+ out = _SCI_SUPERSCRIPT.sub(lambda m: "x10^" + m.group(1).translate(_FROM_SUPERSCRIPT), text)
394
+ return out.replace("\N{MULTIPLICATION SIGN}", "x")
395
+
396
+
397
+ def _issue(
398
+ rule: str,
399
+ severity: str,
400
+ message: str,
401
+ fix_hint: str,
402
+ *,
403
+ panel: str | None = None,
404
+ ) -> dict[str, Any]:
405
+ return {
406
+ "rule": rule,
407
+ "severity": severity,
408
+ "panel": panel,
409
+ "message": message,
410
+ "fix_hint": fix_hint,
411
+ }
412
+
413
+
414
+ def _is_number(value: object) -> bool:
415
+ if isinstance(value, (bool, np.bool_)):
416
+ return False
417
+ if isinstance(value, (numbers.Real, np.integer, np.floating)):
418
+ return True
419
+ # 0-d numpy arrays (e.g. ``arr.sum(keepdims=False)`` from some libraries)
420
+ return isinstance(value, np.ndarray) and value.ndim == 0 and value.dtype.kind in "iuf"
421
+
422
+
423
+ def _to_float(value: object, what: str) -> float:
424
+ if value is None:
425
+ return float("nan")
426
+ if not _is_number(value):
427
+ raise ExplainError(
428
+ f"{what} must be a number, got {value!r}.",
429
+ fix_hint="Pass plain numbers (not strings); convert or drop missing values first.",
430
+ )
431
+ return float(value) # type: ignore[arg-type]
432
+
433
+
434
+ def _has_items(obj: object) -> bool:
435
+ """Mapping-like: a dict, a dict view owner, a pandas Series or DataFrame (duck typed)."""
436
+ return (
437
+ not isinstance(obj, (str, bytes))
438
+ and callable(getattr(obj, "items", None))
439
+ and not isinstance(obj, np.ndarray)
440
+ )
441
+
442
+
443
+ def _is_one_dimensional(obj: object) -> bool:
444
+ """A pandas Series (or similar) is a sequence of values even though it has ``.items()``."""
445
+ return getattr(obj, "ndim", None) == 1 and not isinstance(obj, Mapping)
446
+
447
+
448
+ def _pairs(obj: object) -> list[tuple[Any, Any]]:
449
+ return list(obj.items()) # type: ignore[attr-defined]
450
+
451
+
452
+ #: Issues that indicate a real visual or legibility defect (as opposed to advisory polish).
453
+ _VISUAL_DEFECT_RULES: frozenset[str] = frozenset(
454
+ {
455
+ "text_overlaps",
456
+ "text_struck_by_line",
457
+ "text_malformed",
458
+ "canvas_clipping",
459
+ "line_past_axis",
460
+ "glyph_missing",
461
+ "latex_markup",
462
+ "event_label_collides",
463
+ "reference_label_collides",
464
+ "value_label_on_reference",
465
+ "text_on_data",
466
+ "small_at_chat_size",
467
+ }
468
+ )
469
+
470
+ _STRICT: contextvars.ContextVar[bool] = contextvars.ContextVar("mintfig_strict", default=True)
471
+ _ADJUSTMENTS: contextvars.ContextVar[list[str] | None] = contextvars.ContextVar(
472
+ "mintfig_adjustments", default=None
473
+ )
474
+
475
+
476
+ def _is_strict() -> bool:
477
+ return _STRICT.get()
478
+
479
+
480
+ def _record_adjustment(message: str) -> None:
481
+ log = _ADJUSTMENTS.get()
482
+ if log is not None and message not in log:
483
+ log.append(message)
484
+
485
+
486
+ @contextlib.contextmanager
487
+ def lenient() -> Iterator[None]:
488
+ """Non-strict context for fast chat figures: auto-adjusts soft limits instead of raising.
489
+
490
+ Inside ``with mint.lenient():`` (or when passing ``strict=False`` to :func:`explain`),
491
+ mintfig auto-facets >4 trend series, trims oversized lists/highlights, drops missing
492
+ entries, stacks cramped side-by-side panels into full-width rows, and separates minor
493
+ advisory warnings from real visual defects so an agent can ship a good-enough figure
494
+ on the first try. Every adjustment is recorded in ``summary["adjustments"]``.
495
+ """
496
+ tok_s = _STRICT.set(False)
497
+ existing = _ADJUSTMENTS.get()
498
+ tok_a = _ADJUSTMENTS.set([] if existing is None else existing)
499
+ try:
500
+ yield
501
+ finally:
502
+ _STRICT.reset(tok_s)
503
+ _ADJUSTMENTS.reset(tok_a)
504
+
505
+
506
+ def _named_values(values: object, what: str, *, allow_nan: bool = False) -> dict[str, float]:
507
+ """Normalise a mapping or a sequence of ``(name, value)`` pairs to ``{name: float}``.
508
+
509
+ Anything with ``.items()`` (a dict, a pandas Series) counts as a mapping.
510
+ """
511
+ if _has_items(values):
512
+ items = _pairs(values)
513
+ elif isinstance(values, Sequence) and not isinstance(values, (str, bytes)):
514
+ from .._tabular import is_row_records
515
+
516
+ if is_row_records(values):
517
+ cols = list(dict.fromkeys(str(k) for row in values for k in row))
518
+ shown = ", ".join(repr(c) for c in cols[:8])
519
+ raise ExplainError(
520
+ f"{what} received row-shaped dicts (columns: {shown}) instead of a name -> number mapping.",
521
+ fix_hint=(
522
+ f'Pass name="...", value="..." (e.g. name="{cols[0]}", value="{cols[-1]}") '
523
+ "or convert to a dict {row[name]: row[value]}."
524
+ ),
525
+ )
526
+ try:
527
+ items = [(pair[0], pair[1]) for pair in values]
528
+ except (TypeError, IndexError, KeyError) as exc:
529
+ raise ExplainError(
530
+ f"{what} must be a mapping of name -> number.",
531
+ fix_hint='Pass a dict such as {"checkout": 1840, "search": 460}.',
532
+ ) from exc
533
+ else:
534
+ raise ExplainError(
535
+ f"{what} must be a mapping of name -> number, got {type(values).__name__}.",
536
+ fix_hint='Pass a dict such as {"checkout": 1840, "search": 460}.',
537
+ )
538
+ out: dict[str, float] = {}
539
+ dropped_nan: list[str] = []
540
+ for name, value in items:
541
+ key = str(name)
542
+ if getattr(value, "ndim", 0) >= 1: # a DataFrame column, a list
543
+ raise ExplainError(
544
+ f"{what}[{key!r}] is a column of values, not one number.",
545
+ fix_hint="Pass one number per name: a dict or a pandas Series (index = names), "
546
+ 'e.g. df["p99"] or df.median(); for raw observations per group use distribution().',
547
+ )
548
+ if key in out:
549
+ raise ExplainError(
550
+ f"{what} repeats the name {key!r}.",
551
+ fix_hint="Give every item a unique name (aggregate duplicates first).",
552
+ )
553
+ number = _to_float(value, f"{what}[{key!r}]")
554
+ if not math.isfinite(number) and not allow_nan:
555
+ if not _is_strict():
556
+ dropped_nan.append(key)
557
+ continue
558
+ raise ExplainError(
559
+ f"{what}[{key!r}] is not finite ({value!r}).",
560
+ fix_hint="Drop or impute missing values before plotting, and say so in `note`.",
561
+ )
562
+ out[key] = number
563
+ if dropped_nan and out:
564
+ _record_adjustment(f"{what}: dropped non-finite item(s) {dropped_nan[:4]!r}")
565
+ if not out:
566
+ raise ExplainError(f"{what} is empty.", fix_hint="Pass at least one named value.")
567
+ return out
568
+
569
+
570
+ def _names(highlight: object, valid: Sequence[str], what: str = "highlight") -> list[str]:
571
+ if highlight is None:
572
+ return []
573
+ names = [highlight] if isinstance(highlight, str) else [str(h) for h in highlight] # type: ignore[union-attr]
574
+ unknown = [n for n in names if n not in valid]
575
+ if unknown:
576
+ if not _is_strict():
577
+ names = [n for n in names if n in valid]
578
+ _record_adjustment(f"{what}: ignored unknown name(s) {unknown[:4]!r}")
579
+ else:
580
+ raise ExplainError(
581
+ f"{what} names {unknown!r} that are not in the data.",
582
+ fix_hint=f"Use names from: {', '.join(map(repr, list(valid)[:12]))}.",
583
+ )
584
+ if len(names) > MAX_HIGHLIGHTS:
585
+ if not _is_strict():
586
+ _record_adjustment(
587
+ f"{what}: trimmed {len(names)} highlights to first {MAX_HIGHLIGHTS}"
588
+ )
589
+ names = names[:MAX_HIGHLIGHTS]
590
+ else:
591
+ raise ExplainError(
592
+ f"{what} lists {len(names)} items; more than {MAX_HIGHLIGHTS} highlights nothing.",
593
+ fix_hint=f"At most {MAX_HIGHLIGHTS} highlights: name only the items the takeaway "
594
+ "sentence names (the rest stay as grey context), or split the claim across two "
595
+ "panels with up to 3 highlights each.",
596
+ rule="too_many_highlights",
597
+ )
598
+ return names
599
+
600
+
601
+ # --------------------------------------------------------------------------- #
602
+ # Argument checking shared by every form (unknown keywords -> ExplainError)
603
+ # --------------------------------------------------------------------------- #
604
+
605
+ #: Valid keyword arguments of each guarded callable, filled in by ``_guarded``.
606
+ _FORM_ARGS: dict[str, tuple[str, ...]] = {}
607
+ _EXPLAIN_ARGS = (
608
+ "subtitle",
609
+ "source",
610
+ "note",
611
+ "layout",
612
+ "target",
613
+ "width",
614
+ "style",
615
+ "palette",
616
+ "colors",
617
+ "strict",
618
+ "out",
619
+ )
620
+ _LOG_X_WORDS = {"x_scale", "xscale", "x_log", "logx", "log_x", "xlog", "log_scale_x"}
621
+ _LOG_Y_WORDS = {
622
+ "y_scale",
623
+ "yscale",
624
+ "y_log",
625
+ "logy",
626
+ "log_y",
627
+ "ylog",
628
+ "log_scale",
629
+ "logscale",
630
+ "log_axis",
631
+ "log",
632
+ }
633
+ _INTERVAL_WORDS = {
634
+ "errors",
635
+ "err",
636
+ "yerr",
637
+ "xerr",
638
+ "error_bars",
639
+ "errorbars",
640
+ "ci",
641
+ "ci95",
642
+ "std",
643
+ "sd",
644
+ "sem",
645
+ "stderr",
646
+ "uncertainty",
647
+ "interval",
648
+ "intervals",
649
+ "error",
650
+ "band",
651
+ "bands",
652
+ "spread",
653
+ }
654
+ _COLOUR_WORDS = {"color", "colour", "colors", "colours", "palette", "cmap", "colormap", "hue"}
655
+ _END_VALUE_WORDS = {
656
+ "end_values",
657
+ "end_value",
658
+ "end_labels",
659
+ "end_label",
660
+ "show_values",
661
+ "show_value",
662
+ "label_values",
663
+ "values_at_end",
664
+ "show_end_values",
665
+ "value_labels",
666
+ }
667
+ _ORDER_WORDS = {"sort", "order", "sorted", "sort_by", "ascending", "descending"}
668
+
669
+
670
+ def _specific_hint(kind: str, name: str, valid: Sequence[str]) -> str | None:
671
+ """A hint for a keyword a scientist plausibly tries that this form does not take."""
672
+ if kind != "explain" and name in _EXPLAIN_ARGS:
673
+ return (
674
+ f"`{name}=` belongs on mint.explain(...), not on a panel: "
675
+ f"mint.explain(takeaway, mint.{kind}(...), {name}=...)."
676
+ )
677
+ if kind == "explain" and name in {"title", "label", "unit", "highlight", "fmt"}:
678
+ return f"`{name}=` belongs on a panel, e.g. mint.compare({{...}}, {name}=...)."
679
+ if name in _COLOUR_WORDS:
680
+ return (
681
+ "Colours are assigned by rule, not chosen: name the 1-3 things the takeaway is "
682
+ "about in highlight= and everything else turns grey. A name keeps one colour "
683
+ "across panels; to keep it across figures pin it on the figure: "
684
+ 'mint.explain(..., colors={"name": "red"}) (slots: blue, red, green, amber).'
685
+ )
686
+ if name in {"legend", "show_legend", "legend_loc"}:
687
+ return "There are no legends: names are written on the data."
688
+ if name in _LOG_X_WORDS:
689
+ if "log_x" in valid:
690
+ return "Use log_x=True for a logarithmic x axis."
691
+ if "log" in valid:
692
+ return f"{kind}() has one value axis; use log=True to make it logarithmic."
693
+ if name in _LOG_Y_WORDS:
694
+ if kind == "relate":
695
+ return "Use log_y=True (and/or log_x=True) for logarithmic axes."
696
+ if "log" in valid:
697
+ return "Use log=True for a logarithmic value axis."
698
+ if name in _INTERVAL_WORDS:
699
+ if "error" in valid:
700
+ return (
701
+ "Use error= with (low, high) bounds or one half-width per item (or one "
702
+ 'number for all), plus error_label="95% CI".'
703
+ )
704
+ if "band" in valid:
705
+ return (
706
+ "Use band= with (low_values, high_values) or half-widths per series, plus "
707
+ 'band_label="95% CI"; raw replicates go in points=.'
708
+ )
709
+ return "Intervals are drawn by compare(error=...) and trend(band=...)."
710
+ if name in _END_VALUE_WORDS and "end_values" in valid:
711
+ return "Use end_values=False to keep the name at the line end but drop the value."
712
+ if name in _ORDER_WORDS and "sort" not in valid:
713
+ if kind == "share":
714
+ return "share() always sorts parts largest first (part-of-whole reads by rank)."
715
+ return f"{kind}() keeps the order you give: reorder the input (dicts keep insertion order)."
716
+ if name in {"xlabel", "x_axis_label", "xaxis_label"} and "x_label" in valid:
717
+ return "Use x_label=."
718
+ if name in {"ylabel", "y_axis_label", "yaxis_label"}:
719
+ if "y_label" in valid:
720
+ return "Use y_label=."
721
+ if "label" in valid:
722
+ return 'Name the measure with label= and its unit with unit=, e.g. label="Yield", unit="%".'
723
+ if name in {"units"} and "unit" in valid:
724
+ return "Use unit= (singular)."
725
+ if name in {"labels", "name", "names"} and kind in {"compare", "share"}:
726
+ return "Did you mean label=? Item names are the keys of the values mapping; label= names the measure."
727
+ return None
728
+
729
+
730
+ def _unknown_argument(kind: str, name: str, valid: Sequence[str]) -> ExplainError:
731
+ hint = _specific_hint(kind, name, valid)
732
+ if hint is None:
733
+ elsewhere = [form for form, args in _FORM_ARGS.items() if form != kind and name in args]
734
+ close = difflib.get_close_matches(name, valid, n=1, cutoff=0.6)
735
+ if close:
736
+ hint = f"Did you mean {close[0]}=?"
737
+ elif elsewhere:
738
+ hint = f"`{name}=` is an argument of {', '.join(f + '()' for f in elsewhere)}, not {kind}()."
739
+ else:
740
+ hint = f"{kind}() has no `{name}` argument."
741
+ listed = ", ".join(valid)
742
+ return ExplainError(
743
+ f"{kind}() got an unexpected keyword argument {name!r}.",
744
+ fix_hint=f"{hint} Valid arguments of {kind}(): {listed}.",
745
+ rule="unknown_argument",
746
+ )
747
+
748
+
749
+ def _guarded(kind: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
750
+ """Turn unknown or mis-passed arguments into an ExplainError naming the valid ones."""
751
+
752
+ def deco(fn: Callable[..., Any]) -> Callable[..., Any]:
753
+ sig = inspect.signature(fn)
754
+ valid = tuple(
755
+ p.name
756
+ for p in sig.parameters.values()
757
+ if p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
758
+ )
759
+ positional = [
760
+ p.name
761
+ for p in sig.parameters.values()
762
+ if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and p.default is p.empty
763
+ ]
764
+ _FORM_ARGS[kind] = valid
765
+
766
+ @functools.wraps(fn)
767
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
768
+ for name in kwargs:
769
+ if name not in valid:
770
+ raise _unknown_argument(kind, name, valid)
771
+ try:
772
+ sig.bind(*args, **kwargs)
773
+ except TypeError as exc:
774
+ shown = ", ".join(positional) or "..."
775
+ raise ExplainError(
776
+ f"{kind}(): {exc}.",
777
+ fix_hint=f"Call it as mint.{kind}({shown}, keyword=...); every option after "
778
+ f"the data is a keyword. Valid arguments: {', '.join(valid)}.",
779
+ rule="unknown_argument",
780
+ ) from exc
781
+ return fn(*args, **kwargs)
782
+
783
+ return wrapper
784
+
785
+ return deco
786
+
787
+
788
+ _CURRENCY_UNITS = frozenset({"$", "\N{EURO SIGN}", "\N{POUND SIGN}", "\N{YEN SIGN}"})
789
+ _SUPERSCRIPT = str.maketrans("0123456789-+", "⁰¹²³⁴⁵⁶⁷⁸⁹⁻⁺")
790
+ #: Magnitudes at or above this are written in scientific notation (any unit).
791
+ _SCI_LARGE = 1e12
792
+ #: With a physical unit (not a currency) plain numbers stop here.
793
+ _SCI_LARGE_PHYSICAL = 1e6
794
+ #: A set whose magnitudes are all below this is written in scientific notation.
795
+ _SCI_SMALL = 1e-3
796
+ _FMT_HINT = (
797
+ 'Pass fmt as a format spec such as ".2f", ".1%" or ".3g", or as a template such as '
798
+ '"{:.2f}" or "{:,.0f} ms".'
799
+ )
800
+
801
+
802
+ def _shows_zero(text: str) -> bool:
803
+ """True when a formatted number has no non-zero digit (so it reads as zero)."""
804
+ mantissa = text.split("\N{MULTIPLICATION SIGN}10", 1)[0]
805
+ return not any(ch in "123456789" for ch in mantissa)
806
+
807
+
808
+ def _clean_sign(text: str) -> str:
809
+ """Unicode minus, and never a signed zero ("−0.0" becomes "0.0")."""
810
+ if _shows_zero(text):
811
+ text = text.replace("-", "").replace("+", "").replace("\N{MINUS SIGN}", "")
812
+ return text.replace("-", "\N{MINUS SIGN}")
813
+
814
+
815
+ def _sci_text(v: float, digits: int = 3, *, pad: bool = False) -> str:
816
+ """``1.3×10⁻⁷``: real multiplication sign and Unicode superscripts, ``digits`` s.f.
817
+
818
+ ``pad=True`` keeps trailing zeros ("1.20×10¹⁶") so every label of a set shows
819
+ the same number of significant figures.
820
+ """
821
+ if v == 0 or not math.isfinite(v):
822
+ return "0" if v == 0 else "\N{EN DASH}"
823
+ mantissa, exponent = f"{v:.{max(0, digits - 1)}e}".split("e")
824
+ if "." in mantissa and not pad:
825
+ mantissa = mantissa.rstrip("0").rstrip(".")
826
+ exp = int(exponent)
827
+ if exp == 0:
828
+ return _clean_sign(mantissa)
829
+ return _clean_sign(f"{mantissa}\N{MULTIPLICATION SIGN}10{str(exp).translate(_SUPERSCRIPT)}")
830
+
831
+
832
+ def _sig_text(
833
+ v: float, digits: int = 3, *, large: float = _SCI_LARGE, pad: bool = False
834
+ ) -> str:
835
+ """One value to its own ``digits`` significant figures (scientific when extreme;
836
+ ``pad`` keeps a scientific mantissa's trailing zeros)."""
837
+ if not math.isfinite(v):
838
+ return "\N{EN DASH}"
839
+ if v == 0:
840
+ return "0"
841
+ mag = abs(v)
842
+ if mag < _SCI_SMALL or mag >= large:
843
+ return _sci_text(v, digits, pad=pad)
844
+ decimals = max(0, digits - 1 - math.floor(math.log10(mag)))
845
+ text = f"{v:,.{decimals}f}"
846
+ if "." in text:
847
+ text = text.rstrip("0").rstrip(".")
848
+ return _clean_sign(text)
849
+
850
+
851
+ def _check_fmt(fmt: object) -> str | None:
852
+ """Validate ``fmt=``: a format spec (".2f") or a template ("{:.2f}"); returns a template."""
853
+ if fmt is None:
854
+ return None
855
+ if not isinstance(fmt, str) or not fmt.strip():
856
+ raise ExplainError(
857
+ f"fmt={fmt!r} cannot format a number (an empty fmt would blank every label and fact).",
858
+ fix_hint=_FMT_HINT + " Omit fmt for automatic formatting.",
859
+ rule="bad_fmt",
860
+ )
861
+ template = fmt if "{" in fmt else "{:" + fmt + "}"
862
+ try:
863
+ sample = template.format(1.2345)
864
+ template.format(-12345.678)
865
+ except (ValueError, TypeError, KeyError, IndexError, AttributeError) as exc:
866
+ raise ExplainError(
867
+ f"fmt={fmt!r} is not a usable number format ({exc}).",
868
+ fix_hint=_FMT_HINT,
869
+ rule="bad_fmt",
870
+ ) from exc
871
+ if not any(ch.isdigit() for ch in sample):
872
+ raise ExplainError(
873
+ f"fmt={fmt!r} does not print the number.",
874
+ fix_hint=_FMT_HINT,
875
+ rule="bad_fmt",
876
+ )
877
+ return template
878
+
879
+
880
+ def _formatter(
881
+ values: Sequence[float],
882
+ fmt: str | None = None,
883
+ *,
884
+ unit: str | None = None,
885
+ log: bool = False,
886
+ suffix: bool | None = None,
887
+ ) -> Callable[[float], str]:
888
+ """Number formatter for one set of values. A non-zero value never reads as zero.
889
+
890
+ * About three significant figures, with the same decimals across the set when
891
+ it spans less than three orders of magnitude ("1,840", "0.74", "12.5").
892
+ * Scientific notation ("1.3×10⁻⁷") when the largest magnitude is >= 1e12, when
893
+ every magnitude is < 1e-3, or above 1e6 with a physical (non-currency) unit.
894
+ "M"/"B" suffixes are kept only without a unit or with a currency.
895
+ * Sets spanning >= 3 orders of magnitude, and log axes, give each value its
896
+ own three significant figures. On a log axis (``log=True``), when any value
897
+ needs scientific notation, every value uses it.
898
+ * ``fmt`` (spec ".2f" or template "{:.2f}") overrides all of this, except that a
899
+ non-zero value it would print as zero falls back to its own significant figures.
900
+ """
901
+ template = _check_fmt(fmt)
902
+ allow_suffix = (unit is None or unit in _CURRENCY_UNITS) if suffix is None else suffix
903
+ large = _SCI_LARGE if allow_suffix else _SCI_LARGE_PHYSICAL
904
+ finite = [abs(float(v)) for v in values if math.isfinite(float(v))]
905
+ mags = [v for v in finite if v > 0]
906
+ top = max(mags, default=0.0)
907
+ small = min(mags, default=0.0)
908
+
909
+ if template is not None:
910
+
911
+ def _custom(v: float) -> str:
912
+ if not math.isfinite(v):
913
+ return "\N{EN DASH}"
914
+ text = template.format(v)
915
+ if v != 0 and _shows_zero(text):
916
+ return _sig_text(v, large=large)
917
+ return _clean_sign(text)
918
+
919
+ return _custom
920
+
921
+ if not mags:
922
+ return lambda v: "\N{EN DASH}" if not math.isfinite(v) else "0"
923
+
924
+ # Scientific labels of one set show one number of significant figures (the most
925
+ # any of them needs, at most 3): "1.20×10¹⁶" beside "3.89×10¹⁷", not "1.2×10¹⁶".
926
+ def _sci_digits(shown: Sequence[float]) -> int:
927
+ need = [
928
+ len(re.sub(r"\D", "", _sci_text(v).split("\N{MULTIPLICATION SIGN}")[0]))
929
+ for v in shown
930
+ if v > 0
931
+ ]
932
+ return max(need, default=3)
933
+
934
+ if log and (small < _SCI_SMALL or top >= large):
935
+ # On a log axis one notation per set: "5.93×10⁻⁶" beside "0.00634" reads as
936
+ # two kinds of number, so once any value needs scientific notation all use it.
937
+ d_all = _sci_digits(mags)
938
+ return lambda v: _sci_text(v, d_all, pad=True) if math.isfinite(v) else "\N{EN DASH}"
939
+ if log or top / small >= 1e3:
940
+ d_sci = _sci_digits([v for v in mags if v < _SCI_SMALL or v >= large])
941
+
942
+ def _mixed(v: float) -> str:
943
+ if math.isfinite(v) and v != 0 and (abs(v) < _SCI_SMALL or abs(v) >= large):
944
+ return _sci_text(v, d_sci, pad=True)
945
+ return _sig_text(v, large=large)
946
+
947
+ return _mixed
948
+ if top >= large or top < _SCI_SMALL:
949
+ d_all = _sci_digits(mags)
950
+ return lambda v: _sci_text(v, d_all, pad=True) if math.isfinite(v) else "\N{EN DASH}"
951
+
952
+ if allow_suffix and top >= 1e9:
953
+ scale, suffix_text = 1e9, "B"
954
+ elif allow_suffix and top >= 1e6:
955
+ scale, suffix_text = 1e6, "M"
956
+ else:
957
+ scale, suffix_text = 1.0, ""
958
+ scaled = [v / scale for v in finite]
959
+ top_s = top / scale
960
+ if top_s >= 100 or all(abs(v - round(v)) < 1e-9 for v in scaled):
961
+ decimals = 0
962
+ elif top_s >= 10:
963
+ decimals = 1
964
+ elif top_s >= 1:
965
+ decimals = 2
966
+ else:
967
+ decimals = max(2, 2 - math.floor(math.log10(top_s)))
968
+ while decimals > 0 and all(
969
+ abs(round(v, decimals - 1) - v) < 0.5 * 10 ** (-decimals - 2) for v in scaled
970
+ ):
971
+ decimals -= 1
972
+
973
+ def _format(v: float) -> str:
974
+ if not math.isfinite(v):
975
+ return "\N{EN DASH}"
976
+ text = f"{v / scale:,.{decimals}f}"
977
+ if v != 0 and _shows_zero(text):
978
+ return _sig_text(v, large=large)
979
+ return _clean_sign(text) + suffix_text
980
+
981
+ return _format
982
+
983
+
984
+ def _tick_text(v: float, minus: str = "\N{MINUS SIGN}", axis: Any = None) -> str:
985
+ """Axis tick label: plain ``,.10g`` for ordinary numbers, scientific when extreme."""
986
+ if axis is not None and v != 0 and axis.get_scale() == "linear":
987
+ lo, hi = axis.get_view_interval()
988
+ if abs(v) < 1e-9 * abs(hi - lo):
989
+ v = 0.0 # floating-point noise of a tick at zero
990
+ if v != 0 and math.isfinite(v) and (abs(v) < _SCI_SMALL or abs(v) >= _SCI_LARGE):
991
+ return _sci_text(v).replace("\N{MINUS SIGN}", minus)
992
+ return f"{v:,.10g}".replace("-", minus)
993
+
994
+
995
+ def _tick_label(v: float, minus: str = "\N{MINUS SIGN}", axis: Any = None) -> str:
996
+ """What a tick shows: :func:`_tick_text` with the style's glyphs ("1.3x10^-7" in ASCII
997
+ styles) and super/subscripts drawn in the body font."""
998
+ ascii_only = minus != "\N{MINUS SIGN}"
999
+ text = _tick_text(v, "\N{MINUS SIGN}", axis)
1000
+ if ascii_only:
1001
+ text = _ascii_sci(text).replace("\N{MINUS SIGN}", minus)
1002
+ return _glyphs(text, ascii_only=ascii_only)
1003
+
1004
+
1005
+ def _narrow_log_ticks(
1006
+ axis: Any,
1007
+ lo: float,
1008
+ hi: float,
1009
+ minus: str = "\N{MINUS SIGN}",
1010
+ *,
1011
+ max_ticks: int = 6,
1012
+ extend: bool = True,
1013
+ data_hi: float | None = None,
1014
+ ) -> tuple[float, float]:
1015
+ """Ticks and labels for a log axis; returns the (possibly widened) limits to set.
1016
+
1017
+ * Under ~1.5 decades: 1-2-5 ticks (a decade locator would show one label).
1018
+ * Otherwise decades, thinned to at most ``max_ticks`` counting down from the top,
1019
+ so the largest values always sit under or just above a labelled tick; when the
1020
+ data reach more than half a decade past the top labelled decade (and ``extend``),
1021
+ the axis grows to the next decade and labels it.
1022
+ * ``data_hi`` (the largest observation) marks a value axis: it then always gets
1023
+ at least two labelled ticks and one at or above ``data_hi``, widening the
1024
+ returned limits as needed.
1025
+ * Labels are text in the body font: plain numbers between 0.01 and 10,000,
1026
+ otherwise "10⁻⁸" (super/subscripts drawn as one run; "10^-8" in ASCII styles).
1027
+ """
1028
+ ascii_only = minus != "\N{MINUS SIGN}"
1029
+ lo = lo if lo > 0 else hi / 10.0
1030
+ if hi / lo < 10**1.5 and data_hi is not None:
1031
+ k0, k1 = math.floor(math.log10(lo)) - 1, math.ceil(math.log10(hi)) + 1
1032
+ cands = [m * 10.0**k for k in range(k0, k1 + 1) for m in (1.0, 2.0, 5.0)]
1033
+ top_tick = min(c for c in cands if c >= data_hi * (1 - 1e-9))
1034
+ hi = max(hi, top_tick)
1035
+ ticks = [c for c in cands if lo * (1 - 1e-9) <= c <= hi * (1 + 1e-9)]
1036
+ if len(ticks) < 2:
1037
+ below = max(c for c in cands if c < ticks[0])
1038
+ lo = min(lo, below)
1039
+ ticks = [below, *ticks]
1040
+ axis.set_major_locator(FixedLocator(ticks))
1041
+ elif hi / lo < 10**1.5:
1042
+ axis.set_major_locator(LogLocator(base=10.0, subs=(1.0, 2.0, 5.0)))
1043
+ else:
1044
+ bottom = math.ceil(math.log10(lo) - 1e-9)
1045
+ top = math.floor(math.log10(hi) + 1e-9)
1046
+ if data_hi is not None and 10.0**top < data_hi * (1 - 1e-9):
1047
+ top = math.ceil(math.log10(data_hi) - 1e-9)
1048
+ hi = max(hi, 10.0**top)
1049
+ elif extend and math.log10(hi) - top > 0.5:
1050
+ top += 1
1051
+ hi = 10.0**top
1052
+ count = top - bottom + 1
1053
+ stride = max(1, math.ceil(count / max(2, max_ticks)))
1054
+ decades = list(range(top, bottom - 1, -stride))[::-1]
1055
+ axis.set_major_locator(FixedLocator([10.0**d for d in decades]))
1056
+ plain = lo >= 0.0099 and hi <= 10_001
1057
+
1058
+ def _label(v: float, _p: Any) -> str:
1059
+ if v <= 0 or not math.isfinite(v):
1060
+ return ""
1061
+ exp = math.log10(v)
1062
+ if not plain and abs(exp - round(exp)) < 1e-9:
1063
+ power = str(round(exp))
1064
+ text = f"10^{power}" if ascii_only else "10" + power.translate(_SUPERSCRIPT)
1065
+ return _glyphs(text, ascii_only=ascii_only)
1066
+ return _tick_label(v, minus)
1067
+
1068
+ axis.set_major_formatter(FuncFormatter(_label))
1069
+ axis.set_minor_formatter(NullFormatter())
1070
+ # No minor ticks on chat-figure log axes. Matplotlib's default decides from the
1071
+ # axis length, so two side-by-side panels a few points apart in width would
1072
+ # differ (one with 2..9 ticks, one without); the labelled decades say "log".
1073
+ axis.set_minor_locator(NullLocator())
1074
+ return lo, hi
1075
+
1076
+
1077
+ def _ratio_text(ratio: float) -> str:
1078
+ """A ratio to 3 significant figures: 4.0×, 62×, 1,200×, 63,900× (from unrounded values)."""
1079
+ if ratio >= 1000 and ratio < _SCI_LARGE:
1080
+ rounded = round(ratio, 2 - math.floor(math.log10(ratio)))
1081
+ return f"{rounded:,.0f}\N{MULTIPLICATION SIGN}"
1082
+ if ratio >= 100:
1083
+ return f"{_sig_text(ratio)}\N{MULTIPLICATION SIGN}"
1084
+ if ratio >= 10:
1085
+ return f"{ratio:.0f}\N{MULTIPLICATION SIGN}"
1086
+ if 0 < ratio < 1: # "0.72×": a fraction keeps two significant figures
1087
+ decimals = 1 - math.floor(math.log10(ratio))
1088
+ return f"{ratio:.{decimals}f}\N{MULTIPLICATION SIGN}"
1089
+ return f"{ratio:.1f}\N{MULTIPLICATION SIGN}"
1090
+
1091
+
1092
+ def _has_unit(text: str, unit: str) -> bool:
1093
+ """True when ``text`` already carries ``unit`` (a ``fmt`` such as "{:+.0f}%").
1094
+
1095
+ A trailing unit counts only at a word boundary: "12 ms" does not end with "s".
1096
+ A currency counts anywhere ("$12", "−$0.10").
1097
+ """
1098
+ u = unit.strip()
1099
+ if not u:
1100
+ return False
1101
+ t = text.strip()
1102
+ if u in _CURRENCY_UNITS:
1103
+ return u in t
1104
+ if not t.endswith(u) or len(t) == len(u):
1105
+ return False
1106
+ return not (u[0].isalpha() and t[: -len(u)][-1:].isalpha())
1107
+
1108
+
1109
+ def _with_unit(text: str, unit: str | None) -> str:
1110
+ if not unit:
1111
+ return text
1112
+ if _has_unit(text, unit): # fmt already wrote it: never "−28%%"
1113
+ return text
1114
+ if unit in {"$", "\N{EURO SIGN}", "\N{POUND SIGN}"}:
1115
+ if text.startswith(("\N{MINUS SIGN}", "+")): # the sign leads: "−$0.10", "+$0.50"
1116
+ return f"{text[0]}{unit}{text[1:]}"
1117
+ return f"{unit}{text}"
1118
+ if unit in {"%", "\N{MULTIPLICATION SIGN}", "x", "\N{DEGREE SIGN}"} or unit.startswith("%"):
1119
+ return f"{text}{unit}"
1120
+ return f"{text} {unit}"
1121
+
1122
+
1123
+ def _range_with_unit(lo: str, hi: str, unit: str | None) -> str:
1124
+ """A range with its unit once at the end ("32\N{EN DASH}52%", "12\N{EN DASH}15 ms"), or on
1125
+ both ends for a currency, which leads its number ("$1.20\N{EN DASH}$1.50"). When either bound
1126
+ is negative, use " to " ("−1.7 to −1.1%") rather than colliding a dash and a minus sign."""
1127
+ sep = (
1128
+ " to "
1129
+ if (lo.startswith(("\N{MINUS SIGN}", "-")) or hi.startswith(("\N{MINUS SIGN}", "-")))
1130
+ else "\N{EN DASH}"
1131
+ )
1132
+ if unit in _CURRENCY_UNITS:
1133
+ return f"{_with_unit(lo, unit)}{sep}{_with_unit(hi, unit)}"
1134
+ return f"{lo}{sep}{_with_unit(hi, unit)}"
1135
+
1136
+
1137
+ def _inline_unit(unit: str | None) -> bool:
1138
+ """Short units that belong on every value label, not just the first."""
1139
+ return unit in {"%", "$", "\N{EURO SIGN}", "\N{POUND SIGN}", "\N{MULTIPLICATION SIGN}", "x"}
1140
+
1141
+
1142
+ _FOLD_UNITS = {"\N{MULTIPLICATION SIGN}", "x", "fold", "-fold", "fold change", "fold-change"}
1143
+
1144
+
1145
+ def _fold_unit(unit: str | None, label: str | None, positive_log: bool) -> bool:
1146
+ """True when the values are raw ratios: unit "×"/"x"/"fold", or (on a log axis of
1147
+ positive values, with no unit) a label naming a fold change that is not log-transformed."""
1148
+ if isinstance(unit, str) and unit.strip().lower() in _FOLD_UNITS:
1149
+ return True
1150
+ return (
1151
+ unit is None
1152
+ and positive_log
1153
+ and bool(label)
1154
+ and re.search(r"\bfold\b", str(label), re.IGNORECASE) is not None
1155
+ and re.search(r"\blog", str(label), re.IGNORECASE) is None
1156
+ )
1157
+
1158
+
1159
+ def _long_unit_issue(unit: object) -> dict[str, Any] | None:
1160
+ """Warn when ``unit=`` is words, not a symbol: it is printed after every value."""
1161
+ if not isinstance(unit, str):
1162
+ return None
1163
+ u = unit.strip()
1164
+ if len(u.split()) <= 2 and len(u) <= 16:
1165
+ return None
1166
+ return _issue(
1167
+ "unit_is_long",
1168
+ "warning",
1169
+ f"unit={unit!r} is words, and the unit is printed after every value in the facts "
1170
+ "and labels.",
1171
+ "Put the words in label= and keep unit= a symbol (ms, %, mg/L).",
1172
+ )
1173
+
1174
+
1175
+ def _measure_text(label: str | None, unit: str | None) -> str | None:
1176
+ if label and unit:
1177
+ if re.search(rf"[(\[]\s*{re.escape(unit.strip())}\s*[)\]]\s*$", label):
1178
+ return label # the label already ends with its unit: "Yield (MPa)"
1179
+ return f"{label} ({unit})"
1180
+ return label or unit or None
1181
+
1182
+
1183
+ def _relative_luminance(color: str) -> float:
1184
+ return relative_luminance(color)
1185
+
1186
+
1187
+ def _contrast_on_white(color: str) -> float:
1188
+ return contrast_ratio(color, "#FFFFFF")
1189
+
1190
+
1191
+ def _text_color(
1192
+ color: str,
1193
+ *,
1194
+ minimum: float = 4.5,
1195
+ background: str = "#FFFFFF",
1196
+ ink: str = INK,
1197
+ ) -> str:
1198
+ """Darken a series colour toward ink until it is legible as small text on ``background``."""
1199
+ rgb = np.array(to_rgb(color))
1200
+ ink_rgb = np.array(to_rgb(ink))
1201
+ for mix in (0.0, 0.15, 0.3, 0.45, 0.6, 0.8, 1.0):
1202
+ blended = rgb * (1 - mix) + ink_rgb * mix
1203
+ candidate = "#{:02X}{:02X}{:02X}".format(*(round(c * 255) for c in blended))
1204
+ if contrast_ratio(candidate, background) >= minimum:
1205
+ return candidate
1206
+ return ink
1207
+
1208
+
1209
+ def _percent_change(first: float, last: float, *, precise: bool = False) -> str | None:
1210
+ """"+46%"; with ``precise``, changes under 10% keep one decimal ("+2.9%", "\N{MINUS SIGN}0.4%")."""
1211
+ if first == 0 or not math.isfinite(first) or not math.isfinite(last):
1212
+ return None
1213
+ pct = (last - first) / abs(first) * 100.0
1214
+ sign = "+" if pct >= 0 else "\N{MINUS SIGN}"
1215
+ if precise and abs(pct) < 9.95:
1216
+ return f"{sign}{abs(pct):.1f}%"
1217
+ return f"{sign}{abs(pct):.0f}%"
1218
+
1219
+
1220
+ def _signed(text: str) -> str:
1221
+ """Prefix "+" to a formatted non-negative, non-zero difference."""
1222
+ if text.startswith(("\N{MINUS SIGN}", "+")) or _shows_zero(text):
1223
+ return text
1224
+ return "+" + text
1225
+
1226
+
1227
+ def _unsigned(text: str) -> str:
1228
+ """A width or gap from a possibly signed ``fmt`` ("+26%"): no leading "+"."""
1229
+ return text.strip().removeprefix("+")
1230
+
1231
+
1232
+ def _diff_with_unit(text: str, unit: str | None) -> str:
1233
+ """A difference: in points when the unit is "%" (a percent of a percent misleads)."""
1234
+ if unit is not None and unit.strip().startswith("%"):
1235
+ if _has_unit(text, unit): # fmt="{:+.0f}%": the difference is still in points
1236
+ text = text.strip()[: -len(unit.strip())].rstrip()
1237
+ bare = text.lstrip("+\N{MINUS SIGN}")
1238
+ return f"{text} {'point' if bare == '1' else 'points'}"
1239
+ return _with_unit(text, unit)
1240
+
1241
+
1242
+ def _relative_text(value: float, base: float, unit: str | None) -> str | None:
1243
+ """``value`` relative to ``base``: a ratio for "%" units ("0.58×"), else a percent change.
1244
+
1245
+ None when the relation is meaningless: a zero or non-finite base, or a sign change.
1246
+ """
1247
+ if not (math.isfinite(value) and math.isfinite(base)) or base == 0:
1248
+ return None
1249
+ if unit is not None and unit.strip().startswith("%"):
1250
+ return _ratio_text(value / base) if value > 0 and base > 0 else None
1251
+ if (value < 0 < base) or (base < 0 < value):
1252
+ return None
1253
+ return _percent_change(base, value, precise=True)
1254
+
1255
+
1256
+ def _vs_text(
1257
+ value: float,
1258
+ base: float,
1259
+ *,
1260
+ unit: str | None,
1261
+ diff_fmt: Callable[[float], str],
1262
+ log: bool = False,
1263
+ relative: bool = True,
1264
+ ) -> str:
1265
+ """``value`` against a baseline: "+12 ms (+46%)", "−33 points (0.58×)", or "4.7×" on a log axis.
1266
+
1267
+ ``relative=False`` (zero is not meaningful, e.g. wavelengths) keeps only the difference.
1268
+ """
1269
+ if log:
1270
+ return _ratio_text(value / base)
1271
+ text = _diff_with_unit(_signed(diff_fmt(value - base)), unit)
1272
+ rel = _relative_text(value, base, unit) if relative else None
1273
+ return f"{text} ({rel})" if rel else text
1274
+
1275
+
1276
+ def _baseline_name(
1277
+ baseline: object, names: Sequence[str], highlight: Sequence[str], kind: str
1278
+ ) -> str | None:
1279
+ """Check ``baseline=``: one item name, not also highlighted."""
1280
+ if baseline is None:
1281
+ return None
1282
+ if not isinstance(baseline, (str, numbers.Number)) or isinstance(baseline, bool):
1283
+ raise ExplainError(
1284
+ f"{kind}(baseline=...) must be one item name, got {type(baseline).__name__}.",
1285
+ fix_hint='Pass the reference item\'s name, e.g. baseline="control" or '
1286
+ 'baseline="before".',
1287
+ )
1288
+ name = str(baseline)
1289
+ if name not in names:
1290
+ if not _is_strict():
1291
+ _record_adjustment(f"{kind}(baseline={name!r}): ignored (not in items)")
1292
+ return None
1293
+ raise ExplainError(
1294
+ f"{kind}(baseline={name!r}) is not one of the items.",
1295
+ fix_hint=f"Use one of: {', '.join(map(repr, list(names)[:12]))}.",
1296
+ )
1297
+ if name in highlight:
1298
+ if not _is_strict() and isinstance(highlight, list):
1299
+ highlight.remove(name)
1300
+ _record_adjustment(f"{kind}: kept baseline {name!r} in ink instead of highlight")
1301
+ else:
1302
+ raise ExplainError(
1303
+ f"{kind}(baseline={name!r}) is also in highlight.",
1304
+ fix_hint="The baseline is the reference, drawn in ink; highlight only the items "
1305
+ f"compared against it, e.g. highlight=[...] without {name!r}.",
1306
+ )
1307
+ if len(names) < 2:
1308
+ if not _is_strict():
1309
+ return None
1310
+ raise ExplainError(
1311
+ f"{kind}(baseline=...) needs at least one other item to compare with it.",
1312
+ fix_hint="Drop baseline=, or add the items to compare.",
1313
+ )
1314
+ return name
1315
+
1316
+
1317
+ def _change_text(
1318
+ first: float,
1319
+ last: float,
1320
+ *,
1321
+ series_range: float,
1322
+ unit: str | None,
1323
+ diff_fmt: Callable[[float], str],
1324
+ log: bool = False,
1325
+ ) -> str | None:
1326
+ """How a series moved, in the terms that are meaningful for it.
1327
+
1328
+ * Log axis: fold change ("rises 2.3-fold", "falls 7,900-fold, 3.9 decades").
1329
+ * Unit "%": the difference in points ("+94 points"), never a percent of a percent.
1330
+ * Otherwise a percent change, omitted when the baseline is within ~5% of the
1331
+ series' range from zero or the sign changes (both make the percent meaningless).
1332
+ """
1333
+ if not (math.isfinite(first) and math.isfinite(last)):
1334
+ return None
1335
+ if log:
1336
+ if first <= 0 or last <= 0:
1337
+ return None
1338
+ decades = math.log10(last / first)
1339
+ word = "rises" if decades > 0 else "falls"
1340
+ fold = 10 ** abs(decades)
1341
+ if fold < 1.005:
1342
+ return "unchanged"
1343
+ # One wording for every series in a panel: the fold, plus decades once >= 1.
1344
+ text = f"{word} {_ratio_text(fold).rstrip(chr(0xD7))}-fold"
1345
+ return text + (f", {abs(decades):.1f} decades" if abs(decades) >= 1 else "")
1346
+ if unit is not None and unit.strip().startswith("%"):
1347
+ return _diff_with_unit(_signed(diff_fmt(last - first)), unit)
1348
+ if first == 0 or (first < 0 < last) or (last < 0 < first):
1349
+ return None
1350
+ if abs(first) <= 0.05 * series_range:
1351
+ return None
1352
+ return _percent_change(first, last)
1353
+
1354
+
1355
+ # --------------------------------------------------------------------------- #
1356
+ # Typography and drawing context
1357
+ # --------------------------------------------------------------------------- #
1358
+
1359
+
1360
+ @dataclass(frozen=True)
1361
+ class _Sizes:
1362
+ """Type scale derived from the target spec (points)."""
1363
+
1364
+ scale: float
1365
+ title: float
1366
+ body: float
1367
+ small: float
1368
+ foot: float
1369
+
1370
+ @classmethod
1371
+ def from_spec(cls, spec: JournalSpec, theme: Theme = MINTFIG_THEME) -> _Sizes:
1372
+ return cls(
1373
+ scale=spec.body_pt / 8.5,
1374
+ title=min(spec.font_max_pt, round(spec.body_pt * theme.title_scale)),
1375
+ body=spec.body_pt,
1376
+ small=spec.tick_pt,
1377
+ foot=max(spec.font_min_pt, spec.tick_pt - 0.5),
1378
+ )
1379
+
1380
+
1381
+ class _Measure:
1382
+ """Measure and wrap text with the active rcParams font.
1383
+
1384
+ Measured at 720 dpi and scaled back to points: small pixel sizes hit
1385
+ embedded bitmap strikes in some system fonts (Helvetica.ttc), which FreeType
1386
+ cannot load.
1387
+ """
1388
+
1389
+ _DPI = 720
1390
+
1391
+ def __init__(self, theme: Theme | None = None) -> None:
1392
+ self._renderer = FigureCanvasAgg(Figure(figsize=(1, 1), dpi=self._DPI)).get_renderer()
1393
+ self.theme = theme
1394
+
1395
+ def width_pt(
1396
+ self,
1397
+ text: str,
1398
+ size: float,
1399
+ weight: str = "normal",
1400
+ family: Sequence[str] | str | None = None,
1401
+ ) -> float:
1402
+ if not text:
1403
+ return 0.0
1404
+ if family is None:
1405
+ prop = FontProperties(size=size, weight=weight)
1406
+ else:
1407
+ fam = list(family) if not isinstance(family, str) else family
1408
+ prop = FontProperties(family=fam, size=size, weight=weight)
1409
+ # Measure exactly what is drawn: the same symbol normalisation and, for
1410
+ # super/subscript runs, the same mathtext layout.
1411
+ from matplotlib import cbook
1412
+
1413
+ shown = _plain(text, self.theme)
1414
+ ismath = bool(cbook.is_math_text(shown))
1415
+ if not ismath:
1416
+ shown = shown.replace(r"\$", "$")
1417
+ width, _, _ = self._renderer.get_text_width_height_descent(shown, prop, ismath=ismath)
1418
+ return float(width) * 72.0 / self._DPI
1419
+
1420
+ def wrap(
1421
+ self,
1422
+ text: str,
1423
+ max_pt: float,
1424
+ size: float,
1425
+ weight: str = "normal",
1426
+ family: Sequence[str] | str | None = None,
1427
+ ) -> list[str]:
1428
+ lines: list[str] = []
1429
+ for paragraph in str(text).splitlines() or [""]:
1430
+ current = ""
1431
+ for word in paragraph.split():
1432
+ trial = f"{current} {word}".strip()
1433
+ if current and self.width_pt(trial, size, weight, family) > max_pt:
1434
+ lines.append(current)
1435
+ current = word
1436
+ else:
1437
+ current = trial
1438
+ lines.append(current)
1439
+ return lines
1440
+
1441
+
1442
+ @dataclass
1443
+ class _Ctx:
1444
+ """What a panel needs while drawing."""
1445
+
1446
+ fig: Figure
1447
+ sizes: _Sizes
1448
+ key: str
1449
+ cell_width_mm: float
1450
+ measure: _Measure
1451
+ theme: Theme = MINTFIG_THEME
1452
+ measure_label: str | None = None
1453
+ extra_axes: list[Axes] = field(default_factory=list)
1454
+ finishers: list[Callable[[], None]] = field(default_factory=list)
1455
+ issues: list[dict[str, Any]] = field(default_factory=list)
1456
+ #: Figure-level colour of each name this panel colours (from ``_colour_registry``).
1457
+ colors: dict[str, str] = field(default_factory=dict)
1458
+ #: Colour of a panel that colours its items uniformly (None: the theme default).
1459
+ uniform_color: str | None = None
1460
+
1461
+ @property
1462
+ def default_color(self) -> str:
1463
+ return self.uniform_color or self.theme.default_color
1464
+
1465
+ @property
1466
+ def pt_per_px(self) -> float:
1467
+ return 72.0 / float(self.fig.dpi)
1468
+
1469
+ def tag(self, ax: Axes) -> Axes:
1470
+ ax._mintfig_panel_key = self.key # type: ignore[attr-defined]
1471
+ ax._mintfig_measure_label = self.measure_label # type: ignore[attr-defined]
1472
+ return ax
1473
+
1474
+ def text_color(self, color: str, *, minimum: float = 4.5) -> str:
1475
+ return _text_color(
1476
+ color,
1477
+ minimum=minimum,
1478
+ background=self.theme.background,
1479
+ ink=self.theme.ink,
1480
+ )
1481
+
1482
+ def halo_bbox(self, pad: float = 0.1, alpha: float | None = None) -> dict[str, Any]:
1483
+ return {
1484
+ "boxstyle": f"square,pad={pad}",
1485
+ "facecolor": self.theme.background,
1486
+ "edgecolor": "none",
1487
+ "alpha": self.theme.halo_alpha if alpha is None else alpha,
1488
+ }
1489
+
1490
+ def line_effects(self) -> list[Any] | None:
1491
+ if self.theme.stroke_outline_pt <= 0.0:
1492
+ return None
1493
+ return [
1494
+ patheffects.withStroke(
1495
+ linewidth=self.theme.stroke_outline_pt * self.sizes.scale,
1496
+ foreground=self.theme.background,
1497
+ )
1498
+ ]
1499
+
1500
+
1501
+ @dataclass
1502
+ class Panel:
1503
+ """One piece of evidence: a form chosen by the question it answers."""
1504
+
1505
+ kind: str
1506
+ title: str | None
1507
+ label: str | None
1508
+ unit: str | None
1509
+ spec: dict[str, Any]
1510
+ facts: list[str]
1511
+ describe: str
1512
+ _height_mm: Callable[[float, _Measure, _Sizes, Theme], float]
1513
+ _draw: Callable[[_Ctx, Axes], Callable[[], None] | None]
1514
+ issues: list[dict[str, Any]] = field(default_factory=list)
1515
+ _frames: Callable[[_Ctx, Axes, Bbox], list[tuple[Axes, Bbox]]] | None = None
1516
+ #: Line and scatter panels grow to fill their row; bar-like panels keep their pitch.
1517
+ stretch: bool = False
1518
+ #: Appended to the measure line under the headline (what an interval means, log scale).
1519
+ measure_note: str | None = None
1520
+ #: Colour identity (see ``_colour_registry``): every name this panel could colour,
1521
+ #: the names it emphasises (highlighted, or coloured by default such as trend series),
1522
+ #: and how it colours: "highlight", "series", "uniform" (one default colour) or "none".
1523
+ color_items: tuple[str, ...] = ()
1524
+ color_focus: tuple[str, ...] = ()
1525
+ color_mode: str = "none"
1526
+ #: True when, with no figure entity among its items, the panel draws in the default colour.
1527
+ uses_default: bool = False
1528
+ #: The reference item (``baseline=``): drawn in ink, never given a palette colour.
1529
+ color_baseline: str | None = None
1530
+ #: The smallest plot height (mm at scale 1, same arguments as ``_height_mm``) at
1531
+ #: which the form still reads: a figure too tall for one screen is first
1532
+ #: compressed toward it. None: the natural height is the minimum.
1533
+ _min_height_mm: Callable[[float, _Measure, _Sizes, Theme], float] | None = None
1534
+ #: The facts the alt text reads out: every group or series the panel is about (or
1535
+ #: the highlighted ones plus the baseline), not just the first fact. None: facts[0].
1536
+ alt_facts: list[str] | None = None
1537
+
1538
+ def __post_init__(self) -> None:
1539
+ issue = _long_unit_issue(self.unit)
1540
+ if issue is not None and not any(i["rule"] == "unit_is_long" for i in self.issues):
1541
+ self.issues.append(issue)
1542
+
1543
+ def to_spec(self) -> dict[str, Any]:
1544
+ out: dict[str, Any] = {"kind": self.kind}
1545
+ out.update({k: _jsonable(v) for k, v in self.spec.items() if v is not None})
1546
+ return out
1547
+
1548
+ def to_markdown(self) -> str:
1549
+ """Return a formatted Markdown table for ``table`` panels (raises for other forms)."""
1550
+ md = getattr(self, "_markdown", None)
1551
+ if md is None:
1552
+ raise ExplainError(
1553
+ f"{self.kind}() panels do not have a Markdown table representation.",
1554
+ fix_hint="Use mint.table(...) to render or export a Markdown table.",
1555
+ )
1556
+ return str(md)
1557
+
1558
+
1559
+ def _jsonable(value: Any) -> Any:
1560
+ """Plain JSON types for a spec: numpy, pandas-like, dates, tuples, NaN -> None."""
1561
+ if value is None or isinstance(value, (str, bool)):
1562
+ return value
1563
+ if isinstance(value, np.bool_):
1564
+ return bool(value)
1565
+ if isinstance(value, (numbers.Integral, np.integer)):
1566
+ return int(value) # type: ignore[arg-type]
1567
+ if _is_number(value):
1568
+ number = float(value) # type: ignore[arg-type]
1569
+ return number if math.isfinite(number) else None
1570
+ if isinstance(value, datetime):
1571
+ if value.tzinfo is not None: # the spec's ISO dates are naive UTC (as drawn)
1572
+ value = value.astimezone(timezone.utc).replace(tzinfo=None)
1573
+ text = value.isoformat()
1574
+ return text[:10] if text[10:] in ("T00:00:00", "") else text
1575
+ if isinstance(value, date):
1576
+ return value.isoformat()
1577
+ if isinstance(value, np.datetime64):
1578
+ return str(np.datetime64(value, "s")).replace("T00:00:00", "")
1579
+ if _has_items(value):
1580
+ return {str(k): _jsonable(v) for k, v in _pairs(value)}
1581
+ if isinstance(value, np.ndarray):
1582
+ return [_jsonable(v) for v in value.tolist()]
1583
+ if isinstance(value, (list, tuple)) or (
1584
+ isinstance(value, Sequence) and not isinstance(value, (str, bytes))
1585
+ ):
1586
+ return [_jsonable(v) for v in value]
1587
+ if hasattr(value, "tolist"):
1588
+ return _jsonable(value.tolist())
1589
+ return str(value)
1590
+
1591
+
1592
+ def _base_spec(
1593
+ title: str | None, label: str | None, unit: str | None, **extra: Any
1594
+ ) -> dict[str, Any]:
1595
+ spec: dict[str, Any] = dict(extra)
1596
+ spec.update({"title": title, "label": label, "unit": unit})
1597
+ return spec
1598
+
1599
+
1600
+ def _bare_axes(ax: Axes) -> None:
1601
+ for spine in ax.spines.values():
1602
+ spine.set_visible(False)
1603
+ ax.set_facecolor("none")
1604
+
1605
+
1606
+ def _value_axis(
1607
+ ax: Axes,
1608
+ sizes: _Sizes,
1609
+ theme: Theme = MINTFIG_THEME,
1610
+ *,
1611
+ axis: str = "y",
1612
+ nbins: int = 4,
1613
+ ) -> None:
1614
+ """Quiet quantitative axis: themed gridlines, spines, and thousands-separated labels."""
1615
+ other = "x" if axis == "y" else "y"
1616
+ if theme.hide_spines:
1617
+ for spine in ax.spines.values():
1618
+ spine.set_visible(False)
1619
+ else:
1620
+ for name in ("top", "right", "left" if axis == "y" else "bottom"):
1621
+ ax.spines[name].set_visible(False)
1622
+ base = ax.spines["bottom" if axis == "y" else "left"]
1623
+ base.set_color(theme.axis)
1624
+ base.set_linewidth(theme.axis_lw)
1625
+ ax.tick_params(axis=axis, length=0, labelsize=sizes.small, labelcolor=theme.muted, pad=3)
1626
+ ax.tick_params(
1627
+ axis=other,
1628
+ length=theme.tick_length,
1629
+ width=theme.tick_width,
1630
+ color=theme.axis,
1631
+ labelsize=sizes.small,
1632
+ labelcolor=theme.muted,
1633
+ )
1634
+ if theme.grid_style != "none" and theme.grid_lw > 0:
1635
+ grid_axis = "both" if theme.grid_both_axes else axis
1636
+ ax.grid(
1637
+ axis=grid_axis,
1638
+ color=theme.grid,
1639
+ linestyle=theme.grid_style,
1640
+ linewidth=theme.grid_lw,
1641
+ )
1642
+ else:
1643
+ ax.grid(False)
1644
+ ax.set_axisbelow(True)
1645
+ target = ax.yaxis if axis == "y" else ax.xaxis
1646
+ minus = theme.minus_sign
1647
+ if target.get_scale() == "linear":
1648
+ target.set_major_locator(MaxNLocator(nbins=nbins, steps=[1, 2, 2.5, 5, 10]))
1649
+ target.set_major_formatter(
1650
+ FuncFormatter(lambda v, _pos, m=minus, a=target: _tick_label(v, m, a))
1651
+ )
1652
+
1653
+
1654
+ def _apply_inline_y_ticks(
1655
+ ax: Axes,
1656
+ sizes: _Sizes,
1657
+ theme: Theme,
1658
+ *,
1659
+ unit: str | None = None,
1660
+ ) -> None:
1661
+ """Editorial-style inline y-tick labels sitting directly above each horizontal gridline.
1662
+
1663
+ Hides the left-gutter y-tick labels, ensures headroom above the highest tick,
1664
+ and prints the unit on the topmost tick only.
1665
+ """
1666
+ y0, y1 = ax.get_ylim()
1667
+ span = (y1 - y0) or 1.0
1668
+ ticks = [float(t) for t in ax.yaxis.get_majorticklocs() if y0 + 0.01 * span <= t <= y1]
1669
+ if not ticks:
1670
+ return
1671
+ # Ensure room above the highest gridline so its inline label stays inside the axes.
1672
+ top_tick = ticks[-1]
1673
+ if y1 - top_tick < 0.14 * span:
1674
+ ax.set_ylim(y0, top_tick + 0.16 * span)
1675
+ y0, y1 = ax.get_ylim()
1676
+ span = (y1 - y0) or 1.0
1677
+ ticks = [float(t) for t in ax.yaxis.get_majorticklocs() if y0 + 0.01 * span <= t <= y1]
1678
+ if not ticks:
1679
+ return
1680
+ ax.tick_params(axis="y", labelleft=False)
1681
+ minus = theme.minus_sign
1682
+ inline: list[tuple[Any, bool]] = []
1683
+ ax._mintfig_inline_ticks = inline # type: ignore[attr-defined]
1684
+ for idx, tick in enumerate(ticks):
1685
+ raw = _tick_text(tick, minus, ax.yaxis)
1686
+ top = idx == len(ticks) - 1
1687
+ text = _with_unit(raw, unit) if (top and unit) else raw
1688
+ note = ax.annotate(
1689
+ _plain(text, theme),
1690
+ (0.0, tick),
1691
+ xycoords=("axes fraction", "data"),
1692
+ xytext=(0.0, 2.0),
1693
+ textcoords="offset points",
1694
+ ha="left",
1695
+ va="bottom",
1696
+ fontsize=sizes.small,
1697
+ color=theme.muted,
1698
+ zorder=3,
1699
+ bbox={
1700
+ "boxstyle": "square,pad=0.05",
1701
+ "facecolor": theme.background,
1702
+ "edgecolor": "none",
1703
+ "alpha": theme.halo_alpha,
1704
+ },
1705
+ )
1706
+ inline.append((note, top and bool(unit)))
1707
+
1708
+
1709
+ def _clear_inline_ticks(ctx: _Ctx, ax: Axes) -> None:
1710
+ """Keep inline y-tick labels off the data lines (runs after layout).
1711
+
1712
+ A label a data line passes through is dropped (its gridline still marks the
1713
+ value, and the labels above and below give the scale). The top label carries
1714
+ the unit, so it is kept and lifted above the lines on its halo instead.
1715
+ """
1716
+ inline = getattr(ax, "_mintfig_inline_ticks", None)
1717
+ if not inline:
1718
+ return
1719
+ renderer = ctx.fig.canvas.get_renderer()
1720
+ # Horizontal rules (reference, zero line) sit on a tick by design: not data.
1721
+ paths = [
1722
+ path
1723
+ for path in _data_paths(ax, [])
1724
+ if len(path.vertices) and np.ptp(path.vertices[:, 1]) > 0.5
1725
+ ]
1726
+ for note, carries_unit in inline:
1727
+ if not note.get_visible():
1728
+ continue
1729
+ box = note.get_window_extent(renderer)
1730
+ if any(path.intersects_bbox(box, filled=False) for path in paths):
1731
+ if carries_unit:
1732
+ note.set_zorder(6)
1733
+ else:
1734
+ note.set_visible(False)
1735
+
1736
+
1737
+ def _keep_inside_x(ctx: _Ctx, ax: Axes, note: Any) -> None:
1738
+ """Re-anchor a label centred on a data x so it stays within the axes' width.
1739
+
1740
+ A centred label near the right edge would run into text drawn beside the axes
1741
+ (the "median" column header of distribution()).
1742
+ """
1743
+ renderer = ctx.fig.canvas.get_renderer()
1744
+ box = note.get_window_extent(renderer)
1745
+ frame = ax.get_window_extent(renderer)
1746
+ if box.x1 > frame.x1:
1747
+ note.set_horizontalalignment("right")
1748
+ note.set_position((-2.0, note.xyann[1]))
1749
+ elif box.x0 < frame.x0:
1750
+ note.set_horizontalalignment("left")
1751
+ note.set_position((2.0, note.xyann[1]))
1752
+
1753
+
1754
+ def _reference_line(reference: object, what: str) -> tuple[float, str] | None:
1755
+ if reference is None:
1756
+ return None
1757
+ if _is_number(reference):
1758
+ return float(reference), "" # type: ignore[arg-type]
1759
+ try:
1760
+ value, text = reference # type: ignore[misc]
1761
+ except (TypeError, ValueError) as exc:
1762
+ raise ExplainError(
1763
+ f"{what} must be a number or a (value, label) pair.",
1764
+ fix_hint='Use reference=(300, "target") or reference=300.',
1765
+ ) from exc
1766
+ return _to_float(value, what), str(text)
1767
+
1768
+
1769
+ _INTERVAL_MODES = {
1770
+ "bounds": "absolute bounds (low, high)",
1771
+ "halfwidth": "\N{PLUS-MINUS SIGN} half-widths",
1772
+ }
1773
+
1774
+
1775
+ def _interval_mode_text(modes: set[str], what: str) -> str:
1776
+ if len(modes) == 1:
1777
+ return f"{what} read as {_INTERVAL_MODES[next(iter(modes))]}"
1778
+ return f"{what} read as absolute bounds (low, high) for some items, \N{PLUS-MINUS SIGN} half-widths for others"
1779
+
1780
+
1781
+ def _halfwidth(value: object, what: str) -> float:
1782
+ hw = _to_float(value, what)
1783
+ if not math.isfinite(hw) or hw < 0:
1784
+ raise ExplainError(
1785
+ f"{what} = {value!r} is not a usable half-width.",
1786
+ fix_hint="A half-width is one non-negative number (the \N{PLUS-MINUS SIGN} value).",
1787
+ )
1788
+ return hw
1789
+
1790
+
1791
+ def _interval_issue(form: str, arg: str, label_arg: str) -> dict[str, Any]:
1792
+ return _issue(
1793
+ "interval_unlabelled",
1794
+ "warning",
1795
+ f"{form}({arg}=...) draws intervals without saying what they are; a whisker with no "
1796
+ "stated meaning cannot be interpreted.",
1797
+ f'Pass {label_arg}="95% CI" (or "\N{PLUS-MINUS SIGN} 1 s.d., n = 5", "min\N{EN DASH}max of 3 runs").',
1798
+ )
1799
+
1800
+
1801
+ def _or_list(items: Sequence[str]) -> str:
1802
+ """"a", "a or b", "a, b or c"."""
1803
+ items = list(items)
1804
+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " or " + items[-1]
1805
+
1806
+
1807
+ _X_UNIT = re.compile(r"[(\[]\s*([^()\[\]]{1,16}?)\s*[)\]]\s*$")
1808
+
1809
+
1810
+ def _x_unit(x_label: str | None) -> str | None:
1811
+ """The unit at the end of an axis label: "Time after dose (h)" -> "h".
1812
+
1813
+ Only a bracket that reads as a unit: one token that does not start with a
1814
+ digit. "Cycle (1C/1C)" or "Dose (per 70 kg)" give no unit (pass ``x_unit=``).
1815
+ """
1816
+ if not x_label:
1817
+ return None
1818
+ found = _X_UNIT.search(x_label)
1819
+ if not found:
1820
+ return None
1821
+ text = found.group(1)
1822
+ if text[:1].isdigit() or any(ch.isspace() for ch in text):
1823
+ return None
1824
+ return text
1825
+
1826
+
1827
+ def _resolve_x_unit(x_unit: object, x_label: str | None, kind: str) -> str | None:
1828
+ """``x_unit=`` when given ("" turns the unit off), else the one parsed from ``x_label``."""
1829
+ if x_unit is None:
1830
+ return _x_unit(x_label)
1831
+ if not isinstance(x_unit, str):
1832
+ raise ExplainError(
1833
+ f"{kind}(x_unit={x_unit!r}) must be a string.",
1834
+ fix_hint='Pass the x unit as text, e.g. x_unit="h" or x_unit="cycles"; '
1835
+ 'x_unit="" states x values with no unit.',
1836
+ )
1837
+ return x_unit.strip() or None
1838
+
1839
+
1840
+ class _DateTickFormatter(mdates.ConciseDateFormatter):
1841
+ """Concise date ticks where a day-of-month always carries its month.
1842
+
1843
+ Matplotlib's concise labels read "15, Oct, 15, Nov": the first "15" (15 Sep) looks
1844
+ like 15 Oct. Here day ticks read "15 Sep", "1 Oct", "15 Oct"; month ticks stay
1845
+ "Oct" (January shows the year). Leading zeros are dropped portably.
1846
+ """
1847
+
1848
+ def format_ticks(self, values: Any) -> list[str]:
1849
+ return [re.sub(r"^0(?=\d)", "", text) for text in super().format_ticks(values)]
1850
+
1851
+
1852
+ def _date_formatter(locator: mdates.DateLocator) -> mdates.ConciseDateFormatter:
1853
+ return _DateTickFormatter(
1854
+ locator,
1855
+ formats=["%Y", "%b", "%d %b", "%H:%M", "%H:%M", "%S.%f"],
1856
+ zero_formats=["", "%Y", "%d %b", "%d %b", "%H:%M", "%H:%M"],
1857
+ show_offset=False,
1858
+ )
1859
+
1860
+
1861
+ def _values_array(values: object, what: str) -> np.ndarray:
1862
+ if values is None or isinstance(values, (str, bytes)) or _is_number(values):
1863
+ raise ExplainError(
1864
+ f"{what} must be a list of numbers, got {values!r}.",
1865
+ fix_hint="Pass one number per x position (None for gaps).",
1866
+ )
1867
+ try:
1868
+ return np.asarray(
1869
+ [np.nan if v is None else _to_float(v, what) for v in values], # type: ignore[union-attr]
1870
+ dtype=float,
1871
+ )
1872
+ except TypeError as exc:
1873
+ raise ExplainError(
1874
+ f"{what} must be a list of numbers.",
1875
+ fix_hint="Pass numbers (use None for gaps).",
1876
+ ) from exc
1877
+
1878
+
1879
+ def _and_list(items: Sequence[str]) -> str:
1880
+ """"a", "a and b", "a, b and c"."""
1881
+ items = list(items)
1882
+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
1883
+
1884
+
1885
+ def _data_paths(ax: Axes, skip: Sequence[Any]) -> list[Any]:
1886
+ """Display-space paths of the lines and markers drawn on ``ax`` (not ``skip``)."""
1887
+ paths = []
1888
+ for line in ax.get_lines():
1889
+ if line in skip or not line.get_visible():
1890
+ continue
1891
+ xy = line.get_xydata()
1892
+ if xy is None or len(xy) == 0:
1893
+ continue
1894
+ path = line.get_transform().transform_path(line.get_path())
1895
+ paths.append(path)
1896
+ return paths
1897
+
1898
+
1899
+ def _small_n_caution(sizes: Mapping[str, int], what: str) -> str | None:
1900
+ """One caution for every group with fewer than five observations (never one per group)."""
1901
+ small = {nm: n for nm, n in sizes.items() if n < 5}
1902
+ if not small:
1903
+ return None
1904
+ counts = set(small.values())
1905
+ if len(small) == len(sizes) and len(counts) == 1:
1906
+ if len(sizes) == 1:
1907
+ return f"n = {next(iter(counts))}: {what}"
1908
+ return f"every group has n = {next(iter(counts))}: {what}"
1909
+ listed = ", ".join(f"{nm} (n = {n})" for nm, n in small.items())
1910
+ return f"n < 5 in {listed}: {what}"
1911
+
1912
+
1913
+ #: Two-sided 95% Student t quantiles (0.975) for 1-30 degrees of freedom.
1914
+ _T975 = (
1915
+ 12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228,
1916
+ 2.201, 2.179, 2.160, 2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086,
1917
+ 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, 2.045, 2.042,
1918
+ ) # fmt: skip
1919
+
1920
+
1921
+ def _t975(df: int) -> float:
1922
+ """The 0.975 quantile of Student's t: a table to 30 df, then the Cornish-Fisher
1923
+ series in 1/df (within 0.01% of the exact value beyond 30 df)."""
1924
+ if df < 1:
1925
+ return float("nan")
1926
+ if df <= len(_T975):
1927
+ return _T975[df - 1]
1928
+ z = 1.959964
1929
+ g1 = (z**3 + z) / 4.0
1930
+ g2 = (5 * z**5 + 16 * z**3 + 3 * z) / 96.0
1931
+ g3 = (3 * z**7 + 19 * z**5 + 17 * z**3 - 15 * z) / 384.0
1932
+ return z + g1 / df + g2 / df**2 + g3 / df**3
1933
+
1934
+
1935
+ def _slope_ci(gx: np.ndarray, gy: np.ndarray, slope: float, intercept: float) -> tuple[float, float]:
1936
+ """95% confidence interval of a least-squares slope (t with n - 2 df)."""
1937
+ n = gx.size
1938
+ sxx = float(((gx - gx.mean()) ** 2).sum())
1939
+ if n < 3 or sxx <= 0:
1940
+ return float("nan"), float("nan")
1941
+ resid = gy - (slope * gx + intercept)
1942
+ se = math.sqrt(float((resid**2).sum()) / (n - 2) / sxx)
1943
+ half = _t975(n - 2) * se
1944
+ return slope - half, slope + half
1945
+
1946
+
1947
+ def _fit_axes(fig: Figure, ax: Axes, rect: Bbox) -> None:
1948
+ """Resize ``ax`` so that it and everything attached to it exactly fills ``rect`` (pixels)."""
1949
+ renderer = fig.canvas.get_renderer()
1950
+ fig_w, fig_h = fig.bbox.width, fig.bbox.height
1951
+ ax.set_position([rect.x0 / fig_w, rect.y0 / fig_h, rect.width / fig_w, rect.height / fig_h])
1952
+ for _ in range(6):
1953
+ tight = ax.get_tightbbox(renderer)
1954
+ if tight is None:
1955
+ return
1956
+ box = ax.get_window_extent(renderer)
1957
+ x0 = box.x0 + (rect.x0 - tight.x0)
1958
+ x1 = box.x1 - (tight.x1 - rect.x1)
1959
+ y0 = box.y0 + (rect.y0 - tight.y0)
1960
+ y1 = box.y1 - (tight.y1 - rect.y1)
1961
+ if x1 - x0 < 24 or y1 - y0 < 16:
1962
+ raise ExplainError(
1963
+ "A panel's labels leave no room for its data at this width.",
1964
+ fix_hint="Shorten item or series names, use fewer columns (a full-width row via "
1965
+ 'layout=[["a"], ["b", "c"]]), pass end_values=False on a trend to drop the '
1966
+ "numbers at the line ends, or split the figure in two.",
1967
+ rule="panel_too_small",
1968
+ )
1969
+ moved = max(abs(x0 - box.x0), abs(x1 - box.x1), abs(y0 - box.y0), abs(y1 - box.y1))
1970
+ ax.set_position([x0 / fig_w, y0 / fig_h, (x1 - x0) / fig_w, (y1 - y0) / fig_h])
1971
+ if moved < 0.5:
1972
+ return
1973
+
1974
+
1975
+ def _cover_with_ticks(axis: Any, lo: float, hi: float) -> None:
1976
+ """Widen a linear axis to the ticks just beyond [lo, hi] so no mark sits past the
1977
+ last labelled value (at most half the data span on each side)."""
1978
+ v0, v1 = sorted(axis.get_view_interval())
1979
+ span = (hi - lo) or abs(hi) or 1.0
1980
+ ticks = axis.get_major_locator().tick_values(v0, v1)
1981
+ above = [float(t) for t in ticks if t >= hi - 1e-12 * span]
1982
+ below = [float(t) for t in ticks if t <= lo + 1e-12 * span]
1983
+ if above and above[0] - hi < 0.5 * span:
1984
+ v1 = max(v1, above[0])
1985
+ if below and lo - below[-1] < 0.5 * span:
1986
+ v0 = min(v0, below[-1])
1987
+ if axis.axis_name == "x":
1988
+ axis.axes.set_xlim(v0, v1)
1989
+ else:
1990
+ axis.axes.set_ylim(v0, v1)
1991
+
1992
+
1993
+ def _tick_label_boxes(axis: Any, renderer: Any) -> list[tuple[float, Bbox]]:
1994
+ """(location, window box) of every visible, non-empty major tick label in view."""
1995
+ out: list[tuple[float, Bbox]] = []
1996
+ for tick in axis._update_ticks():
1997
+ label = tick.label1
1998
+ if label.get_visible() and label.get_text().strip():
1999
+ out.append((float(tick.get_loc()), label.get_window_extent(renderer)))
2000
+ return out
2001
+
2002
+
2003
+ def _labels_collide(boxes: list[tuple[float, Bbox]], horizontal: bool, gap: float) -> bool:
2004
+ spans = sorted(((b.x0, b.x1) if horizontal else (b.y0, b.y1)) for _, b in boxes)
2005
+ return any(nxt[0] - cur[1] < gap for cur, nxt in itertools.pairwise(spans))