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,459 @@
1
+ """waterfall() attribution / bridge form for mint.explain.
2
+
3
+ Answers: "How do individual gains and losses add up from start to finish?"
4
+ Draws horizontal floating bars connected by subtle vertical bridge connectors,
5
+ with optional starting anchor and final total bar grounded at zero.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping, Sequence
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ from matplotlib.axes import Axes
15
+
16
+ from .._tabular import resolve_named_table
17
+ from ..themes import MINTFIG_THEME, Theme
18
+ from .core import (
19
+ PT_TO_MM,
20
+ ExplainError,
21
+ Panel,
22
+ _bare_axes,
23
+ _base_spec,
24
+ _Ctx,
25
+ _diff_with_unit,
26
+ _formatter,
27
+ _guarded,
28
+ _inline_unit,
29
+ _is_number,
30
+ _is_strict,
31
+ _issue,
32
+ _jsonable,
33
+ _Measure,
34
+ _named_values,
35
+ _names,
36
+ _plain,
37
+ _record_adjustment,
38
+ _reference_line,
39
+ _signed,
40
+ _Sizes,
41
+ _to_float,
42
+ _with_unit,
43
+ )
44
+
45
+ MAX_WATERFALL_STEPS = 14
46
+ COMFORTABLE_WATERFALL_STEPS = 10
47
+
48
+
49
+ def _parse_start(start: object) -> tuple[str, float] | None:
50
+ if start is None:
51
+ return None
52
+ if _is_number(start):
53
+ return ("Start", _to_float(start, "waterfall(start)"))
54
+ if (
55
+ isinstance(start, Sequence)
56
+ and not isinstance(start, (str, bytes))
57
+ and len(start) == 2
58
+ and isinstance(start[0], str)
59
+ ):
60
+ return (start[0].strip() or "Start", _to_float(start[1], "waterfall(start)"))
61
+ raise ExplainError(
62
+ f"waterfall(start={start!r}) must be a number or (label, number).",
63
+ fix_hint='Pass start=69.0 or start=("Base model", 69.0).',
64
+ )
65
+
66
+
67
+ @_guarded("waterfall")
68
+ def waterfall(
69
+ steps: Mapping[str, float] | Sequence[tuple[str, float]] | Sequence[Mapping[str, Any]],
70
+ *,
71
+ name: str | None = None,
72
+ value: str | None = None,
73
+ start: float | tuple[str, float] | None = None,
74
+ total_label: str = "Total",
75
+ show_total: bool = True,
76
+ title: str | None = None,
77
+ label: str | None = None,
78
+ unit: str | None = None,
79
+ highlight: str | Sequence[str] | None = None,
80
+ reference: float | tuple[float, str] | None = None,
81
+ fmt: str | None = None,
82
+ ) -> Panel:
83
+ """How do individual gains and losses add up from start to finish?
84
+
85
+ ``steps`` maps step names to signed deltas (a dict, Series, or row-shaped
86
+ data with ``name=`` and ``value=``). Optional ``start=`` anchors the bridge
87
+ at a starting value (e.g. ``start=("Base", 69.0)``); ``show_total=True``
88
+ adds a final anchored bar labelled ``total_label`` showing the cumulative sum.
89
+ """
90
+ tabular = resolve_named_table(
91
+ steps,
92
+ "waterfall(steps)",
93
+ name=name,
94
+ value=value,
95
+ form="waterfall",
96
+ )
97
+ if tabular is not None:
98
+ steps = tabular[0]
99
+ data = _named_values(steps, "waterfall(steps)")
100
+ step_names = list(data)
101
+ if not step_names:
102
+ raise ExplainError("waterfall(steps) is empty.", fix_hint="Pass at least one step.")
103
+
104
+ start_anchor = _parse_start(start)
105
+ ref = _reference_line(reference, "waterfall(reference)")
106
+
107
+ # Limit handling: in lenient mode, fold smallest steps into "Other (k)" so the total stays exact!
108
+ if len(step_names) > MAX_WATERFALL_STEPS:
109
+ if not _is_strict():
110
+ req_hl = (
111
+ [highlight]
112
+ if isinstance(highlight, str)
113
+ else ([str(h) for h in highlight] if highlight is not None else [])
114
+ )
115
+ must_keep = [nm for nm in req_hl if nm in data]
116
+ by_mag = sorted(step_names, key=lambda nm: abs(data[nm]), reverse=True)
117
+ keep_limit = MAX_WATERFALL_STEPS - 1
118
+ chosen = list(dict.fromkeys(must_keep))
119
+ for nm in by_mag:
120
+ if len(chosen) >= keep_limit:
121
+ break
122
+ if nm not in chosen:
123
+ chosen.append(nm)
124
+ chosen_set = set(chosen)
125
+ folded = [nm for nm in step_names if nm not in chosen_set]
126
+ folded_sum = sum(data[nm] for nm in folded)
127
+ new_data = {nm: data[nm] for nm in step_names if nm in chosen_set}
128
+ new_data[f"Other ({len(folded)})"] = folded_sum
129
+ _record_adjustment(
130
+ f"waterfall(): folded {len(folded)} smaller step(s) into Other ({len(folded)})"
131
+ )
132
+ data = new_data
133
+ step_names = list(data)
134
+ else:
135
+ raise ExplainError(
136
+ f"waterfall() got {len(step_names)} steps; more than {MAX_WATERFALL_STEPS} "
137
+ "cannot be read in one bridge.",
138
+ fix_hint=f"Keep at most {MAX_WATERFALL_STEPS} steps (fold minor contributions into 'Other').",
139
+ rule="too_many_items",
140
+ )
141
+
142
+ hl = _names(highlight, step_names, "waterfall(highlight)")
143
+
144
+ issues: list[dict[str, Any]] = []
145
+ if len(step_names) > COMFORTABLE_WATERFALL_STEPS:
146
+ issues.append(
147
+ _issue(
148
+ "many_items",
149
+ "warning",
150
+ f"{len(step_names)} waterfall steps is a long bridge for one glance.",
151
+ "Group minor contributions into one 'Other' step.",
152
+ )
153
+ )
154
+
155
+ # Build ordered bar entries: (row_label, x_start, x_end, kind_tag, delta_val)
156
+ # kind_tag in {"start", "pos", "neg", "zero", "total"}
157
+ entries: list[tuple[str, float, float, str, float]] = []
158
+ running = 0.0
159
+ if start_anchor is not None:
160
+ s_label, s_val = start_anchor
161
+ entries.append((s_label, 0.0, s_val, "start", s_val))
162
+ running = s_val
163
+ for nm in step_names:
164
+ delta = data[nm]
165
+ nxt = running + delta
166
+ tag = "pos" if delta > 0 else ("neg" if delta < 0 else "zero")
167
+ entries.append((nm, running, nxt, tag, delta))
168
+ running = nxt
169
+ final_total = running
170
+ if show_total:
171
+ t_lbl = str(total_label).strip() or "Total"
172
+ entries.append((t_lbl, 0.0, final_total, "total", final_total))
173
+
174
+ all_levels = [0.0, *[e[1] for e in entries], *[e[2] for e in entries]]
175
+ all_deltas = [abs(data[nm]) for nm in step_names]
176
+ level_fmt = _formatter(all_levels, fmt, unit=unit)
177
+ delta_fmt = _formatter(all_deltas or [0.0], fmt, unit=unit)
178
+ inline_u = _inline_unit(unit)
179
+
180
+ def _lvl(v: float) -> str:
181
+ return _with_unit(level_fmt(v), unit)
182
+
183
+ def _dlt(v: float) -> str:
184
+ return _diff_with_unit(_signed(delta_fmt(v)), unit)
185
+
186
+ # Compute facts
187
+ net_delta = sum(data[nm] for nm in step_names)
188
+ facts: list[str] = []
189
+ if start_anchor is not None:
190
+ facts.append(
191
+ f"{start_anchor[0]} {_lvl(start_anchor[1])} \N{RIGHTWARDS ARROW} "
192
+ f"{total_label} {_lvl(final_total)} (net {_dlt(net_delta)})"
193
+ )
194
+ else:
195
+ facts.append(f"net {total_label.lower()}: {_lvl(final_total)} across {len(step_names)} steps")
196
+
197
+ pos_steps = [nm for nm in step_names if data[nm] > 0]
198
+ neg_steps = [nm for nm in step_names if data[nm] < 0]
199
+ if pos_steps:
200
+ best_pos = max(pos_steps, key=lambda nm: data[nm])
201
+ facts.append(f"largest positive driver: {best_pos} ({_dlt(data[best_pos])})")
202
+ if neg_steps:
203
+ worst_neg = min(neg_steps, key=lambda nm: data[nm])
204
+ facts.append(f"largest negative drag: {worst_neg} ({_dlt(data[worst_neg])})")
205
+
206
+ cum_after: dict[str, float] = {}
207
+ cur = start_anchor[1] if start_anchor is not None else 0.0
208
+ for nm in step_names:
209
+ cur += data[nm]
210
+ cum_after[nm] = cur
211
+ for item in hl:
212
+ facts.append(f"{item}: {_dlt(data[item])} (cumulative {_lvl(cum_after[item])})")
213
+ if ref is not None:
214
+ gap = final_total - ref[0]
215
+ ref_nm = f" ({ref[1]})" if ref[1] else ""
216
+ facts.append(
217
+ f"{total_label} vs reference {_lvl(ref[0])}{ref_nm}: {_dlt(gap)}"
218
+ )
219
+
220
+ n_rows = len(entries)
221
+ row_labels = [e[0] for e in entries]
222
+ hl_set = set(hl)
223
+
224
+ def _wrapped(
225
+ cell_width_mm: float,
226
+ measure: _Measure,
227
+ sizes: _Sizes,
228
+ theme: Theme = MINTFIG_THEME,
229
+ ) -> list[str]:
230
+ cell_pt = cell_width_mm * sizes.scale / PT_TO_MM
231
+ out: list[str] = []
232
+ for idx, nm in enumerate(row_labels):
233
+ tag = entries[idx][3]
234
+ weight = "bold" if (nm in hl_set or tag in {"start", "total"}) else "normal"
235
+ lines = measure.wrap(nm, 0.36 * cell_pt, sizes.body, weight)
236
+ if len(lines) > 2:
237
+ lines = [lines[0], " ".join(lines[1:])]
238
+ out.append("\n".join(lines))
239
+ return out
240
+
241
+ def _pitch(wrapped: list[str], tight: bool = False) -> float:
242
+ lines = max(nm.count("\n") + 1 for nm in wrapped)
243
+ if tight:
244
+ return {1: 4.8, 2: 7.4}.get(lines, 9.5)
245
+ return {1: 5.5, 2: 8.4}.get(lines, 10.5)
246
+
247
+ def _draw(ctx: _Ctx, ax: Axes) -> None:
248
+ sz = ctx.sizes
249
+ theme = ctx.theme
250
+ y = np.arange(n_rows, dtype=float)
251
+ bar_h = min(theme.bar_height, 0.64)
252
+
253
+ pos_col = theme.series_colors[2] if len(theme.series_colors) > 2 else theme.series_colors[0]
254
+ neg_col = theme.series_colors[1] if len(theme.series_colors) > 1 else theme.accent_colors[0]
255
+ focus_mode = bool(hl_set)
256
+
257
+ lo = float(min(*all_levels, ref[0] if ref else 0.0))
258
+ hi = float(max(*all_levels, ref[0] if ref else 0.0))
259
+ span = (hi - lo) or abs(hi) or 1.0
260
+ pad_r = 0.22 * span
261
+ pad_l = 0.14 * span if lo < 0 else 0.0
262
+ ax.set_xlim(lo - pad_l, hi + pad_r)
263
+ ax.set_ylim(n_rows - 0.5, -0.5)
264
+ _bare_axes(ax)
265
+ ax.xaxis.set_visible(False)
266
+
267
+ # Draw bars + collect bridge connector x positions
268
+ bridge_xs: list[float] = []
269
+ bridge_y0: list[float] = []
270
+ bridge_y1: list[float] = []
271
+ value_notes: list[tuple[Any, float]] = []
272
+
273
+ for idx, (nm, x0, x1, tag, delta) in enumerate(entries):
274
+ if tag in {"start", "total"}:
275
+ col = theme.ink
276
+ alpha = 0.92
277
+ elif nm in hl_set:
278
+ col = ctx.colors.get(nm, pos_col if tag == "pos" else neg_col)
279
+ alpha = 1.0
280
+ else:
281
+ col = pos_col if tag == "pos" else (neg_col if tag == "neg" else theme.muted)
282
+ alpha = 0.42 if focus_mode else 0.88
283
+
284
+ left = min(x0, x1)
285
+ width = abs(x1 - x0)
286
+ if width <= 1e-12:
287
+ # Zero-delta step: crisp vertical tick mark
288
+ ax.vlines(
289
+ [x0],
290
+ [idx - bar_h * 0.45],
291
+ [idx + bar_h * 0.45],
292
+ color=theme.muted,
293
+ linewidth=1.4 * sz.scale,
294
+ zorder=3,
295
+ )
296
+ else:
297
+ ax.barh(
298
+ [idx],
299
+ [width],
300
+ left=[left],
301
+ height=bar_h,
302
+ color=col,
303
+ alpha=alpha,
304
+ edgecolor="none",
305
+ zorder=2,
306
+ )
307
+
308
+ # Vertical bridge connector from this bar's ending cumulative level to next row
309
+ if idx < n_rows - 1:
310
+ bridge_x = x1
311
+ bridge_xs.append(bridge_x)
312
+ bridge_y0.append(idx + bar_h * 0.5)
313
+ bridge_y1.append(idx + 1 - bar_h * 0.5)
314
+
315
+ # Value / delta label
316
+ if tag in {"start", "total"}:
317
+ txt = _with_unit(level_fmt(delta), unit) if (idx == 0 or inline_u or tag == "total") else level_fmt(delta)
318
+ else:
319
+ signed_txt = _signed(delta_fmt(delta))
320
+ txt = _with_unit(signed_txt, unit) if inline_u else signed_txt
321
+
322
+ anchor_x = max(x0, x1)
323
+ is_bold = nm in hl_set or tag == "total"
324
+ lbl_col = (
325
+ theme.ink
326
+ if (is_bold or tag == "start" or not focus_mode)
327
+ else theme.muted
328
+ )
329
+ note = ax.annotate(
330
+ _plain(txt, theme),
331
+ (anchor_x, idx),
332
+ xytext=(5.0, 0.0),
333
+ textcoords="offset points",
334
+ ha="left",
335
+ va="center",
336
+ fontsize=sz.small,
337
+ fontweight="bold" if is_bold else "normal",
338
+ color=lbl_col,
339
+ annotation_clip=False,
340
+ )
341
+ value_notes.append((note, min(x0, x1)))
342
+
343
+ if bridge_xs:
344
+ ax.vlines(
345
+ bridge_xs,
346
+ bridge_y0,
347
+ bridge_y1,
348
+ color=theme.axis,
349
+ linewidth=0.65 * sz.scale,
350
+ linestyle=(0, (2, 2)),
351
+ zorder=1,
352
+ )
353
+
354
+ ax.vlines(
355
+ [0.0],
356
+ [-0.45],
357
+ [n_rows - 0.55],
358
+ color=theme.zero_line,
359
+ linewidth=theme.zero_line_lw,
360
+ zorder=3,
361
+ )
362
+
363
+ if ref is not None:
364
+ ax.axvline(
365
+ ref[0],
366
+ color=theme.ink,
367
+ linewidth=0.7,
368
+ linestyle=(0, (3, 2)),
369
+ zorder=4,
370
+ )
371
+ if ref[1]:
372
+ ax.annotate(
373
+ _plain(ref[1], theme),
374
+ (ref[0], 1.0),
375
+ xycoords=("data", "axes fraction"),
376
+ xytext=(0.0, 2.5),
377
+ textcoords="offset points",
378
+ ha="center",
379
+ va="bottom",
380
+ fontsize=sz.small,
381
+ color=theme.muted,
382
+ annotation_clip=False,
383
+ )
384
+
385
+ shown_names = _wrapped(ctx.cell_width_mm, ctx.measure, sz, theme)
386
+ ax.set_yticks(y, [_plain(nm, theme) for nm in shown_names])
387
+ ax.tick_params(axis="y", length=0, labelsize=sz.body, labelcolor=theme.ink, pad=5)
388
+ for tick, (nm, _x0, _x1, tag, _d) in zip(ax.get_yticklabels(), entries, strict=True):
389
+ tick.set_linespacing(1.05)
390
+ if nm in hl_set or tag in {"start", "total"}:
391
+ tick.set_fontweight("bold")
392
+ elif focus_mode:
393
+ tick.set_color(theme.muted)
394
+
395
+ if ref is None:
396
+ return None
397
+ ref_x = ref[0]
398
+
399
+ def _clear_reference() -> None:
400
+ renderer = ctx.fig.canvas.get_renderer()
401
+ k = ctx.pt_per_px
402
+ cell = ax.get_tightbbox(renderer)
403
+ frame = ax.get_window_extent(renderer)
404
+ right_limit = max(frame.x1, cell.x1 if cell is not None else frame.x1)
405
+ line_px = float(ax.transData.transform((ref_x, 0.0))[0])
406
+ gap = 3.0 / k
407
+ for note, left_anchor in value_notes:
408
+ box = note.get_window_extent(renderer)
409
+ if not (box.x0 - 1 <= line_px <= box.x1 + 1):
410
+ continue
411
+ dx, dy = note.xyann
412
+ shift = (line_px + gap - box.x0) * k
413
+ note.set_position((dx + shift, dy))
414
+ moved = note.get_window_extent(renderer)
415
+ if moved.x1 <= right_limit + 1:
416
+ continue
417
+ note.xy = (left_anchor, note.xy[1])
418
+ note.set_horizontalalignment("right")
419
+ note.set_position((-5.0, dy))
420
+
421
+ return _clear_reference
422
+
423
+ spec = _base_spec(
424
+ title,
425
+ label,
426
+ unit,
427
+ steps={nm: _jsonable(data[nm]) for nm in step_names},
428
+ start=_jsonable(start_anchor) if start_anchor is not None else None,
429
+ total_label=total_label if total_label != "Total" else None,
430
+ show_total=show_total if not show_total else None,
431
+ highlight=hl or None,
432
+ reference=list(ref) if ref else None,
433
+ fmt=fmt,
434
+ )
435
+ describe = (
436
+ f"Waterfall bridge of {label or 'values'}"
437
+ + (f" ({unit})" if unit else "")
438
+ + f" across {len(step_names)} steps"
439
+ + (f" from {start_anchor[0]} to {total_label}" if start_anchor else f" to {total_label}")
440
+ )
441
+ return Panel(
442
+ kind="waterfall",
443
+ title=title,
444
+ label=label,
445
+ unit=unit,
446
+ spec=spec,
447
+ facts=facts,
448
+ describe=describe,
449
+ issues=issues,
450
+ _height_mm=lambda w, m, s, t: n_rows * _pitch(_wrapped(w, m, s, t))
451
+ + (4.5 if ref and ref[1] else 1.5),
452
+ _min_height_mm=lambda w, m, s, t: n_rows * _pitch(_wrapped(w, m, s, t), tight=True)
453
+ + (4.0 if ref and ref[1] else 1.0),
454
+ _draw=_draw,
455
+ color_items=tuple(step_names),
456
+ color_focus=tuple(hl),
457
+ color_mode="highlight" if hl else "none",
458
+ alt_facts=facts[: min(3, len(facts))],
459
+ )