mintfig 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mintfig/__init__.py +162 -0
- mintfig/_explain/__init__.py +1 -0
- mintfig/_explain/change.py +392 -0
- mintfig/_explain/compare.py +1308 -0
- mintfig/_explain/compare_grouped.py +472 -0
- mintfig/_explain/core.py +2005 -0
- mintfig/_explain/distribution.py +1268 -0
- mintfig/_explain/flow.py +508 -0
- mintfig/_explain/layout.py +2012 -0
- mintfig/_explain/matrix.py +623 -0
- mintfig/_explain/relate.py +1318 -0
- mintfig/_explain/timeline.py +595 -0
- mintfig/_explain/trend.py +2557 -0
- mintfig/_explain/waterfall.py +459 -0
- mintfig/_table.py +691 -0
- mintfig/_tabular.py +738 -0
- mintfig/annotations.py +1165 -0
- mintfig/assets/AGENTS_SNIPPET.md +11 -0
- mintfig/assets/SKILL.md +143 -0
- mintfig/assets/__init__.py +1 -0
- mintfig/assets/references/publication.md +79 -0
- mintfig/assets/references/scientific_and_recipes.md +213 -0
- mintfig/audit.py +179 -0
- mintfig/brief.py +518 -0
- mintfig/bundle.py +333 -0
- mintfig/cli.py +1300 -0
- mintfig/edit.py +347 -0
- mintfig/epistemic.py +1083 -0
- mintfig/explainer.py +194 -0
- mintfig/export.py +247 -0
- mintfig/inspect_data.py +583 -0
- mintfig/interactive.py +1028 -0
- mintfig/palettes.py +233 -0
- mintfig/plate.py +784 -0
- mintfig/preflight.py +2398 -0
- mintfig/proof.py +627 -0
- mintfig/runner.py +403 -0
- mintfig/skill.py +167 -0
- mintfig/specs.py +291 -0
- mintfig/style.py +151 -0
- mintfig/terminal.py +785 -0
- mintfig/themes.py +660 -0
- mintfig-0.2.0.dist-info/METADATA +239 -0
- mintfig-0.2.0.dist-info/RECORD +47 -0
- mintfig-0.2.0.dist-info/WHEEL +4 -0
- mintfig-0.2.0.dist-info/entry_points.txt +2 -0
- mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
mintfig/_table.py
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
"""Structured booktabs-style table form (``mint.table``) for exact lookups and scorecards.
|
|
2
|
+
|
|
3
|
+
Designed as an independent module so ``explainer.py`` stays modular. Obeys the
|
|
4
|
+
same contract as every other ``mint.explain`` form: declarative spec, computed
|
|
5
|
+
``facts``, shared entity colours across panels, theme/palette support, and
|
|
6
|
+
strict layout/legibility verification.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
import numbers
|
|
13
|
+
from collections.abc import Mapping, Sequence
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
|
+
|
|
16
|
+
from matplotlib.patches import Rectangle
|
|
17
|
+
|
|
18
|
+
from ._tabular import extract_table_data
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from matplotlib.axes import Axes
|
|
22
|
+
|
|
23
|
+
from .explainer import Panel, _Ctx, _Measure, _Sizes
|
|
24
|
+
from .themes import Theme
|
|
25
|
+
|
|
26
|
+
MAX_TABLE_ROWS = 20
|
|
27
|
+
MAX_TABLE_COLS = 8
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _is_missing(val: Any) -> bool:
|
|
31
|
+
if val is None:
|
|
32
|
+
return True
|
|
33
|
+
if isinstance(val, float) and (math.isnan(val) or math.isinf(val)):
|
|
34
|
+
return True
|
|
35
|
+
return bool(isinstance(val, str) and not val.strip())
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _as_float_or_none(val: Any) -> float | None:
|
|
39
|
+
if _is_missing(val) or isinstance(val, bool):
|
|
40
|
+
return None
|
|
41
|
+
if isinstance(val, numbers.Real):
|
|
42
|
+
f = float(val)
|
|
43
|
+
return f if math.isfinite(f) else None
|
|
44
|
+
if isinstance(val, str):
|
|
45
|
+
text = val.strip()
|
|
46
|
+
try:
|
|
47
|
+
f = float(text)
|
|
48
|
+
except ValueError:
|
|
49
|
+
return None
|
|
50
|
+
return f if math.isfinite(f) else None
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _wrap_header(text: str, max_pt: float, measure: _Measure, size_pt: float) -> str:
|
|
55
|
+
"""Wrap a multi-word header onto at most two balanced lines when needed."""
|
|
56
|
+
if "\n" in text or measure.width_pt(text, size_pt) <= max_pt:
|
|
57
|
+
return text
|
|
58
|
+
words = text.split()
|
|
59
|
+
if len(words) < 2:
|
|
60
|
+
return text
|
|
61
|
+
best = text
|
|
62
|
+
best_width = float("inf")
|
|
63
|
+
for idx in range(1, len(words)):
|
|
64
|
+
top = " ".join(words[:idx])
|
|
65
|
+
bot = " ".join(words[idx:])
|
|
66
|
+
w = max(measure.width_pt(top, size_pt), measure.width_pt(bot, size_pt))
|
|
67
|
+
if w < best_width:
|
|
68
|
+
best_width = w
|
|
69
|
+
best = f"{top}\n{bot}"
|
|
70
|
+
return best
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _format_cell_markdown(headers: list[str], aligns: list[str], rows: list[list[str]]) -> str:
|
|
74
|
+
"""Render formatted table strings as a clean GitHub-Flavored Markdown table."""
|
|
75
|
+
widths = [
|
|
76
|
+
max(len(headers[c]), *(len(r[c]) for r in rows), 3) for c in range(len(headers))
|
|
77
|
+
]
|
|
78
|
+
align_sep = {
|
|
79
|
+
"left": lambda w: ":" + "-" * (w - 1),
|
|
80
|
+
"right": lambda w: "-" * (w - 1) + ":",
|
|
81
|
+
"center": lambda w: ":" + "-" * max(1, w - 2) + ":",
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
def _pad(val: str, w: int, al: str) -> str:
|
|
85
|
+
if al == "right":
|
|
86
|
+
return val.rjust(w)
|
|
87
|
+
if al == "center":
|
|
88
|
+
return val.center(w)
|
|
89
|
+
return val.ljust(w)
|
|
90
|
+
|
|
91
|
+
lines = [
|
|
92
|
+
"| " + " | ".join(_pad(headers[c], widths[c], aligns[c]) for c in range(len(headers))) + " |",
|
|
93
|
+
"| " + " | ".join(align_sep[aligns[c]](widths[c]) for c in range(len(headers))) + " |",
|
|
94
|
+
]
|
|
95
|
+
for row in rows:
|
|
96
|
+
lines.append(
|
|
97
|
+
"| " + " | ".join(_pad(row[c], widths[c], aligns[c]) for c in range(len(headers))) + " |"
|
|
98
|
+
)
|
|
99
|
+
return "\n".join(lines)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def table(
|
|
103
|
+
rows: Sequence[Mapping[str, Any]] | Mapping[str, Sequence[Any]] | Sequence[Sequence[Any]],
|
|
104
|
+
*,
|
|
105
|
+
columns: Sequence[str] | None = None,
|
|
106
|
+
title: str | None = None,
|
|
107
|
+
label: str | None = None,
|
|
108
|
+
unit: str | None = None,
|
|
109
|
+
units: Mapping[str, str] | None = None,
|
|
110
|
+
highlight: str | Sequence[str] | None = None,
|
|
111
|
+
baseline: str | None = None,
|
|
112
|
+
bold_best: bool | str | Mapping[str, str] = False,
|
|
113
|
+
sort: str | None = None,
|
|
114
|
+
align: Mapping[str, str] | None = None,
|
|
115
|
+
fmt: str | Mapping[str, str] | None = None,
|
|
116
|
+
) -> Panel:
|
|
117
|
+
"""Exact lookup table or multi-metric scorecard with booktabs rules and aligned figures.
|
|
118
|
+
|
|
119
|
+
``rows`` accepts a list of row dicts (``[{"Model": "A", "GPQA": 84.1, ...}]``),
|
|
120
|
+
a pandas DataFrame, a column-oriented dict ``{"Model": [...], "GPQA": [...]}``,
|
|
121
|
+
or a 2-D list paired with ``columns=[...]``.
|
|
122
|
+
|
|
123
|
+
- ``highlight`` emphasizes 1–3 rows by column-0 name (sharing colours with
|
|
124
|
+
adjacent chart panels in the same figure).
|
|
125
|
+
- ``baseline`` marks a reference row in ink and states highlighted/best rows
|
|
126
|
+
against it in ``facts``.
|
|
127
|
+
- ``bold_best`` bolds each numeric column's winner: ``True`` / ``"max"``,
|
|
128
|
+
``"min"``, or ``{col: "max" | "min"}`` for mixed-direction scorecards
|
|
129
|
+
(e.g. ``{"GPQA": "max", "Cost": "min"}``).
|
|
130
|
+
- ``sort`` sorts by a column name (``"col"`` ascending, ``"-col"`` descending).
|
|
131
|
+
- ``units`` attaches per-column units (``{"GPQA": "%", "Cost": "$/M"}``).
|
|
132
|
+
- ``fmt`` sets a global format string or ``{col: fmt_str}``.
|
|
133
|
+
"""
|
|
134
|
+
from ._explain.core import (
|
|
135
|
+
_LINE,
|
|
136
|
+
PT_TO_MM,
|
|
137
|
+
ExplainError,
|
|
138
|
+
Panel,
|
|
139
|
+
_bare_axes,
|
|
140
|
+
_baseline_name,
|
|
141
|
+
_formatter,
|
|
142
|
+
_is_strict,
|
|
143
|
+
_jsonable,
|
|
144
|
+
_names,
|
|
145
|
+
_plain,
|
|
146
|
+
_record_adjustment,
|
|
147
|
+
_relative_luminance,
|
|
148
|
+
_with_unit,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
def _line_mm(pt: float) -> float:
|
|
152
|
+
return pt * _LINE * PT_TO_MM
|
|
153
|
+
|
|
154
|
+
col_names, raw_rows = extract_table_data(rows, columns=columns)
|
|
155
|
+
if not col_names:
|
|
156
|
+
raise ExplainError("table() has no columns.", fix_hint="Pass at least one column.")
|
|
157
|
+
if not raw_rows:
|
|
158
|
+
raise ExplainError("table() has no rows.", fix_hint="Pass at least one row.")
|
|
159
|
+
|
|
160
|
+
# Column limit
|
|
161
|
+
if len(col_names) > MAX_TABLE_COLS:
|
|
162
|
+
if not _is_strict():
|
|
163
|
+
orig = len(col_names)
|
|
164
|
+
col_names = col_names[:MAX_TABLE_COLS]
|
|
165
|
+
raw_rows = [r[:MAX_TABLE_COLS] for r in raw_rows]
|
|
166
|
+
_record_adjustment(f"table(): trimmed {orig} columns to first {MAX_TABLE_COLS}")
|
|
167
|
+
else:
|
|
168
|
+
raise ExplainError(
|
|
169
|
+
f"table() got {len(col_names)} columns; beyond {MAX_TABLE_COLS} columns "
|
|
170
|
+
"a chat table becomes unreadable.",
|
|
171
|
+
fix_hint=f"Keep at most {MAX_TABLE_COLS} columns via columns=[...], or split into two tables.",
|
|
172
|
+
rule="too_many_items",
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
# Validate units / align / fmt / bold_best column keys
|
|
176
|
+
unit_map: dict[str, str] = {}
|
|
177
|
+
if units is not None:
|
|
178
|
+
if not isinstance(units, Mapping):
|
|
179
|
+
raise ExplainError(
|
|
180
|
+
"table(units) must be a mapping of column name -> unit.",
|
|
181
|
+
fix_hint='e.g. units={"GPQA": "%", "Cost": "$/M"}.',
|
|
182
|
+
)
|
|
183
|
+
for k, v in units.items():
|
|
184
|
+
ks = str(k)
|
|
185
|
+
if ks not in col_names:
|
|
186
|
+
raise ExplainError(
|
|
187
|
+
f"table(units) names unknown column {ks!r}.",
|
|
188
|
+
fix_hint=f"Use column names from: {', '.join(map(repr, col_names))}.",
|
|
189
|
+
)
|
|
190
|
+
unit_map[ks] = str(v)
|
|
191
|
+
|
|
192
|
+
fmt_map: dict[str, str] = {}
|
|
193
|
+
global_fmt: str | None = None
|
|
194
|
+
if isinstance(fmt, str):
|
|
195
|
+
global_fmt = fmt
|
|
196
|
+
elif isinstance(fmt, Mapping):
|
|
197
|
+
for k, v in fmt.items():
|
|
198
|
+
ks = str(k)
|
|
199
|
+
if ks not in col_names:
|
|
200
|
+
raise ExplainError(
|
|
201
|
+
f"table(fmt) names unknown column {ks!r}.",
|
|
202
|
+
fix_hint=f"Use column names from: {', '.join(map(repr, col_names))}.",
|
|
203
|
+
)
|
|
204
|
+
fmt_map[ks] = str(v)
|
|
205
|
+
elif fmt is not None:
|
|
206
|
+
raise ExplainError(
|
|
207
|
+
"table(fmt) must be a format string or a dict of {column: fmt}.",
|
|
208
|
+
fix_hint='e.g. fmt=".1f" or fmt={"Score": ".1f", "Cost": "${:.2f}"}.',
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
# Optional sort before row-limit trimming so top rows are kept
|
|
212
|
+
if sort is not None:
|
|
213
|
+
if not isinstance(sort, str) or not sort.strip():
|
|
214
|
+
raise ExplainError(
|
|
215
|
+
"table(sort) must be a column name (prefix '-' for descending).",
|
|
216
|
+
fix_hint=f'e.g. sort="-{col_names[-1]}" or sort="{col_names[0]}".',
|
|
217
|
+
)
|
|
218
|
+
desc = sort.startswith("-")
|
|
219
|
+
sort_col = sort[1:] if desc else sort
|
|
220
|
+
if sort_col not in col_names:
|
|
221
|
+
raise ExplainError(
|
|
222
|
+
f"table(sort={sort!r}) names unknown column {sort_col!r}.",
|
|
223
|
+
fix_hint=f"Use a column from: {', '.join(map(repr, col_names))} (prefix '-' for descending).",
|
|
224
|
+
)
|
|
225
|
+
cidx = col_names.index(sort_col)
|
|
226
|
+
col_nums = [_as_float_or_none(r[cidx]) for r in raw_rows]
|
|
227
|
+
if any(v is not None for v in col_nums):
|
|
228
|
+
present = [i for i, v in enumerate(col_nums) if v is not None]
|
|
229
|
+
missing_idx = [i for i, v in enumerate(col_nums) if v is None]
|
|
230
|
+
present.sort(key=lambda i: col_nums[i], reverse=desc) # type: ignore[arg-type,return-value]
|
|
231
|
+
raw_rows = [raw_rows[i] for i in (*present, *missing_idx)]
|
|
232
|
+
else:
|
|
233
|
+
raw_rows = sorted(
|
|
234
|
+
raw_rows,
|
|
235
|
+
key=lambda r: ("" if _is_missing(r[cidx]) else str(r[cidx]).lower()),
|
|
236
|
+
reverse=desc,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
row_keys = [
|
|
240
|
+
"\N{EM DASH}" if _is_missing(r[0]) else str(r[0]) for r in raw_rows
|
|
241
|
+
]
|
|
242
|
+
|
|
243
|
+
# Row limit
|
|
244
|
+
if len(raw_rows) > MAX_TABLE_ROWS:
|
|
245
|
+
if not _is_strict():
|
|
246
|
+
req_hl = (
|
|
247
|
+
[highlight]
|
|
248
|
+
if isinstance(highlight, str)
|
|
249
|
+
else ([str(h) for h in highlight] if highlight is not None else [])
|
|
250
|
+
)
|
|
251
|
+
must_keep = set(req_hl)
|
|
252
|
+
if baseline is not None:
|
|
253
|
+
must_keep.add(str(baseline))
|
|
254
|
+
kept_idx: list[int] = [i for i, rk in enumerate(row_keys) if rk in must_keep]
|
|
255
|
+
for i in range(len(raw_rows)):
|
|
256
|
+
if len(kept_idx) >= MAX_TABLE_ROWS:
|
|
257
|
+
break
|
|
258
|
+
if i not in kept_idx:
|
|
259
|
+
kept_idx.append(i)
|
|
260
|
+
kept_idx.sort()
|
|
261
|
+
orig_n = len(raw_rows)
|
|
262
|
+
raw_rows = [raw_rows[i] for i in kept_idx]
|
|
263
|
+
row_keys = [row_keys[i] for i in kept_idx]
|
|
264
|
+
_record_adjustment(f"table(): trimmed {orig_n} rows to {len(raw_rows)}")
|
|
265
|
+
else:
|
|
266
|
+
raise ExplainError(
|
|
267
|
+
f"table() got {len(raw_rows)} rows; beyond {MAX_TABLE_ROWS} rows a chat "
|
|
268
|
+
"table is scanned, not read.",
|
|
269
|
+
fix_hint=f"Keep at most {MAX_TABLE_ROWS} rows (e.g. top rows in sort=), or split into two tables.",
|
|
270
|
+
rule="too_many_items",
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
hl = _names(highlight, row_keys, "table(highlight)")
|
|
274
|
+
base = _baseline_name(baseline, row_keys, hl, "table")
|
|
275
|
+
|
|
276
|
+
# Detect numeric columns (excluding column 0 unless only 1 column exists)
|
|
277
|
+
n_rows = len(raw_rows)
|
|
278
|
+
n_cols = len(col_names)
|
|
279
|
+
col_numeric: list[bool] = []
|
|
280
|
+
col_floats: list[list[float | None]] = []
|
|
281
|
+
for c in range(n_cols):
|
|
282
|
+
vals = [raw_rows[r][c] for r in range(n_rows)]
|
|
283
|
+
parsed = [_as_float_or_none(v) for v in vals]
|
|
284
|
+
non_missing = [v for v in vals if not _is_missing(v)]
|
|
285
|
+
is_num = (
|
|
286
|
+
bool(non_missing)
|
|
287
|
+
and all(_as_float_or_none(v) is not None for v in non_missing)
|
|
288
|
+
and (c > 0 or n_cols == 1)
|
|
289
|
+
)
|
|
290
|
+
col_numeric.append(is_num)
|
|
291
|
+
col_floats.append(parsed)
|
|
292
|
+
|
|
293
|
+
# Alignment per column
|
|
294
|
+
col_align: list[str] = ["right" if col_numeric[c] else "left" for c in range(n_cols)]
|
|
295
|
+
if align is not None:
|
|
296
|
+
if not isinstance(align, Mapping):
|
|
297
|
+
raise ExplainError(
|
|
298
|
+
"table(align) must map column name to 'left', 'right' or 'center'.",
|
|
299
|
+
fix_hint='e.g. align={"Rank": "center"}.',
|
|
300
|
+
)
|
|
301
|
+
for k, v in align.items():
|
|
302
|
+
ks = str(k)
|
|
303
|
+
vs = str(v).lower()
|
|
304
|
+
if ks not in col_names:
|
|
305
|
+
raise ExplainError(
|
|
306
|
+
f"table(align) names unknown column {ks!r}.",
|
|
307
|
+
fix_hint=f"Use column names from: {', '.join(map(repr, col_names))}.",
|
|
308
|
+
)
|
|
309
|
+
if vs not in {"left", "right", "center"}:
|
|
310
|
+
raise ExplainError(
|
|
311
|
+
f"table(align[{ks!r}]) must be 'left', 'right' or 'center', got {v!r}.",
|
|
312
|
+
fix_hint='Use "left", "right", or "center".',
|
|
313
|
+
)
|
|
314
|
+
col_align[col_names.index(ks)] = vs
|
|
315
|
+
|
|
316
|
+
# Best-in-column bolding
|
|
317
|
+
best_dir: dict[int, str] = {}
|
|
318
|
+
if bold_best is True or bold_best == "max":
|
|
319
|
+
for c in range(n_cols):
|
|
320
|
+
if col_numeric[c]:
|
|
321
|
+
best_dir[c] = "max"
|
|
322
|
+
elif bold_best == "min":
|
|
323
|
+
for c in range(n_cols):
|
|
324
|
+
if col_numeric[c]:
|
|
325
|
+
best_dir[c] = "min"
|
|
326
|
+
elif isinstance(bold_best, Mapping):
|
|
327
|
+
for k, v in bold_best.items():
|
|
328
|
+
ks = str(k)
|
|
329
|
+
vs = str(v).lower()
|
|
330
|
+
if ks not in col_names:
|
|
331
|
+
raise ExplainError(
|
|
332
|
+
f"table(bold_best) names unknown column {ks!r}.",
|
|
333
|
+
fix_hint=f"Use column names from: {', '.join(map(repr, col_names))}.",
|
|
334
|
+
)
|
|
335
|
+
if vs not in {"max", "min"}:
|
|
336
|
+
raise ExplainError(
|
|
337
|
+
f"table(bold_best[{ks!r}]) must be 'max' or 'min', got {v!r}.",
|
|
338
|
+
fix_hint='Use "max" (higher is better) or "min" (lower is better).',
|
|
339
|
+
)
|
|
340
|
+
best_dir[col_names.index(ks)] = vs
|
|
341
|
+
elif bold_best not in (False, None):
|
|
342
|
+
raise ExplainError(
|
|
343
|
+
f"table(bold_best={bold_best!r}) is not valid.",
|
|
344
|
+
fix_hint='Pass True, False, "max", "min", or {column: "max"|"min"}.',
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
best_cells: set[tuple[int, int]] = set()
|
|
348
|
+
for c, direction in best_dir.items():
|
|
349
|
+
finite_pairs = [(r, col_floats[c][r]) for r in range(n_rows) if col_floats[c][r] is not None]
|
|
350
|
+
if not finite_pairs:
|
|
351
|
+
continue
|
|
352
|
+
target_val = (
|
|
353
|
+
max(v for _, v in finite_pairs) # type: ignore[type-var]
|
|
354
|
+
if direction == "max"
|
|
355
|
+
else min(v for _, v in finite_pairs) # type: ignore[type-var]
|
|
356
|
+
)
|
|
357
|
+
for r, v in finite_pairs:
|
|
358
|
+
if v is not None and target_val is not None and math.isclose(v, target_val, rel_tol=1e-9, abs_tol=1e-12):
|
|
359
|
+
best_cells.add((r, c))
|
|
360
|
+
|
|
361
|
+
# Format headers (include per-column unit cleanly when not already in header)
|
|
362
|
+
header_labels: list[str] = []
|
|
363
|
+
for c, cname in enumerate(col_names):
|
|
364
|
+
u = unit_map.get(cname)
|
|
365
|
+
if u and f"({u})" not in cname and f"[{u}]" not in cname:
|
|
366
|
+
header_labels.append(f"{cname} ({u})")
|
|
367
|
+
else:
|
|
368
|
+
header_labels.append(cname)
|
|
369
|
+
|
|
370
|
+
# Format cell strings
|
|
371
|
+
col_formatters: dict[int, Any] = {}
|
|
372
|
+
formatted: list[list[str]] = [["" for _ in range(n_cols)] for _ in range(n_rows)]
|
|
373
|
+
missing_count = 0
|
|
374
|
+
for c in range(n_cols):
|
|
375
|
+
cname = col_names[c]
|
|
376
|
+
u = unit_map.get(cname) or (unit if col_numeric[c] and not unit_map else None)
|
|
377
|
+
if col_numeric[c]:
|
|
378
|
+
finite_vals = [v for v in col_floats[c] if v is not None]
|
|
379
|
+
cfmt = fmt_map.get(cname, global_fmt)
|
|
380
|
+
fmt_fn = _formatter(finite_vals, cfmt, unit=u)
|
|
381
|
+
col_formatters[c] = fmt_fn
|
|
382
|
+
for r in range(n_rows):
|
|
383
|
+
fv = col_floats[c][r]
|
|
384
|
+
if fv is None:
|
|
385
|
+
formatted[r][c] = "\N{EM DASH}"
|
|
386
|
+
missing_count += 1
|
|
387
|
+
else:
|
|
388
|
+
formatted[r][c] = fmt_fn(fv)
|
|
389
|
+
else:
|
|
390
|
+
for r in range(n_rows):
|
|
391
|
+
val = raw_rows[r][c]
|
|
392
|
+
if _is_missing(val):
|
|
393
|
+
formatted[r][c] = "\N{EM DASH}"
|
|
394
|
+
missing_count += 1
|
|
395
|
+
else:
|
|
396
|
+
formatted[r][c] = str(val)
|
|
397
|
+
|
|
398
|
+
def _cell_with_unit(val_str: str, u: str | None) -> str:
|
|
399
|
+
if not u:
|
|
400
|
+
return val_str
|
|
401
|
+
if val_str.startswith("$") and u.startswith("$"):
|
|
402
|
+
return val_str + u[1:]
|
|
403
|
+
return _with_unit(val_str, u)
|
|
404
|
+
|
|
405
|
+
# Compute facts
|
|
406
|
+
facts: list[str] = [f"{n_rows} rows \N{MULTIPLICATION SIGN} {n_cols} columns"]
|
|
407
|
+
base_idx = row_keys.index(base) if base is not None else None
|
|
408
|
+
for c in range(n_cols):
|
|
409
|
+
if not col_numeric[c]:
|
|
410
|
+
continue
|
|
411
|
+
cname = col_names[c]
|
|
412
|
+
u = unit_map.get(cname) or (unit if not unit_map else None)
|
|
413
|
+
fmt_fn = col_formatters[c]
|
|
414
|
+
finite_pairs = [(r, col_floats[c][r]) for r in range(n_rows) if col_floats[c][r] is not None]
|
|
415
|
+
if not finite_pairs:
|
|
416
|
+
continue
|
|
417
|
+
hi_r, hi_v = max(finite_pairs, key=lambda kv: kv[1]) # type: ignore[arg-type,return-value]
|
|
418
|
+
lo_r, lo_v = min(finite_pairs, key=lambda kv: kv[1]) # type: ignore[arg-type,return-value]
|
|
419
|
+
hi_txt = _cell_with_unit(fmt_fn(hi_v), u)
|
|
420
|
+
lo_txt = _cell_with_unit(fmt_fn(lo_v), u)
|
|
421
|
+
if hi_r == lo_r:
|
|
422
|
+
facts.append(f"{cname}: all {hi_txt}")
|
|
423
|
+
else:
|
|
424
|
+
facts.append(f"{cname}: highest {row_keys[hi_r]} ({hi_txt}), lowest {row_keys[lo_r]} ({lo_txt})")
|
|
425
|
+
if base_idx is not None and col_floats[c][base_idx] is not None:
|
|
426
|
+
bv = col_floats[c][base_idx]
|
|
427
|
+
assert bv is not None
|
|
428
|
+
targets = [row_keys.index(nm) for nm in hl] if hl else [hi_r]
|
|
429
|
+
for tr in targets:
|
|
430
|
+
if tr == base_idx or col_floats[c][tr] is None:
|
|
431
|
+
continue
|
|
432
|
+
tv = col_floats[c][tr]
|
|
433
|
+
assert tv is not None
|
|
434
|
+
diff = tv - bv
|
|
435
|
+
sign = "+" if diff > 0 else ("\N{MINUS SIGN}" if diff < 0 else "")
|
|
436
|
+
dtxt = _cell_with_unit(fmt_fn(abs(diff)), u)
|
|
437
|
+
facts.append(f"{cname}: {row_keys[tr]} vs {base} is {sign}{dtxt}")
|
|
438
|
+
if missing_count:
|
|
439
|
+
facts.append(f"{missing_count} empty cell(s) shown as \N{EM DASH}")
|
|
440
|
+
|
|
441
|
+
markdown_text = _format_cell_markdown(header_labels, col_align, formatted)
|
|
442
|
+
|
|
443
|
+
# Height computation: proportional to row count + header height
|
|
444
|
+
def _height_mm(cell_w_mm: float, measure: _Measure, sizes: _Sizes, theme: Theme) -> float:
|
|
445
|
+
row_h = max(_line_mm(sizes.small) * 1.48, 5.2 * sizes.scale)
|
|
446
|
+
# Estimate whether any header wraps to 2 lines
|
|
447
|
+
head_lines = 1
|
|
448
|
+
est_col_pt = (cell_w_mm / PT_TO_MM) / max(n_cols, 1)
|
|
449
|
+
if any(measure.width_pt(h, sizes.small) > est_col_pt * 1.15 and " " in h for h in header_labels):
|
|
450
|
+
head_lines = 2
|
|
451
|
+
head_h = max(_line_mm(sizes.small) * (1.25 * head_lines + 0.55), 6.2 * sizes.scale)
|
|
452
|
+
return head_h + n_rows * row_h + 2.2 * sizes.scale
|
|
453
|
+
|
|
454
|
+
def _min_height_mm(cell_w_mm: float, measure: _Measure, sizes: _Sizes, theme: Theme) -> float:
|
|
455
|
+
row_h = max(_line_mm(sizes.small) * 1.32, 4.6 * sizes.scale)
|
|
456
|
+
head_h = max(_line_mm(sizes.small) * 1.7, 5.8 * sizes.scale)
|
|
457
|
+
return head_h + n_rows * row_h + 1.8 * sizes.scale
|
|
458
|
+
|
|
459
|
+
def _draw(ctx: _Ctx, ax: Axes) -> Any:
|
|
460
|
+
sz = ctx.sizes
|
|
461
|
+
theme = ctx.theme
|
|
462
|
+
measure = ctx.measure
|
|
463
|
+
cell_w_pt = ctx.cell_width_mm / PT_TO_MM
|
|
464
|
+
|
|
465
|
+
pad_pt = 4.2 * sz.scale
|
|
466
|
+
stripe_pad_pt = 4.0 * sz.scale if (hl or base) else 1.5 * sz.scale
|
|
467
|
+
|
|
468
|
+
# Measure natural column widths
|
|
469
|
+
data_widths = [
|
|
470
|
+
max(
|
|
471
|
+
(measure.width_pt(_plain(formatted[r][c], theme), sz.small) for r in range(n_rows)),
|
|
472
|
+
default=14.0,
|
|
473
|
+
)
|
|
474
|
+
for c in range(n_cols)
|
|
475
|
+
]
|
|
476
|
+
head_widths_1 = [
|
|
477
|
+
measure.width_pt(_plain(header_labels[c], theme), sz.small) * 1.06
|
|
478
|
+
for c in range(n_cols)
|
|
479
|
+
]
|
|
480
|
+
|
|
481
|
+
# Decide whether to wrap headers to fit width
|
|
482
|
+
need_1 = [max(data_widths[c], head_widths_1[c]) + 2 * pad_pt for c in range(n_cols)]
|
|
483
|
+
need_1[0] += stripe_pad_pt
|
|
484
|
+
drawn_headers = list(header_labels)
|
|
485
|
+
if sum(need_1) > cell_w_pt:
|
|
486
|
+
# Try wrapping multi-word headers
|
|
487
|
+
for c in range(n_cols):
|
|
488
|
+
target_w = max(data_widths[c], head_widths_1[c] * 0.58)
|
|
489
|
+
wrapped = _wrap_header(header_labels[c], target_w, measure, sz.small)
|
|
490
|
+
drawn_headers[c] = wrapped
|
|
491
|
+
head_widths_2 = [
|
|
492
|
+
max(
|
|
493
|
+
measure.width_pt(_plain(line, theme), sz.small) * 1.06
|
|
494
|
+
for line in drawn_headers[c].split("\n")
|
|
495
|
+
)
|
|
496
|
+
for c in range(n_cols)
|
|
497
|
+
]
|
|
498
|
+
need = [max(data_widths[c], head_widths_2[c]) + 2 * pad_pt for c in range(n_cols)]
|
|
499
|
+
need[0] += stripe_pad_pt
|
|
500
|
+
else:
|
|
501
|
+
need = need_1
|
|
502
|
+
|
|
503
|
+
total_need = sum(need)
|
|
504
|
+
if total_need > cell_w_pt * 1.04:
|
|
505
|
+
raise ExplainError(
|
|
506
|
+
f"table() needs about {total_need:.0f} pt width but this panel has {cell_w_pt:.0f} pt.",
|
|
507
|
+
fix_hint="Give the table a full-width row via layout=, drop or shorten columns "
|
|
508
|
+
"with columns=[...], or use a tighter fmt=.",
|
|
509
|
+
rule="table_too_wide",
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
# Distribute any surplus width proportionally across columns (slightly favouring col 0)
|
|
513
|
+
surplus = max(0.0, cell_w_pt - total_need)
|
|
514
|
+
weights = [1.4 if c == 0 else 1.0 for c in range(n_cols)]
|
|
515
|
+
w_sum = sum(weights)
|
|
516
|
+
col_w = [need[c] + surplus * (weights[c] / w_sum) for c in range(n_cols)]
|
|
517
|
+
total_w = sum(col_w)
|
|
518
|
+
col_x = [0.0]
|
|
519
|
+
for w in col_w:
|
|
520
|
+
col_x.append(col_x[-1] + w / total_w)
|
|
521
|
+
|
|
522
|
+
has_two_line_head = any("\n" in h for h in drawn_headers)
|
|
523
|
+
head_units = 1.65 if has_two_line_head else 1.18
|
|
524
|
+
total_y = head_units + n_rows
|
|
525
|
+
|
|
526
|
+
_bare_axes(ax)
|
|
527
|
+
ax.set_xticks([])
|
|
528
|
+
ax.set_yticks([])
|
|
529
|
+
ax.set_xlim(0.0, 1.0)
|
|
530
|
+
ax.set_ylim(total_y, 0.0)
|
|
531
|
+
|
|
532
|
+
light_ground = _relative_luminance(theme.background) > 0.5
|
|
533
|
+
tint_alpha = 0.11 if light_ground else 0.18
|
|
534
|
+
base_alpha = 0.06 if light_ground else 0.10
|
|
535
|
+
|
|
536
|
+
# Row background tints + left accent stripes (Patches, never Line2D)
|
|
537
|
+
stripe_w = min(0.012, 2.2 / max(total_w, 1.0))
|
|
538
|
+
for r in range(n_rows):
|
|
539
|
+
y0 = head_units + r
|
|
540
|
+
rk = row_keys[r]
|
|
541
|
+
if rk in hl:
|
|
542
|
+
accent = ctx.colors.get(rk, theme.series_colors[0])
|
|
543
|
+
ax.add_patch(
|
|
544
|
+
Rectangle(
|
|
545
|
+
(0.0, y0),
|
|
546
|
+
1.0,
|
|
547
|
+
1.0,
|
|
548
|
+
facecolor=accent,
|
|
549
|
+
edgecolor="none",
|
|
550
|
+
alpha=tint_alpha,
|
|
551
|
+
zorder=1,
|
|
552
|
+
)
|
|
553
|
+
)
|
|
554
|
+
ax.add_patch(
|
|
555
|
+
Rectangle(
|
|
556
|
+
(0.0, y0 + 0.06),
|
|
557
|
+
stripe_w,
|
|
558
|
+
0.88,
|
|
559
|
+
facecolor=accent,
|
|
560
|
+
edgecolor="none",
|
|
561
|
+
alpha=0.95,
|
|
562
|
+
zorder=2,
|
|
563
|
+
)
|
|
564
|
+
)
|
|
565
|
+
elif base is not None and rk == base:
|
|
566
|
+
ax.add_patch(
|
|
567
|
+
Rectangle(
|
|
568
|
+
(0.0, y0),
|
|
569
|
+
1.0,
|
|
570
|
+
1.0,
|
|
571
|
+
facecolor=theme.ink,
|
|
572
|
+
edgecolor="none",
|
|
573
|
+
alpha=base_alpha,
|
|
574
|
+
zorder=1,
|
|
575
|
+
)
|
|
576
|
+
)
|
|
577
|
+
ax.add_patch(
|
|
578
|
+
Rectangle(
|
|
579
|
+
(0.0, y0 + 0.06),
|
|
580
|
+
stripe_w,
|
|
581
|
+
0.88,
|
|
582
|
+
facecolor=theme.ink,
|
|
583
|
+
edgecolor="none",
|
|
584
|
+
alpha=0.85,
|
|
585
|
+
zorder=2,
|
|
586
|
+
)
|
|
587
|
+
)
|
|
588
|
+
|
|
589
|
+
# Booktabs horizontal rules via hlines (LineCollection -> never trips struck-by-line)
|
|
590
|
+
ax.hlines(0.02, 0.0, 1.0, color=theme.ink, linewidth=0.9 * sz.scale, zorder=3)
|
|
591
|
+
ax.hlines(head_units, 0.0, 1.0, color=theme.ink, linewidth=0.8 * sz.scale, zorder=3)
|
|
592
|
+
if n_rows > 1:
|
|
593
|
+
inner_ys = [head_units + r for r in range(1, n_rows)]
|
|
594
|
+
ax.hlines(inner_ys, 0.0, 1.0, color=theme.grid, linewidth=0.45 * sz.scale, zorder=2)
|
|
595
|
+
ax.hlines(total_y - 0.02, 0.0, 1.0, color=theme.ink, linewidth=0.9 * sz.scale, zorder=3)
|
|
596
|
+
|
|
597
|
+
# Column header text
|
|
598
|
+
pad_frac = pad_pt / max(total_w, 1.0)
|
|
599
|
+
stripe_frac = stripe_pad_pt / max(total_w, 1.0)
|
|
600
|
+
for c in range(n_cols):
|
|
601
|
+
al = col_align[c]
|
|
602
|
+
left_x = col_x[c] + (stripe_frac if c == 0 else 0.0) + pad_frac
|
|
603
|
+
right_x = col_x[c + 1] - pad_frac
|
|
604
|
+
if al == "right":
|
|
605
|
+
tx, ha = right_x, "right"
|
|
606
|
+
elif al == "center":
|
|
607
|
+
tx, ha = 0.5 * (left_x + right_x), "center"
|
|
608
|
+
else:
|
|
609
|
+
tx, ha = left_x, "left"
|
|
610
|
+
t = ax.text(
|
|
611
|
+
tx,
|
|
612
|
+
head_units * 0.52,
|
|
613
|
+
_plain(drawn_headers[c], theme),
|
|
614
|
+
ha=ha,
|
|
615
|
+
va="center",
|
|
616
|
+
fontsize=sz.small,
|
|
617
|
+
fontweight="bold",
|
|
618
|
+
color=theme.ink,
|
|
619
|
+
zorder=4,
|
|
620
|
+
)
|
|
621
|
+
t._mintfig_heatmap_text = True # type: ignore[attr-defined]
|
|
622
|
+
|
|
623
|
+
# Data cell text
|
|
624
|
+
for r in range(n_rows):
|
|
625
|
+
yc = head_units + r + 0.5
|
|
626
|
+
rk = row_keys[r]
|
|
627
|
+
is_hl = rk in hl
|
|
628
|
+
is_base = base is not None and rk == base
|
|
629
|
+
for c in range(n_cols):
|
|
630
|
+
al = col_align[c]
|
|
631
|
+
left_x = col_x[c] + (stripe_frac if c == 0 else 0.0) + pad_frac
|
|
632
|
+
right_x = col_x[c + 1] - pad_frac
|
|
633
|
+
if al == "right":
|
|
634
|
+
tx, ha = right_x, "right"
|
|
635
|
+
elif al == "center":
|
|
636
|
+
tx, ha = 0.5 * (left_x + right_x), "center"
|
|
637
|
+
else:
|
|
638
|
+
tx, ha = left_x, "left"
|
|
639
|
+
|
|
640
|
+
cell_str = formatted[r][c]
|
|
641
|
+
is_dash = cell_str == "\N{EM DASH}"
|
|
642
|
+
is_winner = (r, c) in best_cells
|
|
643
|
+
weight = "bold" if (is_winner or (c == 0 and (is_hl or is_base))) else "normal"
|
|
644
|
+
color = theme.muted if is_dash else theme.ink
|
|
645
|
+
t = ax.text(
|
|
646
|
+
tx,
|
|
647
|
+
yc,
|
|
648
|
+
_plain(cell_str, theme),
|
|
649
|
+
ha=ha,
|
|
650
|
+
va="center",
|
|
651
|
+
fontsize=sz.small,
|
|
652
|
+
fontweight=weight,
|
|
653
|
+
color=color,
|
|
654
|
+
zorder=4,
|
|
655
|
+
)
|
|
656
|
+
t._mintfig_heatmap_text = True # type: ignore[attr-defined]
|
|
657
|
+
return None
|
|
658
|
+
|
|
659
|
+
spec: dict[str, Any] = {
|
|
660
|
+
"rows": [_jsonable(r) for r in raw_rows],
|
|
661
|
+
"columns": list(col_names),
|
|
662
|
+
"title": title,
|
|
663
|
+
"label": label,
|
|
664
|
+
"unit": unit,
|
|
665
|
+
"units": dict(unit_map) if unit_map else None,
|
|
666
|
+
"highlight": hl or None,
|
|
667
|
+
"baseline": base,
|
|
668
|
+
"bold_best": bold_best if bold_best else None,
|
|
669
|
+
"align": dict(align) if align else None,
|
|
670
|
+
"fmt": fmt,
|
|
671
|
+
}
|
|
672
|
+
describe = f"Table of {n_rows} rows across {', '.join(col_names)}"
|
|
673
|
+
panel = Panel(
|
|
674
|
+
kind="table",
|
|
675
|
+
title=title,
|
|
676
|
+
label=label,
|
|
677
|
+
unit=unit,
|
|
678
|
+
spec=spec,
|
|
679
|
+
facts=facts,
|
|
680
|
+
describe=describe,
|
|
681
|
+
_height_mm=_height_mm,
|
|
682
|
+
_min_height_mm=_min_height_mm,
|
|
683
|
+
_draw=_draw,
|
|
684
|
+
color_items=tuple(row_keys),
|
|
685
|
+
color_focus=tuple(hl),
|
|
686
|
+
color_mode="highlight" if hl else "none",
|
|
687
|
+
color_baseline=base,
|
|
688
|
+
alt_facts=facts[: min(4, len(facts))],
|
|
689
|
+
)
|
|
690
|
+
panel._markdown = markdown_text # type: ignore[attr-defined]
|
|
691
|
+
return panel
|