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,583 @@
1
+ """Zero-dependency tabular file loader and data inspector for agent workflows.
2
+
3
+ Reads CSV, TSV, JSON, or JSONL files without pandas, profiles columns and shapes,
4
+ and recommends ready-to-run ``mintfig`` forms so agents skip exploratory boilerplate.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import csv
10
+ import json
11
+ import math
12
+ import re
13
+ import statistics
14
+ from collections.abc import Mapping, Sequence
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from ._explain.core import ExplainError
19
+ from ._tabular import extract_records, is_tabular
20
+
21
+ __all__ = ["auto_panel", "inspect_data", "load_table_file"]
22
+
23
+ _NULL_TOKENS = {"", "na", "n/a", "nan", "none", "null", "-", "—"}
24
+ _ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}(-\d{2})?([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?$")
25
+ _TIME_COL_HINTS = ("date", "time", "day", "week", "month", "year", "step", "epoch", "dose", "iter", "round", "version")
26
+ _DELTA_COL_HINTS = ("delta", "diff", "change", "gain", "contrib", "contribution", "impact", "effect")
27
+ _FLOW_STAGE_HINTS = ("stage", "step", "phase", "funnel", "cohort", "gate", "filter")
28
+ _FLOW_REASON_HINTS = ("reason", "drop_reason", "exclusion", "excluded", "cause", "note")
29
+ _COST_COL_HINTS = ("cost", "price", "latency", "ms", "time", "flops", "params", "memory", "size")
30
+ _SCORE_COL_HINTS = ("score", "acc", "accuracy", "pass", "f1", "gpqa", "swe", "aime", "quality", "win", "rate")
31
+
32
+
33
+ def _parse_scalar(raw: Any) -> Any:
34
+ if raw is None or isinstance(raw, (int, float, bool)):
35
+ if isinstance(raw, float) and not math.isfinite(raw):
36
+ return None
37
+ return raw
38
+ text = str(raw).strip()
39
+ if text.lower() in _NULL_TOKENS:
40
+ return None
41
+ # Preserve ISO dates and strings with leading zeros like "001"
42
+ if _ISO_DATE_RE.match(text):
43
+ return text
44
+ cleaned = text.replace(",", "")
45
+ if cleaned.endswith("%") and len(cleaned) > 1:
46
+ try:
47
+ return float(cleaned[:-1])
48
+ except ValueError:
49
+ return text
50
+ try:
51
+ num = float(cleaned)
52
+ except ValueError:
53
+ return text
54
+ if not math.isfinite(num):
55
+ return None
56
+ if num.is_integer() and "." not in cleaned and "e" not in cleaned.lower():
57
+ return int(num)
58
+ return num
59
+
60
+
61
+ def load_table_file(path: str | Path) -> list[dict[str, Any]]:
62
+ """Load rows from a ``.csv``, ``.tsv``, ``.json``, or ``.jsonl`` file without pandas."""
63
+ src = Path(path)
64
+ if not src.exists():
65
+ raise ExplainError(
66
+ f"Data file {src} does not exist.",
67
+ fix_hint="Check the file path and pass a .csv, .tsv, .json, or .jsonl file.",
68
+ )
69
+ suffix = src.suffix.lower()
70
+ raw_text = src.read_text(encoding="utf-8-sig")
71
+
72
+ if suffix in {".csv", ".tsv"}:
73
+ delimiter = "\t" if suffix == ".tsv" else ","
74
+ reader = csv.DictReader(raw_text.splitlines(), delimiter=delimiter)
75
+ if not reader.fieldnames:
76
+ raise ExplainError(
77
+ f"{src.name} has no header row.",
78
+ fix_hint="Ensure the first line contains column names.",
79
+ )
80
+ rows: list[dict[str, Any]] = []
81
+ for raw_row in reader:
82
+ if not any(v is not None and str(v).strip() for v in raw_row.values()):
83
+ continue
84
+ rows.append({str(k).strip(): _parse_scalar(v) for k, v in raw_row.items() if k is not None})
85
+ return rows
86
+
87
+ if suffix in {".jsonl", ".ndjson"}:
88
+ rows = []
89
+ for idx, line in enumerate(raw_text.splitlines(), 1):
90
+ stripped = line.strip()
91
+ if not stripped:
92
+ continue
93
+ try:
94
+ obj = json.loads(stripped)
95
+ except json.JSONDecodeError as exc:
96
+ raise ExplainError(
97
+ f"{src.name} line {idx} is invalid JSON: {exc}.",
98
+ fix_hint="Ensure every non-empty line in a JSONL file is a JSON object.",
99
+ ) from exc
100
+ if not isinstance(obj, Mapping):
101
+ raise ExplainError(
102
+ f"{src.name} line {idx} is {type(obj).__name__}, expected a JSON object.",
103
+ fix_hint="Each JSONL line must be a {...} dict.",
104
+ )
105
+ rows.append({str(k): _parse_scalar(v) for k, v in obj.items()})
106
+ return rows
107
+
108
+ if suffix == ".json":
109
+ try:
110
+ payload = json.loads(raw_text)
111
+ except json.JSONDecodeError as exc:
112
+ raise ExplainError(
113
+ f"{src.name} is not valid JSON: {exc}.",
114
+ fix_hint="Fix JSON syntax or pass a CSV/TSV/JSONL file.",
115
+ ) from exc
116
+ if isinstance(payload, Mapping):
117
+ # Wrapper keys like {"rows": [...]} or {"data": [...]}
118
+ for wrapper_key in ("rows", "data", "records", "results", "items"):
119
+ inner = payload.get(wrapper_key)
120
+ if isinstance(inner, list) and inner and isinstance(inner[0], Mapping):
121
+ return [{str(k): _parse_scalar(v) for k, v in r.items()} for r in inner]
122
+ # Column-oriented dict {"col": [v1, v2, ...]}
123
+ if payload and all(
124
+ isinstance(v, list) for v in payload.values()
125
+ ):
126
+ cols = [str(k) for k in payload]
127
+ lengths = {len(v) for v in payload.values()}
128
+ if len(lengths) == 1:
129
+ n = next(iter(lengths))
130
+ return [
131
+ {c: _parse_scalar(payload[c][i]) for c in cols}
132
+ for i in range(n)
133
+ ]
134
+ # Single flat mapping {"item": number, ...} -> 2-column rows
135
+ if payload and all(not isinstance(v, (dict, list)) for v in payload.values()):
136
+ return [{"name": str(k), "value": _parse_scalar(v)} for k, v in payload.items()]
137
+ raise ExplainError(
138
+ f"{src.name} is a JSON object whose shape could not be interpreted as rows.",
139
+ fix_hint="Use a list of row dicts [{...}, ...], a column dict {'col': [...]}, or {'rows': [...]}.",
140
+ )
141
+ if isinstance(payload, list):
142
+ if not payload:
143
+ return []
144
+ if isinstance(payload[0], Mapping):
145
+ return [{str(k): _parse_scalar(v) for k, v in r.items()} for r in payload]
146
+ raise ExplainError(
147
+ f"{src.name} must contain a list of row objects or a column mapping.",
148
+ fix_hint="Pass a CSV, TSV, JSONL, or tabular JSON file.",
149
+ )
150
+
151
+ raise ExplainError(
152
+ f"Unsupported data file suffix {suffix!r} for {src.name}.",
153
+ fix_hint="Supported formats: .csv, .tsv, .json, .jsonl, .ndjson.",
154
+ )
155
+
156
+
157
+ def _is_num(val: Any) -> bool:
158
+ return isinstance(val, (int, float)) and not isinstance(val, bool) and math.isfinite(float(val))
159
+
160
+
161
+ def _profile_column(col: str, values: Sequence[Any]) -> dict[str, Any]:
162
+ non_null = [v for v in values if v is not None and not (isinstance(v, str) and not v.strip())]
163
+ missing = len(values) - len(non_null)
164
+ unique_vals = list(dict.fromkeys(str(v) for v in non_null))
165
+
166
+ if non_null and all(_is_num(v) for v in non_null):
167
+ nums = [float(v) for v in non_null]
168
+ lo, hi = min(nums), max(nums)
169
+ pos = [v for v in nums if v > 0]
170
+ spans_decades = bool(pos and (max(pos) / min(pos) >= 50.0))
171
+ return {
172
+ "name": col,
173
+ "type": "numeric",
174
+ "non_null": len(nums),
175
+ "missing": missing,
176
+ "unique": len(set(nums)),
177
+ "min": round(lo, 6),
178
+ "median": round(float(statistics.median(nums)), 6),
179
+ "mean": round(float(statistics.fmean(nums)), 6),
180
+ "max": round(hi, 6),
181
+ "has_negative": lo < 0,
182
+ "spans_decades": spans_decades,
183
+ }
184
+
185
+ if non_null and all(isinstance(v, str) and bool(_ISO_DATE_RE.match(v)) for v in non_null):
186
+ return {
187
+ "name": col,
188
+ "type": "date",
189
+ "non_null": len(non_null),
190
+ "missing": missing,
191
+ "unique": len(unique_vals),
192
+ "min": min(unique_vals),
193
+ "max": max(unique_vals),
194
+ }
195
+
196
+ col_type = "categorical" if len(unique_vals) <= max(20, int(0.6 * max(len(non_null), 1))) else "text"
197
+ return {
198
+ "name": col,
199
+ "type": col_type,
200
+ "non_null": len(non_null),
201
+ "missing": missing,
202
+ "unique": len(unique_vals),
203
+ "samples": unique_vals[:6],
204
+ }
205
+
206
+
207
+ def inspect_data(
208
+ source: str | Path | Sequence[Mapping[str, Any]] | Any,
209
+ ) -> dict[str, Any]:
210
+ """Inspect a tabular file, list of row dicts, or DataFrame and recommend ``mintfig`` forms.
211
+
212
+ Returns a JSON-serializable dict with ``rows``, ``columns``, ``column_profiles``,
213
+ ``recommendations`` (ordered best-fit forms with concrete Python & CLI commands),
214
+ and ``preview`` (first 3 rows).
215
+ """
216
+ src_label: str | None = None
217
+ if isinstance(source, (str, Path)):
218
+ src_label = str(source)
219
+ rows = load_table_file(source)
220
+ cols = list(dict.fromkeys(k for r in rows for k in r))
221
+ elif is_tabular(source):
222
+ cols, rows = extract_records(source, what="inspect_data(source)")
223
+ rows = [{k: _parse_scalar(v) for k, v in r.items()} for r in rows]
224
+ else:
225
+ raise ExplainError(
226
+ f"inspect_data() expected a file path, list of dicts, or DataFrame; got {type(source).__name__}.",
227
+ fix_hint='Pass a path like "results.csv" or rows=[{"model": "A", "score": 0.8}].',
228
+ )
229
+
230
+ if not rows:
231
+ return {
232
+ "source": src_label,
233
+ "rows": 0,
234
+ "columns": cols,
235
+ "column_profiles": [],
236
+ "recommendations": [],
237
+ "preview": [],
238
+ }
239
+
240
+ profiles = [_profile_column(c, [r.get(c) for r in rows]) for c in cols]
241
+ by_name = {p["name"]: p for p in profiles}
242
+ num_cols = [p["name"] for p in profiles if p["type"] == "numeric"]
243
+ date_cols = [p["name"] for p in profiles if p["type"] == "date"]
244
+ cat_cols = [p["name"] for p in profiles if p["type"] in {"categorical", "text"}]
245
+ lower_cols = {c.lower(): c for c in cols}
246
+
247
+ recs: list[dict[str, Any]] = []
248
+
249
+ def _add_rec(
250
+ kind: str,
251
+ reason: str,
252
+ python_call: str,
253
+ cli_flags: str = "",
254
+ params: dict[str, Any] | None = None,
255
+ ) -> None:
256
+ if any(r["kind"] == kind and r["python"] == python_call for r in recs):
257
+ return
258
+ entry: dict[str, Any] = {"kind": kind, "reason": reason, "python": python_call}
259
+ if cli_flags and src_label:
260
+ entry["cli"] = f'mintfig plot {src_label} --kind {kind} {cli_flags} --takeaway "..." --out fig.png'
261
+ if params:
262
+ entry["params"] = params
263
+ recs.append(entry)
264
+
265
+ # 1. Timeline spans: explicit start & end numeric columns
266
+ start_c = next((lower_cols[k] for k in ("start", "t_start", "start_s", "start_ms", "begin") if k in lower_cols), None)
267
+ end_c = next((lower_cols[k] for k in ("end", "t_end", "end_s", "end_ms", "finish") if k in lower_cols), None)
268
+ if start_c in num_cols and end_c in num_cols and cat_cols:
269
+ nm_c = cat_cols[0]
270
+ grp_col = cat_cols[1] if len(cat_cols) >= 2 and by_name[cat_cols[1]]["unique"] <= 4 else None
271
+ grp_extra = f', group="{grp_col}"' if grp_col else ""
272
+ cli_g = f" --group {grp_col}" if grp_col else ""
273
+ _add_rec(
274
+ "timeline",
275
+ f"Detected start/end span columns ({start_c!r}, {end_c!r}) for {len(rows)} stages.",
276
+ f'mint.timeline(rows, name="{nm_c}", start="{start_c}", end="{end_c}"{grp_extra})',
277
+ f"--name {nm_c} --start {start_c} --end {end_c}{cli_g}",
278
+ {"name": nm_c, "start": start_c, "end": end_c, **({"group": grp_col} if grp_col else {})},
279
+ )
280
+
281
+ # 1b. Flow / attrition funnel: stage column + monotonic non-increasing positive count column (+ optional reason)
282
+ if cat_cols and len(num_cols) == 1 and 3 <= len(rows) <= 12:
283
+ stage_c = cat_cols[0]
284
+ val_c = num_cols[0]
285
+ rsn_c = next((c for c in cat_cols[1:] if any(h in c.lower() for h in _FLOW_REASON_HINTS)), None)
286
+ col_vals = [r.get(val_c) for r in rows]
287
+ if (
288
+ by_name[stage_c]["unique"] == len(rows)
289
+ and all(_is_num(v) and float(v) >= 0 for v in col_vals)
290
+ and float(col_vals[0]) > float(col_vals[-1])
291
+ and all(float(col_vals[i]) <= float(col_vals[i - 1]) for i in range(1, len(col_vals)))
292
+ and (rsn_c is not None or any(h in stage_c.lower() for h in _FLOW_STAGE_HINTS))
293
+ ):
294
+ rsn_py = f', reason="{rsn_c}"' if rsn_c else ""
295
+ rsn_cli = f" --reason {rsn_c}" if rsn_c else ""
296
+ _add_rec(
297
+ "flow",
298
+ f"Monotonic attrition across {len(rows)} stages in {stage_c!r} ({col_vals[0]} -> {col_vals[-1]}).",
299
+ f'mint.flow(rows, name="{stage_c}", value="{val_c}"{rsn_py})',
300
+ f"--name {stage_c} --value {val_c}{rsn_cli}",
301
+ {"name": stage_c, "value": val_c, **({"reason": rsn_c} if rsn_c else {})},
302
+ )
303
+
304
+ # 2. Trend: date column or time/step/dose numeric column
305
+ x_cand = (
306
+ date_cols[0]
307
+ if date_cols
308
+ else next(
309
+ (c for c in num_cols if any(h in c.lower() for h in _TIME_COL_HINTS) and by_name[c]["unique"] >= 3),
310
+ None,
311
+ )
312
+ )
313
+ if x_cand is not None:
314
+ y_cands = [c for c in num_cols if c != x_cand]
315
+ if y_cands:
316
+ y_c = y_cands[0]
317
+ series_c = next((c for c in cat_cols if 2 <= by_name[c]["unique"] <= 12), None)
318
+ log_x_flag = bool(by_name[x_cand].get("spans_decades"))
319
+ log_x_note = ", log_x=True" if log_x_flag else ""
320
+ if series_c:
321
+ # Check if replicates exist
322
+ pairs = [(r.get(x_cand), r.get(series_c)) for r in rows]
323
+ rep_note = " (repeated rows auto-plot as replicate points)" if len(pairs) > len(set(pairs)) else ""
324
+ _add_rec(
325
+ "trend",
326
+ f"Ordered x column {x_cand!r} with {by_name[series_c]['unique']} series in {series_c!r}{rep_note}.",
327
+ f'mint.trend("{x_cand}", "{series_c}", y="{y_c}", data=rows{log_x_note})',
328
+ f"--x {x_cand} --series {series_c} --y {y_c}",
329
+ {"x": x_cand, "series": series_c, "y": y_c, "log_x": log_x_flag},
330
+ )
331
+ else:
332
+ _add_rec(
333
+ "trend",
334
+ f"Ordered x column {x_cand!r} against {y_c!r}.",
335
+ f'mint.trend("{x_cand}", y="{y_c}", data=rows{log_x_note})',
336
+ f"--x {x_cand} --y {y_c}",
337
+ {"x": x_cand, "y": y_c, "log_x": log_x_flag},
338
+ )
339
+
340
+ # 3. Grouped compare / matrix: 2 categorical + 1 numeric with unique pairs
341
+ if len(cat_cols) >= 2 and num_cols:
342
+ c0, c1, val_c = cat_cols[0], cat_cols[1], num_cols[0]
343
+ pairs = [(r.get(c0), r.get(c1)) for r in rows]
344
+ if len(pairs) == len(set(pairs)):
345
+ u0, u1 = by_name[c0]["unique"], by_name[c1]["unique"]
346
+ if 2 <= u1 <= 4 and u0 <= 12:
347
+ _add_rec(
348
+ "compare",
349
+ f"Tidy 2D grid ({u0} {c0} × {u1} {c1}) fits grouped horizontal bars.",
350
+ f'mint.compare(rows, name="{c0}", group="{c1}", value="{val_c}")',
351
+ f"--name {c0} --group {c1} --value {val_c}",
352
+ {"name": c0, "group": c1, "value": val_c},
353
+ )
354
+ if u0 <= 16 and u1 <= 12:
355
+ _add_rec(
356
+ "matrix",
357
+ f"Two categorical dimensions ({u0}×{u1}) fit an annotated heat table.",
358
+ f'mint.matrix(rows, rows="{c0}", cols="{c1}", value="{val_c}")',
359
+ f"--rows {c0} --cols {c1} --value {val_c}",
360
+ {"rows": c0, "cols": c1, "value": val_c},
361
+ )
362
+
363
+ # 4. Distribution vs single-item compare / waterfall / change / scorecard
364
+ if cat_cols and num_cols:
365
+ id_col = cat_cols[0]
366
+ u_id = by_name[id_col]["unique"]
367
+ val_c = num_cols[0]
368
+ if u_id < len(rows) and u_id <= 8 and (len(rows) / max(u_id, 1)) >= 3:
369
+ log_f = bool(by_name[val_c].get("spans_decades"))
370
+ use_q = (len(rows) / max(u_id, 1)) >= 15
371
+ log_flag = ", log=True" if log_f else ""
372
+ q_flag = ', mode="quantile"' if use_q else ""
373
+ _add_rec(
374
+ "distribution",
375
+ f"Multiple raw observations per {id_col!r} ({len(rows)} rows across {u_id} groups).",
376
+ f'mint.distribution(rows, group="{id_col}", value="{val_c}"{log_flag}{q_flag})',
377
+ f"--group {id_col} --value {val_c}",
378
+ {"group": id_col, "value": val_c, "log": log_f, "mode": "quantile" if use_q else "dots"},
379
+ )
380
+ elif u_id == len(rows):
381
+ if len(num_cols) == 1:
382
+ if by_name[val_c]["has_negative"] and any(h in val_c.lower() for h in _DELTA_COL_HINTS):
383
+ _add_rec(
384
+ "waterfall",
385
+ f"Signed contribution column {val_c!r} across {len(rows)} steps.",
386
+ f'mint.waterfall(rows, name="{id_col}", value="{val_c}")',
387
+ f"--name {id_col} --value {val_c}",
388
+ {"name": id_col, "value": val_c},
389
+ )
390
+ _add_rec(
391
+ "compare",
392
+ f"One value per {id_col!r} ({len(rows)} items) for ranked comparison.",
393
+ f'mint.compare(rows, name="{id_col}", value="{val_c}")',
394
+ f"--name {id_col} --value {val_c}",
395
+ {"name": id_col, "value": val_c},
396
+ )
397
+ elif len(num_cols) == 2:
398
+ _add_rec(
399
+ "change",
400
+ f"Two numeric states ({num_cols[0]!r}, {num_cols[1]!r}) per {id_col!r} fit a slopegraph.",
401
+ f'mint.change("{num_cols[0]}", "{num_cols[1]}", data=rows, name="{id_col}")',
402
+ f"--before {num_cols[0]} --after {num_cols[1]} --name {id_col}",
403
+ {"before": num_cols[0], "after": num_cols[1], "name": id_col},
404
+ )
405
+ elif len(num_cols) >= 3 and len(rows) <= 20:
406
+ _add_rec(
407
+ "table",
408
+ f"Multi-metric scorecard ({len(rows)} rows × {len(cols)} columns).",
409
+ f'mint.table(rows, bold_best=True, sort="-{num_cols[0]}")',
410
+ f"--sort -{num_cols[0]}",
411
+ {"bold_best": True, "sort": f"-{num_cols[0]}"},
412
+ )
413
+
414
+ # 5. Relate / Pareto frontier for >=2 continuous numeric columns
415
+ if len(num_cols) >= 2 and len(rows) >= 3:
416
+ cost_c = next((c for c in num_cols if any(h in c.lower() for h in _COST_COL_HINTS)), None)
417
+ score_c = next((c for c in num_cols if c != cost_c and any(h in c.lower() for h in _SCORE_COL_HINTS)), None)
418
+ rx = cost_c or num_cols[0]
419
+ ry = score_c or next(c for c in num_cols if c != rx)
420
+ nm_col = cat_cols[0] if cat_cols else None
421
+ nm_extra = f', names="{nm_col}"' if nm_col else ""
422
+ use_front = bool(cost_c and score_c and len(rows) <= 20 and nm_col)
423
+ front_extra = ", frontier=True, label_all=True" if use_front else ""
424
+ _add_rec(
425
+ "relate",
426
+ f"Continuous pair ({rx!r} vs {ry!r}) across {len(rows)} points.",
427
+ f'mint.relate("{rx}", "{ry}", data=rows{nm_extra}{front_extra}, x_label="{rx}", y_label="{ry}")',
428
+ f"--x {rx} --y {ry}" + (f" --names {nm_col}" if nm_col else ""),
429
+ {"x": rx, "y": ry, "names": nm_col, "frontier": use_front, "label_all": use_front},
430
+ )
431
+
432
+ # Always offer table fallback for compact tabular data
433
+ if not recs and len(rows) <= 20 and len(cols) <= 8:
434
+ _add_rec("table", f"Compact {len(rows)}×{len(cols)} table for exact lookup.", "mint.table(rows)", "", {})
435
+
436
+ return {
437
+ "source": src_label,
438
+ "rows": len(rows),
439
+ "columns": cols,
440
+ "column_profiles": profiles,
441
+ "recommendations": recs[:4],
442
+ "preview": rows[:3],
443
+ }
444
+
445
+
446
+ def auto_panel(
447
+ source: str | Path | Sequence[Mapping[str, Any]] | Any,
448
+ *,
449
+ title: str | None = None,
450
+ label: str | None = None,
451
+ unit: str | None = None,
452
+ highlight: str | Sequence[str] | None = None,
453
+ baseline: str | None = None,
454
+ ) -> Any:
455
+ """Automatically build the top-recommended :class:`Panel` for a data file or table.
456
+
457
+ Uses :func:`inspect_data` to pick the highest-ranked form and column mapping,
458
+ then constructs the corresponding panel cleanly with zero column boilerplate.
459
+ """
460
+ from . import explainer as fm_exp
461
+
462
+ if isinstance(source, (str, Path)):
463
+ rows = load_table_file(source)
464
+ info = inspect_data(rows)
465
+ elif is_tabular(source):
466
+ _, rows = extract_records(source, what="auto_panel(source)")
467
+ rows = [{k: _parse_scalar(v) for k, v in r.items()} for r in rows]
468
+ info = inspect_data(rows)
469
+ else:
470
+ raise ExplainError(
471
+ f"auto_panel() expected a data file path, list of dicts, or DataFrame; got {type(source).__name__}.",
472
+ fix_hint='Pass a path like "results.csv" or rows=[{"model": "A", "score": 0.8}].',
473
+ )
474
+
475
+ recs = info.get("recommendations") or []
476
+ if not recs:
477
+ raise ExplainError(
478
+ "auto_panel() could not infer a chart form for this dataset.",
479
+ fix_hint="Call mint.inspect_data(source) to view columns and choose an explicit form.",
480
+ )
481
+
482
+ top = recs[0]
483
+ kind = top["kind"]
484
+ params = dict(top.get("params") or {})
485
+ common: dict[str, Any] = {}
486
+ if title is not None:
487
+ common["title"] = title
488
+ if label is not None:
489
+ common["label"] = label
490
+ if unit is not None:
491
+ common["unit"] = unit
492
+ if highlight is not None:
493
+ common["highlight"] = highlight
494
+
495
+ if kind == "timeline":
496
+ return fm_exp.timeline(
497
+ rows,
498
+ name=params.get("name"),
499
+ start=params.get("start"),
500
+ end=params.get("end"),
501
+ group=params.get("group"),
502
+ **common,
503
+ )
504
+ if kind == "flow":
505
+ return fm_exp.flow(
506
+ rows,
507
+ name=params.get("name"),
508
+ value=params.get("value"),
509
+ reason=params.get("reason"),
510
+ **common,
511
+ )
512
+ if kind == "waterfall":
513
+ return fm_exp.waterfall(
514
+ rows,
515
+ name=params.get("name"),
516
+ value=params.get("value"),
517
+ **common,
518
+ )
519
+ if kind == "trend":
520
+ kw = {**common, "data": rows, "y": params.get("y"), "x_label": params.get("x")}
521
+ if params.get("log_x"):
522
+ kw["log_x"] = True
523
+ if baseline is not None:
524
+ kw["baseline"] = baseline
525
+ kw.setdefault("label", params.get("y"))
526
+ return fm_exp.trend(params["x"], params.get("series"), **kw)
527
+ if kind == "compare":
528
+ kw = {**common, "name": params.get("name"), "value": params.get("value")}
529
+ if params.get("group"):
530
+ kw["group"] = params["group"]
531
+ if baseline is not None:
532
+ kw["baseline"] = baseline
533
+ kw.setdefault("label", params.get("value"))
534
+ return fm_exp.compare(rows, **kw)
535
+ if kind == "distribution":
536
+ kw = {
537
+ **common,
538
+ "group": params.get("group"),
539
+ "value": params.get("value"),
540
+ "mode": params.get("mode", "dots"),
541
+ }
542
+ if params.get("log"):
543
+ kw["log"] = True
544
+ if baseline is not None:
545
+ kw["baseline"] = baseline
546
+ kw.setdefault("label", params.get("value"))
547
+ return fm_exp.distribution(rows, **kw)
548
+ if kind == "change":
549
+ kw = {**common, "data": rows, "name": params.get("name")}
550
+ kw.setdefault("label", f"{params['before']} -> {params['after']}")
551
+ return fm_exp.change(params["before"], params["after"], **kw)
552
+ if kind == "matrix":
553
+ kw = {
554
+ **common,
555
+ "rows": params.get("rows"),
556
+ "cols": params.get("cols"),
557
+ "value": params.get("value"),
558
+ }
559
+ kw.setdefault("label", params.get("value"))
560
+ return fm_exp.matrix(rows, **kw)
561
+ if kind == "relate":
562
+ kw = {
563
+ **common,
564
+ "data": rows,
565
+ "x_label": params["x"],
566
+ "y_label": params["y"],
567
+ }
568
+ if params.get("names"):
569
+ kw["names"] = params["names"]
570
+ if params.get("frontier"):
571
+ kw["frontier"] = True
572
+ if params.get("label_all"):
573
+ kw["label_all"] = True
574
+ return fm_exp.relate(params["x"], params["y"], **kw)
575
+ # Default: table
576
+ kw = {**common}
577
+ if baseline is not None:
578
+ kw["baseline"] = baseline
579
+ if params.get("bold_best"):
580
+ kw["bold_best"] = True
581
+ if params.get("sort"):
582
+ kw["sort"] = params["sort"]
583
+ return fm_exp.table(rows, **kw)