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,623 @@
1
+ """matrix() annotated heat-table form for mint.explain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import numbers
7
+ from collections.abc import Callable, Mapping, Sequence
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+ from matplotlib.axes import Axes
12
+ from matplotlib.colors import to_rgb
13
+ from matplotlib.transforms import Bbox
14
+
15
+ from ..themes import (
16
+ MINTFIG_THEME,
17
+ )
18
+ from .core import (
19
+ MAX_HIGHLIGHTS,
20
+ MAX_MATRIX_COLS,
21
+ MAX_MATRIX_ROWS,
22
+ ExplainError,
23
+ Panel,
24
+ _bare_axes,
25
+ _base_spec,
26
+ _Ctx,
27
+ _diff_with_unit,
28
+ _fit_axes,
29
+ _formatter,
30
+ _guarded,
31
+ _jsonable,
32
+ _labels_collide,
33
+ _plain,
34
+ _relative_luminance,
35
+ _to_float,
36
+ _with_unit,
37
+ )
38
+
39
+ # --------------------------------------------------------------------------- #
40
+ # matrix
41
+ # --------------------------------------------------------------------------- #
42
+
43
+ _SEQ_STOPS = MINTFIG_THEME.seq_stops
44
+ _DIV_LOW = MINTFIG_THEME.div_low
45
+ _DIV_HIGH = MINTFIG_THEME.div_high
46
+ _DIV_MID = MINTFIG_THEME.div_mid
47
+
48
+
49
+ def _ramp(stops: Sequence[str], t: np.ndarray) -> np.ndarray:
50
+ colors = np.array([to_rgb(c) for c in stops])
51
+ pos = np.clip(t, 0.0, 1.0) * (len(stops) - 1)
52
+ lower = np.floor(pos).astype(int).clip(0, len(stops) - 2)
53
+ frac = (pos - lower)[..., None]
54
+ return colors[lower] * (1 - frac) + colors[lower + 1] * frac
55
+
56
+
57
+ def _matrix_highlight(
58
+ highlight: object, row_names: list[str], col_names: list[str]
59
+ ) -> tuple[list[tuple[int, int]], list[int], list[int]]:
60
+ """Cells ``(row, col)``, whole rows and whole columns named by ``matrix(highlight=...)``."""
61
+ hint = (
62
+ 'Use highlight=("row name", "col name") for one cell, a list of such pairs, or a row '
63
+ 'or column name alone, e.g. highlight="Rust" or highlight=[("Rust", "perf"), "Go"].'
64
+ )
65
+ cells: list[tuple[int, int]] = []
66
+ hl_rows: list[int] = []
67
+ hl_cols: list[int] = []
68
+ if highlight is None:
69
+ return cells, hl_rows, hl_cols
70
+
71
+ def _name(entry: object) -> None:
72
+ key = str(entry)
73
+ if key not in row_names and key not in col_names:
74
+ raise ExplainError(
75
+ f"matrix(highlight) names {key!r}, which is neither a row nor a column.",
76
+ fix_hint=hint,
77
+ )
78
+ if key in row_names:
79
+ hl_rows.append(row_names.index(key))
80
+ if key in col_names:
81
+ hl_cols.append(col_names.index(key))
82
+
83
+ def _cell(pair: Sequence[Any]) -> None:
84
+ r_name, c_name = str(pair[0]), str(pair[1])
85
+ if r_name not in row_names or c_name not in col_names:
86
+ raise ExplainError(
87
+ f"matrix(highlight) cell ({r_name!r}, {c_name!r}) is not in rows/cols.",
88
+ fix_hint="Use (row name, column name) pairs exactly as given. " + hint,
89
+ )
90
+ cells.append((row_names.index(r_name), col_names.index(c_name)))
91
+
92
+ def _is_pair(entry: object) -> bool:
93
+ return (
94
+ isinstance(entry, (tuple, list))
95
+ and len(entry) == 2
96
+ and not any(isinstance(e, (list, tuple)) for e in entry)
97
+ )
98
+
99
+ if isinstance(highlight, (str, numbers.Number)):
100
+ _name(highlight)
101
+ elif (
102
+ _is_pair(highlight)
103
+ and str(highlight[0]) in row_names # type: ignore[index]
104
+ and str(highlight[1]) in col_names # type: ignore[index]
105
+ ):
106
+ _cell(highlight) # type: ignore[arg-type]
107
+ elif isinstance(highlight, (list, tuple)):
108
+ for entry in highlight:
109
+ if _is_pair(entry):
110
+ _cell(entry) # type: ignore[arg-type]
111
+ elif isinstance(entry, (str, numbers.Number)):
112
+ _name(entry)
113
+ else:
114
+ raise ExplainError(
115
+ f"matrix(highlight) entry {entry!r} is not a (row, col) pair or a name.",
116
+ fix_hint=hint,
117
+ )
118
+ else:
119
+ raise ExplainError(
120
+ f"matrix(highlight) must be a pair, a list of pairs or a name, got "
121
+ f"{type(highlight).__name__}.",
122
+ fix_hint=hint,
123
+ )
124
+ total = len(cells) + len(set(hl_rows)) + len(set(hl_cols))
125
+ if total > MAX_HIGHLIGHTS:
126
+ raise ExplainError(
127
+ f"matrix(highlight) marks {total} cells/rows/columns; more than {MAX_HIGHLIGHTS} "
128
+ "highlights nothing.",
129
+ fix_hint=f"At most {MAX_HIGHLIGHTS} highlights: outline only the cells, rows or "
130
+ "columns the takeaway names; the numbers in every cell carry the rest.",
131
+ rule="too_many_highlights",
132
+ )
133
+ return cells, sorted(set(hl_rows)), sorted(set(hl_cols))
134
+
135
+
136
+ def _matrix_outlier(
137
+ body: np.ndarray, lo: float, hi: float
138
+ ) -> tuple[tuple[int, int], tuple[float, float], str] | None:
139
+ """The single cell furthest below (or above) the rest of both its row and its column.
140
+
141
+ A cell stands out when it departs from the additive pattern of the grid (its row
142
+ mean + column mean - grand mean) by at least a tenth of the value range and three
143
+ times the typical departure, and is the lowest (highest) of its row and of its
144
+ column; the gaps are to the next-lowest (next-highest) there. Needs 3+ rows and
145
+ columns. A smooth gradient has no outlier, only a corner.
146
+ """
147
+ n_rows, n_cols = body.shape
148
+ ok = np.isfinite(body)
149
+ if n_rows < 3 or n_cols < 3 or ok.sum() < 6:
150
+ return None
151
+ with np.errstate(all="ignore"):
152
+ grand = float(np.nanmean(body))
153
+ fitted = (
154
+ np.nanmean(body, axis=1)[:, None] + np.nanmean(body, axis=0)[None, :] - grand
155
+ )
156
+ resid = np.where(ok, body - fitted, np.nan)
157
+ flat = np.abs(resid[ok])
158
+ order = np.argsort(-np.nan_to_num(np.abs(resid), nan=-1.0), axis=None)
159
+ i, j = np.unravel_index(int(order[0]), body.shape)
160
+ size = abs(float(resid[i, j]))
161
+ typical = float(np.median(np.sort(flat)[:-1])) if flat.size > 1 else 0.0
162
+ if size < 0.1 * ((hi - lo) or 1.0) or size < 3.0 * typical:
163
+ return None
164
+ v = float(body[i, j])
165
+ row = np.delete(body[i], j)
166
+ col = np.delete(body[:, j], i)
167
+ row, col = row[np.isfinite(row)], col[np.isfinite(col)]
168
+ if row.size < 2 or col.size < 2:
169
+ return None
170
+ if resid[i, j] < 0:
171
+ word, gaps = "below", (float(row.min()) - v, float(col.min()) - v)
172
+ else:
173
+ word, gaps = "above", (v - float(row.max()), v - float(col.max()))
174
+ if min(gaps) <= 0: # not the extreme of both its row and its column
175
+ return None
176
+ return (int(i), int(j)), gaps, word
177
+
178
+
179
+ @_guarded("matrix")
180
+ def matrix(
181
+ values: Sequence[Sequence[float | None]] | Sequence[Mapping[str, Any]],
182
+ *,
183
+ rows: Sequence[str] | str | None = None,
184
+ cols: Sequence[str] | str | None = None,
185
+ value: str | None = None,
186
+ title: str | None = None,
187
+ label: str | None = None,
188
+ unit: str | None = None,
189
+ diverging: bool = False,
190
+ center: float = 0.0,
191
+ triangle: str | None = None,
192
+ mask_diagonal: bool = False,
193
+ highlight: Any = None,
194
+ fmt: str | None = None,
195
+ ) -> Panel:
196
+ """How do two categorical dimensions interact? A heat table: colour for the pattern, a number in every cell.
197
+
198
+ ``values[i][j]`` belongs to ``rows[i]`` and ``cols[j]``; a wide pandas
199
+ DataFrame supplies ``rows`` and ``cols`` from its index and columns. For
200
+ long/row-shaped data (``list[dict]`` or tidy DataFrame), pass column names
201
+ ``rows="row_col", cols="col_col", value="val_col"`` to pivot automatically.
202
+ One hue runs light to dark; ``diverging=True`` uses two hues around ``center``
203
+ for signed data. ``highlight`` outlines cells: one ``(row, col)`` pair, a list
204
+ of pairs, or a row or column name for the whole strip.
205
+ """
206
+ from .._tabular import resolve_matrix_table
207
+
208
+ pivoted = resolve_matrix_table(values, rows_arg=rows, cols_arg=cols, value_col=value)
209
+ if pivoted is not None:
210
+ values, rows, cols = pivoted
211
+ else:
212
+ is_frame = hasattr(values, "columns") and hasattr(values, "index")
213
+ if is_frame:
214
+ rows = [str(r) for r in values.index] if rows is None else rows # type: ignore[attr-defined]
215
+ cols = [str(c) for c in values.columns] if cols is None else cols # type: ignore[attr-defined]
216
+ values = values.to_numpy().tolist() if hasattr(values, "to_numpy") else values # type: ignore[attr-defined]
217
+ if rows is None or cols is None:
218
+ raise ExplainError(
219
+ "matrix() needs rows= and cols= to name its rows and columns.",
220
+ fix_hint='Pass rows=["r1", ...] and cols=["c1", ...] aligned with values, or pass a '
221
+ "pandas DataFrame (its index and columns are used).",
222
+ )
223
+ if isinstance(rows, (str, bytes)) or isinstance(cols, (str, bytes)):
224
+ raise ExplainError(
225
+ "matrix(rows) and matrix(cols) must be lists of names.",
226
+ fix_hint='e.g. rows=["Python", "Go"], cols=["bugfix", "docs"].',
227
+ )
228
+ try:
229
+ grid = np.array(
230
+ [
231
+ [np.nan if v is None else _to_float(v, "matrix(values)") for v in row]
232
+ for row in values
233
+ ],
234
+ dtype=float,
235
+ )
236
+ except (TypeError, ValueError) as exc:
237
+ raise ExplainError(
238
+ "matrix(values) must be a rectangular list of rows of numbers.",
239
+ fix_hint="Pass values[i][j] for rows[i] and cols[j]; use None for empty cells.",
240
+ ) from exc
241
+ row_names, col_names = [str(r) for r in rows], [str(c) for c in cols]
242
+ if grid.ndim != 2 or grid.shape != (len(row_names), len(col_names)):
243
+ raise ExplainError(
244
+ f"matrix(values) has shape {grid.shape} but there are {len(row_names)} rows and "
245
+ f"{len(col_names)} cols.",
246
+ fix_hint="values must have one inner list per row, each with one number per column.",
247
+ )
248
+ if len(row_names) > MAX_MATRIX_ROWS or len(col_names) > MAX_MATRIX_COLS:
249
+ raise ExplainError(
250
+ f"matrix() got {len(row_names)}x{len(col_names)} cells; beyond "
251
+ f"{MAX_MATRIX_ROWS}x{MAX_MATRIX_COLS} the numbers stop being readable at chat size.",
252
+ fix_hint=f"matrix() takes at most {MAX_MATRIX_ROWS} rows and {MAX_MATRIX_COLS} "
253
+ "columns (swap rows and cols if only the columns are over): aggregate, keep the "
254
+ "rows/columns the takeaway is about, or split into two matrix() panels.",
255
+ rule="too_many_items",
256
+ )
257
+ if triangle is not None:
258
+ tri_norm = str(triangle).strip().lower()
259
+ if tri_norm not in {"lower", "upper"}:
260
+ raise ExplainError(
261
+ f"matrix(triangle={triangle!r}) must be 'lower', 'upper', or None.",
262
+ fix_hint="Use triangle='lower' or triangle='upper' for symmetric matrices.",
263
+ )
264
+ if len(row_names) != len(col_names):
265
+ raise ExplainError(
266
+ f"matrix(triangle={tri_norm!r}) requires a square matrix, got {len(row_names)}x{len(col_names)}.",
267
+ fix_hint="Drop triangle= for rectangular matrices.",
268
+ )
269
+ triangle = tri_norm
270
+ if mask_diagonal and len(row_names) != len(col_names):
271
+ raise ExplainError(
272
+ f"matrix(mask_diagonal=True) requires a square matrix, got {len(row_names)}x{len(col_names)}.",
273
+ fix_hint="Drop mask_diagonal=True for rectangular matrices.",
274
+ )
275
+
276
+ n_r, n_c = grid.shape
277
+ hidden_mask = np.zeros((n_r, n_c), dtype=bool)
278
+ if triangle == "lower":
279
+ hidden_mask[np.triu_indices(n_r, k=1)] = True
280
+ elif triangle == "upper":
281
+ hidden_mask[np.tril_indices(n_r, k=-1)] = True
282
+ diag_mask = np.eye(n_r, n_c, dtype=bool) if mask_diagonal else np.zeros((n_r, n_c), dtype=bool)
283
+ active_mask = ~(hidden_mask | diag_mask)
284
+
285
+ visible_grid = np.where(active_mask, grid, np.nan)
286
+ finite = visible_grid[np.isfinite(visible_grid)]
287
+ if finite.size == 0:
288
+ raise ExplainError("matrix(values) has no finite visible cells.", fix_hint="Pass numbers.")
289
+ cells, hl_rows, hl_cols = _matrix_highlight(highlight, row_names, col_names)
290
+
291
+ fmt_fn = _formatter(list(finite), fmt, unit=unit)
292
+ lo, hi = float(finite.min()), float(finite.max())
293
+
294
+ square = row_names == col_names and len(row_names) > 1
295
+ diag = np.diag(grid) if square else np.empty(0)
296
+ # A constant diagonal (a correlation matrix's 1s) says nothing: leave it out of
297
+ # highest/lowest and the means, and say so once.
298
+ drop_diag = bool(
299
+ square
300
+ and (
301
+ mask_diagonal
302
+ or (np.isfinite(diag).all() and np.all(diag == diag[0]) and grid.size > diag.size)
303
+ )
304
+ )
305
+ body = grid.copy()
306
+ if drop_diag:
307
+ np.fill_diagonal(body, np.nan)
308
+
309
+ def _cell_text(at: tuple[int, int], source: np.ndarray = grid) -> str:
310
+ return (
311
+ f"{row_names[at[0]]} \N{MULTIPLICATION SIGN} {col_names[at[1]]} = "
312
+ f"{_with_unit(fmt_fn(float(source[at])), unit)}"
313
+ )
314
+
315
+ hi_at = np.unravel_index(int(np.nanargmax(body)), grid.shape)
316
+ lo_at = np.unravel_index(int(np.nanargmin(body)), grid.shape)
317
+ facts = [f"highest: {_cell_text(hi_at)}", f"lowest: {_cell_text(lo_at)}"]
318
+ if drop_diag:
319
+ if mask_diagonal:
320
+ facts.append("diagonal masked from colour scale and extrema")
321
+ else:
322
+ one = _formatter([float(diag[0])], fmt, unit=unit)(float(diag[0]))
323
+ facts.append(f"diagonal is {_with_unit(one, unit)} throughout (excluded)")
324
+ with np.errstate(all="ignore"):
325
+ row_means = np.array(
326
+ [float(np.mean(r[np.isfinite(r)])) if np.isfinite(r).any() else np.nan for r in body]
327
+ )
328
+ col_means = np.array(
329
+ [
330
+ float(np.mean(c[np.isfinite(c)])) if np.isfinite(c).any() else np.nan
331
+ for c in body.T
332
+ ]
333
+ )
334
+ symmetric = square and bool(np.allclose(grid, grid.T, equal_nan=True))
335
+ shown_means = [*row_means, *([] if symmetric else col_means)]
336
+ mean_fmt = _formatter([v for v in shown_means if math.isfinite(v)], fmt, unit=unit)
337
+
338
+ def _mean_fact(which: str, means: np.ndarray, labels_: Sequence[str]) -> None:
339
+ if np.isfinite(means).sum() < 2:
340
+ return
341
+ for word, pick in (("highest", np.nanargmax), ("lowest", np.nanargmin)):
342
+ at = int(pick(means))
343
+ facts.append(
344
+ f"{word} {which} mean: {labels_[at]} "
345
+ f"({_with_unit(mean_fmt(float(means[at])), unit)})"
346
+ )
347
+
348
+ if np.isfinite(row_means).sum() >= 2:
349
+ _mean_fact("row", row_means, row_names)
350
+ else:
351
+ facts.append(
352
+ f"highest row mean: {row_names[int(np.nanargmax(row_means))]} "
353
+ f"({_with_unit(mean_fmt(float(np.nanmax(row_means))), unit)})"
354
+ )
355
+ if not symmetric: # a symmetric matrix's column means are its row means
356
+ _mean_fact("column", col_means, col_names)
357
+ outlier = _matrix_outlier(body, lo, hi)
358
+ if outlier is not None:
359
+ at, gaps, word = outlier
360
+ gap_fmt = _formatter(list(gaps), fmt, unit=unit)
361
+ row_gap, col_gap = (_diff_with_unit(gap_fmt(g), unit) for g in gaps)
362
+ nxt = "next-lowest" if word == "below" else "next-highest"
363
+ facts.append(
364
+ f"outlier: {_cell_text(at)}, {row_gap} {word} the {nxt} in its row and "
365
+ f"{col_gap} {word} the {nxt} in its column"
366
+ )
367
+
368
+ def _same(a: tuple[int, int], b: tuple[int, int]) -> bool:
369
+ cells_match = a == b or (symmetric and a == (b[1], b[0]))
370
+ return cells_match and grid[a] == grid[b]
371
+
372
+ if square:
373
+ off = grid.copy()
374
+ np.fill_diagonal(off, np.nan)
375
+ if np.isfinite(off).any():
376
+ at = np.unravel_index(int(np.nanargmax(off)), off.shape)
377
+ if not (drop_diag and _same(at, hi_at)): # already stated as "highest"
378
+ facts.append(f"largest off-diagonal: {_cell_text(at, off)}")
379
+ if diverging:
380
+ # Signed data: the strongest relationship may be negative. A symmetric
381
+ # matrix names each pair once (upper triangle).
382
+ mag = np.abs(off - center)
383
+ if symmetric:
384
+ mag[np.tril_indices_from(mag)] = np.nan
385
+ if np.isfinite(mag).any():
386
+ st = np.unravel_index(int(np.nanargmax(mag)), mag.shape)
387
+ if not _same(st, at):
388
+ facts.append(f"strongest off-diagonal: {_cell_text(st, off)}")
389
+ # Every highlighted cell's value; for a highlighted row or column, its strongest cell.
390
+ for cell in cells:
391
+ facts.append(_cell_text(cell))
392
+
393
+ def _strongest(sel: np.ndarray, where: str, to_cell: Callable[[int], tuple[int, int]]) -> None:
394
+ if not np.isfinite(sel).any():
395
+ return
396
+ score = np.abs(sel - center) if diverging else sel
397
+ facts.append(f"{where}: strongest {_cell_text(to_cell(int(np.nanargmax(score))))}")
398
+
399
+ for r in hl_rows:
400
+ row = grid[r].copy()
401
+ if square:
402
+ row[r] = np.nan
403
+ _strongest(row, f"{row_names[r]} row", lambda k, r=r: (r, k))
404
+ for c in hl_cols:
405
+ if square and symmetric and c in hl_rows:
406
+ continue # a symmetric matrix's row already said it
407
+ col = grid[:, c].copy()
408
+ if square:
409
+ col[c] = np.nan
410
+ _strongest(col, f"{col_names[c]} column", lambda k, c=c: (k, c))
411
+ empty = int((active_mask & ~np.isfinite(grid)).sum())
412
+ if empty:
413
+ active_total = int(active_mask.sum())
414
+ facts.append(f"{empty} of {active_total} cells empty (no value)")
415
+ longest = max(len(fmt_fn(float(v))) for v in finite)
416
+
417
+ def _draw(ctx: _Ctx, ax: Axes) -> None:
418
+ sz = ctx.sizes
419
+ theme = ctx.theme
420
+ n_rows, n_cols = grid.shape
421
+ if diverging:
422
+ reach = max(hi - center, center - lo) or 1.0
423
+ t = (visible_grid - center) / reach # -1 .. 1
424
+ rgb = np.where(
425
+ (t < 0)[..., None],
426
+ _ramp((*theme.div_low, theme.div_mid), 1.0 + np.nan_to_num(t)),
427
+ _ramp((theme.div_mid, *theme.div_high), np.nan_to_num(t)),
428
+ )
429
+ else:
430
+ t = (visible_grid - lo) / ((hi - lo) or 1.0)
431
+ rgb = _ramp(theme.seq_stops, np.nan_to_num(t))
432
+ bg_rgb = np.array(to_rgb(theme.background))
433
+ empty_rgb = 0.85 * bg_rgb + 0.15 * np.array(to_rgb(theme.context_fill))
434
+ rgb = np.where(np.isfinite(visible_grid)[..., None], rgb, empty_rgb)
435
+ rgb = np.where(hidden_mask[..., None], bg_rgb, rgb)
436
+
437
+ _bare_axes(ax)
438
+ ax.imshow(
439
+ rgb,
440
+ aspect="auto",
441
+ interpolation="nearest",
442
+ zorder=1,
443
+ extent=(-0.5, n_cols - 0.5, n_rows - 0.5, -0.5),
444
+ )
445
+ divider_col = theme.ink if theme.sketch is not None else theme.background
446
+ divider_lw = 0.8 if theme.sketch is not None else 1.6
447
+ if triangle is None or theme.sketch is None:
448
+ ax.hlines(
449
+ np.arange(n_rows + 1) - 0.5,
450
+ -0.5,
451
+ n_cols - 0.5,
452
+ color=divider_col,
453
+ linewidth=divider_lw,
454
+ zorder=2,
455
+ )
456
+ ax.vlines(
457
+ np.arange(n_cols + 1) - 0.5,
458
+ -0.5,
459
+ n_rows - 0.5,
460
+ color=divider_col,
461
+ linewidth=divider_lw,
462
+ zorder=2,
463
+ )
464
+ ax.set_xlim(-0.5, n_cols - 0.5)
465
+ ax.set_ylim(n_rows - 0.5, -0.5)
466
+ if triangle == "lower":
467
+ ax.xaxis.tick_bottom()
468
+ else:
469
+ ax.xaxis.tick_top()
470
+ ax.set_xticks(range(n_cols), [_plain(c, theme) for c in col_names])
471
+ ax.set_yticks(range(n_rows), [_plain(r, theme) for r in row_names])
472
+ ax.tick_params(length=0, labelsize=sz.small, labelcolor=theme.ink, pad=3)
473
+ light_ground = _relative_luminance(theme.background) > 0.5
474
+ light_fg = "#FFFFFF" if light_ground else theme.ink
475
+ dark_fg = theme.ink if light_ground else theme.background
476
+ for (i, j), cell_val in np.ndenumerate(grid):
477
+ if hidden_mask[i, j]:
478
+ continue
479
+ if diag_mask[i, j] or not math.isfinite(cell_val):
480
+ note = ax.text(
481
+ j,
482
+ i,
483
+ "\N{EM DASH}",
484
+ ha="center",
485
+ va="center",
486
+ fontsize=sz.small,
487
+ color=theme.muted,
488
+ zorder=3,
489
+ )
490
+ note._mintfig_heatmap_text = True # type: ignore[attr-defined]
491
+ continue
492
+ dark = (
493
+ _relative_luminance(
494
+ "#{:02X}{:02X}{:02X}".format(*(round(c * 255) for c in rgb[i, j]))
495
+ )
496
+ < 0.36
497
+ )
498
+ note = ax.text(
499
+ j,
500
+ i,
501
+ _plain(fmt_fn(float(cell_val)), theme),
502
+ ha="center",
503
+ va="center",
504
+ fontsize=sz.small,
505
+ color=light_fg if dark else dark_fg,
506
+ zorder=3,
507
+ )
508
+ note._mintfig_heatmap_text = True # type: ignore[attr-defined]
509
+ strips = [
510
+ *((i, j, i, j) for i, j in cells),
511
+ *((i, 0, i, n_cols - 1) for i in hl_rows),
512
+ *((0, j, n_rows - 1, j) for j in hl_cols),
513
+ ]
514
+ for i in hl_rows:
515
+ ax.get_yticklabels()[i].set_fontweight("bold")
516
+ for j in hl_cols:
517
+ ax.get_xticklabels()[j].set_fontweight("bold")
518
+ for i0, j0, i1, j1 in strips:
519
+ ax.plot(
520
+ [j0 - 0.5, j1 + 0.5, j1 + 0.5, j0 - 0.5, j0 - 0.5],
521
+ [i0 - 0.5, i0 - 0.5, i1 + 0.5, i1 + 0.5, i0 - 0.5],
522
+ color=theme.ink,
523
+ linewidth=1.6 * sz.scale,
524
+ zorder=4,
525
+ solid_joinstyle="miter",
526
+ clip_on=False,
527
+ label="_cell",
528
+ )
529
+
530
+ def _check_fit(ctx: _Ctx, ax: Axes) -> None:
531
+ cell_pt = (
532
+ ax.get_window_extent(ctx.fig.canvas.get_renderer()).width
533
+ * ctx.pt_per_px
534
+ / grid.shape[1]
535
+ )
536
+ need_pt = longest * ctx.sizes.small * 0.6 + 3.0
537
+ if cell_pt < need_pt:
538
+ raise ExplainError(
539
+ f"matrix() cells are {cell_pt:.0f} pt wide but the numbers need about {need_pt:.0f} pt.",
540
+ fix_hint="Give the matrix a full-width row, swap rows and cols so fewer run "
541
+ "across, shorten the numbers with fmt, or cut columns.",
542
+ rule="matrix_cells_too_small",
543
+ )
544
+
545
+ def _draw_and_check(ctx: _Ctx, ax: Axes) -> Callable[[], None]:
546
+ _draw(ctx, ax)
547
+ return lambda: _check_fit(ctx, ax)
548
+
549
+ def _headers(ctx: _Ctx, ax: Axes, rect: Bbox) -> list[tuple[Axes, Bbox]]:
550
+ """Column headers must not touch: wrap long ones to two lines, else refuse.
551
+
552
+ Runs between drawing and the final fit, on the axes at its final width.
553
+ """
554
+ _fit_axes(ctx.fig, ax, rect)
555
+ renderer = ctx.fig.canvas.get_renderer()
556
+ gap = 0.35 * ctx.sizes.small / ctx.pt_per_px
557
+
558
+ def _collide() -> bool:
559
+ boxes = [t.get_window_extent(renderer) for t in ax.get_xticklabels() if t.get_text()]
560
+ return _labels_collide([(0.0, b) for b in boxes], True, gap)
561
+
562
+ if not _collide():
563
+ return [(ax, rect)]
564
+ cell_pt = ax.get_window_extent(renderer).width * ctx.pt_per_px / grid.shape[1]
565
+ wrapped: list[str] = []
566
+ for name in col_names:
567
+ words = name.split()
568
+ if len(words) < 2 or ctx.measure.width_pt(name, ctx.sizes.small) <= cell_pt:
569
+ wrapped.append(name)
570
+ continue
571
+ splits = [(" ".join(words[:i]), " ".join(words[i:])) for i in range(1, len(words))]
572
+ best = min(
573
+ splits,
574
+ key=lambda pair: max(ctx.measure.width_pt(p, ctx.sizes.small) for p in pair),
575
+ )
576
+ wrapped.append("\n".join(best))
577
+ ax.set_xticks(range(len(col_names)), [_plain(c, ctx.theme) for c in wrapped])
578
+ for j in hl_cols:
579
+ ax.get_xticklabels()[j].set_fontweight("bold")
580
+ for header in ax.get_xticklabels():
581
+ header.set_linespacing(1.05)
582
+ if _collide():
583
+ raise ExplainError(
584
+ f"matrix() column headers overlap: {grid.shape[1]} columns of about "
585
+ f"{cell_pt:.0f} pt cannot hold names such as "
586
+ f"{max(col_names, key=len)!r}.",
587
+ fix_hint='Give the matrix a wider cell with layout= (e.g. layout=[["a"], '
588
+ '["b", "c"]] for a full-width row), shorten the column names, or swap rows '
589
+ "and cols so the long names run down the side.",
590
+ rule="matrix_cells_too_small",
591
+ )
592
+ return [(ax, rect)]
593
+
594
+ return Panel(
595
+ kind="matrix",
596
+ title=title,
597
+ label=label,
598
+ unit=unit,
599
+ spec=_base_spec(
600
+ title,
601
+ label,
602
+ unit,
603
+ values=[[None if not math.isfinite(v) else float(v) for v in row] for row in grid],
604
+ rows=row_names,
605
+ cols=col_names,
606
+ diverging=diverging or None,
607
+ center=center if diverging else None,
608
+ triangle=triangle,
609
+ mask_diagonal=mask_diagonal or None,
610
+ highlight=_jsonable(highlight) if highlight is not None else None,
611
+ fmt=fmt,
612
+ ),
613
+ facts=facts,
614
+ describe=(
615
+ f"Heat table of {label or 'values'}"
616
+ + (f" ({unit})" if unit else "")
617
+ + f", {len(row_names)} rows by {len(col_names)} columns, a number in every cell"
618
+ ),
619
+ _height_mm=lambda _w, _m, _s, _t: 6.2 * len(row_names) + 6.0,
620
+ _min_height_mm=lambda _w, _m, _s, _t: 5.0 * len(row_names) + 6.0,
621
+ _draw=_draw_and_check,
622
+ _frames=_headers,
623
+ )