gleplot 6.0.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.
- gleplot/__init__.py +772 -0
- gleplot/_warn.py +45 -0
- gleplot/axes.py +10714 -0
- gleplot/cairo_support.py +232 -0
- gleplot/colors.py +721 -0
- gleplot/compiler.py +863 -0
- gleplot/config.py +491 -0
- gleplot/dataio.py +1403 -0
- gleplot/figure.py +5789 -0
- gleplot/guides.py +172 -0
- gleplot/markers.py +424 -0
- gleplot/mathtext.py +679 -0
- gleplot/palettes.py +243 -0
- gleplot/parser/__init__.py +83 -0
- gleplot/parser/expr.py +196 -0
- gleplot/parser/lexer.py +289 -0
- gleplot/parser/metadata.py +374 -0
- gleplot/parser/recognizer.py +12654 -0
- gleplot/parser/report.py +74 -0
- gleplot/parser/syntax.py +756 -0
- gleplot/parser/tables.py +484 -0
- gleplot/parser/units.py +196 -0
- gleplot/py.typed +0 -0
- gleplot/series.py +1609 -0
- gleplot/sources.py +623 -0
- gleplot/writer.py +7215 -0
- gleplot-6.0.0.dist-info/METADATA +138 -0
- gleplot-6.0.0.dist-info/RECORD +31 -0
- gleplot-6.0.0.dist-info/WHEEL +5 -0
- gleplot-6.0.0.dist-info/licenses/LICENSE +25 -0
- gleplot-6.0.0.dist-info/top_level.txt +1 -0
gleplot/parser/tables.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
"""Reference tables shared by the GLE writer and the (forthcoming) GLE parser.
|
|
2
|
+
|
|
3
|
+
All lookup tables that a parser must invert live here in one place:
|
|
4
|
+
|
|
5
|
+
- ``COLORS`` / color helpers: transcribed from GLE 4.3.10's
|
|
6
|
+
``src/gle/color.cpp`` (``defineDefaultColors`` -> ``defineGrays`` +
|
|
7
|
+
``defineSVGColors``) and the hex literals in ``src/gle/color.h``, i.e. the
|
|
8
|
+
151 names GLE recognizes out of the box (SVG named colors plus the
|
|
9
|
+
``GRAY1``..``GRAY90`` grayscale ramp). The legacy ``defineOldGLEColors``
|
|
10
|
+
table (old GLE color names like ``BAKERS_CHOCOLATE``) is intentionally
|
|
11
|
+
*not* included -- gleplot's writer never emits those names.
|
|
12
|
+
- ``MARKERS`` / ``GLE_MARKER_TO_MATPLOTLIB``: transcribed from GLE 4.3.10's
|
|
13
|
+
``src/gle/pass.cpp`` (the ``stdmark[]`` array, lines ~2371-2468). The
|
|
14
|
+
matplotlib-facing inverse map is derived programmatically from
|
|
15
|
+
:data:`gleplot.markers.MATPLOTLIB_TO_GLE_MARKERS` so the two can never
|
|
16
|
+
drift apart.
|
|
17
|
+
- ``LSTYLE_TO_MATPLOTLIB`` / ``MATPLOTLIB_TO_LSTYLE``: GLE ``lstyle`` integer
|
|
18
|
+
<-> matplotlib linestyle string, derived programmatically from the
|
|
19
|
+
``line_style_*`` fields of ``GLEStyleConfig`` -- the same fields
|
|
20
|
+
``GLEWriter.add_line``/``add_errorbar_series``/``add_file_series``
|
|
21
|
+
read when emitting -- so the parser's inverse cannot drift from the
|
|
22
|
+
writer's forward choice. Also consumed by ``Axes.errorbar``'s ``fmt``
|
|
23
|
+
parsing.
|
|
24
|
+
- ``KEY_POSITIONS``: long-form <-> short-form GLE legend position, mirroring
|
|
25
|
+
``GLEWriter.add_legend``'s ``pos_map`` and ``Axes.legend``'s ``loc_map``.
|
|
26
|
+
- ``LEGEND_SPACING_TO_KEY`` / ``KEY_ANCHOR_X`` / ``KEY_ANCHOR_Y``: the legend
|
|
27
|
+
spacing keywords and the ``begin key`` ``absolute`` coordinates the writer
|
|
28
|
+
emits for ``legend(bbox_to_anchor=...)``.
|
|
29
|
+
|
|
30
|
+
Provenance is documented per table below.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import re
|
|
36
|
+
from typing import Dict, Optional, Tuple
|
|
37
|
+
|
|
38
|
+
from .. import markers as _markers
|
|
39
|
+
|
|
40
|
+
# The raw GLE name tables live with the modules that own the forward
|
|
41
|
+
# mappings; they are re-exported here so the parser has one place to look.
|
|
42
|
+
from ..colors import COLORS, gle_color_rgb, nearest_gle_color
|
|
43
|
+
from ..config import GLEStyleConfig
|
|
44
|
+
from ..markers import MARKERS
|
|
45
|
+
from ..palettes import NATIVE_CMAPS, cmap_needs_sub, is_native, palette_sub_name
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"COLORS",
|
|
49
|
+
"gle_color_rgb",
|
|
50
|
+
"nearest_gle_color",
|
|
51
|
+
"MARKERS",
|
|
52
|
+
"GLE_MARKER_TO_MATPLOTLIB",
|
|
53
|
+
"LSTYLE_TO_MATPLOTLIB",
|
|
54
|
+
"MATPLOTLIB_TO_LSTYLE",
|
|
55
|
+
"LINE_MODES",
|
|
56
|
+
"DRAWSTYLE_TO_LINE_MODE",
|
|
57
|
+
"resolve_line_mode",
|
|
58
|
+
"NUMBER_FORMAT_KEYWORDS",
|
|
59
|
+
"KEY_POSITIONS_LONG_TO_SHORT",
|
|
60
|
+
"KEY_POSITIONS_SHORT_TO_LONG",
|
|
61
|
+
"TEXT_HA_VALUES",
|
|
62
|
+
"TEXT_VA_VALUES",
|
|
63
|
+
"TEXT_BOX_PAD_CM",
|
|
64
|
+
"text_align_to_just",
|
|
65
|
+
"text_box_pad_token",
|
|
66
|
+
"text_just_to_align",
|
|
67
|
+
"PALETTE_SUB_TO_CMAP",
|
|
68
|
+
"FIT_MODEL_TO_ROUTINE",
|
|
69
|
+
"FIT_ROUTINE_TO_MODEL",
|
|
70
|
+
"FIT_RESULT_PLACEHOLDERS",
|
|
71
|
+
"FIT_PLACEHOLDER_RE",
|
|
72
|
+
"FIT_PLACEHOLDER_SPEC_RE",
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ---------------------------------------------------------------------------
|
|
77
|
+
# Markers
|
|
78
|
+
# ---------------------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _build_gle_marker_to_matplotlib() -> Dict[str, str]:
|
|
82
|
+
"""Invert :data:`gleplot.markers.MATPLOTLIB_TO_GLE_MARKERS`.
|
|
83
|
+
|
|
84
|
+
Built programmatically (rather than hand-transcribed) so the parser's
|
|
85
|
+
GLE->matplotlib marker map can never drift out of sync with the writer's
|
|
86
|
+
matplotlib->GLE map in ``gleplot.markers``.
|
|
87
|
+
|
|
88
|
+
Several matplotlib codes map to the same GLE name (e.g. ``'<'`` and
|
|
89
|
+
``'>'`` both map to ``'TRIANGLE'``; ``'+'``/``'P'``/``'|'``/``'_'`` all
|
|
90
|
+
map to ``'PLUS'``; ``'x'``/``'X'`` both map to ``'PCROSS'``;
|
|
91
|
+
``'.'``/``','`` both map to ``'DOT'``). For each such GLE name, the
|
|
92
|
+
*first* matplotlib code encountered in
|
|
93
|
+
``MATPLOTLIB_TO_GLE_MARKERS`` (dict iteration / insertion order) is kept
|
|
94
|
+
as the canonical inverse -- i.e. the earliest-defined mpl code for that
|
|
95
|
+
GLE name in ``gleplot/markers.py`` wins:
|
|
96
|
+
|
|
97
|
+
- ``'<'`` (not ``'>'``) is canonical for ``TRIANGLE``
|
|
98
|
+
- ``'+'`` (not ``'P'``, ``'|'``, ``'_'``) is canonical for ``PLUS``
|
|
99
|
+
- ``'x'`` (not ``'X'``) is canonical for ``PCROSS``
|
|
100
|
+
- ``'.'`` (not ``','``) is canonical for ``DOT``
|
|
101
|
+
"""
|
|
102
|
+
inverse: Dict[str, str] = {}
|
|
103
|
+
for mpl_code, gle_name in _markers.MATPLOTLIB_TO_GLE_MARKERS.items():
|
|
104
|
+
if gle_name not in inverse:
|
|
105
|
+
inverse[gle_name] = mpl_code
|
|
106
|
+
return inverse
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
GLE_MARKER_TO_MATPLOTLIB: Dict[str, str] = _build_gle_marker_to_matplotlib()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ---------------------------------------------------------------------------
|
|
113
|
+
# Line styles
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
#
|
|
116
|
+
# GLE ``lstyle`` integer <-> matplotlib linestyle string.
|
|
117
|
+
#
|
|
118
|
+
# DERIVED from ``GLEStyleConfig``'s defaults rather than transcribed, for the
|
|
119
|
+
# same reason ``GLE_MARKER_TO_MATPLOTLIB`` is: the writer emits ``lstyle
|
|
120
|
+
# {style.line_style_dashed}`` for ``'--'``, ``{...dotted}`` for ``':'`` and
|
|
121
|
+
# ``{...dashdot}`` for ``'-.'`` (see ``GLEWriter.add_line`` /
|
|
122
|
+
# ``add_errorbar_series`` / ``add_file_series``), so building the parser's
|
|
123
|
+
# inverse from the very same fields makes it impossible for the two to drift
|
|
124
|
+
# apart. They previously did: the config said dashed=2/dotted=3 while GLE
|
|
125
|
+
# 4.3.10 renders 2 as dotted and 3 as dashed, and this table faithfully
|
|
126
|
+
# reproduced the transposition on the way back in.
|
|
127
|
+
#
|
|
128
|
+
# Solid lines (``'-'``) never emit an ``lstyle`` token at all (GLE's default
|
|
129
|
+
# is style 1), but the pair is still listed so a hand-written ``lstyle 1``
|
|
130
|
+
# round-trips. The reverse map is also used by ``Axes.errorbar``'s ``fmt``
|
|
131
|
+
# parsing and by ``Axes._linestyle_to_lstyle`` for contour lines; it
|
|
132
|
+
# recognizes exactly ``'-'``, ``'--'``, ``':'``, ``'-.'``.
|
|
133
|
+
#
|
|
134
|
+
# NOTE: this is a module-level constant keyed off the *default* config. A
|
|
135
|
+
# figure that overrides ``line_style_dashed`` etc. will emit numbers this
|
|
136
|
+
# table cannot invert -- a pre-existing limitation of parsing without the
|
|
137
|
+
# producing config in hand.
|
|
138
|
+
def _build_lstyle_to_matplotlib() -> Dict[int, str]:
|
|
139
|
+
"""Invert the writer's linestyle -> ``lstyle`` choice, from the defaults."""
|
|
140
|
+
defaults = GLEStyleConfig()
|
|
141
|
+
return {
|
|
142
|
+
defaults.line_style_solid: "-",
|
|
143
|
+
defaults.line_style_dashed: "--",
|
|
144
|
+
defaults.line_style_dotted: ":",
|
|
145
|
+
defaults.line_style_dashdot: "-.",
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
LSTYLE_TO_MATPLOTLIB: Dict[int, str] = _build_lstyle_to_matplotlib()
|
|
150
|
+
|
|
151
|
+
MATPLOTLIB_TO_LSTYLE: Dict[str, int] = {v: k for k, v in LSTYLE_TO_MATPLOTLIB.items()}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ---------------------------------------------------------------------------
|
|
155
|
+
# Dataset line modes
|
|
156
|
+
# ---------------------------------------------------------------------------
|
|
157
|
+
#
|
|
158
|
+
# GLE 4.3.10 ``src/gle/graph2.cpp`` ``do_dataset``: ``STEPS``, ``FSTEPS``,
|
|
159
|
+
# ``HIST``, ``BAR`` and ``IMPULSES`` each assign ``dp[d]->line_mode`` (the
|
|
160
|
+
# last keyword wins). After the keyword loop, any non-plain mode sets
|
|
161
|
+
# ``line = true`` even when the ``line`` keyword itself was omitted.
|
|
162
|
+
#
|
|
163
|
+
# Drawing (``do_draw_*`` in the same file, and the manual's line-mode list):
|
|
164
|
+
# steps (x1,y1) -> (x2,y1) -> (x2,y2) horizontal, then vertical
|
|
165
|
+
# fsteps (x1,y1) -> (x1,y2) -> (x2,y2) vertical, then horizontal
|
|
166
|
+
# hist each point is the center of a bin
|
|
167
|
+
# bar hist, plus a separator down to the impulse origin
|
|
168
|
+
# impulses a vertical from the impulse origin to each point
|
|
169
|
+
#
|
|
170
|
+
# matplotlib's step drawstyles land on the first three. ``impulses`` is
|
|
171
|
+
# ``Axes.stem``. ``bar`` is this per-dataset line mode, not the graph-level
|
|
172
|
+
# ``bar`` command :meth:`Axes.bar` emits.
|
|
173
|
+
# steps / steps-pre / where="pre" -> fsteps
|
|
174
|
+
# steps-post / where="post" -> steps
|
|
175
|
+
# steps-mid / where="mid" -> hist
|
|
176
|
+
|
|
177
|
+
LINE_MODES: Tuple[str, ...] = ("steps", "fsteps", "hist", "bar", "impulses")
|
|
178
|
+
|
|
179
|
+
#: matplotlib ``drawstyle`` → GLE line mode. ``None`` is a plain polyline,
|
|
180
|
+
#: so the writer keeps emitting a bare ``line`` and old scripts stay
|
|
181
|
+
#: byte-identical. Keys are matplotlib's own spellings (case-sensitive).
|
|
182
|
+
DRAWSTYLE_TO_LINE_MODE: Dict[str, Optional[str]] = {
|
|
183
|
+
"default": None,
|
|
184
|
+
"steps": "fsteps",
|
|
185
|
+
"steps-pre": "fsteps",
|
|
186
|
+
"steps-post": "steps",
|
|
187
|
+
"steps-mid": "hist",
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def resolve_line_mode(
|
|
192
|
+
drawstyle: Optional[str] = None,
|
|
193
|
+
line_mode: Optional[str] = None,
|
|
194
|
+
) -> Optional[str]:
|
|
195
|
+
"""The GLE line mode for a plot call, or ``None`` for a plain polyline.
|
|
196
|
+
|
|
197
|
+
``line_mode`` is the GLE token itself (see :data:`LINE_MODES`). When a
|
|
198
|
+
drawstyle and a ``line_mode`` are both given they must name the same
|
|
199
|
+
mode.
|
|
200
|
+
"""
|
|
201
|
+
from_style = _drawstyle_mode(drawstyle)
|
|
202
|
+
if line_mode is None:
|
|
203
|
+
return from_style
|
|
204
|
+
mode = str(line_mode).strip().lower()
|
|
205
|
+
if mode not in LINE_MODES:
|
|
206
|
+
raise ValueError(f"line_mode must be one of {LINE_MODES}, got {line_mode!r}")
|
|
207
|
+
if from_style is not None and from_style != mode:
|
|
208
|
+
raise ValueError(
|
|
209
|
+
f"drawstyle {drawstyle!r} is GLE {from_style!r}, "
|
|
210
|
+
f"which disagrees with line_mode {line_mode!r}"
|
|
211
|
+
)
|
|
212
|
+
return mode
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _drawstyle_mode(drawstyle: Optional[str]) -> Optional[str]:
|
|
216
|
+
if drawstyle is None:
|
|
217
|
+
return None
|
|
218
|
+
key = str(drawstyle).strip()
|
|
219
|
+
try:
|
|
220
|
+
return DRAWSTYLE_TO_LINE_MODE[key]
|
|
221
|
+
except KeyError:
|
|
222
|
+
known = ", ".join(repr(name) for name in DRAWSTYLE_TO_LINE_MODE)
|
|
223
|
+
raise ValueError(
|
|
224
|
+
f"drawstyle must be one of {known}, got {drawstyle!r}"
|
|
225
|
+
) from None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# ---------------------------------------------------------------------------
|
|
229
|
+
# Number-format keywords
|
|
230
|
+
# ---------------------------------------------------------------------------
|
|
231
|
+
#
|
|
232
|
+
# Every specifier GLE's number-format parser understands, transcribed from
|
|
233
|
+
# GLE 4.3.10 ``src/gle/numberformat.cpp``, ``GLENumberFormat::GLENumberFormat``
|
|
234
|
+
# (the ``if (name == ...)`` chain) -- the code behind both ``format$(x, fmt)``
|
|
235
|
+
# and the graph block's ``xaxis format "<fmt>"``. Documented in the manual
|
|
236
|
+
# under ``format$`` ("Programming"), which omits ``nozero``, ``add`` and
|
|
237
|
+
# ``otherwise``; the source is authoritative and they are included here.
|
|
238
|
+
#
|
|
239
|
+
# GLE does NOT abort on an unrecognized specifier -- it prints "Unknown
|
|
240
|
+
# specifier in number format string" and skips it -- so this table is used
|
|
241
|
+
# only for a light "did you mean a format string at all?" check
|
|
242
|
+
# (:func:`gleplot.axes.validate_tick_format`), never to reject arguments.
|
|
243
|
+
NUMBER_FORMAT_KEYWORDS: Tuple[str, ...] = (
|
|
244
|
+
# Base formats (each starts a new format in the chain).
|
|
245
|
+
"fix",
|
|
246
|
+
"percent",
|
|
247
|
+
"dec",
|
|
248
|
+
"hex",
|
|
249
|
+
"bin",
|
|
250
|
+
"round",
|
|
251
|
+
"sci",
|
|
252
|
+
"eng",
|
|
253
|
+
"frac",
|
|
254
|
+
"pi",
|
|
255
|
+
# Modifiers of the preceding format.
|
|
256
|
+
"prefix",
|
|
257
|
+
"nozeroes",
|
|
258
|
+
"nozero",
|
|
259
|
+
"sign",
|
|
260
|
+
"pad",
|
|
261
|
+
"min",
|
|
262
|
+
"max",
|
|
263
|
+
"append",
|
|
264
|
+
"add",
|
|
265
|
+
"prepend",
|
|
266
|
+
"otherwise",
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
# ---------------------------------------------------------------------------
|
|
271
|
+
# Legend / key positions
|
|
272
|
+
# ---------------------------------------------------------------------------
|
|
273
|
+
#
|
|
274
|
+
# Long-form <-> short-form GLE legend position, mirroring
|
|
275
|
+
# ``GLEWriter.add_legend``'s ``pos_map`` (long -> short; falls through to the
|
|
276
|
+
# value as-is if already short-form) and
|
|
277
|
+
# ``gleplot.axes.MATPLOTLIB_TO_GLE_LEGEND_LOC`` (matplotlib ``loc`` ->
|
|
278
|
+
# gleplot's long form, which ``add_legend`` then maps to short form). All nine
|
|
279
|
+
# GLE key anchors are reachable from a matplotlib ``loc``, so all nine appear
|
|
280
|
+
# here.
|
|
281
|
+
KEY_POSITIONS_LONG_TO_SHORT: Dict[str, str] = {
|
|
282
|
+
"top right": "tr",
|
|
283
|
+
"top left": "tl",
|
|
284
|
+
"top center": "tc",
|
|
285
|
+
"bottom right": "br",
|
|
286
|
+
"bottom left": "bl",
|
|
287
|
+
"bottom center": "bc",
|
|
288
|
+
"left center": "lc",
|
|
289
|
+
"right center": "rc",
|
|
290
|
+
"center": "cc",
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
# matplotlib legend spacing keyword -> GLE key option, in emission order. Both
|
|
294
|
+
# sides measure a length; matplotlib's in units of the legend font size, GLE's
|
|
295
|
+
# in cm, so the writer multiplies by the key text height. ``margins`` takes an
|
|
296
|
+
# x and a y; matplotlib's ``borderpad`` is one value for both.
|
|
297
|
+
LEGEND_SPACING_TO_KEY: Dict[str, str] = {
|
|
298
|
+
"handlelength": "llen",
|
|
299
|
+
"handletextpad": "dist",
|
|
300
|
+
"columnspacing": "coldist",
|
|
301
|
+
"borderpad": "margins",
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
# A page coordinate for an axes fraction ``{}`` of the graph that has just
|
|
305
|
+
# ended: a ``begin key`` ``absolute`` anchor, or the ``amove`` of an
|
|
306
|
+
# ``Axes.text(transform=ax.transAxes)``. ``min``/``abs`` keep fraction 0 at the left
|
|
307
|
+
# (bottom) of the box on a ``negate`` axis, as matplotlib's axes coordinates do.
|
|
308
|
+
KEY_ANCHOR_X = "min(xg(xgmin),xg(xgmax))+{}*abs(xg(xgmax)-xg(xgmin))"
|
|
309
|
+
KEY_ANCHOR_Y = "min(yg(ygmin),yg(ygmax))+{}*abs(yg(ygmax)-yg(ygmin))"
|
|
310
|
+
|
|
311
|
+
# ---------------------------------------------------------------------------
|
|
312
|
+
# Palette subroutine names (contour/heatmap support)
|
|
313
|
+
# ---------------------------------------------------------------------------
|
|
314
|
+
#
|
|
315
|
+
# A ``colormap`` calls a native map's wrapper sub, ``cmap_<name>`` (see
|
|
316
|
+
# :mod:`gleplot.palettes`). The recognizer maps a ``colormap ... palette
|
|
317
|
+
# cmap_<name>`` clause back to the cmap name via this table, and treats any
|
|
318
|
+
# other palette sub name as an unknown/foreign palette (passthrough with a
|
|
319
|
+
# warning). ``gray`` and ``rainbow`` are no ``palette`` clause (grayscale = no
|
|
320
|
+
# clause; rainbow = the ``color`` switch), and rainbow has no reversed form.
|
|
321
|
+
PALETTE_SUB_TO_CMAP: Dict[str, str] = {
|
|
322
|
+
palette_sub_name(c): c
|
|
323
|
+
for base in NATIVE_CMAPS
|
|
324
|
+
for c in (base, base + "_r")
|
|
325
|
+
if is_native(c) and cmap_needs_sub(c)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
KEY_POSITIONS_SHORT_TO_LONG: Dict[str, str] = {
|
|
330
|
+
v: k for k, v in KEY_POSITIONS_LONG_TO_SHORT.items()
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
# ---------------------------------------------------------------------------
|
|
335
|
+
# Free-form text justification (``set just``)
|
|
336
|
+
# ---------------------------------------------------------------------------
|
|
337
|
+
#
|
|
338
|
+
# GLE's ``set just`` is one word or a two-letter code. The two-letter form is
|
|
339
|
+
# vertical then horizontal: ``t``/``c``/``b`` × ``l``/``c``/``r`` (manual,
|
|
340
|
+
# ``set just``: the ``tl tc tr / lc cc rc / bl bc br`` grid).
|
|
341
|
+
#
|
|
342
|
+
# The single-word forms are the vertically-centred row, not the baseline and
|
|
343
|
+
# not the bottom. Measured on GLE 4.3.10: ``set just left`` puts the current
|
|
344
|
+
# point on the vertical centre of the text, the same place as ``lc``; ``center``
|
|
345
|
+
# and ``right`` match ``cc`` and ``rc``. gleplot therefore emits the single
|
|
346
|
+
# word whenever ``va`` is ``center``, which is what every script written before
|
|
347
|
+
# vertical alignment was emitted already said.
|
|
348
|
+
|
|
349
|
+
TEXT_HA_VALUES: Tuple[str, ...] = ("left", "center", "right")
|
|
350
|
+
TEXT_VA_VALUES: Tuple[str, ...] = ("top", "center", "bottom")
|
|
351
|
+
|
|
352
|
+
_HA_LETTER = {"left": "l", "center": "c", "right": "r"}
|
|
353
|
+
_VA_LETTER = {"top": "t", "center": "c", "bottom": "b"}
|
|
354
|
+
_CENTERED_JUST = {"l": "left", "c": "center", "r": "right"}
|
|
355
|
+
|
|
356
|
+
#: ``set just`` token -> ``(ha, va)``. Includes the single-word aliases of the
|
|
357
|
+
#: centred row so a hand-written ``lc`` recovers the same alignment as ``left``.
|
|
358
|
+
_JUST_TO_ALIGN: Dict[str, Tuple[str, str]] = {
|
|
359
|
+
"left": ("left", "center"),
|
|
360
|
+
"center": ("center", "center"),
|
|
361
|
+
"right": ("right", "center"),
|
|
362
|
+
"tl": ("left", "top"),
|
|
363
|
+
"tc": ("center", "top"),
|
|
364
|
+
"tr": ("right", "top"),
|
|
365
|
+
"lc": ("left", "center"),
|
|
366
|
+
"cc": ("center", "center"),
|
|
367
|
+
"rc": ("right", "center"),
|
|
368
|
+
"bl": ("left", "bottom"),
|
|
369
|
+
"bc": ("center", "bottom"),
|
|
370
|
+
"br": ("right", "bottom"),
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def text_align_to_just(ha: str, va: str) -> str:
|
|
375
|
+
"""GLE ``set just`` token for a matplotlib ``ha``/``va`` pair.
|
|
376
|
+
|
|
377
|
+
An unknown ``va`` is treated as ``center`` and an unknown ``ha`` as
|
|
378
|
+
``left``, so a restored annotation keeps whichever half is valid.
|
|
379
|
+
``Axes.text`` already stores those fallbacks, but ``Figure.from_dict``
|
|
380
|
+
writes the dict straight through. ``va='center'`` uses the single-word
|
|
381
|
+
form (``left``/``center``/``right``) so a default annotation stays
|
|
382
|
+
byte-identical to one emitted before ``va`` was written.
|
|
383
|
+
"""
|
|
384
|
+
hl = _HA_LETTER.get(str(ha).strip().lower(), "l")
|
|
385
|
+
vl = _VA_LETTER.get(str(va).strip().lower(), "c")
|
|
386
|
+
if vl == "c":
|
|
387
|
+
return _CENTERED_JUST[hl]
|
|
388
|
+
return vl + hl
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
#: Margin, in cm, that ``begin box add`` puts around a text background.
|
|
392
|
+
#: GLE sizes the box from the ink inside the block; 0.05 cm is the pad
|
|
393
|
+
#: ``contour_labels`` in ``contour.gle`` uses. Not a model field: every box
|
|
394
|
+
#: gleplot draws uses :func:`text_box_pad_token`, and a hand-written box
|
|
395
|
+
#: whose ``add`` token is anything else stays unrecognized.
|
|
396
|
+
TEXT_BOX_PAD_CM = 0.05
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def text_box_pad_token() -> str:
|
|
400
|
+
"""The ``add`` spelling written for :data:`TEXT_BOX_PAD_CM`.
|
|
401
|
+
|
|
402
|
+
Same cut as ``GLEWriter._format_number`` for a modest positive number
|
|
403
|
+
(``f"{value:.6g}"``). The recognizer accepts only this token, so a pad
|
|
404
|
+
spelled any other way is not rewritten to this one.
|
|
405
|
+
"""
|
|
406
|
+
return f"{TEXT_BOX_PAD_CM:.6g}"
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def text_just_to_align(just: str) -> Optional[Tuple[str, str]]:
|
|
410
|
+
"""``(ha, va)`` for a ``set just`` token, or ``None`` if it is not one.
|
|
411
|
+
|
|
412
|
+
The return is the matplotlib pair gleplot stores. ``left`` and ``lc`` both
|
|
413
|
+
come back as ``('left', 'center')``, and re-emission uses
|
|
414
|
+
:func:`text_align_to_just`, which writes the single word.
|
|
415
|
+
"""
|
|
416
|
+
return _JUST_TO_ALIGN.get(str(just).strip().lower())
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
# -- annotation arrows ------------------------------------------------------
|
|
420
|
+
#
|
|
421
|
+
# ``Axes.annotate`` draws its arrow with ``join`` from the text's named box to
|
|
422
|
+
# a ``save``d point at ``xy``, so GLE clips the start at the box edge (the
|
|
423
|
+
# matplotlib ``patchA`` behaviour) instead of drawing over the text. The
|
|
424
|
+
# separator is the head placement; ``set arrowstyle`` is the tip shape.
|
|
425
|
+
# GLE's own default style is ``filled`` (core.cpp ``g.arrowstyle``), so the
|
|
426
|
+
# writer always states it.
|
|
427
|
+
|
|
428
|
+
#: GLE ``join`` separators: ``-`` is a bare line.
|
|
429
|
+
ARROW_JOIN_SEPS: Tuple[str, ...] = ("->", "<-", "<->", "-")
|
|
430
|
+
#: GLE ``set arrowstyle`` values gleplot writes.
|
|
431
|
+
ARROW_TIP_STYLES: Tuple[str, ...] = ("simple", "filled")
|
|
432
|
+
|
|
433
|
+
#: matplotlib ``arrowprops['arrowstyle']`` -> ``(join separator, tip style)``.
|
|
434
|
+
#: Open heads (``->``) are GLE ``simple``, triangle heads (``-|>``) ``filled``.
|
|
435
|
+
MPL_ARROWSTYLE_TO_GLE: Dict[str, Tuple[str, Optional[str]]] = {
|
|
436
|
+
"-": ("-", None),
|
|
437
|
+
"->": ("->", "simple"),
|
|
438
|
+
"<-": ("<-", "simple"),
|
|
439
|
+
"<->": ("<->", "simple"),
|
|
440
|
+
"-|>": ("->", "filled"),
|
|
441
|
+
"<|-": ("<-", "filled"),
|
|
442
|
+
"<|-|>": ("<->", "filled"),
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
#: GLE ``xlabels log`` modes: which sub-decades of a log axis get a label
|
|
446
|
+
#: (``graph.cpp`` ``do_labels``).
|
|
447
|
+
LOG_LABEL_MODES: Tuple[str, ...] = ("off", "l1", "l25", "l25b", "n1")
|
|
448
|
+
|
|
449
|
+
# -- closed-form fits -------------------------------------------------------
|
|
450
|
+
#
|
|
451
|
+
# ``Axes.fit(model=...)`` -> the GLE ``let`` routine that fits it
|
|
452
|
+
# (graph2.cpp ``GLELet::doFitFunction``): ``y = a*x+b``, ``y = a*exp(b*x)``,
|
|
453
|
+
# ``y = a*10^(b*x)`` and ``y = a*x^b``, each by ordinary least squares:
|
|
454
|
+
# ``linfit`` on the data, the others on its logs (y, and x for ``powxfit``).
|
|
455
|
+
FIT_MODEL_TO_ROUTINE: Dict[str, str] = {
|
|
456
|
+
"linear": "linfit",
|
|
457
|
+
"exp": "logefit",
|
|
458
|
+
"exp10": "log10fit",
|
|
459
|
+
"power": "powxfit",
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
FIT_ROUTINE_TO_MODEL: Dict[str, str] = {v: k for k, v in FIT_MODEL_TO_ROUTINE.items()}
|
|
463
|
+
|
|
464
|
+
#: The label placeholders a model fit fills from its routine's result
|
|
465
|
+
#: variables, in the order GLE writes those: ``let dK = linfit dJ v1 v2 v3``.
|
|
466
|
+
#: ``logefit``, ``log10fit`` and ``powxfit`` store the exponent ``b`` first
|
|
467
|
+
#: and the prefactor ``a`` second, the reverse of the GLE manual (measured
|
|
468
|
+
#: on GLE 4.3.10).
|
|
469
|
+
FIT_RESULT_PLACEHOLDERS: Dict[str, Tuple[str, str, str]] = {
|
|
470
|
+
"linear": ("slope", "offset", "rsq"),
|
|
471
|
+
"exp": ("exponent", "prefactor", "rsq"),
|
|
472
|
+
"exp10": ("exponent", "prefactor", "rsq"),
|
|
473
|
+
"power": ("exponent", "prefactor", "rsq"),
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
#: A result placeholder in a model fit's label, ``{name}`` or
|
|
477
|
+
#: ``{name:spec}``; the spec is checked against
|
|
478
|
+
#: :data:`FIT_PLACEHOLDER_SPEC_RE`.
|
|
479
|
+
FIT_PLACEHOLDER_RE = re.compile(
|
|
480
|
+
r"\{(slope|offset|prefactor|exponent|rsq)(?::([^{}]*))?\}"
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
#: The placeholder specs GLE's ``format$`` can match: ``.Nf`` and ``.Ne``.
|
|
484
|
+
FIT_PLACEHOLDER_SPEC_RE = re.compile(r"\.(\d+)([fe])")
|
gleplot/parser/units.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Single-source unit-conversion functions for gleplot <-> GLE round-tripping.
|
|
2
|
+
|
|
3
|
+
Every physical-unit conversion used by :mod:`gleplot.writer`, :mod:`gleplot.axes`,
|
|
4
|
+
and :mod:`gleplot.figure` when emitting GLE lives here, exactly once, so that a
|
|
5
|
+
future ``.gle`` parser can invert each one with the matching ``*_to_*``
|
|
6
|
+
function instead of re-deriving (and potentially drifting from) the constant.
|
|
7
|
+
|
|
8
|
+
Provenance
|
|
9
|
+
----------
|
|
10
|
+
Each constant below is transcribed verbatim from the call site it replaces, as
|
|
11
|
+
when this module was created. The
|
|
12
|
+
refactor that follows this module's creation intentionally does **not**
|
|
13
|
+
"correct" or unify inconsistent constants (e.g. ``0.03528`` vs ``0.0353``)
|
|
14
|
+
-- see :func:`linewidth_pt_to_cm` and :func:`capsize_pt_to_cm` docstrings.
|
|
15
|
+
|
|
16
|
+
- ``figsize`` (inches) <-> ``size`` (cm): factor 2.54, from
|
|
17
|
+
``src/gleplot/writer.py:34-35`` (``GLEWriter.__init__``):
|
|
18
|
+
``self.width_cm = figsize[0] * 2.54``.
|
|
19
|
+
- line width (points) -> GLE ``lwidth`` (cm): factor ``0.03528``, from
|
|
20
|
+
``src/gleplot/writer.py:332,334,590,592,715,717``
|
|
21
|
+
(``GLEWriter.add_line``, ``add_errorbar_series``, ``add_file_series``).
|
|
22
|
+
- font size (points) -> GLE ``set hei`` (cm): divisor ``28.35``, from
|
|
23
|
+
``src/gleplot/writer.py:71`` (``GLEWriter.add_preamble``) and
|
|
24
|
+
``src/gleplot/writer.py:779`` (``GLEWriter.add_text_annotation``).
|
|
25
|
+
- matplotlib ``markersize``/``s`` -> GLE ``msize``: factor
|
|
26
|
+
``0.025 * msize_scale``, from ``src/gleplot/axes.py:231`` (``Axes.plot``),
|
|
27
|
+
``src/gleplot/axes.py:350`` (``Axes.errorbar``), and
|
|
28
|
+
``src/gleplot/axes.py:468`` (``Axes.errorbar_from_file``).
|
|
29
|
+
- matplotlib ``capsize`` (points) -> GLE ``errwidth``/``herrwidth`` (cm):
|
|
30
|
+
factor ``0.0353``, from ``src/gleplot/axes.py:363`` (``Axes.errorbar``) and
|
|
31
|
+
``src/gleplot/axes.py:469`` (``Axes.errorbar_from_file``).
|
|
32
|
+
|
|
33
|
+
Note the line-width factor (``0.03528``) and the capsize factor (``0.0353``)
|
|
34
|
+
are numerically different roundings of the same physical constant
|
|
35
|
+
(1 pt = 1/72 in = 2.54/72 cm = 0.0352777... cm) used at different call sites
|
|
36
|
+
in the pre-refactor code. Both are preserved verbatim as separate functions
|
|
37
|
+
(``linewidth_pt_to_cm`` / ``capsize_pt_to_cm``) rather than unified, per the
|
|
38
|
+
"zero behavior change" requirement -- unifying them would change already
|
|
39
|
+
-committed golden GLE output for existing round-trip tests.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"INCH_TO_CM",
|
|
46
|
+
"LINEWIDTH_PT_TO_CM_FACTOR",
|
|
47
|
+
"FONTSIZE_PT_TO_CM_DIVISOR",
|
|
48
|
+
"MARKERSIZE_TO_MSIZE_FACTOR",
|
|
49
|
+
"CAPSIZE_PT_TO_CM_FACTOR",
|
|
50
|
+
"inches_to_cm",
|
|
51
|
+
"cm_to_inches",
|
|
52
|
+
"linewidth_pt_to_cm",
|
|
53
|
+
"linewidth_cm_to_pt",
|
|
54
|
+
"fontsize_pt_to_cm",
|
|
55
|
+
"fontsize_cm_to_pt",
|
|
56
|
+
"markersize_to_msize",
|
|
57
|
+
"msize_to_markersize",
|
|
58
|
+
"capsize_pt_to_cm",
|
|
59
|
+
"capsize_cm_to_pt",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
# 1 inch = 2.54 cm (exact, by definition).
|
|
63
|
+
INCH_TO_CM = 2.54
|
|
64
|
+
|
|
65
|
+
# points -> cm for line widths, as used by GLEWriter.add_line et al.
|
|
66
|
+
# 1 point = 1/72 inch = 2.54/72 cm = 0.035277... cm, rounded here to 0.03528.
|
|
67
|
+
LINEWIDTH_PT_TO_CM_FACTOR = 0.03528
|
|
68
|
+
|
|
69
|
+
# points -> cm divisor for font/text height (``set hei``), as used by
|
|
70
|
+
# GLEWriter.add_preamble and GLEWriter.add_text_annotation. 28.35 points/cm
|
|
71
|
+
# is the conventional PostScript approximation (72 pt/in / 2.54 cm/in = 28.346...).
|
|
72
|
+
FONTSIZE_PT_TO_CM_DIVISOR = 28.35
|
|
73
|
+
|
|
74
|
+
# matplotlib markersize/scatter-size -> GLE msize factor (before msize_scale),
|
|
75
|
+
# as used by Axes.plot, Axes.errorbar, Axes.errorbar_from_file.
|
|
76
|
+
MARKERSIZE_TO_MSIZE_FACTOR = 0.025
|
|
77
|
+
|
|
78
|
+
# matplotlib capsize (points) -> GLE errwidth/herrwidth (cm), as used by
|
|
79
|
+
# Axes.errorbar and Axes.errorbar_from_file. Distinct rounding of 1/72*2.54
|
|
80
|
+
# from LINEWIDTH_PT_TO_CM_FACTOR -- see module docstring; preserved verbatim.
|
|
81
|
+
CAPSIZE_PT_TO_CM_FACTOR = 0.0353
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _snap(value: float) -> float:
|
|
85
|
+
"""Snap a float to 12 significant digits.
|
|
86
|
+
|
|
87
|
+
Applied to every inverse-direction conversion (cm -> pt, msize ->
|
|
88
|
+
markersize, cm -> inches on request): the forward/backward float op
|
|
89
|
+
pairs are not bit-exact for every input (deltas ~1e-14 to 1e-16),
|
|
90
|
+
and round-trip identity checks in the parser compare model values
|
|
91
|
+
exactly. 12 significant digits is far beyond any UI-entered
|
|
92
|
+
precision while safely absorbing the noise.
|
|
93
|
+
"""
|
|
94
|
+
return float(f"{value:.12g}")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def inches_to_cm(inches: float) -> float:
|
|
98
|
+
"""Convert inches to centimeters (figure ``figsize`` -> GLE ``size``)."""
|
|
99
|
+
return inches * INCH_TO_CM
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def cm_to_inches(cm: float) -> float:
|
|
103
|
+
"""Convert centimeters to inches (GLE ``size`` -> figure ``figsize``).
|
|
104
|
+
|
|
105
|
+
Inverse of :func:`inches_to_cm`, snapped to 12 significant digits
|
|
106
|
+
for uniformity with the other inverse-direction conversions (the
|
|
107
|
+
2.54 pair happens to be bit-exact for common values, but the snap
|
|
108
|
+
makes the guarantee unconditional).
|
|
109
|
+
"""
|
|
110
|
+
return _snap(cm / INCH_TO_CM)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def linewidth_pt_to_cm(points: float) -> float:
|
|
114
|
+
"""Convert a matplotlib line width in points to GLE ``lwidth`` cm.
|
|
115
|
+
|
|
116
|
+
Uses :data:`LINEWIDTH_PT_TO_CM_FACTOR` (``0.03528``), matching
|
|
117
|
+
``GLEWriter.add_line``/``add_errorbar_series``/``add_file_series``.
|
|
118
|
+
"""
|
|
119
|
+
return points * LINEWIDTH_PT_TO_CM_FACTOR
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def linewidth_cm_to_pt(cm: float) -> float:
|
|
123
|
+
"""Convert a GLE ``lwidth`` value in cm back to points.
|
|
124
|
+
|
|
125
|
+
Inverse of :func:`linewidth_pt_to_cm`, snapped to 12 significant
|
|
126
|
+
digits (see the module note on inverse-direction snapping).
|
|
127
|
+
"""
|
|
128
|
+
return _snap(cm / LINEWIDTH_PT_TO_CM_FACTOR)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def fontsize_pt_to_cm(points: float) -> float:
|
|
132
|
+
"""Convert a font size in points to a GLE ``set hei`` value in cm.
|
|
133
|
+
|
|
134
|
+
Uses :data:`FONTSIZE_PT_TO_CM_DIVISOR` (``28.35``), matching
|
|
135
|
+
``GLEWriter.add_preamble``/``add_text_annotation``.
|
|
136
|
+
"""
|
|
137
|
+
return points / FONTSIZE_PT_TO_CM_DIVISOR
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def fontsize_cm_to_pt(cm: float) -> float:
|
|
141
|
+
"""Convert a GLE ``set hei`` value in cm back to points.
|
|
142
|
+
|
|
143
|
+
Inverse of :func:`fontsize_pt_to_cm`, snapped to 12 significant
|
|
144
|
+
digits: the divide/multiply pair is not bit-exact for every value
|
|
145
|
+
(e.g. 1.5pt round-trips to 1.5000000000000002 unsnapped).
|
|
146
|
+
"""
|
|
147
|
+
return _snap(cm * FONTSIZE_PT_TO_CM_DIVISOR)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def markersize_to_msize(markersize: float, msize_scale: float = 1.0) -> float:
|
|
151
|
+
"""Convert a matplotlib marker size to a GLE ``msize`` value.
|
|
152
|
+
|
|
153
|
+
Formula: ``msize = markersize * 0.025 * msize_scale``, matching
|
|
154
|
+
``Axes.plot``/``Axes.errorbar``/``Axes.errorbar_from_file``.
|
|
155
|
+
|
|
156
|
+
Parameters
|
|
157
|
+
----------
|
|
158
|
+
markersize : float
|
|
159
|
+
Matplotlib-convention marker size (e.g. 6 by default).
|
|
160
|
+
msize_scale : float
|
|
161
|
+
Figure/marker-config scale factor (``GLEMarkerConfig.msize_scale``),
|
|
162
|
+
explicit here rather than implicit global state.
|
|
163
|
+
"""
|
|
164
|
+
return markersize * MARKERSIZE_TO_MSIZE_FACTOR * msize_scale
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def msize_to_markersize(msize: float, msize_scale: float = 1.0) -> float:
|
|
168
|
+
"""Convert a GLE ``msize`` value back to a matplotlib marker size.
|
|
169
|
+
|
|
170
|
+
Inverse of :func:`markersize_to_msize` for the same ``msize_scale``,
|
|
171
|
+
snapped to 12 significant digits: the multiply/divide pair is not
|
|
172
|
+
bit-exact for every scale factor (e.g. msize_scale=1.5 leaves ~1e-14
|
|
173
|
+
of float noise) and round-trip identity checks compare exactly.
|
|
174
|
+
"""
|
|
175
|
+
return _snap(msize / (MARKERSIZE_TO_MSIZE_FACTOR * msize_scale))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def capsize_pt_to_cm(points: float) -> float:
|
|
179
|
+
"""Convert a matplotlib error-bar cap size in points to GLE cm.
|
|
180
|
+
|
|
181
|
+
Uses :data:`CAPSIZE_PT_TO_CM_FACTOR` (``0.0353``), matching
|
|
182
|
+
``Axes.errorbar``/``Axes.errorbar_from_file``. This is a *different*
|
|
183
|
+
rounding of 1 pt in cm than :func:`linewidth_pt_to_cm` uses -- both are
|
|
184
|
+
preserved verbatim from their respective call sites (see module
|
|
185
|
+
docstring); do not consolidate them.
|
|
186
|
+
"""
|
|
187
|
+
return points * CAPSIZE_PT_TO_CM_FACTOR
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def capsize_cm_to_pt(cm: float) -> float:
|
|
191
|
+
"""Convert a GLE error-bar cap width in cm back to matplotlib points.
|
|
192
|
+
|
|
193
|
+
Inverse of :func:`capsize_pt_to_cm`, snapped to 12 significant
|
|
194
|
+
digits (see :func:`_snap`).
|
|
195
|
+
"""
|
|
196
|
+
return _snap(cm / CAPSIZE_PT_TO_CM_FACTOR)
|
gleplot/py.typed
ADDED
|
File without changes
|