pubviz 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.
pubviz/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """pubviz: figures and tables for research papers that share one color theme.
2
+
3
+ import pubviz as pv
4
+
5
+ pv.use("paper/main.pubviz.json") # the layout file pubviz.sty writes
6
+ fig, ax = pv.figure("column")
7
+ pv.bars(ax, scores, ours="Ours", ylabel="Accuracy (%)")
8
+ pv.save(fig, "paper/figs/scores")
9
+ """
10
+
11
+ from .color import contrast, hex_to_oklch, lightness, oklch_to_hex, to_gray
12
+ from .layout import PRESETS as LAYOUTS
13
+ from .layout import Layout
14
+ from .classifiers import det, precision_recall, reliability, roc
15
+ from .matrices import attention, confusion
16
+ from .pictures import images, overlay, spectrogram, waveform
17
+ from .plots import (bars, curves, deltas, distributions, dots, embedding, heatmap, label_ends, mean_ci,
18
+ means, pareto, power_fit, ranked, scaling, tradeoff)
19
+ from .ratings import ratings
20
+ from .style import current, figure, panel_labels, save, use, width
21
+ from .table import pvtable
22
+ from .text import pvshade
23
+ from .theme import PRESETS as ACCENTS
24
+ from .theme import Theme
25
+
26
+ __all__ = [
27
+ "ACCENTS", "LAYOUTS", "Layout", "Theme",
28
+ "attention", "bars", "confusion", "contrast", "current", "curves", "deltas", "det", "distributions",
29
+ "dots", "embedding", "figure", "heatmap", "hex_to_oklch", "images", "label_ends", "lightness",
30
+ "mean_ci", "means", "oklch_to_hex", "overlay", "panel_labels", "pareto", "power_fit",
31
+ "precision_recall", "pvshade", "pvtable", "ranked", "ratings", "reliability", "roc", "save",
32
+ "scaling", "spectrogram", "to_gray", "tradeoff", "use", "waveform", "width",
33
+ ]
34
+ __version__ = "0.1.0"
pubviz/__main__.py ADDED
@@ -0,0 +1,38 @@
1
+ """Command line: inspect a theme or a layout.
2
+
3
+ pubviz roles amber # every derived color, with its grey
4
+ pubviz roles "#1A73D5" --mode gray
5
+ pubviz layout paper/main.pubviz.json
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+
12
+ from .layout import PRESETS, resolve
13
+ from .theme import Theme, describe
14
+
15
+
16
+ def main(argv=None) -> None:
17
+ parser = argparse.ArgumentParser(prog="pubviz")
18
+ sub = parser.add_subparsers(dest="command", required=True)
19
+ roles = sub.add_parser("roles", help="print the colors derived from an accent")
20
+ roles.add_argument("accent", nargs="?", default="amber", help="preset name or hex")
21
+ roles.add_argument("--mode", default="color", choices=["color", "gray", "plain"])
22
+ layout = sub.add_parser("layout", help="print a layout preset or a .pubviz.json file")
23
+ layout.add_argument("source", help=f"preset ({', '.join(PRESETS)}) or file")
24
+ args = parser.parse_args(argv)
25
+ if args.command == "roles":
26
+ theme = Theme(args.accent, args.mode)
27
+ print(describe(theme))
28
+ print()
29
+ print("LaTeX:", theme.latex())
30
+ else:
31
+ lay, record = resolve(args.source)
32
+ print(lay)
33
+ if record:
34
+ print("theme:", {k: record[k] for k in ("accent", "mode", "pos", "neg") if k in record})
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()
pubviz/classifiers.py ADDED
@@ -0,0 +1,250 @@
1
+ """How a classifier or detector behaves across every threshold.
2
+
3
+ - ``roc`` True against false positive rate, with the chance line.
4
+ - ``precision_recall`` Precision against recall, with the line a classifier
5
+ that guesses reaches: the share of positives.
6
+ - ``det`` Miss against false alarm rate on normal-deviate
7
+ scales, as in speaker verification, with the equal error rate.
8
+ - ``reliability`` Observed frequency against predicted probability,
9
+ with the line of a perfectly calibrated model.
10
+
11
+ Each takes, per method, the true labels (1 for the positive class) and the
12
+ scores the method gave, computes the curve and prints its summary (area,
13
+ average precision, equal error rate or calibration error) beside the name.
14
+ Ours wears the accent and every compared method a grey; the legend sits
15
+ where the curves are not.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Mapping
21
+ from statistics import NormalDist
22
+
23
+ import numpy as np
24
+
25
+ from .plots import REFERENCE, _is_ours, _series_colors
26
+ from .style import current
27
+
28
+ DASH = (0, (3, 2))
29
+
30
+
31
+ def _counts(labels, scores):
32
+ """True and false positives at each distinct threshold, highest first."""
33
+ y = np.asarray(labels).astype(bool)
34
+ s = np.asarray(scores, dtype=float)
35
+ if y.shape != s.shape:
36
+ raise ValueError("labels and scores must have the same length")
37
+ if y.all() or not y.any():
38
+ raise ValueError("the labels need both classes")
39
+ order = np.argsort(-s, kind="mergesort")
40
+ s, y = s[order], y[order]
41
+ last = np.r_[np.nonzero(np.diff(s))[0], len(s) - 1]
42
+ tp = np.cumsum(y)[last].astype(float)
43
+ fp = np.cumsum(~y)[last].astype(float)
44
+ return tp, fp, float(y.sum()), float((~y).sum())
45
+
46
+
47
+ def rates(labels, scores):
48
+ """False positive rate, true positive rate and the area under the ROC curve."""
49
+ tp, fp, pos, neg = _counts(labels, scores)
50
+ fpr = np.r_[0.0, fp / neg]
51
+ tpr = np.r_[0.0, tp / pos]
52
+ return fpr, tpr, float(np.trapezoid(tpr, fpr))
53
+
54
+
55
+ def _draw(ax, curves: Mapping, ours, style: str = "line"):
56
+ names = list(curves)
57
+ colors = _series_colors(names, ours, "gray", marks="line")
58
+ order = [n for n in names if not _is_ours(n, ours)] + [n for n in names if _is_ours(n, ours)]
59
+ handles = {}
60
+ for name in order:
61
+ x, y, text = curves[name]
62
+ mine = _is_ours(name, ours)
63
+ kwargs = {"color": colors[name], "linewidth": 1.6 if mine else 1.0, "zorder": 4 if mine else 3}
64
+ if style == "step":
65
+ (line,) = ax.step(x, y, where="post", **kwargs)
66
+ else:
67
+ (line,) = ax.plot(x, y, **kwargs)
68
+ handles[name] = (line, f"{name} ({text})")
69
+ return [handles[n][0] for n in names], [handles[n][1] for n in names]
70
+
71
+
72
+ def _legend(ax, handles, labels, names, ours, reference=None):
73
+ """The legend where the curves leave room ("best"), with the dashed
74
+ reference line as its last entry; ours in bold."""
75
+ if reference is not None:
76
+ handles = [*handles, reference[0]]
77
+ labels = [*labels, reference[1]]
78
+ legend = ax.legend(handles, labels, loc="best", frameon=True, framealpha=0.9, edgecolor="none",
79
+ handlelength=1.4, borderaxespad=0.4)
80
+ for text, name in zip(legend.get_texts(), names):
81
+ if _is_ours(name, ours):
82
+ text.set_fontweight("bold")
83
+ return legend
84
+
85
+
86
+ def _unit_square(ax):
87
+ ax.set_xlim(0, 1)
88
+ ax.set_ylim(0, 1.0)
89
+ ax.set_aspect("equal", adjustable="box")
90
+ ax.grid(axis="both", visible=True)
91
+
92
+
93
+ def roc(ax, data: Mapping, *, ours=None, fmt: str = "{:.3f}", xlabel: str | None = None,
94
+ ylabel: str | None = None, legend: bool = True):
95
+ """ROC curves: one per method, from ``data`` mapping name -> (labels, scores).
96
+
97
+ Both axes run from 0 to 1 at the same scale; the dashed diagonal is what
98
+ a classifier that guesses reaches. The area under each curve (AUC) is
99
+ printed beside its name. When positives are rare, a large area can hide
100
+ many false positives among few true ones: show ``precision_recall`` too.
101
+ """
102
+ ctx = current()
103
+ curves = {}
104
+ for name, (labels, scores) in data.items():
105
+ fpr, tpr, area = rates(labels, scores)
106
+ curves[name] = (fpr, tpr, "AUC " + fmt.format(area))
107
+ (chance,) = ax.plot([0, 1], [0, 1], linestyle=DASH, color=REFERENCE, linewidth=0.8, zorder=1)
108
+ handles, labels = _draw(ax, curves, ours)
109
+ _unit_square(ax)
110
+ ax.set_xlabel(xlabel if xlabel is not None else ctx.say("fpr"))
111
+ ax.set_ylabel(ylabel if ylabel is not None else ctx.say("tpr"))
112
+ if legend:
113
+ _legend(ax, handles, labels, list(data), ours, (chance, ctx.say("chance")))
114
+ return {n: c[2] for n, c in curves.items()}
115
+
116
+
117
+ def precision_recall(ax, data: Mapping, *, ours=None, fmt: str = "{:.3f}", xlabel: str | None = None,
118
+ ylabel: str | None = None, legend: bool = True):
119
+ """Precision–recall curves, from ``data`` mapping name -> (labels, scores).
120
+
121
+ The dashed line is the share of positives: the precision of a classifier
122
+ that guesses, which is not 0.5 when the classes are unbalanced. Average
123
+ precision (AP, the area under the steps) is printed beside each name.
124
+ """
125
+ ctx = current()
126
+ curves = {}
127
+ shares = set()
128
+ for name, (labels, scores) in data.items():
129
+ tp, fp, pos, neg = _counts(labels, scores)
130
+ precision = np.r_[1.0, tp / (tp + fp)]
131
+ recall = np.r_[0.0, tp / pos]
132
+ ap = float(np.sum(np.diff(recall) * precision[1:]))
133
+ curves[name] = (recall, precision, "AP " + fmt.format(ap))
134
+ shares.add(round(pos / (pos + neg), 6))
135
+ for share in shares:
136
+ guess = ax.axhline(share, linestyle=DASH, color=REFERENCE, linewidth=0.8, zorder=1)
137
+ handles, labels = _draw(ax, curves, ours, style="step")
138
+ _unit_square(ax)
139
+ ax.set_ylim(0, 1.02)
140
+ ax.set_xlabel(xlabel if xlabel is not None else ctx.say("recall"))
141
+ ax.set_ylabel(ylabel if ylabel is not None else ctx.say("precision"))
142
+ if legend:
143
+ text = ctx.say("positives") + (f" ({min(shares):.2f})" if len(shares) == 1 else "")
144
+ _legend(ax, handles, labels, list(data), ours, (guess, text))
145
+ return {n: c[2] for n, c in curves.items()}
146
+
147
+
148
+ DET_TICKS = (0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 40) # percent
149
+
150
+
151
+ def det(ax, data: Mapping, *, ours=None, fmt: str = "{:.2f}", lim=(0.1, 40), xlabel: str | None = None,
152
+ ylabel: str | None = None, legend: bool = True):
153
+ """DET curves (Martin et al. 1997): miss rate against false alarm rate,
154
+ both on a normal-deviate scale, from ``data`` mapping name ->
155
+ (labels, scores) with 1 for a target trial.
156
+
157
+ On these scales the curves of normally distributed scores are straight
158
+ lines, and the low error rates where systems differ spread out. The
159
+ dashed diagonal joins the points where both rates are equal; the equal
160
+ error rate (EER) is marked on each curve and printed beside its name.
161
+ ``lim`` is the range of both axes in percent.
162
+ """
163
+ ctx = current()
164
+ probit = NormalDist().inv_cdf
165
+ lo, hi = lim[0] / 100, lim[1] / 100
166
+
167
+ def scale(p):
168
+ return np.array([probit(min(max(v, lo / 4), 1 - lo / 4)) for v in np.atleast_1d(p)])
169
+
170
+ curves, eers = {}, {}
171
+ for name, (labels, scores) in data.items():
172
+ fpr, tpr, _ = rates(labels, scores)
173
+ miss = 1 - tpr
174
+ k = int(np.argmin(np.abs(miss - fpr)))
175
+ eer = float((miss[k] + fpr[k]) / 2)
176
+ eers[name] = eer
177
+ curves[name] = (scale(fpr), scale(miss), "EER " + fmt.format(100 * eer) + "%")
178
+ a, b = scale([lo])[0], scale([hi])[0]
179
+ ax.plot([a, b], [a, b], linestyle=DASH, color=REFERENCE, linewidth=0.8, zorder=1)
180
+ handles, labels = _draw(ax, curves, ours)
181
+ for line, eer in zip(handles, eers.values()):
182
+ point = scale([eer])[0]
183
+ ax.plot([point], [point], "o", markersize=3.6, color=line.get_color(), markeredgecolor="white",
184
+ markeredgewidth=0.5, zorder=5)
185
+ ticks = [t for t in DET_TICKS if lim[0] <= t <= lim[1]]
186
+ for setter in (ax.set_xticks, ax.set_yticks):
187
+ setter(scale([t / 100 for t in ticks]), [f"{t:g}" for t in ticks])
188
+ ax.set_xlim(a, b)
189
+ ax.set_ylim(a, b)
190
+ ax.set_aspect("equal", adjustable="box")
191
+ ax.grid(axis="both", visible=True)
192
+ ax.set_xlabel(xlabel if xlabel is not None else ctx.say("false_alarm"))
193
+ ax.set_ylabel(ylabel if ylabel is not None else ctx.say("miss"))
194
+ if legend:
195
+ _legend(ax, handles, labels, list(data), ours)
196
+ return eers
197
+
198
+
199
+ def reliability(ax, data: Mapping, *, ours=None, bins: int = 10, fmt: str = "{:.3f}", counts_ax=None,
200
+ xlabel: str | None = None, ylabel: str | None = None, legend: bool = True):
201
+ """Reliability diagrams, from ``data`` mapping name -> (labels, probabilities).
202
+
203
+ Cases are put into ``bins`` equal-width bins of predicted probability;
204
+ each point is a bin's mean prediction against how often its cases were
205
+ positive, so a calibrated model lies on the dashed diagonal. Bins with no
206
+ cases are left out. The expected calibration error (ECE: the gap between
207
+ the two, weighted by the cases in each bin) is printed beside each name.
208
+ A bin with few cases gives a noisy point: pass ``counts_ax`` (a second
209
+ axes, for instance under this one) to show how many cases each bin holds.
210
+ For a model's confidence in its top class, pass whether each top-class
211
+ prediction was correct as the labels and the confidence as the
212
+ probabilities.
213
+ """
214
+ ctx = current()
215
+ edges = np.linspace(0, 1, bins + 1)
216
+ curves, held = {}, {}
217
+ for name, (labels, probs) in data.items():
218
+ y = np.asarray(labels, dtype=float)
219
+ p = np.asarray(probs, dtype=float)
220
+ which = np.clip(np.digitize(p, edges[1:-1]), 0, bins - 1)
221
+ n = np.bincount(which, minlength=bins).astype(float)
222
+ mean_p = np.bincount(which, weights=p, minlength=bins)
223
+ mean_y = np.bincount(which, weights=y, minlength=bins)
224
+ used = n > 0
225
+ conf, freq = mean_p[used] / n[used], mean_y[used] / n[used]
226
+ ece = float(np.sum(n[used] * np.abs(conf - freq)) / n.sum())
227
+ curves[name] = (conf, freq, "ECE " + fmt.format(ece))
228
+ held[name] = n
229
+ (diagonal,) = ax.plot([0, 1], [0, 1], linestyle=DASH, color=REFERENCE, linewidth=0.8, zorder=1)
230
+ handles, labels = _draw(ax, curves, ours)
231
+ for line in handles:
232
+ line.set_marker("o")
233
+ line.set_markersize(2.8)
234
+ _unit_square(ax)
235
+ ax.set_xlabel(xlabel if xlabel is not None else ctx.say("confidence"))
236
+ ax.set_ylabel(ylabel if ylabel is not None else ctx.say("observed"))
237
+ if legend:
238
+ _legend(ax, handles, labels, list(data), ours, (diagonal, ctx.say("calibrated")))
239
+ if counts_ax is not None:
240
+ names = list(data)
241
+ colors = _series_colors(names, ours, "gray", marks="line")
242
+ width = 1 / bins / max(1, len(names))
243
+ for i, name in enumerate(names):
244
+ offset = edges[:-1] + width * i
245
+ counts_ax.bar(offset, held[name], width=width * 0.9, align="edge", color=colors[name], linewidth=0)
246
+ counts_ax.set_xlim(0, 1)
247
+ counts_ax.set_ylabel(ctx.say("cases"))
248
+ counts_ax.set_xlabel(ax.get_xlabel())
249
+ ax.set_xlabel("")
250
+ return {n: c[2] for n, c in curves.items()}
pubviz/color.py ADDED
@@ -0,0 +1,132 @@
1
+ """Color math shared by the LaTeX package and the Python library.
2
+
3
+ Every derived color is built in OKLCH (lightness, chroma, hue), a color space in
4
+ which equal lightness steps look equally far apart. Setting lightness on
5
+ purpose is what keeps an ordered set of fills (best, second, third) ordered
6
+ when a page is printed in black and white: a grey printer keeps lightness and
7
+ drops hue.
8
+
9
+ ``latex/pubviz.sty`` implements the same steps with the same constants. The
10
+ test ``tests/test_latex_agreement.py`` compiles that file and checks that both
11
+ sides produce the same hex values, so change the two together.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+
18
+ # Gamut test tolerance and bisection depth. Both must match pubviz.sty.
19
+ GAMUT_EPS = 1e-6
20
+ BISECT_STEPS = 18
21
+
22
+
23
+ def hex_to_rgb(value: str) -> tuple[float, float, float]:
24
+ """``"#D8A02C"`` or ``"d8a02c"`` to sRGB channels in [0, 1]."""
25
+ text = value.strip().lstrip("#")
26
+ if len(text) != 6:
27
+ raise ValueError(f"expected a 6-digit hex color, got {value!r}")
28
+ return tuple(int(text[i : i + 2], 16) / 255 for i in (0, 2, 4)) # type: ignore[return-value]
29
+
30
+
31
+ def rgb_to_hex(rgb: tuple[float, float, float]) -> str:
32
+ """sRGB channels to an uppercase hex string, rounding half up like the LaTeX side."""
33
+ channels = (math.floor(255 * min(1.0, max(0.0, c)) + 0.5) for c in rgb)
34
+ return "#" + "".join(f"{c:02X}" for c in channels)
35
+
36
+
37
+ def _to_linear(c: float) -> float:
38
+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
39
+
40
+
41
+ def _to_srgb(c: float) -> float:
42
+ if c <= 0.0031308:
43
+ return 12.92 * c
44
+ return 1.055 * c ** (1 / 2.4) - 0.055
45
+
46
+
47
+ def _cbrt(x: float) -> float:
48
+ return math.copysign(abs(x) ** (1 / 3), x)
49
+
50
+
51
+ def linear_to_oklab(r: float, g: float, b: float) -> tuple[float, float, float]:
52
+ l = _cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
53
+ m = _cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
54
+ s = _cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
55
+ return (
56
+ 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
57
+ 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
58
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s,
59
+ )
60
+
61
+
62
+ def oklab_to_linear(L: float, a: float, b: float) -> tuple[float, float, float]:
63
+ l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3
64
+ m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3
65
+ s = (L - 0.0894841775 * a - 1.2914855480 * b) ** 3
66
+ return (
67
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
68
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
69
+ -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
70
+ )
71
+
72
+
73
+ def hex_to_oklch(value: str) -> tuple[float, float, float]:
74
+ """Hex to (L, C, h) with L in [0, 1], C >= 0 and h in radians."""
75
+ r, g, b = (_to_linear(c) for c in hex_to_rgb(value))
76
+ L, a, bb = linear_to_oklab(r, g, b)
77
+ C = math.hypot(a, bb)
78
+ h = math.atan2(bb, a) if C > 1e-6 else 0.0
79
+ return L, C, h
80
+
81
+
82
+ def _oklch_to_linear(L: float, C: float, h: float) -> tuple[float, float, float]:
83
+ return oklab_to_linear(L, C * math.cos(h), C * math.sin(h))
84
+
85
+
86
+ def in_gamut(L: float, C: float, h: float) -> bool:
87
+ return all(-GAMUT_EPS <= c <= 1 + GAMUT_EPS for c in _oklch_to_linear(L, C, h))
88
+
89
+
90
+ def fit_chroma(L: float, C: float, h: float) -> float:
91
+ """The largest chroma <= C that sRGB can show at this lightness and hue.
92
+
93
+ Lowering chroma rather than clipping channels keeps lightness and hue, so
94
+ a fill meant to be light stays exactly as light as asked.
95
+ """
96
+ if in_gamut(L, C, h):
97
+ return C
98
+ lo, hi = 0.0, C
99
+ for _ in range(BISECT_STEPS):
100
+ mid = (lo + hi) / 2
101
+ if in_gamut(L, mid, h):
102
+ lo = mid
103
+ else:
104
+ hi = mid
105
+ return lo
106
+
107
+
108
+ def oklch_to_hex(L: float, C: float, h: float) -> str:
109
+ C = fit_chroma(L, C, h)
110
+ r, g, b = (_to_srgb(c) for c in _oklch_to_linear(L, C, h))
111
+ return rgb_to_hex((r, g, b))
112
+
113
+
114
+ def lightness(value: str) -> float:
115
+ """OKLCH lightness of a hex color: what survives a greyscale print."""
116
+ return hex_to_oklch(value)[0]
117
+
118
+
119
+ def to_gray(value: str) -> str:
120
+ """Same lightness, no hue: how the color reads on a black-and-white page."""
121
+ return oklch_to_hex(lightness(value), 0.0, 0.0)
122
+
123
+
124
+ def relative_luminance(value: str) -> float:
125
+ r, g, b = (_to_linear(c) for c in hex_to_rgb(value))
126
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
127
+
128
+
129
+ def contrast(fg: str, bg: str) -> float:
130
+ """WCAG 2 contrast ratio between two colors."""
131
+ a, b = sorted((relative_luminance(fg), relative_luminance(bg)), reverse=True)
132
+ return (a + 0.05) / (b + 0.05)
pubviz/layout.py ADDED
@@ -0,0 +1,104 @@
1
+ """Page geometry of a venue: how wide a figure may be and how big its text is.
2
+
3
+ The most reliable source is the paper itself. ``pubviz.sty`` writes
4
+ ``<jobname>.pubviz.json`` on every compile with the column width, the text
5
+ width, the body font size, the font families and the color theme, so
6
+
7
+ use("paper/main.pubviz.json")
8
+
9
+ sizes figures for whatever template the paper uses, including one this module
10
+ has never heard of. The named presets below are for starting before the paper
11
+ compiles.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Layout:
23
+ """Column and text width in inches, body font size in points, font family."""
24
+
25
+ column: float
26
+ text: float
27
+ font_size: float = 10.0
28
+ family: str = "times" # times | cm | libertine | palatino | serif | sans
29
+ name: str = "custom"
30
+
31
+ @property
32
+ def twocolumn(self) -> bool:
33
+ return self.text - self.column > 0.5
34
+
35
+
36
+ # How each preset was obtained (2026-11-21):
37
+ # measured: compiled the class from TeX Live 2026 with pubviz and read the
38
+ # layout file it wrote.
39
+ # style: read \textwidth, \columnsep and the font size from the venue's
40
+ # official style file; column = (text - columnsep) / 2.
41
+ # Venues change their templates. When the paper compiles, prefer its own
42
+ # layout file over these numbers.
43
+ PRESETS: dict[str, Layout] = {
44
+ # measured
45
+ "article": Layout(4.77377, 4.77377, 10, "cm", "article"),
46
+ "ieee": Layout(3.48692, 7.13990, 10, "times", "ieee"), # IEEEtran conference and journal
47
+ "acm": Layout(3.33676, 7.00560, 9, "libertine", "acm"), # acmart sigconf
48
+ "acm-small": Layout(5.47699, 5.47699, 10, "libertine", "acm-small"), # acmart acmsmall
49
+ "lncs": Layout(4.80315, 4.80315, 10, "cm", "lncs"), # Springer llncs
50
+ "elsevier": Layout(3.48692, 7.22292, 10, "cm", "elsevier"), # elsarticle 5p
51
+ # style
52
+ "neurips": Layout(5.5, 5.5, 10, "times", "neurips"), # neurips_2025.sty
53
+ "iclr": Layout(5.5, 5.5, 10, "times", "iclr"), # iclr2026_conference.sty
54
+ "icml": Layout(3.25, 6.75, 10, "times", "icml"), # icml2025.sty
55
+ "cvpr": Layout(3.28125, 6.875, 10, "times", "cvpr"), # cvpr.sty (author kit)
56
+ "acl": Layout(7.7 / 2.54, 16.0 / 2.54, 11, "times", "acl"), # acl.sty, A4 with 2.5 cm margins
57
+ }
58
+
59
+
60
+ def family_of(latex_family: str) -> str:
61
+ """Map a LaTeX font family code (``ptm``, ``ntxtlf``, ``lmr``...) to a font group."""
62
+ code = latex_family.lower()
63
+ if code.startswith(("ptm", "ntx", "qtm", "stix", "txr", "tempora", "times", "nimbusserif")):
64
+ return "times"
65
+ if code.startswith(("cmr", "lmr")):
66
+ return "cm"
67
+ if "libertin" in code or code.startswith("lbt"):
68
+ return "libertine"
69
+ if code.startswith(("ppl", "qpl", "zpl", "pagella", "palatino", "tgpagella")):
70
+ return "palatino"
71
+ if code.startswith(("phv", "qhv", "cmss", "lmss", "helvet")):
72
+ return "sans"
73
+ return "serif"
74
+
75
+
76
+ def from_file(path: str | Path) -> tuple[Layout, dict]:
77
+ """Read a ``.pubviz.json`` file. Returns the layout and the raw record,
78
+ which also carries the theme (``accent``, ``mode``, ``pos``, ``neg``)."""
79
+ path = Path(path)
80
+ record = json.loads(path.read_text())
81
+ layout = Layout(
82
+ column=float(record["columnwidth_in"]),
83
+ text=float(record["textwidth_in"]),
84
+ font_size=float(record["font_size_pt"]),
85
+ family=family_of(str(record.get("rmfamily", ""))),
86
+ name=path.name.removesuffix(".pubviz.json"),
87
+ )
88
+ return layout, record
89
+
90
+
91
+ def resolve(layout: str | Path | Layout) -> tuple[Layout, dict]:
92
+ """A preset name, a layout file, or a Layout to a Layout (and the raw record if any)."""
93
+ if isinstance(layout, Layout):
94
+ return layout, {}
95
+ text = str(layout)
96
+ if text in PRESETS:
97
+ return PRESETS[text], {}
98
+ path = Path(text)
99
+ if path.suffix == ".json" or path.exists():
100
+ return from_file(path)
101
+ raise ValueError(
102
+ f"unknown layout {text!r}: give a preset ({', '.join(PRESETS)}) "
103
+ "or the path of a .pubviz.json file written by pubviz.sty"
104
+ )