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/palettes.py ADDED
@@ -0,0 +1,243 @@
1
+ """Colormap names and the GLE palette routines that draw them.
2
+
3
+ GLE draws every colormap gleplot writes. ``gray`` is ``colormap``'s default
4
+ and ``rainbow`` its ``color`` switch. ``viridis``, ``magma``, ``inferno``,
5
+ ``plasma`` and ``cividis`` are the routines of the same names in GLE's
6
+ ``palettes.gle``, ``coolwarm`` is ``palette_blue_white_red`` from its
7
+ ``color.gle``, and the ColorBrewer maps are the largest palette of each name
8
+ in its ``brewer.gle`` (``Set1Qual9``, ``BluesSeq9``, ``RdBuDiv11``, ...). A
9
+ script includes the file a routine is in.
10
+
11
+ A palette is called through a wrapper sub, ``cmap_<name>``
12
+ (:func:`palette_sub_text`): GLE passes a palette its value unclamped, and the
13
+ ``palettes.gle`` routines fail outside [0, 1], so the wrapper clamps it first.
14
+ A reversed map (``_r``) is the wrapper of the forward routine at ``1-z``, so a
15
+ colorbar, which takes only the palette's name, draws it reversed too.
16
+ ``gray_r`` is a wrapper returning ``rgb`` itself, and ``gray`` gets one where
17
+ a value is coloured outside a ``colormap`` (per-point colours, ``contourf``
18
+ bands).
19
+
20
+ A ``brewer.gle`` routine takes a colour's number, 1 to N, and returns its
21
+ name, which the wrapper converts with ``cvtcolor``. For a qualitative map
22
+ (``Set1``, ``Paired``, ...) the number is the class ``z`` falls in, as
23
+ matplotlib draws it. matplotlib draws the sequential and diverging maps as a
24
+ continuous blend of the same 9 or 11 colours; the wrapper takes the nearest.
25
+
26
+ ``rainbow_r`` (and ``jet_r``), and ``rainbow`` where no ``colormap`` draws it,
27
+ are drawn with the closest native map (:func:`native_cmap`), which the call
28
+ warns about.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ from typing import Dict, Optional, Tuple
34
+
35
+ __all__ = [
36
+ "SUPPORTED_CMAPS",
37
+ "NATIVE_CMAPS",
38
+ "canonical_cmap",
39
+ "native_cmap",
40
+ "is_native",
41
+ "colorbar_cmap",
42
+ "cmap_needs_sub",
43
+ "palette_sub_name",
44
+ "palette_call_name",
45
+ "palette_include",
46
+ "palette_sub_text",
47
+ ]
48
+
49
+
50
+ #: The gleinc file whose ``color_range_vertical``/``_horizontal`` draw a
51
+ #: colorbar (``GLEWriter.add_colorbar``), and ``palette_blue_white_red`` the
52
+ #: ``coolwarm`` map.
53
+ COLOR_INCLUDE = "color.gle"
54
+
55
+ #: The gleinc file whose routines draw ``viridis``, ``magma``, ``inferno``,
56
+ #: ``plasma`` and ``cividis``.
57
+ PALETTES_INCLUDE = "palettes.gle"
58
+
59
+ #: The gleinc file whose routines draw the ColorBrewer maps.
60
+ BREWER_INCLUDE = "brewer.gle"
61
+
62
+ #: The GLE routine behind each native map that is called as a palette sub.
63
+ _ROUTINES: Dict[str, str] = {
64
+ "viridis": "viridis",
65
+ "magma": "magma",
66
+ "inferno": "inferno",
67
+ "plasma": "plasma",
68
+ "cividis": "cividis",
69
+ "coolwarm": "palette_blue_white_red",
70
+ }
71
+
72
+ #: Each ColorBrewer map gleplot accepts, its kind in ``brewer.gle`` and the
73
+ #: number of colours of the palette that draws it: the most ``brewer.gle``
74
+ #: has for the name, which is the count matplotlib's qualitative maps have.
75
+ _BREWER: Dict[str, Tuple[str, int]] = {
76
+ **dict.fromkeys(
77
+ (
78
+ "Blues BuGn BuPu GnBu Greens Greys Oranges OrRd PuBu PuBuGn PuRd "
79
+ "Purples RdPu Reds YlGn YlGnBu YlOrBr YlOrRd"
80
+ ).split(),
81
+ ("Seq", 9),
82
+ ),
83
+ **dict.fromkeys(
84
+ "BrBG PiYG PRGn PuOr RdBu RdGy RdYlBu RdYlGn Spectral".split(), ("Div", 11)
85
+ ),
86
+ **dict.fromkeys("Accent Dark2 Pastel2 Set2".split(), ("Qual", 8)),
87
+ **dict.fromkeys("Pastel1 Set1".split(), ("Qual", 9)),
88
+ **dict.fromkeys("Paired Set3".split(), ("Qual", 12)),
89
+ }
90
+ #: Canonical name -> (the ``brewer.gle`` routine, its colour count).
91
+ _BREWER_ROUTINES: Dict[str, Tuple[str, int]] = {
92
+ name.lower(): (f"{name}{kind}{n}", n) for name, (kind, n) in _BREWER.items()
93
+ }
94
+
95
+ #: The maps GLE draws: the two ``colormap`` modes and the routines above.
96
+ NATIVE_CMAPS: Tuple[str, ...] = ("gray", "rainbow", *_ROUTINES, *_BREWER_ROUTINES)
97
+
98
+ # "jet" is an alias for "rainbow" (both are GLE's built-in ``color`` rainbow);
99
+ # it is canonicalized to "rainbow" at store time so the object model only ever
100
+ # holds canonical names.
101
+ _CMAP_ALIASES: Dict[str, str] = {"jet": "rainbow"}
102
+
103
+ #: Every cmap name accepted by ``imshow``/``tripcolor`` (before alias
104
+ #: canonicalization), each also accepted with ``_r`` appended for its reversed
105
+ #: form. Names are matched case-insensitively; canonical names are lowercase.
106
+ SUPPORTED_CMAPS: Tuple[str, ...] = (
107
+ "gray",
108
+ "rainbow",
109
+ "jet",
110
+ *_ROUTINES,
111
+ *_BREWER,
112
+ )
113
+
114
+ _CANONICAL_CMAPS = frozenset(
115
+ _CMAP_ALIASES.get(c.lower(), c.lower()) for c in SUPPORTED_CMAPS
116
+ )
117
+
118
+
119
+ def canonical_cmap(cmap: str) -> str:
120
+ """Canonicalize a user-facing cmap name (lowercase; ``jet`` -> ``rainbow``).
121
+
122
+ A reversed name keeps its suffix: ``RdBu_r`` -> ``rdbu_r``,
123
+ ``jet_r`` -> ``rainbow_r``.
124
+
125
+ Raises
126
+ ------
127
+ ValueError
128
+ If ``cmap`` is not one of :data:`SUPPORTED_CMAPS`, with or without
129
+ ``_r`` appended.
130
+ """
131
+ key = str(cmap).strip().lower()
132
+ base, suffix = (key[:-2], "_r") if key.endswith("_r") else (key, "")
133
+ base = _CMAP_ALIASES.get(base, base)
134
+ if base not in _CANONICAL_CMAPS:
135
+ supported = ", ".join(SUPPORTED_CMAPS)
136
+ raise ValueError(
137
+ f"Unknown cmap {cmap!r}; supported palettes (any case, and each "
138
+ f"with '_r' appended for its reversed form): {supported}"
139
+ )
140
+ return base + suffix
141
+
142
+
143
+ def native_cmap(cmap: str, sub: bool = False) -> str:
144
+ """The native map GLE draws for ``cmap``: itself, or the closest one.
145
+
146
+ ``sub`` is true where the map is called as a palette sub (per-point
147
+ colours, ``contourf`` bands) rather than drawn by a ``colormap``, which
148
+ leaves out ``rainbow``: GLE has it only as ``colormap``'s ``color``
149
+ switch. It is then drawn as ``viridis``. A result other than the
150
+ canonical ``cmap`` is a fallback the caller warns about.
151
+ """
152
+ c = canonical_cmap(cmap)
153
+ if c == "rainbow_r":
154
+ c = "rainbow"
155
+ if sub and c == "rainbow":
156
+ c = "viridis"
157
+ return c
158
+
159
+
160
+ def is_native(cmap: str, sub: bool = False) -> bool:
161
+ """True if ``cmap`` is a canonical name GLE draws as it is."""
162
+ try:
163
+ return native_cmap(cmap, sub) == cmap
164
+ except ValueError:
165
+ return False
166
+
167
+
168
+ def cmap_needs_sub(cmap: str) -> bool:
169
+ """True if a ``colormap`` in ``cmap`` (native) calls a ``cmap_<name>`` sub.
170
+
171
+ ``gray`` (grayscale default) and ``rainbow`` (built-in ``color``) do not.
172
+ """
173
+ return cmap not in ("gray", "rainbow")
174
+
175
+
176
+ def palette_sub_name(cmap: str) -> str:
177
+ """The wrapper sub that colours a value in ``cmap`` (native)."""
178
+ return f"cmap_{cmap}"
179
+
180
+
181
+ def palette_call_name(cmap: str) -> str:
182
+ """The ``palette$`` value passed to the colorbar sub for ``cmap`` (native).
183
+
184
+ ``gray`` -> ``"gray"`` (grayscale branch), ``rainbow`` -> ``"color"``
185
+ (GLE built-in rainbow branch), everything else its wrapper sub.
186
+ """
187
+ if cmap == "gray":
188
+ return "gray"
189
+ if cmap == "rainbow":
190
+ return "color"
191
+ return palette_sub_name(cmap)
192
+
193
+
194
+ def palette_include(cmap: str) -> Optional[str]:
195
+ """The gleinc file holding the routine ``cmap``'s wrapper calls, if any."""
196
+ base = cmap[:-2] if cmap.endswith("_r") else cmap
197
+ if base in _BREWER_ROUTINES:
198
+ return BREWER_INCLUDE
199
+ if base not in _ROUTINES:
200
+ return None
201
+ return COLOR_INCLUDE if base == "coolwarm" else PALETTES_INCLUDE
202
+
203
+
204
+ def colorbar_cmap(cmap: str, invert: bool) -> str:
205
+ """The cmap a colorbar draws for an image in ``cmap`` (native).
206
+
207
+ GLE's ``colormap ... invert`` flips only the image, so the bar of an
208
+ inverted image draws the reversed palette (``viridis`` <-> ``viridis_r``)
209
+ to match it. Without ``invert`` it is ``cmap`` unchanged; ``rainbow`` has
210
+ no reversed form and stays as it is.
211
+ """
212
+ if not invert or cmap == "rainbow":
213
+ return cmap
214
+ return cmap[:-2] if cmap.endswith("_r") else cmap + "_r"
215
+
216
+
217
+ def palette_sub_text(cmap: str) -> str:
218
+ """The ``sub cmap_<name> z ... end sub`` wrapper for ``cmap`` (native).
219
+
220
+ It clamps ``z`` to [0, 1], reverses it for an ``_r`` map, and calls the
221
+ GLE routine (:func:`palette_include` names its file); ``gray`` and
222
+ ``gray_r`` return the ``rgb`` grey, and a ColorBrewer map the colour of
223
+ the class ``z`` is in. ``rainbow`` has none.
224
+ """
225
+ base, rev = (cmap[:-2], True) if cmap.endswith("_r") else (cmap, False)
226
+ clamped = "max(0,min(1,z))"
227
+ z = f"1-{clamped}" if rev else clamped
228
+ if base == "gray":
229
+ body = f" local g = {z}\n return rgb(g,g,g)"
230
+ elif base in _BREWER_ROUTINES:
231
+ routine, n = _BREWER_ROUTINES[base]
232
+ # The 0-based colour: matplotlib's class for a qualitative map, the
233
+ # nearest of its n blended colours for the others. A reversed map
234
+ # counts it from the other end, as matplotlib reverses the list.
235
+ if "Qual" in routine:
236
+ k = f"min({n - 1},int({clamped}*{n}))"
237
+ else:
238
+ k = f"int({clamped}*{n - 1}+0.5)"
239
+ index = f"{n}-{k}" if rev else f"{k}+1"
240
+ body = f" return cvtcolor({routine}({index}))"
241
+ else:
242
+ body = f" return {_ROUTINES[base]}({z})"
243
+ return f"sub {palette_sub_name(cmap)} z\n{body}\nend sub"
@@ -0,0 +1,83 @@
1
+ """Core GLE-parsing package for gleplot (Track A1: lexer, syntax, expr).
2
+
3
+ This package turns ``.gle`` source text into a structural document tree with
4
+ byte-exact passthrough, ready for a semantic mapper (a separate track) to
5
+ interpret. It contains **no Qt imports** and depends only on the standard
6
+ library, so it is safe to use from any layer.
7
+
8
+ The prime directive is round-trip fidelity: ``emit(parse_gle_source(text))``
9
+ reproduces ``text`` byte-for-byte when nothing has been modified.
10
+
11
+ Public entry points (this track's modules only)::
12
+
13
+ from gleplot.parser import parse_gle_source, emit, GleDocument
14
+ from gleplot.parser import tokenize_line, Token, TokenType
15
+ from gleplot.parser import eval_gle_number, format_gle_number
16
+
17
+ Other modules in this package (``tables``, ``units``, ``metadata``) are owned
18
+ by a parallel track and are intentionally *not* re-exported here.
19
+ """
20
+
21
+ from .expr import eval_gle_number, format_gle_number
22
+ from .lexer import Token, TokenType, tokenize_line
23
+ from .syntax import (
24
+ BlankOrComment,
25
+ GleDocument,
26
+ GraphBlock,
27
+ Node,
28
+ OpaqueBlock,
29
+ ParseWarning,
30
+ SourceLine,
31
+ Statement,
32
+ emit,
33
+ parse_gle_source,
34
+ split_statements,
35
+ )
36
+
37
+ __all__ = [
38
+ # lexer
39
+ "Token",
40
+ "TokenType",
41
+ "tokenize_line",
42
+ # expr
43
+ "eval_gle_number",
44
+ "format_gle_number",
45
+ # syntax
46
+ "SourceLine",
47
+ "Statement",
48
+ "GraphBlock",
49
+ "OpaqueBlock",
50
+ "BlankOrComment",
51
+ "Node",
52
+ "ParseWarning",
53
+ "GleDocument",
54
+ "parse_gle_source",
55
+ "emit",
56
+ "split_statements",
57
+ # recognizer (Track B1) -- lazily loaded (see __getattr__) to avoid a
58
+ # circular import: the recognizer depends on gleplot.figure/axes, which in
59
+ # turn import gleplot.parser.units at package-init time.
60
+ "RecognizedFigure",
61
+ "parse_gle_figure",
62
+ # import report (GLEstudio plan G4) -- pure dataclass/enum, no cycle, but
63
+ # grouped and lazily loaded alongside the recognizer symbols they back
64
+ # since they are meaningless without it.
65
+ "ImportCategory",
66
+ "ImportNote",
67
+ ]
68
+
69
+ _RECOGNIZER_NAMES = ("RecognizedFigure", "parse_gle_figure")
70
+ _REPORT_NAMES = ("ImportCategory", "ImportNote")
71
+
72
+
73
+ def __getattr__(name):
74
+ """Lazily expose the recognizer (+ report) symbols without an import cycle."""
75
+ if name in _RECOGNIZER_NAMES:
76
+ from . import recognizer
77
+
78
+ return getattr(recognizer, name)
79
+ if name in _REPORT_NAMES:
80
+ from . import report
81
+
82
+ return getattr(report, name)
83
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
gleplot/parser/expr.py ADDED
@@ -0,0 +1,196 @@
1
+ """Safe arithmetic evaluator for GLE numeric expressions.
2
+
3
+ This is a tiny recursive-descent evaluator over the tokens produced by
4
+ :mod:`gleplot.parser.lexer`. It exists so the semantic mapper can turn a token
5
+ run such as ``2 * pi`` or ``(1 + 3) / 2`` into a concrete float *without ever
6
+ calling* :func:`eval`. Anything it cannot evaluate to a plain number -- a
7
+ function call like ``sin(x)``, a variable reference, a dataset expression --
8
+ yields ``None``, signalling the caller to treat that statement as opaque
9
+ passthrough.
10
+
11
+ Grammar (standard precedence, ``^`` right-associative)::
12
+
13
+ expr := term (('+' | '-') term)*
14
+ term := power (('*' | '/') power)*
15
+ power := unary ('^' power)? # right-assoc
16
+ unary := ('+' | '-') unary | atom
17
+ atom := NUMBER | CONST | '(' expr ')'
18
+
19
+ Recognised constants (case-insensitive): ``pi``, ``e``.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import math
25
+ from typing import List, Optional, Union
26
+
27
+ from .lexer import Token, TokenType, tokenize_line
28
+
29
+ # Case-insensitive named constants.
30
+ _CONSTANTS = {
31
+ "pi": math.pi,
32
+ "e": math.e,
33
+ }
34
+
35
+
36
+ class _EvalError(Exception):
37
+ """Internal sentinel: expression is not a pure number. Never escapes."""
38
+
39
+
40
+ def eval_gle_number(tokens_or_str: Union[str, List[Token]]) -> Optional[float]:
41
+ """Evaluate an arithmetic expression to a float, or return ``None``.
42
+
43
+ Parameters
44
+ ----------
45
+ tokens_or_str:
46
+ Either a raw source fragment (which will be tokenised) or a list of
47
+ :class:`~gleplot.parser.lexer.Token` already produced by the lexer.
48
+
49
+ Returns
50
+ -------
51
+ float or None
52
+ The evaluated value, or ``None`` if the input is empty, references an
53
+ unknown identifier / function, contains a syntax error, or otherwise
54
+ is not a closed-form arithmetic constant expression. ``None`` is the
55
+ caller's cue to keep the statement as verbatim passthrough.
56
+ """
57
+ if isinstance(tokens_or_str, str):
58
+ tokens = tokenize_line(tokens_or_str)
59
+ else:
60
+ tokens = list(tokens_or_str)
61
+
62
+ # Drop trailing comments -- an inline comment does not invalidate a number.
63
+ tokens = [t for t in tokens if t.type is not TokenType.COMMENT]
64
+
65
+ if not tokens:
66
+ return None
67
+
68
+ parser = _ExprParser(tokens)
69
+ try:
70
+ value = parser.parse_expr()
71
+ parser.expect_end()
72
+ except _EvalError:
73
+ return None
74
+ if not math.isfinite(value):
75
+ # Division by zero / overflow: not a usable literal.
76
+ return None
77
+ return value
78
+
79
+
80
+ class _ExprParser:
81
+ """Recursive-descent parser/evaluator over a token list."""
82
+
83
+ def __init__(self, tokens: List[Token]):
84
+ self._tokens = tokens
85
+ self._pos = 0
86
+
87
+ # -- token cursor helpers ------------------------------------------------
88
+
89
+ def _peek(self) -> Optional[Token]:
90
+ if self._pos < len(self._tokens):
91
+ return self._tokens[self._pos]
92
+ return None
93
+
94
+ def _advance(self) -> Token:
95
+ tok = self._tokens[self._pos]
96
+ self._pos += 1
97
+ return tok
98
+
99
+ def _at_op(self, *ops: str) -> bool:
100
+ tok = self._peek()
101
+ return tok is not None and tok.type is TokenType.OP and tok.value in ops
102
+
103
+ def expect_end(self) -> None:
104
+ if self._pos != len(self._tokens):
105
+ raise _EvalError()
106
+
107
+ # -- grammar -------------------------------------------------------------
108
+
109
+ def parse_expr(self) -> float:
110
+ value = self._parse_term()
111
+ while self._at_op("+", "-"):
112
+ op = self._advance().value
113
+ rhs = self._parse_term()
114
+ value = value + rhs if op == "+" else value - rhs
115
+ return value
116
+
117
+ def _parse_term(self) -> float:
118
+ value = self._parse_power()
119
+ while self._at_op("*", "/"):
120
+ op = self._advance().value
121
+ rhs = self._parse_power()
122
+ if op == "*":
123
+ value = value * rhs
124
+ else:
125
+ if rhs == 0:
126
+ raise _EvalError()
127
+ value = value / rhs
128
+ return value
129
+
130
+ def _parse_power(self) -> float:
131
+ base = self._parse_unary()
132
+ if self._at_op("^"):
133
+ self._advance()
134
+ # Right-associative: recurse into power for the exponent.
135
+ exponent = self._parse_power()
136
+ try:
137
+ return math.pow(base, exponent)
138
+ except (ValueError, OverflowError):
139
+ raise _EvalError()
140
+ return base
141
+
142
+ def _parse_unary(self) -> float:
143
+ if self._at_op("+", "-"):
144
+ op = self._advance().value
145
+ operand = self._parse_unary()
146
+ return operand if op == "+" else -operand
147
+ return self._parse_atom()
148
+
149
+ def _parse_atom(self) -> float:
150
+ tok = self._peek()
151
+ if tok is None:
152
+ raise _EvalError()
153
+
154
+ if tok.type is TokenType.NUMBER:
155
+ self._advance()
156
+ try:
157
+ return float(tok.value)
158
+ except ValueError: # pragma: no cover - lexer guarantees validity
159
+ raise _EvalError()
160
+
161
+ if tok.type is TokenType.WORD:
162
+ key = tok.value.lower()
163
+ if key in _CONSTANTS:
164
+ self._advance()
165
+ # Reject a following '(' -- that would be a function call.
166
+ if self._at_op("("):
167
+ raise _EvalError()
168
+ return _CONSTANTS[key]
169
+ # Unknown identifier (variable or function name) -> not a number.
170
+ raise _EvalError()
171
+
172
+ if tok.type is TokenType.OP and tok.value == "(":
173
+ self._advance()
174
+ value = self.parse_expr()
175
+ if not self._at_op(")"):
176
+ raise _EvalError()
177
+ self._advance()
178
+ return value
179
+
180
+ raise _EvalError()
181
+
182
+
183
+ def format_gle_number(value: float) -> str:
184
+ """Format a float the way the GLE writer does (``.6g``).
185
+
186
+ Mirrors ``GLEWriter._format_number`` conventions so numbers regenerated by
187
+ the semantic layer match the writer's output. Very small magnitudes snap to
188
+ ``'0'`` and very large ones use scientific notation, matching the writer.
189
+ """
190
+ if isinstance(value, (int, float)):
191
+ if abs(value) < 1e-10:
192
+ return "0"
193
+ if abs(value) > 1e10:
194
+ return f"{value:.3e}"
195
+ return f"{value:.6g}"
196
+ return str(value)