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
mintfig/themes.py ADDED
@@ -0,0 +1,660 @@
1
+ """Visual surface themes and color palettes for ``mint.explain``.
2
+
3
+ Built-in themes: ``mintfig`` (default), ``bold``, ``editorial``, ``paper``,
4
+ ``dark``, ``mono``, ``sketch``. Built-in explain palettes: ``default``,
5
+ ``okabe_ito``, ``tol``, ``earth``, ``ocean``, ``berry``.
6
+
7
+ A theme or palette changes only the visual surface — typography, colour palette,
8
+ background, gridlines, axis framing, header/footer rules, and optional hand-drawn
9
+ sketch jitter. It never changes the information-design rules enforced by
10
+ ``mint.explain`` (takeaway titles, sorted zero-based bars, <= 4 coloured series,
11
+ <= 3 highlights, direct labels, chat legibility, or CVD/grayscale separation).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from contextlib import AbstractContextManager
17
+ from dataclasses import dataclass, field, replace
18
+ from typing import Any
19
+
20
+ import matplotlib as mpl
21
+ from matplotlib.colors import to_rgb
22
+
23
+ from . import style
24
+ from .specs import JournalSpec
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Theme:
29
+ """Immutable surface style for ``mint.explain`` figures."""
30
+
31
+ name: str
32
+ description: str
33
+
34
+ # Surface & structural colours
35
+ background: str = "#FFFFFF"
36
+ ink: str = "#1A1D21"
37
+ muted: str = "#5B6570"
38
+ axis: str = "#8A939E"
39
+ grid: str = "#E3E7EC"
40
+ context_line: str = "#B4BCC6"
41
+ context_fill: str = "#CDD3DA"
42
+ zero_line: str = "#1A1D21"
43
+ halo_alpha: float = 0.85
44
+
45
+ # Categorical & matrix palettes (strictly 4 series + 3 accents, CVD/grayscale verified)
46
+ series_colors: tuple[str, ...] = ("#1F5A9D", "#CD4324", "#0F9478", "#CC8800")
47
+ accent_colors: tuple[str, ...] = ("#CD4324", "#1F5A9D", "#0F9478")
48
+ seq_stops: tuple[str, ...] = (
49
+ "#F4F7FB",
50
+ "#C9DBEF",
51
+ "#8FB5DF",
52
+ "#4F8ACB",
53
+ "#1F5A9D",
54
+ "#173F70",
55
+ )
56
+ div_low: tuple[str, ...] = ("#1B4E8A", "#4F8ACB", "#A9C7E6")
57
+ div_high: tuple[str, ...] = ("#F0B7A4", "#DD6F50", "#B5391E")
58
+ div_mid: str = "#F1F2F4"
59
+
60
+ # Typography
61
+ title_family: tuple[str, ...] | None = None
62
+ body_family: tuple[str, ...] | None = None
63
+ title_scale: float = 1.3
64
+ title_weight: str = "bold"
65
+ allow_serif_title: bool = False
66
+ panel_tag_color: str | None = None
67
+
68
+ # Gridlines, spines & ticks
69
+ grid_style: str = "-"
70
+ grid_lw: float = 0.5
71
+ grid_both_axes: bool = False
72
+ hide_spines: bool = False
73
+ axis_lw: float = 0.6
74
+ zero_line_lw: float = 0.7
75
+ tick_length: float = 2.5
76
+ tick_width: float = 0.6
77
+ inline_y_ticks: bool = False
78
+
79
+ # Data strokes & marks
80
+ line_lw: float = 1.7
81
+ context_line_lw: float = 0.9
82
+ facet_line_lw: float = 1.5
83
+ line_capstyle: str = "round"
84
+ bar_height: float = 0.66
85
+ bar_edgecolor: str | None = None
86
+ bar_edge_lw: float = 0.0
87
+
88
+ # Editorial chrome (header & footer rules)
89
+ top_rule: bool = False
90
+ top_rule_color: str | None = None
91
+ top_rule_lw: float = 1.2
92
+ footer_rule: bool = False
93
+ footer_rule_color: str | None = None
94
+ footer_rule_lw: float = 0.7
95
+
96
+ # Glyphs & sketch effects
97
+ minus_sign: str = "\N{MINUS SIGN}"
98
+ ellipsis: str = "\N{HORIZONTAL ELLIPSIS}"
99
+ en_dash: str = "\N{EN DASH}"
100
+ sketch: tuple[float, float, float] | None = None
101
+ stroke_outline_pt: float = 0.0
102
+ warn_unless_illustrative: bool = False
103
+ extra_rc: dict[str, Any] = field(default_factory=dict)
104
+
105
+ @property
106
+ def default_color(self) -> str:
107
+ return self.series_colors[0]
108
+
109
+ @property
110
+ def resolved_panel_tag_color(self) -> str:
111
+ return self.panel_tag_color if self.panel_tag_color is not None else self.muted
112
+
113
+ def rc_params(self, spec: JournalSpec) -> dict[str, Any]:
114
+ """Build Matplotlib rcParams layering theme surface tokens onto ``spec``."""
115
+ params = style.rc_params(spec)
116
+ # Per-glyph fallback: Matplotlib draws a character the body font lacks (an arrow,
117
+ # "∝", "ℏ") from the next family in this list instead of a missing-glyph box.
118
+ # DejaVu Sans ships with Matplotlib, so the fallback exists on every host.
119
+ params["font.family"] = ["sans-serif", "DejaVu Sans"]
120
+ # The "custom" mathtext fontset looks up every slot when it first lays out a
121
+ # super/subscript, including \mathcal's default "cursive" stack, whose first
122
+ # installed entry on some systems has no usable weight: Matplotlib then logs a
123
+ # "findfont: Failed to find font weight normal" warning on every run. Chat
124
+ # figures never draw \mathcal ($...$ is not math there), so point the slot at
125
+ # the body font and the cursive stack is never probed.
126
+ params["mathtext.cal"] = params["mathtext.rm"]
127
+ if self.name == "mintfig" and not self.extra_rc:
128
+ return params
129
+
130
+ if self.body_family is not None:
131
+ font_name = style._resolve_font_tuple(self.body_family)
132
+ params["font.sans-serif"] = list(self.body_family)
133
+ params["mathtext.rm"] = font_name
134
+ params["mathtext.it"] = f"{font_name}:italic"
135
+ params["mathtext.bf"] = f"{font_name}:bold"
136
+ params["mathtext.sf"] = font_name
137
+ params["mathtext.cal"] = font_name
138
+
139
+ if self.title_family is not None:
140
+ params["font.serif"] = list(self.title_family)
141
+
142
+ params["text.color"] = self.ink
143
+ params["axes.labelcolor"] = self.ink
144
+ params["figure.facecolor"] = self.background
145
+ params["figure.edgecolor"] = self.background
146
+ params["savefig.facecolor"] = self.background
147
+ params["savefig.edgecolor"] = self.background
148
+ params["axes.facecolor"] = self.background
149
+ params["axes.edgecolor"] = self.background if self.hide_spines else self.axis
150
+ params["lines.solid_capstyle"] = self.line_capstyle
151
+
152
+ if self.sketch is not None:
153
+ params["path.sketch"] = self.sketch
154
+ if self.minus_sign == "-":
155
+ params["axes.unicode_minus"] = False
156
+
157
+ if self.extra_rc:
158
+ params.update(self.extra_rc)
159
+ return params
160
+
161
+ def rc_context(self, spec: JournalSpec) -> AbstractContextManager[None]:
162
+ """Context manager applying this theme's rcParams without leaking global state."""
163
+ return mpl.rc_context(rc=self.rc_params(spec))
164
+
165
+
166
+ def relative_luminance(color: str) -> float:
167
+ """Compute WCAG 2.1 relative luminance for a Matplotlib color string."""
168
+
169
+ def _lin(c: float) -> float:
170
+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
171
+
172
+ r, g, b = (_lin(c) for c in to_rgb(color))
173
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
174
+
175
+
176
+ def contrast_ratio(fg: str, bg: str = "#FFFFFF") -> float:
177
+ """Return WCAG contrast ratio between ``fg`` and ``bg`` (>= 1.0)."""
178
+ l1 = relative_luminance(fg)
179
+ l2 = relative_luminance(bg)
180
+ hi, lo = (l1, l2) if l1 >= l2 else (l2, l1)
181
+ return (hi + 0.05) / (lo + 0.05)
182
+
183
+
184
+ # --------------------------------------------------------------------------- #
185
+ # Built-in themes
186
+ # --------------------------------------------------------------------------- #
187
+
188
+ MINTFIG_THEME = Theme(
189
+ name="mintfig",
190
+ description="Clean default mintfig chat style: white ground, restrained editorial palette, quiet gridlines.",
191
+ )
192
+
193
+ # bold: high-contrast surface on a #F0F0F0 matte-gray ground with heavy lines.
194
+ # Series palette: bright blue (#008FD5), vermilion (#D6381C),
195
+ # deep plum (#6B1C6D), and warm gold (#DDA324) — min_gray=0.080, min_cvd=0.316.
196
+ BOLD_THEME = Theme(
197
+ name="bold",
198
+ description="Bold, high-contrast data journalism look on a matte-gray ground; best for a single strong comparison or trend.",
199
+ background="#F0F0F0",
200
+ ink="#222222",
201
+ muted="#525252",
202
+ axis="#7A7A7A",
203
+ grid="#CBCBCB",
204
+ context_line="#A6A6A6",
205
+ context_fill="#C6C6C6",
206
+ zero_line="#3A3A3A",
207
+ halo_alpha=0.92,
208
+ series_colors=("#008FD5", "#D6381C", "#6B1C6D", "#DDA324"),
209
+ accent_colors=("#D6381C", "#008FD5", "#6B1C6D"),
210
+ seq_stops=("#E6EEF4", "#B8D8EE", "#74B9E3", "#2A9FD9", "#0079B8", "#005380"),
211
+ div_low=("#005B8C", "#008FD5", "#94CDEB"),
212
+ div_high=("#F0B0A1", "#E36249", "#B82910"),
213
+ div_mid="#E4E4E4",
214
+ body_family=("Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "DejaVu Sans"),
215
+ title_scale=1.42,
216
+ title_weight="bold",
217
+ panel_tag_color="#D6381C",
218
+ grid_style="-",
219
+ grid_lw=0.6,
220
+ grid_both_axes=True,
221
+ hide_spines=True,
222
+ axis_lw=0.0,
223
+ zero_line_lw=1.2,
224
+ tick_length=0.0,
225
+ tick_width=0.0,
226
+ line_lw=2.3,
227
+ context_line_lw=1.2,
228
+ facet_line_lw=1.9,
229
+ line_capstyle="butt",
230
+ bar_height=0.70,
231
+ footer_rule=True,
232
+ footer_rule_color="#BEBEBE",
233
+ footer_rule_lw=0.8,
234
+ )
235
+
236
+ # editorial: newspaper-graphics surface with a stark white ground, crisp black top rule,
237
+ # bold Georgia serif headline paired with Helvetica Neue body, thin dotted horizontal
238
+ # gridlines, dark baseline, and y-tick labels sitting above gridlines with top-only unit.
239
+ # Series palette: editorial steel blue, brick terracotta, sage teal, warm ochre
240
+ # — min_gray=0.075, min_cvd=0.260.
241
+ EDITORIAL_THEME = Theme(
242
+ name="editorial",
243
+ description="Quiet, annotation-led newspaper editorial style with serif headlines and above-gridline labels; best for multi-panel arguments.",
244
+ background="#FFFFFF",
245
+ ink="#121212",
246
+ muted="#666666",
247
+ axis="#333333",
248
+ grid="#D6D6D6",
249
+ context_line="#C0C0C0",
250
+ context_fill="#D8D8D8",
251
+ zero_line="#222222",
252
+ halo_alpha=0.92,
253
+ series_colors=("#285F8A", "#D44D27", "#4B9B88", "#D9A226"),
254
+ accent_colors=("#D44D27", "#285F8A", "#4B9B88"),
255
+ seq_stops=("#F5F7F9", "#D3E0EA", "#9EBBD1", "#6191B5", "#285F8A", "#193F5E"),
256
+ div_low=("#1A476A", "#4A7FA8", "#A7C4DA"),
257
+ div_high=("#F0B8A5", "#DF7452", "#B83B19"),
258
+ div_mid="#F2F2F2",
259
+ title_family=("Georgia", "Charter", "DejaVu Serif", "serif"),
260
+ body_family=("Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "DejaVu Sans"),
261
+ title_scale=1.42,
262
+ title_weight="bold",
263
+ allow_serif_title=True,
264
+ panel_tag_color="#121212",
265
+ grid_style=":",
266
+ grid_lw=0.6,
267
+ grid_both_axes=False,
268
+ hide_spines=False,
269
+ axis_lw=0.65,
270
+ zero_line_lw=0.95,
271
+ tick_length=2.5,
272
+ tick_width=0.6,
273
+ inline_y_ticks=True,
274
+ line_lw=1.65,
275
+ context_line_lw=0.85,
276
+ facet_line_lw=1.45,
277
+ line_capstyle="round",
278
+ bar_height=0.64,
279
+ top_rule=True,
280
+ top_rule_color="#121212",
281
+ top_rule_lw=1.3,
282
+ footer_rule=True,
283
+ footer_rule_color="#DCDCDC",
284
+ footer_rule_lw=0.6,
285
+ )
286
+
287
+ # sketch: hand-drawn style with deterministic Matplotlib path.sketch jitter,
288
+ # hand-lettered font stack, bold black ink strokes, no gridlines, ASCII minus/ellipsis,
289
+ # and an honesty warning unless source/note marks the data as illustrative or synthetic.
290
+ # Series palette: marker blue, comic red, whiteboard green, highlighter gold
291
+ # — min_gray=0.058, min_cvd=0.284.
292
+ SKETCH_THEME = Theme(
293
+ name="sketch",
294
+ description="Hand-drawn sketch style signaling a conceptual or illustrative point rather than exact measurements.",
295
+ background="#FFFFFF",
296
+ ink="#111111",
297
+ muted="#484848",
298
+ axis="#111111",
299
+ grid="#E2E2E2",
300
+ context_line="#9A9A9A",
301
+ context_fill="#D2D2D2",
302
+ zero_line="#111111",
303
+ halo_alpha=0.92,
304
+ series_colors=("#16508F", "#DC4426", "#3D9970", "#E2A61E"),
305
+ accent_colors=("#DC4426", "#16508F", "#3D9970"),
306
+ seq_stops=("#F4F7FC", "#C9DBF2", "#8FB4E2", "#4E88CA", "#16508F", "#0E3563"),
307
+ div_low=("#123F73", "#4A82C2", "#A6C5E8"),
308
+ div_high=("#F5B6A8", "#E56D52", "#BD2F14"),
309
+ div_mid="#F3F3F3",
310
+ body_family=(
311
+ "Humor Sans",
312
+ "Comic Neue",
313
+ "Chalkboard SE",
314
+ "Chalkboard",
315
+ "Comic Sans MS",
316
+ "Liberation Sans",
317
+ "DejaVu Sans",
318
+ ),
319
+ title_scale=1.35,
320
+ title_weight="bold",
321
+ panel_tag_color="#111111",
322
+ grid_style="none",
323
+ grid_lw=0.0,
324
+ grid_both_axes=False,
325
+ hide_spines=False,
326
+ axis_lw=1.2,
327
+ zero_line_lw=1.25,
328
+ tick_length=3.5,
329
+ tick_width=1.1,
330
+ line_lw=1.9,
331
+ context_line_lw=1.15,
332
+ facet_line_lw=1.65,
333
+ line_capstyle="round",
334
+ bar_height=0.64,
335
+ bar_edgecolor="#111111",
336
+ bar_edge_lw=0.9,
337
+ minus_sign="-",
338
+ ellipsis="...",
339
+ en_dash="-",
340
+ sketch=(0.9, 95.0, 2.0),
341
+ stroke_outline_pt=2.5,
342
+ warn_unless_illustrative=True,
343
+ )
344
+
345
+ # paper: warm parchment/ivory ground (#FAF7F0) with espresso ink, serif headline,
346
+ # and warm editorial hues — min_gray=0.135, min_cvd=0.390.
347
+ PAPER_THEME = Theme(
348
+ name="paper",
349
+ description="Warm ivory paper ground with espresso ink, serif headlines, and refined earth-editorial hues.",
350
+ background="#FAF7F0",
351
+ ink="#221E1A",
352
+ muted="#635B52",
353
+ axis="#8F867A",
354
+ grid="#E7E0D3",
355
+ context_line="#BEB5A7",
356
+ context_fill="#D7CFC2",
357
+ zero_line="#221E1A",
358
+ halo_alpha=0.90,
359
+ series_colors=("#1E446E", "#B83B1E", "#36997A", "#DAA424"),
360
+ accent_colors=("#B83B1E", "#1E446E", "#36997A"),
361
+ seq_stops=("#F7F3EA", "#D8E1E8", "#A3BACD", "#608AB0", "#1E446E", "#132D4A"),
362
+ div_low=("#153559", "#4B7CA8", "#A8C3DA"),
363
+ div_high=("#EBB4A2", "#D96B4D", "#A32F14"),
364
+ div_mid="#EFEAE0",
365
+ title_family=("Georgia", "Charter", "DejaVu Serif", "serif"),
366
+ body_family=("Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "DejaVu Sans"),
367
+ title_scale=1.38,
368
+ title_weight="bold",
369
+ allow_serif_title=True,
370
+ panel_tag_color="#635B52",
371
+ grid_style="-",
372
+ grid_lw=0.5,
373
+ axis_lw=0.6,
374
+ zero_line_lw=0.8,
375
+ line_lw=1.75,
376
+ context_line_lw=0.9,
377
+ facet_line_lw=1.5,
378
+ top_rule=True,
379
+ top_rule_color="#221E1A",
380
+ top_rule_lw=1.0,
381
+ footer_rule=True,
382
+ footer_rule_color="#DDD4C4",
383
+ footer_rule_lw=0.6,
384
+ )
385
+
386
+ # dark: deep slate charcoal ground (#14181F) for dark-mode chat UIs and slides,
387
+ # with crisp off-white ink and luminous CVD-safe hues — min_gray=0.094, min_cvd=0.320.
388
+ DARK_THEME = Theme(
389
+ name="dark",
390
+ description="Dark slate ground with crisp light ink and luminous CVD-safe hues for dark UIs and slides.",
391
+ background="#14181F",
392
+ ink="#ECEFF4",
393
+ muted="#9AA5B4",
394
+ axis="#657082",
395
+ grid="#272E3B",
396
+ context_line="#586375",
397
+ context_fill="#3A4354",
398
+ zero_line="#CBD3DF",
399
+ halo_alpha=0.88,
400
+ series_colors=("#4A89DC", "#F47E62", "#4BD9BA", "#F6DF78"),
401
+ accent_colors=("#F47E62", "#4A89DC", "#4BD9BA"),
402
+ seq_stops=("#1C2330", "#223654", "#2B5182", "#3B72B3", "#589BE3", "#8CC4F8"),
403
+ div_low=("#78B8F5", "#4381C4", "#233C59"),
404
+ div_high=("#5B2B24", "#B84C3B", "#F4866C"),
405
+ div_mid="#222936",
406
+ body_family=("Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "DejaVu Sans"),
407
+ title_scale=1.32,
408
+ title_weight="bold",
409
+ panel_tag_color="#9AA5B4",
410
+ grid_style="-",
411
+ grid_lw=0.55,
412
+ axis_lw=0.65,
413
+ zero_line_lw=0.85,
414
+ line_lw=1.85,
415
+ context_line_lw=0.95,
416
+ facet_line_lw=1.55,
417
+ )
418
+
419
+ # mono: crisp monochrome print/handout theme with one vermilion highlight accent
420
+ # — min_gray=0.098, min_cvd=0.343.
421
+ MONO_THEME = Theme(
422
+ name="mono",
423
+ description="High-contrast monochrome print theme with a single vermilion highlight accent.",
424
+ background="#FFFFFF",
425
+ ink="#111111",
426
+ muted="#555555",
427
+ axis="#787878",
428
+ grid="#E5E5E5",
429
+ context_line="#B0B0B0",
430
+ context_fill="#D0D0D0",
431
+ zero_line="#111111",
432
+ halo_alpha=0.90,
433
+ series_colors=("#3F4954", "#C8321E", "#7C858F", "#B0B8C0"),
434
+ accent_colors=("#C8321E", "#3F4954", "#7C858F"),
435
+ seq_stops=("#F5F5F5", "#DCDCDC", "#B4B4B4", "#828282", "#4E4E4E", "#222222"),
436
+ div_low=("#222222", "#666666", "#B8B8B8"),
437
+ div_high=("#F0B8AE", "#DE6A56", "#B82814"),
438
+ div_mid="#F0F0F0",
439
+ body_family=("Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "DejaVu Sans"),
440
+ title_scale=1.32,
441
+ title_weight="bold",
442
+ panel_tag_color="#C8321E",
443
+ grid_style="-",
444
+ grid_lw=0.5,
445
+ axis_lw=0.65,
446
+ zero_line_lw=0.85,
447
+ line_lw=1.75,
448
+ context_line_lw=0.9,
449
+ facet_line_lw=1.5,
450
+ )
451
+
452
+ THEMES: dict[str, Theme] = {
453
+ "mintfig": MINTFIG_THEME,
454
+ "bold": BOLD_THEME,
455
+ "editorial": EDITORIAL_THEME,
456
+ "paper": PAPER_THEME,
457
+ "dark": DARK_THEME,
458
+ "mono": MONO_THEME,
459
+ "sketch": SKETCH_THEME,
460
+ }
461
+
462
+ THEME_ALIASES: dict[str, str] = {
463
+ "default": "mintfig",
464
+ "newspaper": "editorial",
465
+ "warm": "paper",
466
+ "print": "mono",
467
+ "hand_drawn": "sketch",
468
+ }
469
+
470
+
471
+ # --------------------------------------------------------------------------- #
472
+ # Explain color palettes (independent of surface theme)
473
+ # --------------------------------------------------------------------------- #
474
+
475
+
476
+ @dataclass(frozen=True)
477
+ class ExplainPalette:
478
+ """CVD- and grayscale-verified 4-color + matrix palette for ``mint.explain``."""
479
+
480
+ name: str
481
+ description: str
482
+ series_colors: tuple[str, ...]
483
+ accent_colors: tuple[str, ...]
484
+ seq_stops: tuple[str, ...]
485
+ div_low: tuple[str, ...]
486
+ div_high: tuple[str, ...]
487
+ div_mid: str = "#F1F2F4"
488
+
489
+
490
+ EXPLAIN_PALETTES: dict[str, ExplainPalette] = {
491
+ "default": ExplainPalette(
492
+ name="default",
493
+ description="The active style's built-in editorial palette (blue, vermilion, teal, amber).",
494
+ series_colors=MINTFIG_THEME.series_colors,
495
+ accent_colors=MINTFIG_THEME.accent_colors,
496
+ seq_stops=MINTFIG_THEME.seq_stops,
497
+ div_low=MINTFIG_THEME.div_low,
498
+ div_high=MINTFIG_THEME.div_high,
499
+ div_mid=MINTFIG_THEME.div_mid,
500
+ ),
501
+ "okabe_ito": ExplainPalette(
502
+ name="okabe_ito",
503
+ description="Okabe-Ito colorblind-safe palette tuned for grayscale separation and 4.5:1 text contrast.",
504
+ series_colors=("#005E94", "#CC5500", "#00A87E", "#E6AF00"),
505
+ accent_colors=("#CC5500", "#005E94", "#00A87E"),
506
+ seq_stops=("#F2F7FB", "#C2DFEE", "#7BB9DA", "#2E8EC2", "#005E94", "#003D63"),
507
+ div_low=("#00446E", "#2E8EC2", "#9CCCE6"),
508
+ div_high=("#F2B896", "#E07938", "#B54800"),
509
+ div_mid="#F2F3F5",
510
+ ),
511
+ "tol": ExplainPalette(
512
+ name="tol",
513
+ description="Paul Tol scientific palette: indigo, crimson, emerald, and warm gold.",
514
+ series_colors=("#332288", "#CC3344", "#229966", "#DDAA33"),
515
+ accent_colors=("#CC3344", "#332288", "#229966"),
516
+ seq_stops=("#F4F3FA", "#CFCBE8", "#9D95D1", "#685CB2", "#332288", "#21155C"),
517
+ div_low=("#241766", "#5D4FA6", "#ACA4D9"),
518
+ div_high=("#F0B0B8", "#DE6472", "#B52434"),
519
+ div_mid="#F2F2F5",
520
+ ),
521
+ "earth": ExplainPalette(
522
+ name="earth",
523
+ description="Warm natural tones: deep slate blue, terracotta, moss green, and ochre.",
524
+ series_colors=("#203F60", "#B84228", "#4D8B55", "#D49E2A"),
525
+ accent_colors=("#B84228", "#203F60", "#4D8B55"),
526
+ seq_stops=("#F5F6F8", "#CFD8E2", "#97AEC4", "#5B80A3", "#203F60", "#132940"),
527
+ div_low=("#17304A", "#4F7499", "#A6BCD1"),
528
+ div_high=("#EAB5A6", "#D46D52", "#A1341B"),
529
+ div_mid="#F2F1EE",
530
+ ),
531
+ "ocean": ExplainPalette(
532
+ name="ocean",
533
+ description="Marine palette: deep cobalt, reef coral, seafoam teal, and sand gold.",
534
+ series_colors=("#143E66", "#D95240", "#1A9E9E", "#DEB030"),
535
+ accent_colors=("#D95240", "#143E66", "#1A9E9E"),
536
+ seq_stops=("#F2F7F9", "#C5E1E6", "#7EC2CC", "#359EA8", "#1A7D8A", "#0F4D59"),
537
+ div_low=("#103252", "#3A729E", "#99BCD6"),
538
+ div_high=("#F2BAB2", "#E47868", "#BF3B2A"),
539
+ div_mid="#F2F4F5",
540
+ ),
541
+ "berry": ExplainPalette(
542
+ name="berry",
543
+ description="Rich plum, steel blue, forest emerald, and warm honey.",
544
+ series_colors=("#7B2466", "#1D619E", "#128060", "#CE9216"),
545
+ accent_colors=("#7B2466", "#1D619E", "#128060"),
546
+ seq_stops=("#F9F3F7", "#E4C5DC", "#C68DB8", "#A1568E", "#7B2466", "#521444"),
547
+ div_low=("#154878", "#4682B8", "#A3C4E0"),
548
+ div_high=("#E5B3D7", "#BA66A3", "#7B2466"),
549
+ div_mid="#F3F2F4",
550
+ ),
551
+ }
552
+
553
+
554
+ def get_explain_palette(palette: str | ExplainPalette = "default") -> ExplainPalette:
555
+ """Resolve an explain color palette by name or :class:`ExplainPalette` instance."""
556
+ if isinstance(palette, ExplainPalette):
557
+ return palette
558
+ if not isinstance(palette, str):
559
+ raise TypeError(
560
+ f"palette must be a palette name or ExplainPalette instance, got {type(palette).__name__}."
561
+ )
562
+ key = palette.strip().lower().replace("-", "_").replace(" ", "_")
563
+ if key not in EXPLAIN_PALETTES:
564
+ valid = ", ".join(EXPLAIN_PALETTES)
565
+ raise ValueError(f"Unknown palette {palette!r}. Choose one of: {valid}.")
566
+ return EXPLAIN_PALETTES[key]
567
+
568
+
569
+ def _lift_for_dark_ground(color: str, bg: str) -> str:
570
+ """Lighten a series color when placed on a dark theme background so contrast stays >= 4.5:1."""
571
+ if contrast_ratio(color, bg) >= 4.5:
572
+ return color
573
+ rgb = to_rgb(color)
574
+ for mix in (0.18, 0.32, 0.45, 0.58, 0.72):
575
+ lifted = tuple(c + (1.0 - c) * mix for c in rgb)
576
+ cand = "#{:02X}{:02X}{:02X}".format(*(round(v * 255) for v in lifted))
577
+ if contrast_ratio(cand, bg) >= 4.5:
578
+ return cand
579
+ return "#DCE6F2"
580
+
581
+
582
+ def apply_palette(theme: Theme, palette: str | ExplainPalette | None) -> tuple[Theme, str | None]:
583
+ """Overlay ``palette`` onto ``theme``; returns ``(resolved_theme, canonical_palette_name)``."""
584
+ if palette is None:
585
+ return theme, None
586
+ pal = get_explain_palette(palette)
587
+ if pal.name == "default":
588
+ return theme, None
589
+ is_dark = relative_luminance(theme.background) < 0.2
590
+ if is_dark:
591
+ series = tuple(_lift_for_dark_ground(c, theme.background) for c in pal.series_colors)
592
+ accents = tuple(_lift_for_dark_ground(c, theme.background) for c in pal.accent_colors)
593
+ return (
594
+ replace(
595
+ theme,
596
+ series_colors=series,
597
+ accent_colors=accents,
598
+ ),
599
+ pal.name,
600
+ )
601
+ return (
602
+ replace(
603
+ theme,
604
+ series_colors=pal.series_colors,
605
+ accent_colors=pal.accent_colors,
606
+ seq_stops=pal.seq_stops,
607
+ div_low=pal.div_low,
608
+ div_high=pal.div_high,
609
+ div_mid=pal.div_mid,
610
+ ),
611
+ pal.name,
612
+ )
613
+
614
+
615
+ def apply_accent(theme: Theme, accent: str | None) -> tuple[Theme, str | None]:
616
+ """Override the primary highlight colour on ``theme`` with a custom accent hex/color."""
617
+ if accent is None:
618
+ return theme, None
619
+ if not isinstance(accent, str) or not accent.strip():
620
+ raise ValueError(f"accent must be a color string like '#2563EB', got {accent!r}.")
621
+ raw = accent.strip()
622
+ try:
623
+ rgb = to_rgb(raw)
624
+ except ValueError as exc:
625
+ raise ValueError(f"Unknown accent color {accent!r}. Pass a hex color like '#D97757'.") from exc
626
+ orig_hex = "#{:02X}{:02X}{:02X}".format(*(round(c * 255) for c in rgb))
627
+ hex_col = orig_hex
628
+ is_dark = relative_luminance(theme.background) < 0.2
629
+ if is_dark:
630
+ hex_col = _lift_for_dark_ground(hex_col, theme.background)
631
+ elif contrast_ratio(hex_col, theme.background) < 3.0:
632
+ # Gently deepen overly pale accents on light grounds so bars/markers stay readable.
633
+ for factor in (0.82, 0.68, 0.54, 0.40):
634
+ cand = "#{:02X}{:02X}{:02X}".format(*(round(c * factor * 255) for c in rgb))
635
+ if contrast_ratio(cand, theme.background) >= 3.0:
636
+ hex_col = cand
637
+ break
638
+ series = list(theme.series_colors)
639
+ if len(series) >= 2:
640
+ series[1] = hex_col # highlight slot 0 ("red")
641
+ else:
642
+ series[0] = hex_col
643
+ accents = (hex_col, *theme.accent_colors[1:])
644
+ return replace(theme, series_colors=tuple(series), accent_colors=accents), orig_hex
645
+
646
+
647
+ def get_theme(theme: str | Theme = "mintfig") -> Theme:
648
+ """Resolve a theme name, alias, or :class:`Theme` instance."""
649
+ if isinstance(theme, Theme):
650
+ return theme
651
+ if not isinstance(theme, str):
652
+ raise TypeError(
653
+ f"style must be a theme name or Theme instance, got {type(theme).__name__}."
654
+ )
655
+ key = theme.strip().lower().replace("-", "_").replace(" ", "_")
656
+ canonical = THEME_ALIASES.get(key, key)
657
+ if canonical not in THEMES:
658
+ valid = ", ".join(THEMES)
659
+ raise ValueError(f"Unknown style {theme!r}. Choose one of: {valid}.")
660
+ return THEMES[canonical]