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/_tabular.py
ADDED
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
"""Tidy / row-shaped tabular data adapters for mintfig.explain forms.
|
|
2
|
+
|
|
3
|
+
Supports both standard-library row lists (``list[dict]``, e.g. from
|
|
4
|
+
``csv.DictReader`` or ``json.loads``) and duck-typed ``pandas.DataFrame``
|
|
5
|
+
objects without importing pandas.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import difflib
|
|
11
|
+
import math
|
|
12
|
+
import numbers
|
|
13
|
+
from collections.abc import Mapping, Sequence
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _is_number(value: object) -> bool:
|
|
18
|
+
return isinstance(value, (numbers.Real,)) and not isinstance(value, bool)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _looks_numeric(value: object) -> bool:
|
|
22
|
+
if value is None or isinstance(value, bool):
|
|
23
|
+
return False
|
|
24
|
+
if _is_number(value):
|
|
25
|
+
return True
|
|
26
|
+
if isinstance(value, str):
|
|
27
|
+
text = value.strip()
|
|
28
|
+
if not text:
|
|
29
|
+
return False
|
|
30
|
+
try:
|
|
31
|
+
float(text)
|
|
32
|
+
except ValueError:
|
|
33
|
+
return False
|
|
34
|
+
return True
|
|
35
|
+
return False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def is_dataframe(obj: object) -> bool:
|
|
39
|
+
"""True for a pandas-like 2-D DataFrame (duck-typed, no pandas import)."""
|
|
40
|
+
return (
|
|
41
|
+
not isinstance(obj, (str, bytes, Mapping))
|
|
42
|
+
and hasattr(obj, "columns")
|
|
43
|
+
and hasattr(obj, "index")
|
|
44
|
+
and hasattr(obj, "iloc")
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def is_row_records(obj: object) -> bool:
|
|
49
|
+
"""True for a non-empty sequence of row mappings (``[{"col": val}, ...]``)."""
|
|
50
|
+
return (
|
|
51
|
+
isinstance(obj, Sequence)
|
|
52
|
+
and not isinstance(obj, (str, bytes))
|
|
53
|
+
and len(obj) > 0
|
|
54
|
+
and isinstance(obj[0], Mapping)
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def is_tabular(obj: object) -> bool:
|
|
59
|
+
"""True when ``obj`` is either a DataFrame or a non-empty list of row dicts."""
|
|
60
|
+
return is_dataframe(obj) or is_row_records(obj)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _col_hint(name: str, columns: Sequence[str]) -> str:
|
|
64
|
+
close = difflib.get_close_matches(name, list(columns), n=1, cutoff=0.5)
|
|
65
|
+
hint = f" Did you mean {close[0]!r}?" if close else ""
|
|
66
|
+
shown = ", ".join(repr(c) for c in columns[:10])
|
|
67
|
+
extra = f" (+{len(columns) - 10} more)" if len(columns) > 10 else ""
|
|
68
|
+
return f"Available columns: {shown}{extra}.{hint}"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def extract_records(
|
|
72
|
+
obj: object,
|
|
73
|
+
*,
|
|
74
|
+
what: str,
|
|
75
|
+
include_named_index: bool = False,
|
|
76
|
+
) -> tuple[list[str], list[dict[str, Any]]]:
|
|
77
|
+
"""Normalize a DataFrame or ``list[dict]`` into ``(columns, rows)``.
|
|
78
|
+
|
|
79
|
+
Raises :class:`mintfig.explainer.ExplainError` on malformed inputs.
|
|
80
|
+
"""
|
|
81
|
+
from ._explain.core import ExplainError
|
|
82
|
+
|
|
83
|
+
if is_dataframe(obj):
|
|
84
|
+
cols = [str(c) for c in obj.columns] # type: ignore[attr-defined]
|
|
85
|
+
raw_rows = obj.to_dict(orient="records") # type: ignore[attr-defined]
|
|
86
|
+
rows = [{str(k): v for k, v in row.items()} for row in raw_rows]
|
|
87
|
+
if include_named_index:
|
|
88
|
+
idx = obj.index # type: ignore[attr-defined]
|
|
89
|
+
idx_name = getattr(idx, "name", None)
|
|
90
|
+
idx_vals = list(idx)
|
|
91
|
+
is_default_range = (
|
|
92
|
+
idx_name is None
|
|
93
|
+
and len(idx_vals) == len(rows)
|
|
94
|
+
and all(isinstance(v, (int, numbers.Integral)) and int(v) == i for i, v in enumerate(idx_vals))
|
|
95
|
+
)
|
|
96
|
+
if not is_default_range and idx_vals:
|
|
97
|
+
col_label = str(idx_name) if idx_name is not None else ""
|
|
98
|
+
if col_label in cols:
|
|
99
|
+
col_label = "index"
|
|
100
|
+
cols = [col_label, *cols]
|
|
101
|
+
rows = [{col_label: idx_vals[i], **rows[i]} for i in range(len(rows))]
|
|
102
|
+
return cols, rows
|
|
103
|
+
|
|
104
|
+
if is_row_records(obj):
|
|
105
|
+
cols_seen: list[str] = []
|
|
106
|
+
col_set: set[str] = set()
|
|
107
|
+
rows_out: list[dict[str, Any]] = []
|
|
108
|
+
for idx, item in enumerate(obj): # type: ignore[union-attr]
|
|
109
|
+
if not isinstance(item, Mapping):
|
|
110
|
+
raise ExplainError(
|
|
111
|
+
f"{what} row {idx} is {type(item).__name__}, expected a dict.",
|
|
112
|
+
fix_hint="Pass a uniform list of row dicts, e.g. [{'name': 'a', 'value': 1}, ...].",
|
|
113
|
+
)
|
|
114
|
+
row_dict = {str(k): v for k, v in item.items()}
|
|
115
|
+
for key in row_dict:
|
|
116
|
+
if key not in col_set:
|
|
117
|
+
col_set.add(key)
|
|
118
|
+
cols_seen.append(key)
|
|
119
|
+
rows_out.append(row_dict)
|
|
120
|
+
return cols_seen, rows_out
|
|
121
|
+
|
|
122
|
+
raise ExplainError(
|
|
123
|
+
f"{what} expected a list of row dicts or a pandas DataFrame, got {type(obj).__name__}.",
|
|
124
|
+
fix_hint="Pass a list of dicts (e.g. list(csv.DictReader(f))) or a DataFrame.",
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _column_is_numeric(rows: list[dict[str, Any]], col: str) -> bool:
|
|
129
|
+
seen = [row.get(col) for row in rows if row.get(col) is not None]
|
|
130
|
+
non_empty = [v for v in seen if not (isinstance(v, str) and not v.strip())]
|
|
131
|
+
if not non_empty:
|
|
132
|
+
return False
|
|
133
|
+
return all(_looks_numeric(v) for v in non_empty)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _infer_two_col_pair(
|
|
137
|
+
cols: list[str], rows: list[dict[str, Any]]
|
|
138
|
+
) -> tuple[str, str] | None:
|
|
139
|
+
"""When a table has exactly 2 columns (one label, one numeric), infer ``(label_col, value_col)``."""
|
|
140
|
+
if len(cols) != 2:
|
|
141
|
+
return None
|
|
142
|
+
num0 = _column_is_numeric(rows, cols[0])
|
|
143
|
+
num1 = _column_is_numeric(rows, cols[1])
|
|
144
|
+
if num1 and not num0:
|
|
145
|
+
return cols[0], cols[1]
|
|
146
|
+
if num0 and not num1:
|
|
147
|
+
return cols[1], cols[0]
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _require_col(col: str, cols: list[str], what: str) -> str:
|
|
152
|
+
from ._explain.core import ExplainError
|
|
153
|
+
|
|
154
|
+
if col not in cols:
|
|
155
|
+
raise ExplainError(
|
|
156
|
+
f"{what} column {col!r} not found.",
|
|
157
|
+
fix_hint=_col_hint(col, cols),
|
|
158
|
+
)
|
|
159
|
+
return col
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _is_missing(val: Any) -> bool:
|
|
163
|
+
if val is None:
|
|
164
|
+
return True
|
|
165
|
+
if isinstance(val, float) and math.isnan(val):
|
|
166
|
+
return True
|
|
167
|
+
return bool(isinstance(val, str) and not val.strip())
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def resolve_named_table(
|
|
171
|
+
data: object,
|
|
172
|
+
what: str,
|
|
173
|
+
*,
|
|
174
|
+
name: str | None = None,
|
|
175
|
+
value: str | None = None,
|
|
176
|
+
error: Any = None,
|
|
177
|
+
n: Any = None,
|
|
178
|
+
boost: Any = None,
|
|
179
|
+
form: str = "compare",
|
|
180
|
+
) -> tuple[dict[str, Any], Any, Any, Any] | None:
|
|
181
|
+
"""Extract ``({name: val}, error, n, boost)`` from row records or a DataFrame.
|
|
182
|
+
|
|
183
|
+
Returns ``None`` when ``data`` is not tabular (standard dict/Series/pairs
|
|
184
|
+
handling should run instead).
|
|
185
|
+
"""
|
|
186
|
+
from ._explain.core import ExplainError
|
|
187
|
+
|
|
188
|
+
if not is_tabular(data):
|
|
189
|
+
if name is not None or value is not None:
|
|
190
|
+
raise ExplainError(
|
|
191
|
+
f"{form}(name=/value=) requires row-shaped data (a list of dicts or a DataFrame), "
|
|
192
|
+
f"got {type(data).__name__}.",
|
|
193
|
+
fix_hint=f"Pass a list of row dicts or DataFrame to {form}(), or drop name=/value= for a dict.",
|
|
194
|
+
)
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
cols, rows = extract_records(data, what=what)
|
|
198
|
+
if not rows:
|
|
199
|
+
raise ExplainError(f"{what} is empty.", fix_hint="Pass at least one row.")
|
|
200
|
+
|
|
201
|
+
if name is None and value is None:
|
|
202
|
+
inferred = _infer_two_col_pair(cols, rows)
|
|
203
|
+
if inferred is not None:
|
|
204
|
+
name, value = inferred
|
|
205
|
+
else:
|
|
206
|
+
shown = ", ".join(repr(c) for c in cols[:8])
|
|
207
|
+
raise ExplainError(
|
|
208
|
+
f"{what} received row-shaped data with {len(cols)} columns ({shown}); "
|
|
209
|
+
"pass name= and value= to choose which columns to plot.",
|
|
210
|
+
fix_hint=(
|
|
211
|
+
f'Pass {form}(rows, name="{cols[0]}", value="{cols[-1]}") '
|
|
212
|
+
f"(columns: {shown}), or convert to a dict {{name: number}}."
|
|
213
|
+
),
|
|
214
|
+
)
|
|
215
|
+
elif name is None or value is None:
|
|
216
|
+
missing_arg = "name=" if name is None else "value="
|
|
217
|
+
raise ExplainError(
|
|
218
|
+
f"{what} needs both name= and value= when reading row-shaped data (missing {missing_arg}).",
|
|
219
|
+
fix_hint=_col_hint(name or value or "", cols),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
_require_col(name, cols, f"{form}(name)")
|
|
223
|
+
_require_col(value, cols, f"{form}(value)")
|
|
224
|
+
|
|
225
|
+
out: dict[str, Any] = {}
|
|
226
|
+
dups: list[str] = []
|
|
227
|
+
for row in rows:
|
|
228
|
+
key = str(row.get(name, ""))
|
|
229
|
+
if key in out:
|
|
230
|
+
dups.append(key)
|
|
231
|
+
out[key] = row.get(value)
|
|
232
|
+
if dups:
|
|
233
|
+
raise ExplainError(
|
|
234
|
+
f"{what} has duplicate {name!r} values ({dups[:4]!r}); {form}() needs one value per item.",
|
|
235
|
+
fix_hint=(
|
|
236
|
+
"Aggregate duplicates first (e.g. mean per item), pass group= for a grouped comparison, "
|
|
237
|
+
f'or pass raw observations to mint.distribution(rows, group="{name}", value="{value}").'
|
|
238
|
+
),
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
resolved_error = error
|
|
242
|
+
if isinstance(error, str) and error in cols:
|
|
243
|
+
resolved_error = {str(row.get(name, "")): row.get(error) for row in rows}
|
|
244
|
+
elif (
|
|
245
|
+
isinstance(error, (tuple, list))
|
|
246
|
+
and len(error) == 2
|
|
247
|
+
and all(isinstance(c, str) for c in error)
|
|
248
|
+
and all(c in cols for c in error)
|
|
249
|
+
):
|
|
250
|
+
lo_col, hi_col = str(error[0]), str(error[1])
|
|
251
|
+
resolved_error = {
|
|
252
|
+
str(row.get(name, "")): (row.get(lo_col), row.get(hi_col)) for row in rows
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
resolved_n = n
|
|
256
|
+
if isinstance(n, str) and n in cols:
|
|
257
|
+
resolved_n = {str(row.get(name, "")): row.get(n) for row in rows}
|
|
258
|
+
|
|
259
|
+
resolved_boost = boost
|
|
260
|
+
if isinstance(boost, str) and boost in cols:
|
|
261
|
+
resolved_boost = {str(row.get(name, "")): row.get(boost) for row in rows}
|
|
262
|
+
|
|
263
|
+
return out, resolved_error, resolved_n, resolved_boost
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def resolve_grouped_compare_table(
|
|
267
|
+
data: object,
|
|
268
|
+
*,
|
|
269
|
+
name: str | None,
|
|
270
|
+
group: str,
|
|
271
|
+
value: str | None,
|
|
272
|
+
) -> dict[str, dict[str, Any]]:
|
|
273
|
+
"""Pivot tidy rows into ``{item_name: {series_name: val}}`` for grouped ``compare()``."""
|
|
274
|
+
from ._explain.core import ExplainError
|
|
275
|
+
|
|
276
|
+
cols, rows = extract_records(data, what="compare(values)")
|
|
277
|
+
if not rows:
|
|
278
|
+
raise ExplainError("compare(values) is empty.", fix_hint="Pass at least one row.")
|
|
279
|
+
if not name or not value:
|
|
280
|
+
shown = ", ".join(repr(c) for c in cols[:8])
|
|
281
|
+
raise ExplainError(
|
|
282
|
+
f"compare(group={group!r}) also needs name= and value= (columns: {shown}).",
|
|
283
|
+
fix_hint=f'Pass compare(rows, name="{cols[0]}", group="{group}", value="{cols[-1]}").',
|
|
284
|
+
)
|
|
285
|
+
_require_col(name, cols, "compare(name)")
|
|
286
|
+
_require_col(group, cols, "compare(group)")
|
|
287
|
+
_require_col(value, cols, "compare(value)")
|
|
288
|
+
|
|
289
|
+
nested: dict[str, dict[str, Any]] = {}
|
|
290
|
+
for row in rows:
|
|
291
|
+
cat = str(row.get(name, ""))
|
|
292
|
+
ser = str(row.get(group, ""))
|
|
293
|
+
bucket = nested.setdefault(cat, {})
|
|
294
|
+
if ser in bucket:
|
|
295
|
+
raise ExplainError(
|
|
296
|
+
f"compare() grouped table has duplicate ({cat!r}, {ser!r}).",
|
|
297
|
+
fix_hint="Aggregate duplicates first (one value per item × group).",
|
|
298
|
+
)
|
|
299
|
+
val = row.get(value)
|
|
300
|
+
bucket[ser] = None if _is_missing(val) else val
|
|
301
|
+
return nested
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def resolve_trend_table(
|
|
305
|
+
data: object,
|
|
306
|
+
*,
|
|
307
|
+
x_col: Any,
|
|
308
|
+
y_col: str | None,
|
|
309
|
+
series_col: Any = None,
|
|
310
|
+
band: Any = None,
|
|
311
|
+
) -> tuple[list[Any], dict[str, list[Any]] | None, dict[str, list[list[Any]]] | None, Any]:
|
|
312
|
+
"""Pivot long/tidy rows or a DataFrame into ``(x_vals, series, points, band)``."""
|
|
313
|
+
from ._explain.core import ExplainError
|
|
314
|
+
|
|
315
|
+
cols, rows = extract_records(data, what="trend(data)")
|
|
316
|
+
if not rows:
|
|
317
|
+
raise ExplainError("trend(data) is empty.", fix_hint="Pass at least one row.")
|
|
318
|
+
if not isinstance(x_col, str):
|
|
319
|
+
raise ExplainError(
|
|
320
|
+
"When passing data= to trend(), the first argument x must be a column name.",
|
|
321
|
+
fix_hint=f'e.g. mint.trend("{cols[0]}", y="{cols[-1]}", data=rows). {_col_hint("", cols)}',
|
|
322
|
+
)
|
|
323
|
+
if not y_col or not isinstance(y_col, str):
|
|
324
|
+
raise ExplainError(
|
|
325
|
+
"When passing data= to trend(), pass y= naming the numeric value column.",
|
|
326
|
+
fix_hint=f'e.g. mint.trend("{x_col}", y="value", data=rows). {_col_hint("", cols)}',
|
|
327
|
+
)
|
|
328
|
+
_require_col(x_col, cols, "trend(x)")
|
|
329
|
+
_require_col(y_col, cols, "trend(y)")
|
|
330
|
+
if series_col is not None:
|
|
331
|
+
if not isinstance(series_col, str):
|
|
332
|
+
raise ExplainError(
|
|
333
|
+
"When passing data= to trend(), series must be a column name (or None for one series).",
|
|
334
|
+
fix_hint=_col_hint("", cols),
|
|
335
|
+
)
|
|
336
|
+
_require_col(series_col, cols, "trend(series)")
|
|
337
|
+
|
|
338
|
+
x_vals: list[Any] = []
|
|
339
|
+
x_index: dict[Any, int] = {}
|
|
340
|
+
series_names: list[str] = []
|
|
341
|
+
buckets: dict[str, dict[int, list[Any]]] = {}
|
|
342
|
+
|
|
343
|
+
for row in rows:
|
|
344
|
+
xv = row.get(x_col)
|
|
345
|
+
if _is_missing(xv):
|
|
346
|
+
continue
|
|
347
|
+
if xv not in x_index:
|
|
348
|
+
x_index[xv] = len(x_vals)
|
|
349
|
+
x_vals.append(xv)
|
|
350
|
+
xi = x_index[xv]
|
|
351
|
+
sname = str(row.get(series_col, "")) if series_col is not None else ""
|
|
352
|
+
if sname not in buckets:
|
|
353
|
+
buckets[sname] = {}
|
|
354
|
+
series_names.append(sname)
|
|
355
|
+
yv = row.get(y_col)
|
|
356
|
+
if not _is_missing(yv):
|
|
357
|
+
buckets[sname].setdefault(xi, []).append(yv)
|
|
358
|
+
|
|
359
|
+
if not x_vals:
|
|
360
|
+
raise ExplainError(
|
|
361
|
+
f"trend(data) has no non-empty values in x column {x_col!r}.",
|
|
362
|
+
fix_hint="Check the x column name and ensure rows contain values.",
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
has_replicates = any(
|
|
366
|
+
len(vals) > 1 for by_x in buckets.values() for vals in by_x.values()
|
|
367
|
+
)
|
|
368
|
+
n_x = len(x_vals)
|
|
369
|
+
|
|
370
|
+
if has_replicates:
|
|
371
|
+
points: dict[str, list[list[Any]]] = {}
|
|
372
|
+
for sname in series_names:
|
|
373
|
+
by_x = buckets[sname]
|
|
374
|
+
points[sname] = [by_x.get(i, []) for i in range(n_x)]
|
|
375
|
+
return x_vals, None, points, band
|
|
376
|
+
|
|
377
|
+
series_out: dict[str, list[Any]] = {}
|
|
378
|
+
for sname in series_names:
|
|
379
|
+
by_x = buckets[sname]
|
|
380
|
+
series_out[sname] = [by_x[i][0] if i in by_x else None for i in range(n_x)]
|
|
381
|
+
|
|
382
|
+
resolved_band = band
|
|
383
|
+
if isinstance(band, str) and band in cols:
|
|
384
|
+
band_map: dict[str, list[Any]] = {s: [None] * n_x for s in series_names}
|
|
385
|
+
for row in rows:
|
|
386
|
+
xv = row.get(x_col)
|
|
387
|
+
if xv not in x_index:
|
|
388
|
+
continue
|
|
389
|
+
sname = str(row.get(series_col, "")) if series_col is not None else ""
|
|
390
|
+
bv = row.get(band)
|
|
391
|
+
if not _is_missing(bv):
|
|
392
|
+
band_map[sname][x_index[xv]] = bv
|
|
393
|
+
resolved_band = band_map[""] if series_col is None else band_map
|
|
394
|
+
elif (
|
|
395
|
+
isinstance(band, (tuple, list))
|
|
396
|
+
and len(band) == 2
|
|
397
|
+
and all(isinstance(c, str) and c in cols for c in band)
|
|
398
|
+
):
|
|
399
|
+
lo_col, hi_col = str(band[0]), str(band[1])
|
|
400
|
+
lo_map: dict[str, list[Any]] = {s: [None] * n_x for s in series_names}
|
|
401
|
+
hi_map: dict[str, list[Any]] = {s: [None] * n_x for s in series_names}
|
|
402
|
+
for row in rows:
|
|
403
|
+
xv = row.get(x_col)
|
|
404
|
+
if xv not in x_index:
|
|
405
|
+
continue
|
|
406
|
+
sname = str(row.get(series_col, "")) if series_col is not None else ""
|
|
407
|
+
lv, hv = row.get(lo_col), row.get(hi_col)
|
|
408
|
+
if not _is_missing(lv):
|
|
409
|
+
lo_map[sname][x_index[xv]] = lv
|
|
410
|
+
if not _is_missing(hv):
|
|
411
|
+
hi_map[sname][x_index[xv]] = hv
|
|
412
|
+
if series_col is None:
|
|
413
|
+
resolved_band = (lo_map[""], hi_map[""])
|
|
414
|
+
else:
|
|
415
|
+
resolved_band = {s: (lo_map[s], hi_map[s]) for s in series_names}
|
|
416
|
+
|
|
417
|
+
if series_col is None:
|
|
418
|
+
return x_vals, series_out[""], None, resolved_band # type: ignore[return-value]
|
|
419
|
+
return x_vals, series_out, None, resolved_band
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def resolve_change_table(
|
|
423
|
+
data: object,
|
|
424
|
+
*,
|
|
425
|
+
before_col: Any,
|
|
426
|
+
after_col: Any,
|
|
427
|
+
name_col: str | None = None,
|
|
428
|
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
429
|
+
"""Extract ``(before_dict, after_dict)`` from row records or a DataFrame."""
|
|
430
|
+
from ._explain.core import ExplainError
|
|
431
|
+
|
|
432
|
+
cols, rows = extract_records(data, what="change(data)")
|
|
433
|
+
if not rows:
|
|
434
|
+
raise ExplainError("change(data) is empty.", fix_hint="Pass at least one row.")
|
|
435
|
+
if not isinstance(before_col, str) or not isinstance(after_col, str):
|
|
436
|
+
raise ExplainError(
|
|
437
|
+
"When passing data= to change(), before and after must be column names.",
|
|
438
|
+
fix_hint=f'e.g. mint.change("before", "after", data=rows, name="item"). {_col_hint("", cols)}',
|
|
439
|
+
)
|
|
440
|
+
_require_col(before_col, cols, "change(before)")
|
|
441
|
+
_require_col(after_col, cols, "change(after)")
|
|
442
|
+
|
|
443
|
+
if name_col is None:
|
|
444
|
+
candidates = [c for c in cols if c not in {before_col, after_col} and not _column_is_numeric(rows, c)]
|
|
445
|
+
if len(candidates) == 1:
|
|
446
|
+
name_col = candidates[0]
|
|
447
|
+
else:
|
|
448
|
+
raise ExplainError(
|
|
449
|
+
"change(data=) needs name= naming the item column.",
|
|
450
|
+
fix_hint=_col_hint("", cols),
|
|
451
|
+
)
|
|
452
|
+
else:
|
|
453
|
+
_require_col(name_col, cols, "change(name)")
|
|
454
|
+
|
|
455
|
+
left: dict[str, Any] = {}
|
|
456
|
+
right: dict[str, Any] = {}
|
|
457
|
+
for row in rows:
|
|
458
|
+
key = str(row.get(name_col, ""))
|
|
459
|
+
left[key] = row.get(before_col)
|
|
460
|
+
right[key] = row.get(after_col)
|
|
461
|
+
return left, right
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def resolve_distribution_table(
|
|
465
|
+
data: object,
|
|
466
|
+
*,
|
|
467
|
+
group: str | None = None,
|
|
468
|
+
value: str | None = None,
|
|
469
|
+
form: str = "distribution",
|
|
470
|
+
) -> dict[str, list[Any]] | list[Any] | None:
|
|
471
|
+
"""Extract ``{group: [values]}`` (or ``[values]``) from tidy rows or a DataFrame.
|
|
472
|
+
|
|
473
|
+
Returns ``None`` when ``data`` should be handled by the standard wide/mapping path
|
|
474
|
+
(including wide all-numeric DataFrames when ``group`` and ``value`` are omitted).
|
|
475
|
+
"""
|
|
476
|
+
from ._explain.core import ExplainError
|
|
477
|
+
|
|
478
|
+
if not is_tabular(data):
|
|
479
|
+
if group is not None or value is not None:
|
|
480
|
+
raise ExplainError(
|
|
481
|
+
f"{form}(group=/value=) requires row-shaped data (a list of dicts or a DataFrame), "
|
|
482
|
+
f"got {type(data).__name__}.",
|
|
483
|
+
fix_hint=f"Pass rows/DataFrame to {form}(), or drop group=/value= for a dict.",
|
|
484
|
+
)
|
|
485
|
+
return None
|
|
486
|
+
|
|
487
|
+
# Wide all-numeric DataFrame with no group=/value= -> preserve legacy wide behavior
|
|
488
|
+
if is_dataframe(data) and group is None and value is None:
|
|
489
|
+
cols, rows = extract_records(data, what=f"{form}(groups)")
|
|
490
|
+
if not rows:
|
|
491
|
+
return None
|
|
492
|
+
inferred = _infer_two_col_pair(cols, rows)
|
|
493
|
+
if inferred is None:
|
|
494
|
+
# All columns numeric -> wide DataFrame (one column per group)
|
|
495
|
+
if all(_column_is_numeric(rows, c) for c in cols):
|
|
496
|
+
return None
|
|
497
|
+
shown = ", ".join(repr(c) for c in cols[:8])
|
|
498
|
+
raise ExplainError(
|
|
499
|
+
f"{form}() got a long/mixed DataFrame with columns ({shown}); "
|
|
500
|
+
"pass group= and value= to choose which columns to plot.",
|
|
501
|
+
fix_hint=f'Pass {form}(df, group="...", value="..."), or a wide numeric DataFrame.',
|
|
502
|
+
)
|
|
503
|
+
group, value = inferred
|
|
504
|
+
else:
|
|
505
|
+
cols, rows = extract_records(data, what=f"{form}(groups)")
|
|
506
|
+
if not rows:
|
|
507
|
+
raise ExplainError(f"{form}() data is empty.", fix_hint="Pass at least 3 rows.")
|
|
508
|
+
if group is None and value is None:
|
|
509
|
+
inferred = _infer_two_col_pair(cols, rows)
|
|
510
|
+
if inferred is not None:
|
|
511
|
+
group, value = inferred
|
|
512
|
+
elif len(cols) == 1 and _column_is_numeric(rows, cols[0]):
|
|
513
|
+
value = cols[0]
|
|
514
|
+
else:
|
|
515
|
+
shown = ", ".join(repr(c) for c in cols[:8])
|
|
516
|
+
raise ExplainError(
|
|
517
|
+
f"{form}() got row-shaped data with columns ({shown}); "
|
|
518
|
+
"pass value= (and optionally group=) to choose which columns to plot.",
|
|
519
|
+
fix_hint=f'Pass {form}(rows, group="{cols[0]}", value="{cols[-1]}").',
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
if value is None:
|
|
523
|
+
raise ExplainError(
|
|
524
|
+
f"{form}(group={group!r}) also needs value= naming the numeric column.",
|
|
525
|
+
fix_hint=_col_hint("", cols),
|
|
526
|
+
)
|
|
527
|
+
_require_col(value, cols, f"{form}(value)")
|
|
528
|
+
if group is None:
|
|
529
|
+
return [row.get(value) for row in rows]
|
|
530
|
+
_require_col(group, cols, f"{form}(group)")
|
|
531
|
+
|
|
532
|
+
grouped: dict[str, list[Any]] = {}
|
|
533
|
+
for row in rows:
|
|
534
|
+
g = str(row.get(group, ""))
|
|
535
|
+
grouped.setdefault(g, []).append(row.get(value))
|
|
536
|
+
return grouped
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def resolve_relate_table(
|
|
540
|
+
data: object,
|
|
541
|
+
*,
|
|
542
|
+
x_col: Any,
|
|
543
|
+
y_col: Any,
|
|
544
|
+
names: Any = None,
|
|
545
|
+
groups: Any = None,
|
|
546
|
+
) -> tuple[list[Any], list[Any], list[Any] | None, list[Any] | None]:
|
|
547
|
+
"""Extract ``(x, y, names, groups)`` columns from row records or a DataFrame."""
|
|
548
|
+
from ._explain.core import ExplainError
|
|
549
|
+
|
|
550
|
+
cols, rows = extract_records(data, what="relate(data)")
|
|
551
|
+
if not rows:
|
|
552
|
+
raise ExplainError("relate(data) is empty.", fix_hint="Pass at least two rows.")
|
|
553
|
+
if not isinstance(x_col, str) or not isinstance(y_col, str):
|
|
554
|
+
raise ExplainError(
|
|
555
|
+
"When passing data= to relate(), x and y must be column names.",
|
|
556
|
+
fix_hint=f'e.g. mint.relate("cost", "score", data=rows, x_label=..., y_label=...). {_col_hint("", cols)}',
|
|
557
|
+
)
|
|
558
|
+
_require_col(x_col, cols, "relate(x)")
|
|
559
|
+
_require_col(y_col, cols, "relate(y)")
|
|
560
|
+
xs = [row.get(x_col) for row in rows]
|
|
561
|
+
ys = [row.get(y_col) for row in rows]
|
|
562
|
+
|
|
563
|
+
out_names = names
|
|
564
|
+
if isinstance(names, str):
|
|
565
|
+
_require_col(names, cols, "relate(names)")
|
|
566
|
+
out_names = [row.get(names) for row in rows]
|
|
567
|
+
out_groups = groups
|
|
568
|
+
if isinstance(groups, str):
|
|
569
|
+
_require_col(groups, cols, "relate(groups)")
|
|
570
|
+
out_groups = [row.get(groups) for row in rows]
|
|
571
|
+
return xs, ys, out_names, out_groups
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def resolve_matrix_table(
|
|
575
|
+
data: object,
|
|
576
|
+
*,
|
|
577
|
+
rows_arg: Any,
|
|
578
|
+
cols_arg: Any,
|
|
579
|
+
value_col: str | None = None,
|
|
580
|
+
) -> tuple[list[list[Any]], list[str], list[str]] | None:
|
|
581
|
+
"""Pivot long rows/DataFrame into ``(grid_2d, row_names, col_names)`` when requested.
|
|
582
|
+
|
|
583
|
+
Returns ``None`` when ``data`` is a normal 2-D matrix or wide DataFrame.
|
|
584
|
+
"""
|
|
585
|
+
from ._explain.core import ExplainError
|
|
586
|
+
|
|
587
|
+
want_pivot = (
|
|
588
|
+
is_row_records(data)
|
|
589
|
+
or value_col is not None
|
|
590
|
+
or (is_dataframe(data) and isinstance(rows_arg, str) and isinstance(cols_arg, str))
|
|
591
|
+
)
|
|
592
|
+
if not want_pivot:
|
|
593
|
+
return None
|
|
594
|
+
if not is_tabular(data):
|
|
595
|
+
raise ExplainError(
|
|
596
|
+
f"matrix(value={value_col!r}) requires row-shaped data (list of dicts or DataFrame).",
|
|
597
|
+
fix_hint='Pass a list of row dicts or DataFrame with rows="...", cols="...", value="...".',
|
|
598
|
+
)
|
|
599
|
+
|
|
600
|
+
cols, records = extract_records(data, what="matrix(values)")
|
|
601
|
+
if not records:
|
|
602
|
+
raise ExplainError("matrix(values) is empty.", fix_hint="Pass at least one row.")
|
|
603
|
+
if not isinstance(rows_arg, str) or not isinstance(cols_arg, str):
|
|
604
|
+
shown = ", ".join(repr(c) for c in cols[:8])
|
|
605
|
+
raise ExplainError(
|
|
606
|
+
f"matrix() got row-shaped data with columns ({shown}); pass rows=, cols= and value= as column names.",
|
|
607
|
+
fix_hint=f'e.g. mint.matrix(records, rows="{cols[0]}", cols="{cols[min(1, len(cols) - 1)]}", value="{cols[-1]}").',
|
|
608
|
+
)
|
|
609
|
+
_require_col(rows_arg, cols, "matrix(rows)")
|
|
610
|
+
_require_col(cols_arg, cols, "matrix(cols)")
|
|
611
|
+
if value_col is None:
|
|
612
|
+
remaining = [c for c in cols if c not in {rows_arg, cols_arg} and _column_is_numeric(records, c)]
|
|
613
|
+
if len(remaining) == 1:
|
|
614
|
+
value_col = remaining[0]
|
|
615
|
+
else:
|
|
616
|
+
raise ExplainError(
|
|
617
|
+
"matrix() needs value= naming the numeric cell column when pivoting row-shaped data.",
|
|
618
|
+
fix_hint=_col_hint("", cols),
|
|
619
|
+
)
|
|
620
|
+
else:
|
|
621
|
+
_require_col(value_col, cols, "matrix(value)")
|
|
622
|
+
|
|
623
|
+
row_names: list[str] = []
|
|
624
|
+
col_names: list[str] = []
|
|
625
|
+
cells: dict[tuple[str, str], Any] = {}
|
|
626
|
+
for rec in records:
|
|
627
|
+
rk = str(rec.get(rows_arg, ""))
|
|
628
|
+
ck = str(rec.get(cols_arg, ""))
|
|
629
|
+
if rk not in row_names:
|
|
630
|
+
row_names.append(rk)
|
|
631
|
+
if ck not in col_names:
|
|
632
|
+
col_names.append(ck)
|
|
633
|
+
if (rk, ck) in cells:
|
|
634
|
+
raise ExplainError(
|
|
635
|
+
f"matrix() pivot has duplicate cell ({rk!r}, {ck!r}).",
|
|
636
|
+
fix_hint="Aggregate duplicates before passing to matrix().",
|
|
637
|
+
)
|
|
638
|
+
val = rec.get(value_col)
|
|
639
|
+
cells[(rk, ck)] = None if _is_missing(val) else val
|
|
640
|
+
|
|
641
|
+
grid = [[cells.get((r, c)) for c in col_names] for r in row_names]
|
|
642
|
+
return grid, row_names, col_names
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def extract_table_data(
|
|
646
|
+
rows: object,
|
|
647
|
+
*,
|
|
648
|
+
columns: Sequence[str] | None = None,
|
|
649
|
+
) -> tuple[list[str], list[list[Any]]]:
|
|
650
|
+
"""Normalize any tabular input for :func:`mintfig.table` into ``(col_names, cell_rows)``.
|
|
651
|
+
|
|
652
|
+
Accepts:
|
|
653
|
+
- ``list[dict]`` (row records)
|
|
654
|
+
- ``pandas.DataFrame`` (preserving meaningful non-RangeIndex as column 0)
|
|
655
|
+
- ``dict[str, Sequence]`` (column-oriented mapping)
|
|
656
|
+
- 2-D sequence of rows (with ``columns=[...]``)
|
|
657
|
+
"""
|
|
658
|
+
from ._explain.core import ExplainError
|
|
659
|
+
|
|
660
|
+
if is_dataframe(rows):
|
|
661
|
+
cols, recs = extract_records(rows, what="table(rows)", include_named_index=True)
|
|
662
|
+
if columns is not None:
|
|
663
|
+
chosen = [str(c) for c in columns]
|
|
664
|
+
for col in chosen:
|
|
665
|
+
_require_col(col, cols, "table(columns)")
|
|
666
|
+
cols = chosen
|
|
667
|
+
return cols, [[rec.get(c) for c in cols] for rec in recs]
|
|
668
|
+
|
|
669
|
+
if is_row_records(rows):
|
|
670
|
+
cols, recs = extract_records(rows, what="table(rows)")
|
|
671
|
+
if columns is not None:
|
|
672
|
+
chosen = [str(c) for c in columns]
|
|
673
|
+
for col in chosen:
|
|
674
|
+
_require_col(col, cols, "table(columns)")
|
|
675
|
+
cols = chosen
|
|
676
|
+
return cols, [[rec.get(c) for c in cols] for rec in recs]
|
|
677
|
+
|
|
678
|
+
if isinstance(rows, Mapping):
|
|
679
|
+
if not rows:
|
|
680
|
+
raise ExplainError("table(rows) is empty.", fix_hint="Pass at least one row.")
|
|
681
|
+
all_cols = [str(k) for k in rows]
|
|
682
|
+
lengths: list[int] = []
|
|
683
|
+
col_vals: dict[str, list[Any]] = {}
|
|
684
|
+
for k, v in rows.items():
|
|
685
|
+
if isinstance(v, (str, bytes)) or not isinstance(v, Sequence):
|
|
686
|
+
raise ExplainError(
|
|
687
|
+
f"table() column {k!r} must be a sequence of cell values, got {type(v).__name__}.",
|
|
688
|
+
fix_hint='Pass [{"col": val}, ...] or {"col": [v1, v2, ...]}.',
|
|
689
|
+
)
|
|
690
|
+
lst = list(v)
|
|
691
|
+
lengths.append(len(lst))
|
|
692
|
+
col_vals[str(k)] = lst
|
|
693
|
+
if len(set(lengths)) != 1:
|
|
694
|
+
raise ExplainError(
|
|
695
|
+
f"table() columns have unequal lengths: {dict(zip(all_cols, lengths))}.",
|
|
696
|
+
fix_hint="Every column list must have the same number of rows.",
|
|
697
|
+
)
|
|
698
|
+
chosen = all_cols if columns is None else [str(c) for c in columns]
|
|
699
|
+
for col in chosen:
|
|
700
|
+
_require_col(col, all_cols, "table(columns)")
|
|
701
|
+
n_rows = lengths[0]
|
|
702
|
+
return chosen, [[col_vals[c][i] for c in chosen] for i in range(n_rows)]
|
|
703
|
+
|
|
704
|
+
if isinstance(rows, Sequence) and not isinstance(rows, (str, bytes)):
|
|
705
|
+
seq = list(rows)
|
|
706
|
+
if not seq:
|
|
707
|
+
raise ExplainError("table(rows) is empty.", fix_hint="Pass at least one row.")
|
|
708
|
+
if columns is None:
|
|
709
|
+
raise ExplainError(
|
|
710
|
+
"table() needs columns=[...] when rows is a 2-D list of lists.",
|
|
711
|
+
fix_hint='Pass columns=["Model", "Score", ...] or pass a list of dicts [{"Model": ..., "Score": ...}].',
|
|
712
|
+
)
|
|
713
|
+
if isinstance(columns, (str, bytes)):
|
|
714
|
+
raise ExplainError(
|
|
715
|
+
"table(columns) must be a list of column names.",
|
|
716
|
+
fix_hint='e.g. columns=["Model", "Score"].',
|
|
717
|
+
)
|
|
718
|
+
col_names = [str(c) for c in columns]
|
|
719
|
+
out_rows: list[list[Any]] = []
|
|
720
|
+
for idx, row in enumerate(seq):
|
|
721
|
+
if isinstance(row, (str, bytes)) or not isinstance(row, Sequence):
|
|
722
|
+
raise ExplainError(
|
|
723
|
+
f"table(rows[{idx}]) must be a sequence of cell values.",
|
|
724
|
+
fix_hint="Pass a 2-D list of rows or a list of dicts.",
|
|
725
|
+
)
|
|
726
|
+
vals = list(row)
|
|
727
|
+
if len(vals) != len(col_names):
|
|
728
|
+
raise ExplainError(
|
|
729
|
+
f"table(rows[{idx}]) has {len(vals)} cells but columns has {len(col_names)} names.",
|
|
730
|
+
fix_hint="Every row must match len(columns).",
|
|
731
|
+
)
|
|
732
|
+
out_rows.append(vals)
|
|
733
|
+
return col_names, out_rows
|
|
734
|
+
|
|
735
|
+
raise ExplainError(
|
|
736
|
+
f"table(rows) expected a list of dicts, DataFrame, dict of columns, or 2-D list; got {type(rows).__name__}.",
|
|
737
|
+
fix_hint='e.g. mint.table([{"Model": "A", "Score": 91.2}, {"Model": "B", "Score": 84.5}]).',
|
|
738
|
+
)
|