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
mintfig/explainer.py ADDED
@@ -0,0 +1,194 @@
1
+ """Message-first figures for conversations.
2
+
3
+ Public facade re-exporting all forms, layout, and helpers from
4
+ ``mintfig._explain``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from ._explain import (
12
+ change as _change,
13
+ )
14
+ from ._explain import (
15
+ compare as _compare,
16
+ )
17
+ from ._explain import (
18
+ core as _core,
19
+ )
20
+ from ._explain import (
21
+ distribution as _distribution,
22
+ )
23
+ from ._explain import (
24
+ flow as _flow,
25
+ )
26
+ from ._explain import (
27
+ layout as _layout,
28
+ )
29
+ from ._explain import (
30
+ matrix as _matrix,
31
+ )
32
+ from ._explain import (
33
+ relate as _relate,
34
+ )
35
+ from ._explain import (
36
+ timeline as _timeline,
37
+ )
38
+ from ._explain import (
39
+ trend as _trend,
40
+ )
41
+ from ._explain import (
42
+ waterfall as _waterfall,
43
+ )
44
+ from ._explain.change import change
45
+ from ._explain.compare import compare, share
46
+ from ._explain.core import (
47
+ _VISUAL_DEFECT_RULES,
48
+ ACCENT_COLORS,
49
+ AXIS,
50
+ COMFORTABLE_COMPARE_ITEMS,
51
+ COMFORTABLE_PANELS,
52
+ CONTEXT_FILL,
53
+ CONTEXT_LINE,
54
+ DISPLAY_WIDTH_PX,
55
+ GRID,
56
+ INK,
57
+ KINDS,
58
+ MAX_CHANGE_ITEMS,
59
+ MAX_COLORED_SERIES,
60
+ MAX_COMPARE_ITEMS,
61
+ MAX_FACETS,
62
+ MAX_GROUPS,
63
+ MAX_HIGHLIGHTS,
64
+ MAX_MATRIX_COLS,
65
+ MAX_MATRIX_ROWS,
66
+ MAX_PANELS,
67
+ MIN_TEXT_PX,
68
+ MUTED,
69
+ PT_TO_MM,
70
+ SERIES_COLORS,
71
+ ExplainError,
72
+ Panel,
73
+ lenient,
74
+ )
75
+ from ._explain.distribution import MAX_HIST_GROUPS, distribution, histogram
76
+ from ._explain.flow import MAX_FLOW_STAGES, flow
77
+ from ._explain.layout import (
78
+ COLOR_SLOTS,
79
+ EXAMPLE_SPEC,
80
+ NARROW_DISPLAY_WIDTH_PX,
81
+ SLIDE_DISPLAY_WIDTH_PX,
82
+ Explanation,
83
+ Summary,
84
+ custom,
85
+ explain,
86
+ explain_from_spec,
87
+ load,
88
+ panel_from_spec,
89
+ read_png_text,
90
+ table,
91
+ )
92
+ from ._explain.matrix import matrix
93
+ from ._explain.relate import relate
94
+ from ._explain.timeline import MAX_TIMELINE_SPANS, timeline
95
+ from ._explain.trend import trend
96
+ from ._explain.waterfall import MAX_WATERFALL_STEPS, waterfall
97
+ from .brief import Brief, Session, brief
98
+ from .edit import edit
99
+ from .epistemic import audit_epistemic, build_narrative
100
+ from .inspect_data import auto_panel, inspect_data, load_table_file
101
+ from .interactive import render_html
102
+ from .terminal import render_terminal, show_in_terminal
103
+
104
+ _SUBMODULES = (
105
+ _core,
106
+ _layout,
107
+ _compare,
108
+ _trend,
109
+ _change,
110
+ _distribution,
111
+ _relate,
112
+ _matrix,
113
+ _waterfall,
114
+ _timeline,
115
+ _flow,
116
+ )
117
+
118
+
119
+ def __getattr__(name: str) -> Any:
120
+ """Forward legacy internal attribute lookups to the split ``_explain`` submodules."""
121
+ for mod in _SUBMODULES:
122
+ if hasattr(mod, name):
123
+ return getattr(mod, name)
124
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
125
+
126
+ __all__ = [
127
+ "ACCENT_COLORS",
128
+ "AXIS",
129
+ "COLOR_SLOTS",
130
+ "COMFORTABLE_COMPARE_ITEMS",
131
+ "COMFORTABLE_PANELS",
132
+ "CONTEXT_FILL",
133
+ "CONTEXT_LINE",
134
+ "DISPLAY_WIDTH_PX",
135
+ "EXAMPLE_SPEC",
136
+ "GRID",
137
+ "INK",
138
+ "KINDS",
139
+ "MAX_CHANGE_ITEMS",
140
+ "MAX_COLORED_SERIES",
141
+ "MAX_COMPARE_ITEMS",
142
+ "MAX_FACETS",
143
+ "MAX_FLOW_STAGES",
144
+ "MAX_GROUPS",
145
+ "MAX_HIGHLIGHTS",
146
+ "MAX_HIST_GROUPS",
147
+ "MAX_MATRIX_COLS",
148
+ "MAX_MATRIX_ROWS",
149
+ "MAX_PANELS",
150
+ "MAX_TIMELINE_SPANS",
151
+ "MAX_WATERFALL_STEPS",
152
+ "MIN_TEXT_PX",
153
+ "MUTED",
154
+ "NARROW_DISPLAY_WIDTH_PX",
155
+ "PT_TO_MM",
156
+ "SERIES_COLORS",
157
+ "SLIDE_DISPLAY_WIDTH_PX",
158
+ "_VISUAL_DEFECT_RULES",
159
+ "Brief",
160
+ "ExplainError",
161
+ "Explanation",
162
+ "Panel",
163
+ "Session",
164
+ "Summary",
165
+ "audit_epistemic",
166
+ "auto_panel",
167
+ "brief",
168
+ "build_narrative",
169
+ "change",
170
+ "compare",
171
+ "custom",
172
+ "distribution",
173
+ "edit",
174
+ "explain",
175
+ "explain_from_spec",
176
+ "flow",
177
+ "histogram",
178
+ "inspect_data",
179
+ "lenient",
180
+ "load",
181
+ "load_table_file",
182
+ "matrix",
183
+ "panel_from_spec",
184
+ "read_png_text",
185
+ "relate",
186
+ "render_html",
187
+ "render_terminal",
188
+ "share",
189
+ "show_in_terminal",
190
+ "table",
191
+ "timeline",
192
+ "trend",
193
+ "waterfall",
194
+ ]
mintfig/export.py ADDED
@@ -0,0 +1,247 @@
1
+ """Export utilities for journal-compliant figure output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING
8
+
9
+ import matplotlib as mpl
10
+ from matplotlib.collections import PathCollection, PolyCollection, QuadMesh
11
+ from matplotlib.lines import Line2D
12
+
13
+ if TYPE_CHECKING:
14
+ from matplotlib.artist import Artist
15
+ from matplotlib.axes import Axes
16
+ from matplotlib.figure import Figure
17
+
18
+ from .specs import JournalSpec
19
+
20
+
21
+ def _iter_all_axes(fig: Figure) -> Iterator[Axes]:
22
+ """Yield every Axes in *fig*, including nested inset/child axes."""
23
+ seen: set[int] = set()
24
+ stack: list[Axes] = list(fig.axes)
25
+ while stack:
26
+ ax = stack.pop(0)
27
+ aid = id(ax)
28
+ if aid in seen:
29
+ continue
30
+ seen.add(aid)
31
+ yield ax
32
+ for child in getattr(ax, "child_axes", ()):
33
+ if id(child) not in seen:
34
+ stack.append(child)
35
+
36
+
37
+ def _artist_vertex_count(artist: object) -> int:
38
+ """Estimate the number of points or vertices carried by a Matplotlib artist."""
39
+ if isinstance(artist, PathCollection):
40
+ offsets = artist.get_offsets()
41
+ n_offsets = len(offsets) if offsets is not None else 0
42
+ paths = artist.get_paths()
43
+ n_verts = sum(len(p.vertices) for p in paths) if paths else 0
44
+ return max(n_offsets, n_verts)
45
+
46
+ if isinstance(artist, QuadMesh):
47
+ coords = artist.get_coordinates() if hasattr(artist, "get_coordinates") else None
48
+ if coords is not None and coords.ndim >= 2:
49
+ return int(coords.shape[0] * coords.shape[1])
50
+ arr = artist.get_array()
51
+ return int(arr.size) if arr is not None else 0
52
+
53
+ if isinstance(artist, PolyCollection):
54
+ paths = artist.get_paths()
55
+ return sum(len(p.vertices) for p in paths) if paths else 0
56
+
57
+ if isinstance(artist, Line2D):
58
+ xdata = artist.get_xdata(orig=False)
59
+ return len(xdata) if xdata is not None else 0
60
+
61
+ return 0
62
+
63
+
64
+ def _rasterize_heavy_artists(fig: Figure, threshold: int) -> list[tuple[Artist, bool]]:
65
+ """Rasterize dense artists and return ``(artist, previous_rasterized_state)`` pairs."""
66
+ changed: list[tuple[Artist, bool]] = []
67
+ for ax in _iter_all_axes(fig):
68
+ for collection in ax.collections:
69
+ if not collection.get_visible():
70
+ continue
71
+ if (
72
+ isinstance(collection, (PathCollection, PolyCollection, QuadMesh))
73
+ and _artist_vertex_count(collection) >= threshold
74
+ ):
75
+ changed.append((collection, bool(collection.get_rasterized())))
76
+ collection.set_rasterized(True)
77
+
78
+ for line in ax.lines:
79
+ if not line.get_visible():
80
+ continue
81
+ if _artist_vertex_count(line) >= threshold:
82
+ changed.append((line, bool(line.get_rasterized())))
83
+ line.set_rasterized(True)
84
+ return changed
85
+
86
+
87
+ def rasterize_heavy(
88
+ fig: Figure,
89
+ threshold: int = 10_000,
90
+ dpi: int | None = None,
91
+ ) -> int:
92
+ """Selectively rasterize dense data artists while keeping text and axes vector.
93
+
94
+ Scans ``PathCollection``, ``PolyCollection``, ``QuadMesh``, and ``Line2D``
95
+ artists across all axes (including insets) and calls ``set_rasterized(True)``
96
+ whenever an artist has at least ``threshold`` points or vertices. The change
97
+ is permanent on the figure; :func:`save_figure` instead applies it only for
98
+ the duration of the save.
99
+
100
+ Parameters
101
+ ----------
102
+ fig:
103
+ Matplotlib figure to inspect.
104
+ threshold:
105
+ Minimum point/vertex count to trigger selective rasterization.
106
+ dpi:
107
+ Optional DPI to assign on the figure for rasterized artists.
108
+
109
+ Returns
110
+ -------
111
+ int
112
+ Number of artists rasterized.
113
+ """
114
+ if dpi is not None:
115
+ fig.set_dpi(dpi)
116
+ return len(_rasterize_heavy_artists(fig, threshold))
117
+
118
+
119
+ def _resolve_save_spec(
120
+ fig: Figure,
121
+ journal: str | JournalSpec | None,
122
+ spec: JournalSpec | None,
123
+ ) -> JournalSpec | None:
124
+ """Resolve the journal spec for :func:`save_figure` from ``journal``, ``spec``, or the figure tag."""
125
+ from .specs import get_spec
126
+
127
+ if journal is not None and spec is not None:
128
+ resolved = get_spec(journal)
129
+ if resolved != spec:
130
+ raise ValueError(
131
+ "save_figure() received conflicting journal= and spec= arguments; pass only one."
132
+ )
133
+ return resolved
134
+ if journal is not None:
135
+ return get_spec(journal)
136
+ if spec is not None:
137
+ return get_spec(spec)
138
+ tag = getattr(fig, "_mintfig_journal", None)
139
+ if isinstance(tag, str) and tag:
140
+ try:
141
+ return get_spec(tag)
142
+ except ValueError:
143
+ # Custom (unregistered) JournalSpec names cannot be looked up by name.
144
+ return None
145
+ return None
146
+
147
+
148
+ def save_figure(
149
+ fig: Figure,
150
+ path: str | Path,
151
+ *,
152
+ journal: str | JournalSpec | None = None,
153
+ spec: JournalSpec | None = None,
154
+ dpi: int | None = None,
155
+ rasterize_above: int | None = 10_000,
156
+ transparent: bool = False,
157
+ lock_dimensions: bool = True,
158
+ deterministic: bool = True,
159
+ ) -> Path:
160
+ """Save a figure with locked physical dimensions and editable vector fonts.
161
+
162
+ Parameters
163
+ ----------
164
+ fig:
165
+ Matplotlib figure to save.
166
+ path:
167
+ Destination file path (PDF, PNG, SVG, EPS, TIFF, etc.).
168
+ journal:
169
+ Journal name (e.g. ``"nature"``) or :class:`~mintfig.specs.JournalSpec`
170
+ used to choose the default DPI.
171
+ spec:
172
+ Backward-compatible alias for ``journal`` accepting a
173
+ :class:`~mintfig.specs.JournalSpec`.
174
+ dpi:
175
+ Explicit output resolution. Defaults to the journal's ``dpi_combo``.
176
+ When neither ``journal`` nor ``spec`` is given, the journal tagged on
177
+ the figure by :class:`~mintfig.Plate` / :func:`~mintfig.figure` is
178
+ used; otherwise ``500``.
179
+ rasterize_above:
180
+ If positive, selectively rasterize data artists with at least this many
181
+ points/vertices so dense plots produce compact vector PDFs. Each
182
+ artist's previous rasterization state is restored after saving.
183
+ transparent:
184
+ Whether to save with a transparent background.
185
+ lock_dimensions:
186
+ When ``True`` (default), passes ``bbox_inches=None`` so the exported
187
+ MediaBox matches ``fig.get_size_inches()`` exactly without drift.
188
+ deterministic:
189
+ When ``True`` (default), omit PDF/SVG creation timestamps and use a
190
+ fixed SVG id salt so repeated saves of the same figure are
191
+ byte-identical.
192
+
193
+ Returns
194
+ -------
195
+ Path
196
+ Path to the written file.
197
+ """
198
+ out_path = Path(path)
199
+ out_path.parent.mkdir(parents=True, exist_ok=True)
200
+
201
+ resolved_spec = _resolve_save_spec(fig, journal, spec)
202
+ effective_dpi = (
203
+ dpi if dpi is not None else (resolved_spec.dpi_combo if resolved_spec is not None else 500)
204
+ )
205
+
206
+ suffix = out_path.suffix.lower()
207
+ extra_kwargs: dict[str, object] = {}
208
+ if suffix == ".pdf":
209
+ metadata: dict[str, object] = {"Creator": "mintfig"}
210
+ if deterministic:
211
+ metadata["CreationDate"] = None
212
+ extra_kwargs["metadata"] = metadata
213
+ elif suffix == ".svg":
214
+ metadata = {"Creator": "mintfig"}
215
+ if deterministic:
216
+ metadata["Date"] = None
217
+ extra_kwargs["metadata"] = metadata
218
+ elif suffix == ".png":
219
+ extra_kwargs["metadata"] = {"Software": "mintfig"}
220
+
221
+ bbox_inches = None if lock_dimensions else "tight"
222
+
223
+ rc_overrides: dict[str, object] = {
224
+ "pdf.fonttype": 42,
225
+ "ps.fonttype": 42,
226
+ "svg.fonttype": "none",
227
+ }
228
+ if deterministic and mpl.rcParams.get("svg.hashsalt") is None:
229
+ rc_overrides["svg.hashsalt"] = "mintfig"
230
+
231
+ changed: list[tuple[Artist, bool]] = []
232
+ try:
233
+ if rasterize_above is not None and rasterize_above > 0:
234
+ changed = _rasterize_heavy_artists(fig, rasterize_above)
235
+ with mpl.rc_context(rc_overrides):
236
+ fig.savefig(
237
+ out_path,
238
+ dpi=effective_dpi,
239
+ bbox_inches=bbox_inches,
240
+ transparent=transparent,
241
+ **extra_kwargs,
242
+ )
243
+ finally:
244
+ for artist, previous in changed:
245
+ artist.set_rasterized(previous)
246
+
247
+ return out_path