panelist 0.1.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.
panelist/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """panelist: layout documents for multi-panel matplotlib figures, compiled to plain matplotlib."""
2
+
3
+ __version__ = "0.1.0"
panelist/adapters.py ADDED
@@ -0,0 +1,218 @@
1
+ """Adapters: small .py files that build a figure for the editor, outside the plotting script.
2
+
3
+ An adapter defines `build() -> (fig, targets)`, where `targets` maps layout names to artists.
4
+ It lets panelist edit a figure without changing the code that draws it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import importlib.util
10
+ from pathlib import Path
11
+
12
+
13
+ def load_adapter(path: str | Path):
14
+ """Import an adapter file and check that it defines build()."""
15
+ path = Path(path).resolve()
16
+ # Import straight from the file, under a module name of its own, without putting the adapter's
17
+ # folder on sys.path.
18
+ spec = importlib.util.spec_from_file_location(f"panelist_adapter_{path.stem}", path)
19
+ if spec is None or spec.loader is None:
20
+ raise ImportError(f"cannot load adapter {path}")
21
+ # Run the adapter's code; its own imports (the plotting script) happen now.
22
+ mod = importlib.util.module_from_spec(spec)
23
+ spec.loader.exec_module(mod)
24
+ # Without build() the editor has no way to get the figure.
25
+ if not callable(getattr(mod, "build", None)):
26
+ raise TypeError(f"{path}: an adapter must define build() -> (fig, targets)")
27
+ return mod
28
+
29
+
30
+ # --- helpers for adapters (they run only in the editor, so they may import panelist; the published
31
+ # figure never does)
32
+ def capture(draw, intercept=()):
33
+ """Run `draw()`, plotting code that saves or shows a figure, and return that figure without
34
+ writing anything: Figure.savefig, pyplot's savefig, show and close are held for the run, and so
35
+ is each (object, name) in `intercept` (a project's own save function, say), also where a module
36
+ imported it by name. The first figure saved is returned, else the last figure open."""
37
+ import matplotlib.pyplot as plt
38
+
39
+ # Every figure the plotting code tried to save, in order.
40
+ caught = []
41
+ # Hold every save, show and close, run the plotting code, and put the originals back.
42
+ _run_held(_capture_swaps(caught, intercept), draw)
43
+ # The first figure saved is the one the plotting code meant to publish; without a save, the
44
+ # newest open one.
45
+ if caught:
46
+ return caught[0]
47
+ # Nothing saved: the plotting code's newest open figure, if it left one.
48
+ if plt.get_fignums():
49
+ return plt.figure(plt.get_fignums()[-1])
50
+ raise RuntimeError("capture: the plotting code made no figure")
51
+
52
+
53
+ def _capture_swaps(caught: list, intercept) -> list:
54
+ """The swaps capture() makes, as (object, attribute, stand-in): each stand-in appends the figure
55
+ it is given to `caught` and writes nothing; `intercept` lists a project's own save functions."""
56
+ import sys
57
+
58
+ import matplotlib.figure
59
+ import matplotlib.pyplot as plt
60
+
61
+ def keep(*args, **kwargs):
62
+ """Stand-in for an intercepted save function: keep the first Figure among its arguments,
63
+ save nothing."""
64
+ fig = next(
65
+ (x for x in (*args, *kwargs.values()) if isinstance(x, matplotlib.figure.Figure)), None
66
+ )
67
+ if fig is not None:
68
+ caught.append(fig)
69
+
70
+ def savefig(self, *args, **kwargs):
71
+ """Stand-in for Figure.savefig: keep the figure, write no file."""
72
+ caught.append(self)
73
+
74
+ # Each swap is (object, attribute, stand-in). pyplot's savefig keeps the current figure; show
75
+ # and close do nothing, so the figure stays open and can be returned.
76
+ swaps = [
77
+ (matplotlib.figure.Figure, "savefig", savefig),
78
+ (plt, "savefig", lambda *a, **k: caught.append(plt.gcf())),
79
+ (plt, "show", lambda *a, **k: None),
80
+ (plt, "close", lambda *a, **k: None),
81
+ ]
82
+ # A project's own save function is held both where it is defined and wherever it was imported by
83
+ # name.
84
+ for obj, name in intercept:
85
+ original = getattr(obj, name)
86
+ swaps.append((obj, name, keep))
87
+ for m in list(
88
+ sys.modules.values()
89
+ ): # `from panels import save` elsewhere gets the hold too
90
+ if m is not obj and getattr(m, "__dict__", {}).get(name) is original:
91
+ swaps.append((m, name, keep))
92
+ return swaps
93
+
94
+
95
+ def _run_held(swaps: list, draw) -> None:
96
+ """Make every swap, run `draw()`, and put every original back, also when `draw` raises."""
97
+ # The originals, read from the object's own __dict__ where the attribute lives there, so that
98
+ # restoring puts back exactly what was set (an inherited method is restored as the same lookup).
99
+ saved = [
100
+ (obj, name, obj.__dict__[name] if name in vars(obj) else getattr(obj, name))
101
+ for obj, name, _ in swaps
102
+ ]
103
+ # Hold everything, run the plotting code, and put the originals back even when it fails.
104
+ try:
105
+ for obj, name, new in swaps:
106
+ setattr(obj, name, new)
107
+ draw()
108
+ # Every original goes back, also when the plotting code raised.
109
+ finally:
110
+ for obj, name, old in reversed(saved):
111
+ setattr(obj, name, old)
112
+
113
+
114
+ def letter_by_size(size: float):
115
+ """Panel letters are one-character texts at this size (pt)."""
116
+ return lambda t: (
117
+ t.get_text().strip()
118
+ if len(t.get_text().strip()) == 1 and t.get_fontsize() == size
119
+ else None
120
+ )
121
+
122
+
123
+ def letter_by_gid(prefix: str = "letter:"):
124
+ """Panel letters carry the gid "<prefix><panel>" (hidden ones too, so every panel keeps its
125
+ letter)."""
126
+ return lambda t: t.get_gid()[len(prefix) :] if str(t.get_gid()).startswith(prefix) else None
127
+
128
+
129
+ def head_by_size(sizes, above: float | None = None):
130
+ """Headings go to the "head" group: texts at one of these sizes (pt), and with `above`, only
131
+ when their centre lies above that figure fraction."""
132
+ sizes = set(sizes)
133
+ return lambda t, xy: t.get_fontsize() in sizes and (above is None or xy[1] > above)
134
+
135
+
136
+ def _slug(s: str) -> str:
137
+ """A short name part made from a text's content: lower case, runs of other characters turned
138
+ into one "_", at most 24 characters, "text" when nothing is left."""
139
+ import re
140
+
141
+ return re.sub(r"[^a-z0-9]+", "_", s.lower()).strip("_")[:24] or "text"
142
+
143
+
144
+ def _bold_letter(t):
145
+ """A one-character bold text's letter, else None: the panel-letter rule when no text carries a
146
+ letter gid."""
147
+ return (
148
+ t.get_text().strip()
149
+ if len(t.get_text().strip()) == 1 and t.get_fontweight() in ("bold", 700)
150
+ else None
151
+ )
152
+
153
+
154
+ def _panel_of(letters: dict, xy) -> str:
155
+ """The panel letter for a point in figure fractions. Of the letters above the point and not to
156
+ its right (0.01 tolerance), keep the nearest row (letters within 0.02 of the lowest of them) and
157
+ in that row the letter furthest right, the one nearest to the point's left. "head" when no
158
+ letter is above."""
159
+ above = {k: p for k, p in letters.items() if p[1] >= xy[1] - 0.01 and p[0] <= xy[0] + 0.01}
160
+ # No letter above or to the left: the text heads the figure.
161
+ if not above:
162
+ return "head"
163
+ # The lowest of those letters is the nearest row above the point.
164
+ row = min(p[1] for p in above.values())
165
+ return max((p[0], k) for k, p in above.items() if p[1] - row < 0.02)[1]
166
+
167
+
168
+ def targets_by_letter(fig, letter=None, head=None) -> dict:
169
+ """Layout names for every Axes, figure text and figure legend, by panel: each belongs to the
170
+ panel whose letter is in the nearest letter row above it, nearest to its left ("<letter>.ax00",
171
+ "<letter>.t_<text>"; the letter itself "<letter>.t_<letter>"); what has no letter above, or what
172
+ `head(text, centre)` claims, is "head"; legends are "legend0", ... Names follow creation order
173
+ within a panel, so they stay as long as the plotting code does. `letter(text)` gives a text's
174
+ panel letter or None (default: letter_by_gid(), else one-character bold texts).
175
+ """
176
+ import numpy as np
177
+
178
+ # Draw once so every artist's window extent is known, then work in figure fractions (0 at the
179
+ # bottom).
180
+ fig.canvas.draw()
181
+ inv = fig.transFigure.inverted()
182
+ centre = lambda a: inv.transform(a.get_window_extent().get_points().mean(0)) # noqa: E731
183
+ texts = [t for t in fig.texts if t.get_text().strip()]
184
+ # Without a rule, use gids when any text carries a letter gid, else one-character bold texts.
185
+ if letter is None:
186
+ by_gid = letter_by_gid()
187
+ letter = by_gid if any(by_gid(t) for t in texts) else _bold_letter
188
+ # Each letter text and its letter, and where each letter sits, in figure fractions.
189
+ letter_of = {id(t): letter(t) for t in texts if letter(t)}
190
+ letters = {
191
+ letter_of[id(t)]: np.asarray(t.get_position(), float) for t in texts if id(t) in letter_of
192
+ }
193
+ # Number the Axes of each panel in creation order: a.ax00, a.ax01, ...
194
+ targets, count = {}, {}
195
+ for ax in fig.axes:
196
+ # The panel holding the Axes' centre, and the Axes' number within that panel.
197
+ p = _panel_of(letters, centre(ax))
198
+ k = count[p, "ax"] = count.get((p, "ax"), -1) + 1
199
+ targets[f"{p}.ax{k:02d}"] = ax
200
+ # A letter is named after its own panel; another text after its panel (or "head") and its
201
+ # content, with _1, _2, ... added when two texts would get the same name.
202
+ for t in texts:
203
+ if id(t) in letter_of:
204
+ # A letter text: named after its own panel.
205
+ p = letter_of[id(t)]
206
+ name = f"{p}.t_{p}"
207
+ else:
208
+ # Any other text: a heading if `head` claims it, else by the panel it lies in.
209
+ xy = centre(t)
210
+ p = "head" if head is not None and head(t, xy) else _panel_of(letters, xy)
211
+ name = f"{p}.t_{_slug(t.get_text())}"
212
+ # A second text with the same name gets _1, a third _2, and so on.
213
+ n = count[name] = count.get(name, -1) + 1
214
+ targets[name if n == 0 else f"{name}_{n}"] = t
215
+ # Figure legends are numbered in creation order.
216
+ for i, lg in enumerate(fig.legends):
217
+ targets[f"legend{i}"] = lg
218
+ return targets
panelist/apply.py ADDED
@@ -0,0 +1,48 @@
1
+ """Preview a layout on a live figure through the same generated code the public figure runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import types
7
+ from pathlib import Path
8
+
9
+ from .compiler import compile_document
10
+ from .document import load
11
+
12
+
13
+ def load_module(source: str, name: str = "panelist_layout") -> types.ModuleType:
14
+ """Execute generated layout source as a fresh module (no file written)."""
15
+ mod = types.ModuleType(name)
16
+ # Compiling under a pseudo file name makes tracebacks from the generated code name the module.
17
+ exec(compile(source, f"<{name}>", "exec"), mod.__dict__)
18
+ return mod
19
+
20
+
21
+ def apply_document(doc_or_path, fig, targets):
22
+ """Compile the document and apply the generated `apply_layout` to `fig` with `targets`."""
23
+ # A path is loaded and validated, and its location is passed on (a preset is looked up beside
24
+ # the layout); a document already in memory is compiled under a generic source name.
25
+ if isinstance(doc_or_path, (str, Path)):
26
+ path = Path(doc_or_path)
27
+ doc, source_name = load(path), path.name
28
+ else:
29
+ doc, source_name = doc_or_path, "layout.json"
30
+ # Compile and run the module in memory, then apply it exactly as the published figure would.
31
+ mod = load_module(
32
+ compile_document(
33
+ doc, source_name, layout=path if isinstance(doc_or_path, (str, Path)) else None
34
+ )
35
+ )
36
+ return mod.apply_layout(fig, targets)
37
+
38
+
39
+ @functools.lru_cache(maxsize=1)
40
+ def runtime() -> types.ModuleType:
41
+ """The generated module's helpers (no layout): what the editor asks of a figure is answered by
42
+ the same code that styles it, e.g. how many series colours a plot has (`_series_keys`)."""
43
+ # The smallest valid document: an empty one-millimetre page with no targets, compiled once and
44
+ # cached.
45
+ return load_module(
46
+ compile_document({"panelist": 1, "page": {"width_mm": 1, "height_mm": 1}, "targets": {}}),
47
+ "panelist_runtime",
48
+ )