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,11 @@
1
+ <!-- mintfig:start -->
2
+ ## Scientific Figures (`mintfig`)
3
+
4
+ - To explain a result to the user in a conversation, write the takeaway sentence first, then call `mint.explain(takeaway, mint.compare(...) | mint.trend(...) | mint.change(...) | mint.distribution(...) | mint.histogram(...) | mint.relate(...) | mint.share(...) | mint.matrix(...) | mint.table(...) | mint.waterfall(...) | mint.timeline(...) | mint.flow(...), source=...)` and `print(fig.save("out.png"))` (or zero-script CLI: `mintfig inspect data.csv`, `mintfig plot data.csv --kind auto --takeaway "..." --out out.png`, `mintfig edit out.png ...`, `mintfig brief f1.png f2.png --title "..." --out report.html`). Every form accepts row-shaped data (`list[dict]` or tidy DataFrames via `name=`/`value=`/`group=`/`data=`). Show uncertainty and name it (`error=` with `error_label=`, `band=` with `band_label=`, raw observations via `mint.distribution`, `mint.histogram`, or `trend(points=)`), use `log=`/`log_x=` for values spanning decades, check the takeaway against `facts`, and send right away once `summary["ship"]` is `true` (do not re-render for minor advisory warnings). For multi-figure conversations use `mint.Session` (persistent entity colours) and `mint.brief(...).save("report.html"|"report.md")`. For fast ad-hoc chat charts where soft limits should auto-adjust instead of raising, use `with mint.lenient():` / `strict=False` / `--lenient`. For chat figures read `SKILL.md` only down to "Publication Figures".
5
+ - Build publication figures with `mintfig.Plate` or `mintfig.figure`, exposing `def build() -> Plate | Figure` (or top-level `plate` / `fig`) plus optional `CAPTION` / `TAKEAWAY` / `PANEL_NOTES`.
6
+ - Validate and export every figure with: `mintfig run plot.py --journal nature --bundle out/ --json` (supports `nature`, `science`, `science_advances`, `cell`, `pnas`, `neurips`, `screen`).
7
+ - Repair `severity == "error"` items using `issues[].fix_hint`, `panels`, and `element_locations`; review clarity warnings (`color_separation`, `clarity_metadata`, `bar_baseline_nonzero`, `chartjunk_hints`, `text_on_data`).
8
+ - Enforce a **2-loop repair cap** (`<= 2` fixes), then inspect and show `out/preview.png` to the user.
9
+ - Apply Tufte discipline: favor small multiples (`mint.ghost_context`), `mint.slopegraph`, `mint.sparkline`, `mint.range_frame`, and `mint.direct_labels` over boxed legends or spaghetti plots; reserve saturated ink for focal findings and keep bar baselines at zero.
10
+ - Use perceptual colormaps (`viridis`, `magma`, `cividis`, `mintfig_navy`, `mintfig_div`), never `jet`/`rainbow`, and never use `bbox_inches="tight"`.
11
+ <!-- mintfig:end -->
@@ -0,0 +1,143 @@
1
+ ---
2
+ name: mintfig
3
+ description: Explain data to a user with a message-first chat figure or table (one takeaway sentence plus evidence panels), or generate publication-ready Nature, Science, Cell, PNAS, NeurIPS, and screen-review scientific figures with exact millimeter geometry, preflight QA, clarity checks, and reproducible bundles.
4
+ ---
5
+
6
+ # mintfig — Figures That Say One Thing
7
+
8
+ > **Install:** `pip install git+https://github.com/blaiszik/mintfig` (or `uv pip install ...`).
9
+
10
+ **Chat figures: read down to "Publication Figures" and stop.** Deep recipes & sizing: `references/scientific_and_recipes.md`; manuscripts: `references/publication.md`.
11
+
12
+ ## Explain in a Conversation (`mint.explain`)
13
+
14
+ Use a chart for ≥5 numbers or a trend/spread/relationship; `mint.table` for exact lookups/scorecards; prose for 1–3 numbers.
15
+
16
+ **1. Write the takeaway first.** One sentence with its number ("Removing retrieval costs 8 points of accuracy", not "Ablation results"). One takeaway per figure.
17
+
18
+ **2. Pick each panel by the question it answers.** Every form accepts dicts/arrays/Series **and** tidy rows (`list[dict]` / DataFrame).
19
+
20
+ | Question | Form | Wide or tidy input |
21
+ | :--- | :--- | :--- |
22
+ | Compare sizes | `mint.compare(values)` | `{name: num}`, `{cat: {s: num}}`, or rows (`name=`, `value=`, `group=`) |
23
+ | Change over order/time | `mint.trend(x, series)` | `(x, {s: [nums]})` or `("x", "s", y="y", data=rows)` |
24
+ | Two states (before→after) | `mint.change(before, after)` | two `{name: num}` or `("c1", "c2", data=rows, name="item")` |
25
+ | Spread of raw values | `mint.distribution(groups)` | `{g: [obs]}` or rows (`group=`, `value=`; `bins=` / `mint.histogram`) |
26
+ | Two continuous measures | `mint.relate(x, y, x_label=, y_label=)` | two lists or `("x", "y", data=rows, names=, groups=)` |
27
+ | Part of whole | `mint.share(parts)` | `{name: num}` or rows (`name=`, `value=`) |
28
+ | Two categorical axes | `mint.matrix(values, rows=, cols=)` | 2-D array / wide DF, or rows (`rows=`, `cols=`, `value=`) |
29
+ | Exact lookup / scorecard | `mint.table(rows)` | `list[dict]`, DataFrame, `{col: [...]}`, or 2-D + `columns=` |
30
+ | Delta bridge start→total | `mint.waterfall(steps)` | `{step: delta}` or rows (`name=`, `value=`, optional `start=`) |
31
+ | Execution/phase spans | `mint.timeline(spans)` | `{stage: (start, end)}` or rows (`name=`, `start=`, `end=`, `group=`) |
32
+ | Cohort/pipeline attrition | `mint.flow(stages)` | `{stage: n}`, `[(stage, n, reason)]`, or rows (`name=`, `value=`, `reason=`) |
33
+
34
+ **3. Name what is measured and what matters:** `title=`, `label=`, `unit=`, `highlight=` (≤3; rest grey), `source=`.
35
+
36
+ ```python
37
+ import mintfig as mint
38
+
39
+ fig = mint.explain(
40
+ "Removing retrieval costs 8 points of accuracy; removing fine-tuning costs 13",
41
+ mint.compare({"full model": 0.82, "no retrieval": 0.74, "no fine-tuning": 0.69},
42
+ error={"full model": (0.80, 0.84), "no retrieval": (0.71, 0.77),
43
+ "no fine-tuning": (0.66, 0.72)},
44
+ error_label="95% CI, 5 seeds",
45
+ title="Both losses are outside seed noise", label="Test accuracy",
46
+ highlight=["no retrieval", "no fine-tuning"]),
47
+ mint.trend([0, 500, 1000, 1500, 2000],
48
+ {"full model": [0.02, 0.61, 0.76, 0.80, 0.82],
49
+ "no retrieval": [0.02, 0.52, 0.67, 0.72, 0.74],
50
+ "no fine-tuning": [0.01, 0.44, 0.60, 0.66, 0.69]},
51
+ title="The gap opens in the first 500 steps", label="Validation accuracy",
52
+ x_label="Training step"),
53
+ source="runs/ablation_2026-11 (5 seeds per variant)",
54
+ )
55
+ summary = fig.save("ablation.png") # dict (print() renders JSON)
56
+ print(summary)
57
+ ```
58
+
59
+ **Zero-script CLI:** `mintfig inspect data.csv` profiles & recommends forms; `mintfig plot data.csv --kind auto --takeaway "..." --out fig.png` (or explicit `--kind`, `--show`, `.html`) plots directly; `mintfig edit fig.png --style dark --out v2.png` refines saved figures; `mintfig brief f1.png f2.png --title "..." --out report.html` bundles multi-figure reports; `mintfig explain` / `mintfig show` handle JSON specs and terminal views.
60
+
61
+ **4. Check `facts` and `ship`, then deliver.**
62
+ - `summary` returns `panels[i]["facts"]`, `narrative` (L1–L4), `issues`, `ok`, and `ship`.
63
+ - **Read `facts` instead of recomputing:** forms compute rankings, baseline/reference gaps, interval overlaps, exceedance/`P(A > B)`, event medians, log slopes/power-law CIs, correlations, bottlenecks, and winners. Takeaway must agree with `facts` (`claim_overstates_uncertainty` / `claim_number_mismatch` warn advisories only).
64
+ - **`summary["ship"]` gates shipping:** `true` = zero errors and zero layout/text defects (overlaps, struck text, malformed `%`/minus/`nan`, missing glyphs, `$...$`, <11 px text). When `ship` is `true` and facts agree, **send immediately** — ignore advisory polish warnings.
65
+ - **Harness & output modes:** `width="chat"` (700 px), `width="narrow"` (450 px sidebar, auto-stacks), `width="slide"` (1280 px). `fig.save("out.html")` writes zero-CDN interactive HTML (`_repr_html_()` in Jupyter); `fig.to_terminal()` / `mintfig show` renders in terminals.
66
+ - **Lenient mode:** `with mint.lenient():` / `strict=False` / `--lenient` auto-adjusts soft limits (logged in `adjustments`). Visual check if tight; cap fixes at ≤2 rounds.
67
+
68
+ ### Every argument (unknown arguments raise `ExplainError` naming valid ones)
69
+
70
+ ```python
71
+ mint.explain(takeaway, *panels,
72
+ subtitle=None, source=None, note=None, # scope and figure footer
73
+ layout=None, # e.g. [["a"], ["b", "c"]]; repeat key to widen
74
+ colors=None, # pin across figures: {"no retrieval": "red"} (blue/red/green/amber)
75
+ style="mintfig", # "mintfig" | "bold" | "editorial" | "paper" | "dark" | "mono" | "sketch"
76
+ palette=None, # "default" | "okabe_ito" | "tol" | "earth" | "ocean" | "berry"
77
+ accent=None, # custom primary highlight hex, e.g. "#D97757"
78
+ strict=True, # False / `with mint.lenient():`: auto-adjust soft limits
79
+ width="chat") # "narrow" (450 px), "chat" (700 px), "slide" (1280 px)
80
+
81
+ # Shared by every form: title=, label=, unit=, highlight= (1–3 names), fmt=
82
+ # compare, trend, distribution, table also take baseline= (control/"before", drawn in ink)
83
+
84
+ mint.compare(values, # {name: num}, {cat: {s: num}}, Series, or rows
85
+ name=None, group=None, value=None, sort=True, zero=True, log=False,
86
+ error=None, inner_error=None, error_label=None, # inner_error= inner CI inside error=
87
+ boost=None, boost_label=None, show_delta=False, # show_delta= inline (+delta) vs baseline=
88
+ n=None, reference=None)
89
+
90
+ mint.trend(x, series=None, # wide (x, {s: [nums]}) or tidy ("x", "s", y="y", data=rows)
91
+ y=None, data=None, x_label=None, x_unit=None, log=False, log_x=False, zero=False,
92
+ fit=False, # True | "linear" | "log" | "power" overlays dashed regression fit
93
+ band=None, band_label=None, points=None, points_label=None,
94
+ events=None, regions=None, callouts=None, # regions=[(x0, x1, txt)], callouts=[(x, y, txt)]
95
+ reference=None, end_values=True, facet=False)
96
+
97
+ mint.change(before, after, data=None, name=None, labels=("Before", "After"))
98
+
99
+ mint.distribution(groups, # {g: [obs]}, wide DF, or rows (group=/value=)
100
+ group=None, value=None, stat="median",
101
+ mode="dots", quantiles=20, # mode="quantile" countable quantile dotplot (5–50 dots)
102
+ bins=None, log=False, reference=None)
103
+
104
+ mint.histogram(values, group=None, value=None, bins="auto", stat="median", log=False, reference=None)
105
+
106
+ mint.relate(x, y, x_label=, y_label=, data=None, x_unit=None, names=None, groups=None,
107
+ fit=False, frontier=False, label_all=False, connect_groups=False,
108
+ regions=None, callouts=None, log_x=False, log_y=False, reference=None)
109
+
110
+ mint.share(parts, name=None, value=None, top=7)
111
+
112
+ mint.matrix(values, rows=None, cols=None, value=None, diverging=False, center=0.0,
113
+ triangle=None, mask_diagonal=False, highlight=None) # triangle="lower"|"upper" for symmetric matrices
114
+
115
+ mint.table(rows, columns=None, units=None, highlight=None, baseline=None,
116
+ bold_best=False, sort=None, align=None, fmt=None) # panel.to_markdown() exports MD
117
+
118
+ mint.waterfall(steps, name=None, value=None, start=None, total_label="Total", show_total=True, reference=None)
119
+
120
+ mint.timeline(spans, name=None, start=None, end=None, group=None, x_label=None, sort=True, reference=None)
121
+
122
+ mint.flow(stages, name=None, value=None, reason=None, show_pct=True)
123
+
124
+ mint.custom(draw_fn, height_mm=48.0, describe="...") # escape hatch: draw_fn(ax)
125
+ ```
126
+
127
+ ### Limits, edits & multi-turn workflows (`references/scientific_and_recipes.md`)
128
+
129
+ - **Hard limits (strict):** `compare`/`timeline`/`table` ≤20, `change`/`waterfall` ≤14, `flow` ≤12, `distribution` ≤8 groups (≥3 obs), `matrix` ≤16×12, `table` ≤8 cols, `relate(groups=)` ≤4, `trend` ≤4 coloured series (else `highlight=`/`facet=True`, ≤12), `highlight=` ≤3, 4 shared colours, ≤6 panels, `too_tall` >135 mm.
130
+ - **Rules:** zero-baseline bars (`zero=False`/`error=`/`log=True` → dots); no pies, dual axes, legends, or rotated text; name every interval (`error_label=`/`band_label=`); direct Unicode (`µm`, `cm⁻³`, `°C` — never `$...$`).
131
+ - **Auto, edits & memory:** `mint.auto_panel("data.csv")` picks form/columns; `mint.edit("fig.png", highlight=..., drop=..., style=..., out="v2.png")`; `s = mint.Session(style=..., state_path=...)` keeps colours across turns (prefix-matching variants); `s.brief("Title").save("report.html"|"report.md")` bundles reports.
132
+
133
+ ## Publication Figures
134
+
135
+ For manuscripts (`nature`, `science`, `science_advances`, `cell`, `pnas`, `neurips`, `screen`), read **`references/publication.md`** for exact journal specs, script contract, and Tufte primitives. Quick workflow:
136
+
137
+ 1. Write `plot.py` exposing `def build(journal="nature") -> mint.Plate` (or top-level `plate`/`fig`) using `mint.Plate` or `mint.figure`.
138
+ 2. Run preflight + bundle export:
139
+ ```bash
140
+ mintfig run plot.py --journal nature --bundle out/ --json
141
+ ```
142
+ 3. Exit `0` (`ok: true`) → show `out/preview.png` (and `out/proof.png`); exit `1` → fix `severity == "error"` via `fix_hint` (**max 2 repair loops**); exit `2` → fix script contract/exception.
143
+ 4. Apply Tufte discipline (`mint.ghost_context`, `mint.slopegraph`, `mint.range_frame`, `mint.direct_labels`); never use rainbow/jet colormaps or `bbox_inches="tight"`.
@@ -0,0 +1 @@
1
+ """Packaged agent skill and instruction assets for mintfig."""
@@ -0,0 +1,79 @@
1
+ # mintfig Publication Figures Reference
2
+
3
+ Use this workflow when generating manuscript or report plates for *Nature*, *Science*, *Science Advances*, *Cell*, PNAS, NeurIPS, or screen review.
4
+
5
+ ## Standard Agent Workflow
6
+
7
+ 1. Write a self-contained Python plotting script (`plot.py`) following the **Script Contract** below.
8
+ 2. Run preflight + export bundle in one command:
9
+ ```bash
10
+ mintfig run plot.py --journal nature --bundle out/ --json
11
+ ```
12
+ (Supports `--journal nature|science|science_advances|cell|pnas|neurips|screen` and optional `--width`.)
13
+ 3. Inspect the JSON output (`schema_version: "0.2"`):
14
+ - Exit `0` (`ok: true`): passes all deterministic journal rules. Review any clarity `warning` items (`color_separation`, `clarity_metadata`), then show `out/preview.png` (and `out/proof.png` for CVD/print verification).
15
+ - Exit `1` (`stage: "preflight"`): read `issues` where `severity == "error"`, apply each `fix_hint` using `panel`, `panels`, `elements`, and `element_locations`, and re-run.
16
+ - Exit `2` (`stage: "contract"` or `"runtime"`): fix the contract or exception using `error` and `fix_hint`, then re-run.
17
+ 4. **2-Loop Repair Cap:** perform at most 2 repair loops. If an error remains, stop, report remaining `issues`, and show `out/preview.png`.
18
+
19
+ ## Script Contract
20
+
21
+ `mintfig run` discovers your figure in priority order:
22
+ 1. Module-level `def build(...) -> mint.Plate | matplotlib.figure.Figure` (optionally accepting `journal` and/or `width`).
23
+ 2. Module-level `plate` (`mintfig.Plate`) or `fig` (`matplotlib.figure.Figure`).
24
+
25
+ Optional module-level metadata flowing into `figure.tex` and `figure.json`:
26
+ - `CAPTION: str` — manuscript caption
27
+ - `LABEL: str` — LaTeX `\label{...}` (default `"fig:fig1"`)
28
+ - `TAKEAWAY: str` — one-sentence human takeaway
29
+ - `PANEL_NOTES: dict[str, str]` — one-line reading per panel
30
+
31
+ ```python
32
+ import numpy as np
33
+ import mintfig as mint
34
+
35
+
36
+ def build(journal: str = "nature") -> mint.Plate:
37
+ plate = mint.Plate(journal=journal, width="double", height_mm=105.0, layout=(1, 2))
38
+ x = np.linspace(0, 10, 200)
39
+ plate["a"].plot(x, np.exp(-x / 3.0), label="Control")
40
+ plate["a"].plot(x, np.exp(-x / 6.0), label="Treated")
41
+ plate["a"].set_xlabel("Time (h)")
42
+ plate["a"].set_ylabel(r"Signal ($\mu\mathrm{M}$)")
43
+ mint.direct_labels(plate["a"])
44
+
45
+ rng = np.random.default_rng(0)
46
+ plate["b"].scatter(rng.normal(size=200), rng.normal(size=200), s=8, alpha=0.7)
47
+ plate["b"].set_xlabel("PC 1")
48
+ plate["b"].set_ylabel("PC 2")
49
+
50
+ plate.label_panels()
51
+ return plate
52
+ ```
53
+
54
+ ## Journal Specs Quick Reference
55
+
56
+ | Journal | Width Presets (mm) | Max Height | Body / Tick / Panel | Panel Case |
57
+ | :--- | :--- | :---: | :---: | :---: |
58
+ | `nature` | `single`: 89, `mid`/`1.5col`: 120, `double`/`full`: 183 | 170 mm | 6.5 / 6.0 / 8.0 pt | `a, b, c` |
59
+ | `science` | `single`: 55, `double`/`2col`: 120, `full`/`3col`: 184 | 180 mm | 7.0 / 6.0 / 8.5 pt | `A, B, C` |
60
+ | `science_advances` | `single`: 84, `mid`: 120, `double`/`full`: 175 | 180 mm | 7.0 / 6.0 / 8.5 pt | `A, B, C` |
61
+ | `cell` | `single`: 85, `mid`/`1.5col`: 114, `double`/`full`: 174 | 200 mm | 7.0 / 6.0 / 8.5 pt | `A, B, C` |
62
+ | `pnas` | `single`: 87, `mid`/`1.5col`: 114, `double`/`full`: 178 | 200 mm | 7.0 / 6.5 / 9.0 pt | `A, B, C` |
63
+ | `neurips` | `half`/`single`: 67, `mid`: 111.8, `double`/`full`: 139.7 | 180 mm | 7.5 / 6.5 / 8.5 pt | `a, b, c` |
64
+ | `screen` | `chat`/`single`: 140, `wide`/`double`: 180, `slide`: 240 | 135 mm | 8.5 / 7.5 / 10.0 pt | `a, b, c` |
65
+
66
+ ## Tufte & Editorial Visual Grammar
67
+
68
+ - **Small multiples over spaghetti:** for `> 4` curves, split into shared-axis small multiples with `mint.ghost_context(...)`.
69
+ - **High-density comparative forms:** `mint.slopegraph(...)`, `mint.sparkline(...)`, `mint.tufte_boxplot(...)`.
70
+ - **Maximize data-ink & trim spines:** `mint.range_frame(ax, rug=True)`, unboxed legends (`frameon=False`), `mint.direct_labels(ax)`, and `mint.emphasize(ax, keep=...)`.
71
+ - **Micro/macro layering:** keep large fills and CI ribbons pale (`alpha <= 0.14`); reserve saturated ink for focal findings.
72
+ - **Graphical integrity:** start positive bar charts at zero; scale bubble markers by area (`s ∝ value`); always show uncertainty and sample size `n`.
73
+
74
+ ## Publication Best Practices
75
+
76
+ - Never use rainbow/jet colormaps (`jet`, `rainbow`, `hsv`, `gist_rainbow`, `nipy_spectral`, `prism`, `flag`); use perceptual colormaps (`viridis`, `magma`, `cividis`, `inferno`, `mintfig_navy`, `mintfig_teal`, `mintfig_div`).
77
+ - Never pass `bbox_inches="tight"` — `mintfig` locks exact millimeter MediaBox dimensions via `constrained_layout`.
78
+ - Wrap mathtext units in `\mathrm{...}` (e.g. `r"$\mathrm{\mu m}$"`).
79
+ - Bundle outputs in `out/`: `figure.pdf` (Type 42 editable vector), `figure.svg`, `preview.png`, `proof.png`, `figure.tex`, `figure.json`, `reproduce.py`, and `report.json`.
@@ -0,0 +1,213 @@
1
+ # mintfig Chat Figures: Scientific Details, Sizing & Recipes
2
+
3
+ Read this reference when building complex multi-panel scientific figures, sizing tight layouts, pinning entity colours across figures, or editing an existing figure spec.
4
+
5
+ ## Scientific data guidance
6
+
7
+ - **Show uncertainty and name it:**
8
+ | You have | Use |
9
+ | :--- | :--- |
10
+ | Raw replicates per condition (seeds, wells, samples) | `mint.distribution` — every observation drawn (`stat="mean"` if claim is about means), or `mode="quantile", quantiles=20` for countable frequency dotplots (5% per dot) |
11
+ | Raw replicates or units along x (dose, time, step) | `mint.trend(x, points={name: [[reps], ...]})` or tidy `mint.trend("x", "group", y="val", data=rows)` (repeated `(x, group)` rows auto-become `points=`) |
12
+ | Only an estimate and its interval | `mint.compare(error=..., inner_error=..., error_label="50% / 95% CI")` or `mint.trend(band=..., band_label="± 1 s.d.")` |
13
+
14
+ An unlabelled interval triggers `interval_unlabelled`. `facts` state whether intervals overlap, exceedance probabilities above `reference=`, and empirical superiority `P(group > baseline)` on `distribution`. Do not write "significant" unless you ran the test, and name it in `note=`; advisory `claim_overstates_uncertainty` and `claim_number_mismatch` warn on clear mismatches.
15
+ - **Values spanning decades:** `log=True` for y (`compare`, `trend`, `distribution`), `log_x=True` for x (`trend`, `relate`). Bars are never drawn on a log axis.
16
+ - **Lower is better** (loss, error, IC50): `sort="asc"` puts the best item on top (`mint.table(..., sort="cost", bold_best="min")`).
17
+ - **Units & Unicode:** `unit=` is a short symbol (`ms`, `%`, `mg/L`, `×`); words go in `label=`. Write Unicode directly (`µm`, `cm⁻³`, `°C`, `Å`, `χ²`); `$...$` triggers `latex_markup`. Write fractional exponents as `"d⁻½"` or `"1/√d"`, never `"d⁻¹ᐟ²"`.
18
+ - **x unit:** on numeric `trend` and `relate`, a one-word `(...)` or `[...]` at the end of `x_label` ("Time (h)") is parsed as the x unit in `facts` ("4 h"). Override with `x_unit="steps"` or disable with `x_unit=""`.
19
+ - **Numbers:** ~3 significant figures with `×10ⁿ` for extreme magnitudes, never rounded to zero. Override via `fmt=".2f"` or `fmt="{:.1f} ms"`.
20
+ - **Missing values:** pass `None` or `NaN`; gaps draw as gaps (`—` in `matrix` and `table`), are counted in `facts`, and belong in `note=`.
21
+ - **Small n (<5):** `distribution` shows points + centre mark only; mention `n` in the title or `note=`.
22
+ - **>4 ordered levels** (doses, temperatures): `highlight=` the 1–3 the claim is about (rest become labelled grey context) or `facet=True`.
23
+ - **Log-axis slopes:** with `trend(log=True)` and numeric x, `facts` report log₁₀(y) slope per x unit with R² (split around interior peaks/troughs); with `log_x=True` too, power-law exponents with 95% CI.
24
+
25
+ ## Height & layout budgets
26
+
27
+ `too_tall` warns above 135 mm (one screen; at 700 px chat width, 1 mm ≈ 5 px → 675 px). A one-line takeaway plus one full-width panel is approximately:
28
+
29
+ | Panel | Figure height |
30
+ | :--- | :--- |
31
+ | `compare` or `share`, N bars | 23 + 5.3·N mm (5 → 50, 10 → 76, 20 → 129) |
32
+ | `distribution`, G groups | 33 + 8.5·G mm (4 → 67, 8 → 101) |
33
+ | `matrix`, R rows | 28 + 6.3·R mm (6 → 66, 10 → 90, 16 → 128) |
34
+ | `table`, R rows | 30 + 5.4·R mm (5 → 57, 10 → 84, 15 → 111) |
35
+ | `change`, N items | 60 mm at 4, 71 at 8, 99 at 14 |
36
+ | `trend` / `relate` | 79 / 84 mm full width, 66 at half width |
37
+
38
+ Each extra full-width row adds its height minus ~15 mm; side-by-side panels take the tallest height; `subtitle=` adds 4 mm, `source=` 6 mm, `note=` 4 mm, a second takeaway line 5 mm. Give `matrix`, `table`, and long-label panels a full row via `layout=[["a"], ["b", "c"]]`.
39
+
40
+ ## Colour consistency
41
+
42
+ A name keeps one colour across every panel of a figure (e.g., `"no retrieval"` stays red across a dot plot, curve, and `mint.table` highlight). `highlight=` assigns red, blue, green, amber in order unless pinned; everything else turns grey; `baseline=` draws in ink. To keep colours across multiple figures in one conversation, pass `colors=summary["colors"]` (or `colors={"no retrieval": "red"}`) to subsequent `mint.explain` calls.
43
+
44
+ Styles (`style=`): `mintfig`, `bold`, `editorial`, `paper`, `dark`, `mono`, `sketch` (illustrative only; warns unless `source=`/`note=` notes illustrative data).
45
+ Palettes (`palette=`): `default`, `okabe_ito`, `tol`, `earth`, `ocean`, `berry` (CVD-verified independently of `style=`).
46
+
47
+ ## Recipes (tidy rows & wide DataFrames)
48
+
49
+ ```python
50
+ # Row-shaped CSV / JSON records directly (no manual pivoting needed)
51
+ mint.compare(rows, name="model", value="score", error=("ci_lo", "ci_hi"), error_label="95% CI", n="n")
52
+ mint.trend("step", "variant", y="val_acc", data=rows, x_label="Training step", label="Accuracy")
53
+ mint.distribution(rows, group="condition", value="ic50", log=True, label="IC50", unit="µM")
54
+ mint.matrix(rows, rows="model", cols="benchmark", value="score", label="Pass rate", unit="%")
55
+ mint.relate("cost", "score", data=rows, names="model", groups="family", log_x=True,
56
+ x_label="Cost ($/M tokens)", y_label="Score (%)")
57
+
58
+ # Exact-lookup scorecard table with mixed units and bold winners
59
+ mint.table(
60
+ rows,
61
+ columns=["Model", "GPQA", "SWE-bench", "Cost"],
62
+ units={"GPQA": "%", "SWE-bench": "%", "Cost": "$/M"},
63
+ bold_best={"GPQA": "max", "SWE-bench": "max", "Cost": "min"},
64
+ highlight="New Model",
65
+ baseline="Prev Gen",
66
+ sort="-GPQA",
67
+ title="New Model leads reasoning and coding at half the cost",
68
+ )
69
+
70
+ # Model-release hero cards: grouped benchmarks, extended-thinking boosts, & Pareto frontiers
71
+ mint.compare(
72
+ {"GPQA": {"New": 86.4, "Prev": 77.1, "Peer": 83.2}, "SWE": {"New": 74.2, "Prev": 58.6, "Peer": 71.0}},
73
+ highlight="New", baseline="Prev", label="Accuracy", unit="%", title="Head-to-head benchmarks",
74
+ )
75
+ mint.compare(
76
+ {"New": 76.0, "Prev": 64.0, "Peer": 74.0},
77
+ boost={"New": 10.4, "Prev": 6.2, "Peer": 8.0}, boost_label="Extended thinking",
78
+ highlight="New", baseline="Prev", label="AIME accuracy", unit="%",
79
+ )
80
+ mint.relate(
81
+ "cost", "score", data=rows, names="model", groups="family", highlight="NewFamily",
82
+ frontier=True, label_all=True, connect_groups=True, log_x=True,
83
+ x_label="Cost ($/M tokens)", y_label="Score (%)", unit="%",
84
+ )
85
+ # Combine with width="slide", style="paper"|"dark", and accent="#D97757" for wide hero graphics!
86
+
87
+ # Ratio per item against a reference (dots on log axis around 1)
88
+ mint.compare(ratio, log=True, zero=False, reference=(1, "no change"), label="Ratio to reference", unit="×")
89
+
90
+ # Before/after an event with an untreated control (each unit as % of own pre-event median)
91
+ wide = df.pivot(index="time", columns="unit_id", values="value")
92
+ rel = wide / df[df.time < t_event].groupby("unit_id").value.median() * 100
93
+ mint.trend(rel.index, rel, baseline="untreated", events={t_event: "event"},
94
+ label="Value vs own median before", unit="%")
95
+
96
+ # Visual-science upgrades: quantile dotplots, nested intervals + inline deltas, callouts & shaded regions
97
+ mint.distribution(
98
+ {"treated": treated_samples, "control": control_samples},
99
+ mode="quantile", quantiles=20, baseline="control", reference=(50, "target"),
100
+ highlight="treated", label="Response", unit="%", title="90% of treated runs clear target",
101
+ )
102
+ mint.compare(
103
+ {"variant A": 84.2, "variant B": 79.1, "control": 74.9},
104
+ error={"variant A": 3.4, "variant B": 3.1, "control": 2.9},
105
+ inner_error={"variant A": 1.6, "variant B": 1.5, "control": 1.4},
106
+ error_label="50% / 95% CI", baseline="control", show_delta=True,
107
+ highlight="variant A", label="Accuracy", unit="%",
108
+ )
109
+ mint.trend(
110
+ days, {"service": latency}, x_label="Day", label="p99 latency", unit="ms",
111
+ regions=[(10, 14, "migration window")],
112
+ callouts=[(12, 420, "cache cold-start spike")],
113
+ )
114
+ ```
115
+
116
+ ## Harness-adaptive delivery (IDE sidebars, HTML review, & terminals)
117
+
118
+ - **IDE sidebars (~420–480 px):** pass `width="narrow"` (92 mm, 450 px target width; multi-panel layouts auto-stack vertically so panels stay crisp at ≥12 px text).
119
+ - **Interactive HTML review:** `fig.save("review.html")` (or `mintfig explain spec.json --out review.html`) emits a zero-CDN self-contained HTML file with embedded SVG, theme-matched surfaces, a toggleable Facts & Data drawer, Download SVG, Copy Spec JSON, and a Critique / Ask Agent feedback panel. Jupyter notebooks render the interactive fragment automatically via `Explanation._repr_html_()`.
120
+ - **Terminal delivery:** `mintfig show fig.png` (or `spec.json` / `-` with `--mode auto|kitty|iterm2|unicode|ascii`) auto-detects Kitty/Ghostty or iTerm2/WezTerm inline PNG protocols and falls back to crisp Unicode bars, box-drawn tables, and sparklines (`fig.to_terminal()` in Python).
121
+ - **Four-level narrative (`summary["narrative"]`):** returns `L1` (construction), `L2` (statistical facts), `L3` (perceptual patterns), `L4` (domain takeaway), and a reader-first `summary` string.
122
+
123
+ ## Editing a returned figure (`mint.edit` & `mint.load`)
124
+
125
+ ```python
126
+ # One-line surgical edit on a saved PNG, JSON spec, or Explanation
127
+ mint.edit(
128
+ "ablation.png",
129
+ takeaway="Removing fine-tuning costs 13 points of accuracy, retrieval 8",
130
+ highlight="no fine-tuning",
131
+ drop_panel="b",
132
+ style="dark",
133
+ out="ablation_v2.png",
134
+ write_spec=True,
135
+ )
136
+ # CLI equivalent:
137
+ # mintfig edit ablation.png --highlight "no fine-tuning" --drop-panel b --style dark --out ablation_v2.png
138
+ ```
139
+
140
+ ## Attribution bridges (`mint.waterfall`), execution timelines (`mint.timeline`), & zero-script CLI
141
+
142
+ ```python
143
+ # Attribution / delta bridge (ablation gains, cost/latency budgets)
144
+ mint.waterfall(
145
+ {"+RAG": 8.0, "+Reranker": 3.4, "+CoT": 2.1, "Quantization": -1.5},
146
+ start=("Base model", 69.0),
147
+ total_label="Shipped",
148
+ highlight="+RAG",
149
+ reference=(80.0, "Release target"),
150
+ title="RAG drives 67% of the net gain",
151
+ label="Benchmark accuracy",
152
+ unit="%",
153
+ )
154
+
155
+ # Execution / phase span timeline (CI traces, agent runs, protocols)
156
+ mint.timeline(
157
+ [
158
+ ("fetch", 0, 8, "setup"),
159
+ ("compile", 8, 54, "build"),
160
+ ("unit tests", 54, 92, "verify"),
161
+ ("integration", 54, 148, "verify"),
162
+ ("deploy", 148, 160, "release"),
163
+ ],
164
+ highlight="integration",
165
+ reference=(120, "CI SLA"),
166
+ title="Integration tests exceed the 120 s budget",
167
+ x_label="Elapsed (s)",
168
+ unit="s",
169
+ )
170
+
171
+ # Zero-script CLI workflow from a CSV/TSV/JSON/JSONL file:
172
+ # mintfig inspect results.csv
173
+ # mintfig plot results.csv --kind auto --takeaway "..." --out fig1.png
174
+ # mintfig brief fig1.png fig2.png --title "Investigation" --out report.html
175
+
176
+ # Attrition / cohort / filter funnel with exclusion reasons
177
+ mint.flow(
178
+ [
179
+ ("Screened", 1240),
180
+ ("Eligible", 912, "missing baseline"),
181
+ ("Enrolled", 780, "declined consent"),
182
+ ("Completed", 714, "lost to follow-up"),
183
+ ],
184
+ highlight="Eligible",
185
+ title="58% of screened patients complete follow-up",
186
+ label="Cohort size",
187
+ unit="patients",
188
+ )
189
+
190
+ # Fitted scaling curves & clean lower-triangle correlation matrix
191
+ mint.trend(compute, {"Dense": loss_d, "MoE": loss_m}, log=True, log_x=True, fit=True,
192
+ x_label="Compute (FLOPs)", label="Validation loss")
193
+ mint.matrix(corr, rows=metrics, cols=metrics, diverging=True, center=0.0,
194
+ triangle="lower", mask_diagonal=True, title="Metric correlations", label="Pearson r")
195
+ ```
196
+
197
+ ## Multi-turn visual memory (`mint.Session`) & briefings (`mint.brief`)
198
+
199
+ ```python
200
+ session = mint.Session(style="paper", state_path=".mintfig_session.json")
201
+ f1 = session.explain("Alpha-3 leads baseline by 9.3 points", mint.compare({"Alpha-3": 86.4, "Baseline": 77.1}, highlight="Alpha-3", baseline="Baseline", unit="%"))
202
+ # Prefix matching: "Alpha-3 (int4)" automatically inherits "Alpha-3"'s hue on turn 2!
203
+ f2 = session.explain("Quantized Alpha-3 stays within 1.1 points at half the latency", mint.compare({"Alpha-3 (int4)": 85.3, "Baseline": 77.1}, highlight="Alpha-3 (int4)", baseline="Baseline", unit="%"))
204
+
205
+ # Compose into a single zero-CDN HTML report or PR-ready Markdown + PNGs
206
+ report = session.brief(
207
+ "Release candidate evaluation",
208
+ subtitle="Synthetic benchmark suite",
209
+ summary=["Alpha-3 leads by 9.3 points", "int4 quantization retains 99% of accuracy"],
210
+ )
211
+ report.save("eval_brief.html")
212
+ report.save("eval_brief.md") # writes eval_brief.md + eval_brief_figures/fig_01.png ...
213
+ ```
mintfig/audit.py ADDED
@@ -0,0 +1,179 @@
1
+ """Independent drawn-layout and text-quality audit for rendered figures.
2
+
3
+ Inspects the actual artists Matplotlib draws during rendering:
4
+ - Overlapping visible text bounding boxes
5
+ - Visible non-grid lines intersecting text bounding boxes
6
+ - Text formatting faults (doubled ``%``, repeated words, ASCII hyphen minus,
7
+ raw ``nan``/``None``/``inf`` tokens)
8
+
9
+ Used by :func:`mintfig.explain` to gate ``summary["ship"]`` and reusable on
10
+ saved PNGs via :func:`audit_layout`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ if TYPE_CHECKING:
20
+ from matplotlib.figure import Figure
21
+
22
+ _DOUBLED = re.compile(r"\b(\w+(?:\s+\w+)?)\s+\1\b", re.IGNORECASE)
23
+ _ASCII_MINUS = re.compile(r"(?:^|[\s(\[=:,])-\d")
24
+ _JUNK = re.compile(r"\b(nan|NaN|None|inf|-inf)\b")
25
+
26
+
27
+ def audit_figure(
28
+ fig: Figure,
29
+ *,
30
+ pad_px: float = 1.5,
31
+ allow_ascii_minus: bool = False,
32
+ ) -> dict[str, Any]:
33
+ """Audit a drawn Matplotlib figure for overlaps, struck text, and text faults.
34
+
35
+ Must be called while the figure's typography/rc context is active so font
36
+ metrics match the saved output.
37
+
38
+ Returns
39
+ -------
40
+ dict
41
+ ``{"overlaps": [...], "struck": [...], "text_faults": [...], "texts": n}``.
42
+ """
43
+ from matplotlib.text import Text
44
+
45
+ out: dict[str, Any] = {"overlaps": [], "struck": [], "text_faults": [], "texts": 0}
46
+ drawn: list[Text] = []
47
+ original = Text.draw
48
+
49
+ def _recording_draw(self: Text, renderer: Any) -> Any:
50
+ if self.get_visible() and self.get_text().strip() and self.get_alpha() != 0:
51
+ drawn.append(self)
52
+ return original(self, renderer)
53
+
54
+ Text.draw = _recording_draw # type: ignore[method-assign]
55
+ try:
56
+ fig.canvas.draw()
57
+ finally:
58
+ Text.draw = original # type: ignore[method-assign]
59
+
60
+ renderer = fig.canvas.get_renderer() # type: ignore[attr-defined]
61
+ texts = list(dict.fromkeys(drawn))
62
+ out["texts"] = len(texts)
63
+
64
+ shrunk = []
65
+ for text_artist in texts:
66
+ bbox = text_artist.get_window_extent(renderer).expanded(1.0, 1.0)
67
+ if bbox.width > 2 * pad_px and bbox.height > 2 * pad_px:
68
+ bbox = bbox.from_extents(
69
+ bbox.x0 + pad_px,
70
+ bbox.y0 + pad_px,
71
+ bbox.x1 - pad_px,
72
+ bbox.y1 - pad_px,
73
+ )
74
+ shrunk.append((text_artist, bbox))
75
+
76
+ for i, (ti, bi) in enumerate(shrunk):
77
+ for tj, bj in shrunk[i + 1 :]:
78
+ if bi.overlaps(bj):
79
+ out["overlaps"].append(f"{ti.get_text()!r} / {tj.get_text()!r}")
80
+
81
+ grid = {id(g) for ax in fig.axes for g in (*ax.get_xgridlines(), *ax.get_ygridlines())}
82
+ lines = [
83
+ ln
84
+ for ax in fig.axes
85
+ for ln in ax.lines
86
+ if id(ln) not in grid
87
+ and ln.get_visible()
88
+ and len(ln.get_xdata()) >= 2
89
+ and ln.get_linestyle() not in ("None", "", " ")
90
+ and ln.get_linewidth() > 0
91
+ ]
92
+ for ln in lines:
93
+ path = ln.get_transform().transform_path(ln.get_path())
94
+ dashed = ln.get_linestyle() not in ("-", "solid")
95
+ for text_artist, bbox in shrunk:
96
+ if text_artist.axes is not None and text_artist.axes is not ln.axes:
97
+ continue
98
+ if path.intersects_bbox(bbox, filled=False):
99
+ what = "dashed reference line" if dashed else "data line"
100
+ out["struck"].append(f"{text_artist.get_text()!r} crossed by a {what}")
101
+
102
+ for text_artist in texts:
103
+ txt = text_artist.get_text()
104
+ plain = re.sub(r"\$[^$]*\$", "", txt)
105
+ if "%%" in plain:
106
+ out["text_faults"].append(f"doubled %: {txt!r}")
107
+ match = _DOUBLED.search(plain)
108
+ if match and not match.group(1).isdigit():
109
+ out["text_faults"].append(f"repeated words {match.group(0)!r}: {txt!r}")
110
+ if not allow_ascii_minus and _ASCII_MINUS.search(plain) and not re.search(r"\d{4}-\d{2}", plain):
111
+ out["text_faults"].append(f"ASCII hyphen as minus sign: {txt!r}")
112
+ if _JUNK.search(plain):
113
+ out["text_faults"].append(f"junk value: {txt!r}")
114
+
115
+ return out
116
+
117
+
118
+ def audit_layout(png: str | Path) -> dict[str, Any]:
119
+ """Rebuild a mintfig PNG from its embedded spec and run :func:`audit_figure`."""
120
+ from .explainer import load
121
+
122
+ exp = load(str(png))
123
+ with exp.theme.rc_context(exp.spec):
124
+ return audit_figure(exp.fig, allow_ascii_minus=(exp.theme.minus_sign == "-"))
125
+
126
+
127
+ def audit_to_issues(
128
+ audit: dict[str, Any],
129
+ *,
130
+ existing_rules: set[str] | None = None,
131
+ ) -> list[dict[str, Any]]:
132
+ """Translate non-empty :func:`audit_figure` findings into ``explain`` issue dicts."""
133
+ seen = existing_rules or set()
134
+ issues: list[dict[str, Any]] = []
135
+
136
+ if audit["overlaps"] and "text_overlaps" not in seen:
137
+ sample = "; ".join(audit["overlaps"][:4])
138
+ issues.append(
139
+ {
140
+ "rule": "text_overlaps",
141
+ "severity": "warning",
142
+ "message": f"Drawn text overlaps: {sample}.",
143
+ "fix_hint": (
144
+ "Shorten item names, end labels or event text (end_values=False drops "
145
+ "numbers at line ends), show fewer items/series, or give the panel a "
146
+ 'full-width row with layout=[["a"], ["b"]].'
147
+ ),
148
+ }
149
+ )
150
+
151
+ if audit["struck"] and not ({"text_on_data", "value_label_on_reference"} & seen):
152
+ sample = "; ".join(audit["struck"][:4])
153
+ issues.append(
154
+ {
155
+ "rule": "text_struck_by_line",
156
+ "severity": "warning",
157
+ "message": f"Drawn text is crossed by a line: {sample}.",
158
+ "fix_hint": (
159
+ "Shorten labels, move or drop reference/event labels, name fewer items "
160
+ 'in highlight=, or give the panel a full-width row with layout=[["a"], ["b"]].'
161
+ ),
162
+ }
163
+ )
164
+
165
+ if audit["text_faults"]:
166
+ sample = "; ".join(audit["text_faults"][:4])
167
+ issues.append(
168
+ {
169
+ "rule": "text_malformed",
170
+ "severity": "warning",
171
+ "message": f"Malformed drawn text: {sample}.",
172
+ "fix_hint": (
173
+ "Check unit=/fmt= for doubled '%', repeated label words, raw NaN/None "
174
+ "values, or ASCII '-' minus signs in custom text."
175
+ ),
176
+ }
177
+ )
178
+
179
+ return issues