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,472 @@
1
+ """Grouped multi-series compare panel for multi-benchmark / multi-model comparisons."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ from matplotlib.axes import Axes
11
+ from matplotlib.patches import Rectangle
12
+ from matplotlib.ticker import FuncFormatter, MaxNLocator
13
+
14
+ from ..themes import Theme
15
+ from .core import (
16
+ MAX_COLORED_SERIES,
17
+ PT_TO_MM,
18
+ ExplainError,
19
+ Panel,
20
+ _bare_axes,
21
+ _base_spec,
22
+ _baseline_name,
23
+ _Ctx,
24
+ _diff_with_unit,
25
+ _formatter,
26
+ _inline_unit,
27
+ _is_strict,
28
+ _jsonable,
29
+ _Measure,
30
+ _names,
31
+ _narrow_log_ticks,
32
+ _plain,
33
+ _record_adjustment,
34
+ _reference_line,
35
+ _signed,
36
+ _Sizes,
37
+ _tick_label,
38
+ _to_float,
39
+ _with_unit,
40
+ )
41
+
42
+ MAX_GROUPED_COMPARE_ITEMS = 12
43
+ MAX_GROUPED_COMPARE_SERIES = 6
44
+
45
+
46
+ def is_nested_compare(values: object) -> bool:
47
+ """True when ``values`` is a non-empty mapping of ``{category: {series: num}}``."""
48
+ if not isinstance(values, Mapping) or not values:
49
+ return False
50
+ first = next(iter(values.values()))
51
+ return isinstance(first, Mapping)
52
+
53
+
54
+ def build_grouped_compare(
55
+ nested: Mapping[str, Mapping[str, Any]],
56
+ *,
57
+ title: str | None = None,
58
+ label: str | None = None,
59
+ unit: str | None = None,
60
+ highlight: str | Sequence[str] | None = None,
61
+ baseline: str | None = None,
62
+ sort: bool | str = False,
63
+ zero: bool = True,
64
+ reference: float | tuple[float, str] | None = None,
65
+ log: bool = False,
66
+ fmt: str | None = None,
67
+ ) -> Panel:
68
+ """Multi-benchmark / multi-series grouped comparison (horizontal bars or Cleveland dots)."""
69
+ categories: list[str] = []
70
+ series_names: list[str] = []
71
+ grid: dict[str, dict[str, float | None]] = {}
72
+
73
+ for raw_cat, raw_series in nested.items():
74
+ if not isinstance(raw_series, Mapping):
75
+ raise ExplainError(
76
+ f"compare(values[{raw_cat!r}]) must be a dict of series -> number.",
77
+ fix_hint='Pass {category: {series: number}} uniformly for grouped compare().',
78
+ )
79
+ cat = str(raw_cat)
80
+ categories.append(cat)
81
+ bucket: dict[str, float | None] = {}
82
+ for raw_s, raw_v in raw_series.items():
83
+ ser = str(raw_s)
84
+ if ser not in series_names:
85
+ series_names.append(ser)
86
+ if raw_v is None or (isinstance(raw_v, float) and math.isnan(raw_v)):
87
+ bucket[ser] = None
88
+ else:
89
+ bucket[ser] = _to_float(raw_v, f"compare(values[{cat!r}][{ser!r}])")
90
+ grid[cat] = bucket
91
+
92
+ if not categories:
93
+ raise ExplainError("compare(values) is empty.", fix_hint="Pass at least one category.")
94
+ if not series_names:
95
+ raise ExplainError("compare(values) has no series.", fix_hint="Pass at least one series.")
96
+
97
+ if len(categories) > MAX_GROUPED_COMPARE_ITEMS:
98
+ if not _is_strict():
99
+ orig_c = len(categories)
100
+ categories = categories[:MAX_GROUPED_COMPARE_ITEMS]
101
+ grid = {c: grid[c] for c in categories}
102
+ _record_adjustment(
103
+ f"compare(): trimmed {orig_c} grouped categories to first {len(categories)}"
104
+ )
105
+ else:
106
+ raise ExplainError(
107
+ f"Grouped compare() got {len(categories)} categories; beyond "
108
+ f"{MAX_GROUPED_COMPARE_ITEMS} a grouped bar chart gets cramped.",
109
+ fix_hint=f"Keep at most {MAX_GROUPED_COMPARE_ITEMS} categories, or use mint.matrix() / mint.table().",
110
+ rule="too_many_items",
111
+ )
112
+
113
+ hl = _names(highlight, series_names, "compare(highlight)")
114
+ base = _baseline_name(baseline, series_names, hl, "compare")
115
+
116
+ if len(series_names) > MAX_GROUPED_COMPARE_SERIES:
117
+ if not _is_strict():
118
+ must = list(dict.fromkeys([*hl, *([base] if base else [])]))
119
+ kept = list(must)
120
+ for s in series_names:
121
+ if len(kept) >= MAX_GROUPED_COMPARE_SERIES:
122
+ break
123
+ if s not in kept:
124
+ kept.append(s)
125
+ orig_s = len(series_names)
126
+ series_names = [s for s in series_names if s in kept]
127
+ _record_adjustment(f"compare(): trimmed {orig_s} series to {len(series_names)}")
128
+ else:
129
+ raise ExplainError(
130
+ f"Grouped compare() got {len(series_names)} series; beyond "
131
+ f"{MAX_GROUPED_COMPARE_SERIES} series a grouped chart cannot be read.",
132
+ fix_hint=f"Keep at most {MAX_GROUPED_COMPARE_SERIES} series (≤{MAX_COLORED_SERIES} coloured), or use mint.table().",
133
+ rule="too_many_series",
134
+ )
135
+
136
+ if len(series_names) > MAX_COLORED_SERIES and not hl:
137
+ if not _is_strict():
138
+ kept = series_names[:MAX_COLORED_SERIES]
139
+ if base and base not in kept:
140
+ kept[-1] = base
141
+ orig_s = len(series_names)
142
+ series_names = kept
143
+ _record_adjustment(
144
+ f"compare(): trimmed {orig_s} unhighlighted series to {MAX_COLORED_SERIES}"
145
+ )
146
+ else:
147
+ raise ExplainError(
148
+ f"Grouped compare() has {len(series_names)} series; more than {MAX_COLORED_SERIES} "
149
+ "colours cannot be told apart.",
150
+ fix_hint=f"Pass highlight= for 1-3 focal series (others turn grey), or keep at most {MAX_COLORED_SERIES} series.",
151
+ rule="too_many_series",
152
+ )
153
+
154
+ ref = _reference_line(reference, "compare(reference)")
155
+ all_vals = [
156
+ v for c in categories for s in series_names if (v := grid[c].get(s)) is not None
157
+ ]
158
+ if not all_vals:
159
+ raise ExplainError("compare(values) has no finite values.", fix_hint="Pass numbers.")
160
+ if log and min([*all_vals, *([ref[0]] if ref else [])]) <= 0:
161
+ raise ExplainError(
162
+ "compare(log=True) needs strictly positive values.",
163
+ fix_hint="Drop log=True or remove non-positive values.",
164
+ )
165
+
166
+ # Optional sort of categories by focal series (first highlight, else first series)
167
+ if sort in (True, "desc", "asc"):
168
+ focal = hl[0] if hl else series_names[0]
169
+ reverse = sort != "asc"
170
+ categories.sort(
171
+ key=lambda c: (
172
+ grid[c].get(focal) is None,
173
+ -(grid[c].get(focal) or 0.0) if reverse else (grid[c].get(focal) or 0.0),
174
+ )
175
+ )
176
+
177
+ dots = (not zero) or log
178
+ fmt_fn = _formatter(all_vals, fmt, unit=unit, log=log)
179
+ inline_u = _inline_unit(unit)
180
+
181
+ def _u(v: float) -> str:
182
+ return _with_unit(fmt_fn(v), unit)
183
+
184
+ # Order series visually: highlighted first, then remaining (baseline stays in order or after focus)
185
+ ordered_series = list(series_names)
186
+ if hl:
187
+ ordered_series = [*hl, *[s for s in series_names if s not in hl]]
188
+
189
+ # Compute facts
190
+ facts: list[str] = [
191
+ f"{len(categories)} categories \N{MULTIPLICATION SIGN} {len(ordered_series)} series"
192
+ ]
193
+ wins: dict[str, int] = {s: 0 for s in ordered_series}
194
+ lower_better = sort == "asc"
195
+ for cat in categories:
196
+ present = [(s, grid[cat][s]) for s in ordered_series if grid[cat].get(s) is not None]
197
+ if not present:
198
+ continue
199
+ ranked = sorted(present, key=lambda kv: kv[1], reverse=not lower_better) # type: ignore[arg-type,return-value]
200
+ leader_s, leader_v = ranked[0]
201
+ wins[leader_s] += 1
202
+ if len(ranked) >= 2:
203
+ second_s, second_v = ranked[1]
204
+ facts.append(
205
+ f"{cat}: leader {leader_s} ({_u(leader_v)}) vs {second_s} ({_u(second_v)})"
206
+ )
207
+ else:
208
+ facts.append(f"{cat}: {leader_s} ({_u(leader_v)})")
209
+
210
+ top_winner = max(ordered_series, key=lambda s: wins[s])
211
+ facts.insert(1, f"{top_winner} leads {wins[top_winner]} of {len(categories)} categories")
212
+
213
+ if base is not None:
214
+ targets = hl or [s for s in ordered_series if s != base][:2]
215
+ for tgt in targets:
216
+ deltas = [
217
+ grid[c][tgt] - grid[c][base] # type: ignore[operator]
218
+ for c in categories
219
+ if grid[c].get(tgt) is not None and grid[c].get(base) is not None
220
+ ]
221
+ if deltas:
222
+ d_fmt = _formatter(deltas, fmt, unit=unit)
223
+ avg_d = float(np.mean(deltas))
224
+ lo_d, hi_d = min(deltas), max(deltas)
225
+ facts.append(
226
+ f"{tgt} vs {base}: mean {_diff_with_unit(_signed(d_fmt(avg_d)), unit)} "
227
+ f"(range {_diff_with_unit(_signed(d_fmt(lo_d)), unit)} to "
228
+ f"{_diff_with_unit(_signed(d_fmt(hi_d)), unit)})"
229
+ )
230
+
231
+ n_cats = len(categories)
232
+ n_ser = len(ordered_series)
233
+ diverging = min(all_vals) < 0 < max(all_vals)
234
+
235
+ def _height_mm(cell_w_mm: float, measure: _Measure, sizes: _Sizes, theme: Theme) -> float:
236
+ bar_pitch = (3.7 if n_ser >= 3 else 4.3) * sizes.scale
237
+ cluster_gap = 4.2 * sizes.scale
238
+ header_mm = 7.0 * sizes.scale
239
+ axis_mm = 5.5 * sizes.scale if (dots or log) else 1.5 * sizes.scale
240
+ return header_mm + n_cats * (n_ser * bar_pitch + cluster_gap) + axis_mm
241
+
242
+ def _min_height_mm(cell_w_mm: float, measure: _Measure, sizes: _Sizes, theme: Theme) -> float:
243
+ bar_pitch = 3.2 * sizes.scale
244
+ cluster_gap = 3.2 * sizes.scale
245
+ return 6.0 * sizes.scale + n_cats * (n_ser * bar_pitch + cluster_gap) + 2.0 * sizes.scale
246
+
247
+ def _draw(ctx: _Ctx, ax: Axes) -> None:
248
+ sz = ctx.sizes
249
+ theme = ctx.theme
250
+ accent = {s: col for s, col in ctx.colors.items() if s in ordered_series and s != base}
251
+
252
+ def _scolor(s: str) -> str:
253
+ if s == base:
254
+ return ctx.colors.get(s, theme.ink)
255
+ if hl:
256
+ return accent.get(s, theme.context_fill)
257
+ return ctx.colors.get(s, theme.series_colors[ordered_series.index(s) % len(theme.series_colors)])
258
+
259
+ scolors = {s: _scolor(s) for s in ordered_series}
260
+
261
+ # Geometry: each category occupies a vertical cluster centered at c_idx * step
262
+ bar_h = 0.72
263
+ group_gap = 0.95
264
+ cluster_step = n_ser + group_gap
265
+ centers = np.arange(n_cats, dtype=float) * cluster_step
266
+ offsets = (np.arange(n_ser, dtype=float) - (n_ser - 1) / 2.0) * 0.96
267
+
268
+ _bare_axes(ax)
269
+ top_y = -0.5 * n_ser - 1.35 # room at top for inline series key strip
270
+ bot_y = (n_cats - 1) * cluster_step + 0.5 * n_ser + 0.45
271
+ ax.set_ylim(bot_y, top_y)
272
+
273
+ if dots:
274
+ lo_v = float(min([*all_vals, *([ref[0]] if ref else [])]))
275
+ hi_v = float(max([*all_vals, *([ref[0]] if ref else [])]))
276
+ if log:
277
+ ax.set_xscale("log")
278
+ lims = _narrow_log_ticks(ax.xaxis, lo_v, hi_v, theme.minus_sign, extend=False, data_hi=hi_v)
279
+ ax.set_xlim(*lims)
280
+ else:
281
+ span = (hi_v - lo_v) or abs(hi_v) or 1.0
282
+ ax.set_xlim(lo_v - 0.08 * span, hi_v + 0.14 * span)
283
+ if theme.grid_style != "none" and theme.grid_lw > 0:
284
+ ax.grid(axis="x", color=theme.grid, linestyle=theme.grid_style, linewidth=theme.grid_lw)
285
+ ax.set_axisbelow(True)
286
+ for s_idx, s in enumerate(ordered_series):
287
+ ys_s = []
288
+ xs_s = []
289
+ for c_idx, cat in enumerate(categories):
290
+ v = grid[cat].get(s)
291
+ if v is not None:
292
+ ys_s.append(centers[c_idx] + offsets[s_idx])
293
+ xs_s.append(v)
294
+ if xs_s:
295
+ focus = (not hl) or (s in hl) or (s == base)
296
+ ax.scatter(
297
+ xs_s,
298
+ ys_s,
299
+ s=((4.5 if focus else 3.4) * sz.scale) ** 2,
300
+ color=scolors[s],
301
+ edgecolor=theme.background,
302
+ linewidth=0.5,
303
+ zorder=4 if focus else 3,
304
+ )
305
+ if not log:
306
+ minus = theme.minus_sign
307
+ ax.xaxis.set_major_locator(MaxNLocator(nbins=4, steps=[1, 2, 2.5, 5, 10]))
308
+ ax.xaxis.set_major_formatter(
309
+ FuncFormatter(lambda v, _p, m=minus, a=ax.xaxis: _tick_label(v, m, a))
310
+ )
311
+ ax.tick_params(axis="x", length=0, labelsize=sz.small, labelcolor=theme.muted, pad=3)
312
+ else:
313
+ lo_v = float(min(0.0, *all_vals, *([ref[0]] if ref else [])))
314
+ hi_v = float(max(0.0, *all_vals, *([ref[0]] if ref else [])))
315
+ span = (hi_v - lo_v) or 1.0
316
+ ax.set_xlim(lo_v - (0.04 * span if diverging else 0.0), hi_v + 0.18 * span)
317
+ for s_idx, s in enumerate(ordered_series):
318
+ ys_s = []
319
+ vs_s = []
320
+ for c_idx, cat in enumerate(categories):
321
+ v = grid[cat].get(s)
322
+ if v is not None:
323
+ ys_s.append(centers[c_idx] + offsets[s_idx])
324
+ vs_s.append(v)
325
+ if vs_s:
326
+ ax.barh(
327
+ ys_s,
328
+ vs_s,
329
+ height=bar_h,
330
+ color=scolors[s],
331
+ edgecolor="none",
332
+ zorder=2,
333
+ )
334
+ ax.vlines(
335
+ 0.0,
336
+ -0.5 * n_ser - 0.25,
337
+ bot_y - 0.1,
338
+ color=theme.zero_line,
339
+ linewidth=theme.zero_line_lw,
340
+ zorder=3,
341
+ )
342
+ ax.xaxis.set_visible(False)
343
+
344
+ # Direct value labels at the end of every bar / dot
345
+ first_val_done = False
346
+ for c_idx, cat in enumerate(categories):
347
+ for s_idx, s in enumerate(ordered_series):
348
+ v = grid[cat].get(s)
349
+ if v is None:
350
+ continue
351
+ yi = centers[c_idx] + offsets[s_idx]
352
+ txt = fmt_fn(v)
353
+ if inline_u and not first_val_done:
354
+ txt = _with_unit(txt, unit)
355
+ first_val_done = True
356
+ is_hl_s = s in hl
357
+ anchor_x = v if (dots or v >= 0) else 0.0
358
+ ax.annotate(
359
+ _plain(txt, theme),
360
+ (anchor_x, yi),
361
+ xytext=(4.5, 0.0),
362
+ textcoords="offset points",
363
+ ha="left",
364
+ va="center",
365
+ fontsize=sz.foot,
366
+ fontweight="bold" if is_hl_s else "normal",
367
+ color=theme.ink if (is_hl_s or not hl or s == base) else theme.muted,
368
+ annotation_clip=False,
369
+ )
370
+
371
+ # Subtle horizontal separator between benchmark clusters (LineCollection -> never trips struck check)
372
+ if n_cats > 1:
373
+ sep_ys = [centers[i] + 0.5 * cluster_step for i in range(n_cats - 1)]
374
+ x0, x1 = ax.get_xlim()
375
+ ax.hlines(sep_ys, x0, x1, color=theme.grid, linewidth=0.4 * sz.scale, zorder=1)
376
+
377
+ if ref is not None:
378
+ ax.axvline(ref[0], color=theme.ink, linewidth=0.7, linestyle=(0, (3, 2)), zorder=4)
379
+ if ref[1]:
380
+ ax.annotate(
381
+ _plain(ref[1], theme),
382
+ (ref[0], 1.0),
383
+ xycoords=("data", "axes fraction"),
384
+ xytext=(0.0, 2.5),
385
+ textcoords="offset points",
386
+ ha="center",
387
+ va="bottom",
388
+ fontsize=sz.small,
389
+ color=theme.muted,
390
+ annotation_clip=False,
391
+ )
392
+
393
+ # Category names on y axis
394
+ ax.set_yticks(centers, [_plain(c, theme) for c in categories])
395
+ ax.tick_params(axis="y", length=0, labelsize=sz.body, labelcolor=theme.ink, pad=6)
396
+
397
+ # Inline colour-coded series strip at top of axes (no boxed legend!)
398
+ key_y = top_y + 0.48
399
+ x0, x1 = ax.get_xlim()
400
+ # Use axes-fraction x coordinates so linear & log x axes work identically!
401
+ cell_w_pt = max(ctx.cell_width_mm * 0.65 / PT_TO_MM, 80.0)
402
+ cursor_frac = 0.0
403
+ swatch_w = 0.024
404
+ gap_frac = 0.045
405
+ for s in ordered_series:
406
+ is_focus = (not hl) or (s in hl) or (s == base)
407
+ weight = "bold" if s in hl else "normal"
408
+ label_w_pt = ctx.measure.width_pt(_plain(s, theme), sz.small, weight)
409
+ label_frac = label_w_pt / cell_w_pt
410
+ # Small colour swatch rectangle in axes-x / data-y transform
411
+ ax.add_patch(
412
+ Rectangle(
413
+ (cursor_frac, key_y - 0.24),
414
+ swatch_w,
415
+ 0.48,
416
+ transform=ax.get_yaxis_transform(),
417
+ facecolor=scolors[s],
418
+ edgecolor="none",
419
+ zorder=5,
420
+ clip_on=False,
421
+ )
422
+ )
423
+ ax.text(
424
+ cursor_frac + swatch_w + 0.012,
425
+ key_y,
426
+ _plain(s, theme),
427
+ transform=ax.get_yaxis_transform(),
428
+ ha="left",
429
+ va="center",
430
+ fontsize=sz.small,
431
+ fontweight=weight,
432
+ color=theme.ink if is_focus else theme.muted,
433
+ zorder=5,
434
+ clip_on=False,
435
+ )
436
+ cursor_frac += swatch_w + 0.012 + label_frac + gap_frac
437
+
438
+ spec = _base_spec(
439
+ title,
440
+ label,
441
+ unit,
442
+ values={c: {s: _jsonable(grid[c].get(s)) for s in ordered_series} for c in categories},
443
+ highlight=hl or None,
444
+ baseline=base,
445
+ sort=sort,
446
+ zero=zero,
447
+ reference=list(ref) if ref else None,
448
+ log=log or None,
449
+ fmt=fmt,
450
+ )
451
+ describe = (
452
+ f"Grouped {'dot plot' if dots else 'bar chart'} of {label or 'values'}"
453
+ + (f" ({unit})" if unit else "")
454
+ + f" across {n_cats} categories and {n_ser} series"
455
+ )
456
+ return Panel(
457
+ kind="compare",
458
+ title=title,
459
+ label=label,
460
+ unit=unit,
461
+ spec=spec,
462
+ facts=facts,
463
+ describe=describe,
464
+ _height_mm=_height_mm,
465
+ _min_height_mm=_min_height_mm,
466
+ _draw=_draw,
467
+ color_items=tuple(ordered_series),
468
+ color_focus=tuple(hl or ordered_series),
469
+ color_mode="highlight" if hl else "series",
470
+ color_baseline=base,
471
+ alt_facts=facts[: min(4, len(facts))],
472
+ )