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/sources.py
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
"""Where a series' numbers come from: the ``data_source`` abstraction.
|
|
2
|
+
|
|
3
|
+
Historically every series baked its numpy arrays into itself at ``plot()``
|
|
4
|
+
time, and that is still exactly what the scripting API does. This module adds
|
|
5
|
+
the *other* possibility -- a series that holds a **reference** into a table
|
|
6
|
+
owned by something outside the figure (an external table store, a watched file,
|
|
7
|
+
a database query) and is resolved to concrete arrays only when the ``.gle``
|
|
8
|
+
is written.
|
|
9
|
+
|
|
10
|
+
The three source kinds
|
|
11
|
+
----------------------
|
|
12
|
+
|
|
13
|
+
:class:`InlineData`
|
|
14
|
+
The arrays live on the series itself (``series["x"]``, ``series["y"]``,
|
|
15
|
+
...). This is the default and the **implied legacy form**: a series with
|
|
16
|
+
no ``data_source`` key at all *is* an ``InlineData`` series, which is why
|
|
17
|
+
a project written before this module existed loads unchanged and why
|
|
18
|
+
``Figure.to_dict()`` of a scripted figure still produces the historical
|
|
19
|
+
per-series shape byte for byte.
|
|
20
|
+
|
|
21
|
+
:class:`ColumnRef`
|
|
22
|
+
Columnar data: a ``table_id`` plus one column key per *series role*
|
|
23
|
+
(``{'x': ..., 'y': ...}`` for a line, ``{'x': ..., 'height': ...}`` for
|
|
24
|
+
a bar, ``{'x': ..., 'y': ..., 'yerr_up': ...}`` for an errorbar, ...).
|
|
25
|
+
The role names are the series class's own ``ARRAY_FIELDS``, so one
|
|
26
|
+
generic resolver covers every kind and a new kind needs no new code here.
|
|
27
|
+
|
|
28
|
+
:class:`GridRef`
|
|
29
|
+
The same thing for gridded data (heatmaps and contours): a role may map
|
|
30
|
+
to a *list* of column keys, which resolves to a 2-D array built by
|
|
31
|
+
stacking those columns (the ``z`` grid). Scattered-sample grid series
|
|
32
|
+
(``source='points'``) use the plain one-key-per-role form for
|
|
33
|
+
``x``/``y``/``zpts``.
|
|
34
|
+
|
|
35
|
+
Identity and renaming
|
|
36
|
+
---------------------
|
|
37
|
+
|
|
38
|
+
``table_id`` is an opaque, stable identity (a UUID in GLEstudio) and a column
|
|
39
|
+
key is likewise stable; the column's *display name* is a property of the
|
|
40
|
+
table, not of the reference. Renaming a table or a column therefore never
|
|
41
|
+
breaks a reference -- the reference does not mention the name. The display
|
|
42
|
+
name is used for one thing only: the header row of the ``.dat`` sidecar.
|
|
43
|
+
|
|
44
|
+
Dangling references never crash a write
|
|
45
|
+
---------------------------------------
|
|
46
|
+
|
|
47
|
+
A reference can go bad: the table was deleted, a watched file came back
|
|
48
|
+
without the column, or the figure is being written with no provider at all.
|
|
49
|
+
None of that is an error at write time. The affected series is **skipped**
|
|
50
|
+
and a :class:`DanglingSourceRef` -- a structured, inspectable record, not a
|
|
51
|
+
string -- is produced for it. A figure whose every series is dangling still
|
|
52
|
+
writes a valid (empty) ``.gle``. See ``gleplot.writer.resolve_figure`` for
|
|
53
|
+
the resolution pass and ``Figure.source_warnings`` for where the records
|
|
54
|
+
surface.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
from typing import (
|
|
58
|
+
Any,
|
|
59
|
+
Dict,
|
|
60
|
+
Iterable,
|
|
61
|
+
List,
|
|
62
|
+
Mapping,
|
|
63
|
+
Optional,
|
|
64
|
+
Protocol,
|
|
65
|
+
Sequence,
|
|
66
|
+
Tuple,
|
|
67
|
+
Union,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
import numpy as np
|
|
71
|
+
|
|
72
|
+
__all__ = [
|
|
73
|
+
"DataSource",
|
|
74
|
+
"InlineData",
|
|
75
|
+
"ColumnRef",
|
|
76
|
+
"GridRef",
|
|
77
|
+
"TableData",
|
|
78
|
+
"DictDataProvider",
|
|
79
|
+
"DataProvider",
|
|
80
|
+
"ProviderTable",
|
|
81
|
+
"DanglingSourceRef",
|
|
82
|
+
"DanglingSourceWarning",
|
|
83
|
+
"source_from_dict",
|
|
84
|
+
"source_of",
|
|
85
|
+
"is_inline",
|
|
86
|
+
"resolve_reference",
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
#: A column key maps either to a single column (1-D) or, for a ``z`` grid, to
|
|
90
|
+
#: an ordered list of columns stacked into a 2-D array.
|
|
91
|
+
ColumnKey = str
|
|
92
|
+
RoleSpec = Union[ColumnKey, List[ColumnKey]]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# -- the source classes -------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class DataSource(Dict[str, Any]):
|
|
99
|
+
"""Base class for the three source kinds.
|
|
100
|
+
|
|
101
|
+
Like :class:`gleplot.series.Series`, a ``dict`` **subclass** holding all
|
|
102
|
+
of its state as items and none as instance attributes. That is what makes
|
|
103
|
+
a source free to serialize (``_to_jsonable`` already turns any mapping
|
|
104
|
+
into a plain dict), free to ``copy``/``deepcopy``/pickle, and free to
|
|
105
|
+
compare -- the same reasoning that governs the series classes, applied one
|
|
106
|
+
level down.
|
|
107
|
+
|
|
108
|
+
``kind`` is always the first item, so the serialized key order is stable.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
#: Discriminator written as the ``kind`` item and read by
|
|
112
|
+
#: :func:`source_from_dict`.
|
|
113
|
+
KIND: str = ""
|
|
114
|
+
|
|
115
|
+
def __init__(self, **fields: Any) -> None:
|
|
116
|
+
super().__init__(kind=self.KIND, **fields)
|
|
117
|
+
|
|
118
|
+
def __getattr__(self, name: str) -> Any:
|
|
119
|
+
try:
|
|
120
|
+
return self[name]
|
|
121
|
+
except KeyError:
|
|
122
|
+
raise AttributeError(
|
|
123
|
+
f"{type(self).__name__!r} has no attribute {name!r}"
|
|
124
|
+
) from None
|
|
125
|
+
|
|
126
|
+
def __repr__(self) -> str:
|
|
127
|
+
return f"{type(self).__name__}({dict.__repr__(self)})"
|
|
128
|
+
|
|
129
|
+
def is_reference(self) -> bool:
|
|
130
|
+
"""True for the kinds that need a :class:`DataProvider` to resolve."""
|
|
131
|
+
return False
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class InlineData(DataSource):
|
|
135
|
+
"""The arrays are baked into the series itself.
|
|
136
|
+
|
|
137
|
+
Carries no state beyond its discriminator: everything it "holds" is
|
|
138
|
+
already on the series. Constructing one is therefore optional --
|
|
139
|
+
:func:`source_of` returns an ``InlineData`` for any series that has no
|
|
140
|
+
``data_source`` key, which is what keeps the scripting API's output
|
|
141
|
+
(and its serialized form) unchanged.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
KIND = "inline"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class _TableRef(DataSource):
|
|
148
|
+
"""Shared implementation of the two provider-backed kinds.
|
|
149
|
+
|
|
150
|
+
``columns`` maps a series *role* -- one of the series class's
|
|
151
|
+
``ARRAY_FIELDS`` -- onto the stable key of the table column that supplies
|
|
152
|
+
it. Roles the series has but the mapping omits are left alone, so an
|
|
153
|
+
errorbar can reference ``x``/``y`` from a table while keeping constant or
|
|
154
|
+
absent error columns.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
def __init__(self, table_id: str, columns: Mapping[str, RoleSpec]) -> None:
|
|
158
|
+
super().__init__(table_id=str(table_id), columns=dict(columns))
|
|
159
|
+
|
|
160
|
+
def is_reference(self) -> bool:
|
|
161
|
+
return True
|
|
162
|
+
|
|
163
|
+
def column_keys(self) -> List[ColumnKey]:
|
|
164
|
+
"""Every column key this reference mentions, in role order, deduped."""
|
|
165
|
+
keys: List[ColumnKey] = []
|
|
166
|
+
for spec in self["columns"].values():
|
|
167
|
+
for key in spec if isinstance(spec, list) else [spec]:
|
|
168
|
+
if key not in keys:
|
|
169
|
+
keys.append(key)
|
|
170
|
+
return keys
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class ColumnRef(_TableRef):
|
|
174
|
+
"""Columnar data pulled from a provider table.
|
|
175
|
+
|
|
176
|
+
``ColumnRef('t1', {'x': 'time', 'y': 'signal'})`` says: my x column is
|
|
177
|
+
the table column whose stable key is ``'time'``, my y column is
|
|
178
|
+
``'signal'``. Two series referencing the same ``table_id`` share one
|
|
179
|
+
``.dat`` sidecar holding the union of the columns they mention.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
KIND = "column-ref"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class GridRef(_TableRef):
|
|
186
|
+
"""Gridded data pulled from a provider table.
|
|
187
|
+
|
|
188
|
+
Two shapes, matching the two ``HeatmapSeries``/``ContourSeries`` grid
|
|
189
|
+
modes (the series' own ``source`` field, which predates this module and
|
|
190
|
+
is unrelated to ``data_source``):
|
|
191
|
+
|
|
192
|
+
- ``source='grid'``: ``GridRef('t1', {'z': ['c0', 'c1', 'c2']})`` --
|
|
193
|
+
the listed columns are stacked left-to-right into the 2-D ``z`` grid,
|
|
194
|
+
so a table laid out like a spreadsheet resolves to the grid it looks
|
|
195
|
+
like.
|
|
196
|
+
- ``source='points'``: ``GridRef('t1', {'x': ..., 'y': ..., 'zpts': ...})``
|
|
197
|
+
-- scattered samples, one key per role, gridded by GLE's ``fitz``.
|
|
198
|
+
|
|
199
|
+
Grid series write their own raw ``.z``/points sidecar per series (that is
|
|
200
|
+
what GLE's ``colormap``/``fitz`` read), so unlike :class:`ColumnRef` they
|
|
201
|
+
never share a sidecar.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
KIND = "grid-ref"
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
_SOURCE_CLASSES = {cls.KIND: cls for cls in (InlineData, ColumnRef, GridRef)}
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def source_from_dict(payload: Any) -> Any:
|
|
211
|
+
"""Rebuild a :class:`DataSource` from a serialized payload.
|
|
212
|
+
|
|
213
|
+
A payload whose ``kind`` this build does not know is returned **verbatim**
|
|
214
|
+
rather than dropped or rejected: that is the same forward-compatibility
|
|
215
|
+
promise ``Series._restore`` makes for undeclared keys. Such a source is
|
|
216
|
+
treated as unresolvable at write time (a :class:`DanglingSourceRef` with
|
|
217
|
+
reason ``'unknown-kind'``), never as a crash.
|
|
218
|
+
"""
|
|
219
|
+
if isinstance(payload, DataSource):
|
|
220
|
+
return payload
|
|
221
|
+
if not isinstance(payload, Mapping):
|
|
222
|
+
return payload
|
|
223
|
+
cls = _SOURCE_CLASSES.get(str(payload.get("kind", "")))
|
|
224
|
+
if cls is InlineData:
|
|
225
|
+
return InlineData()
|
|
226
|
+
if cls is not None:
|
|
227
|
+
return cls(
|
|
228
|
+
table_id=payload.get("table_id", ""),
|
|
229
|
+
columns=payload.get("columns") or {},
|
|
230
|
+
)
|
|
231
|
+
return dict(payload)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def source_of(series: Mapping[str, Any]) -> Any:
|
|
235
|
+
"""The series' source, with a missing ``data_source`` meaning inline.
|
|
236
|
+
|
|
237
|
+
This is the single place the "absent means :class:`InlineData`" rule is
|
|
238
|
+
implemented; every consumer goes through it rather than testing for the
|
|
239
|
+
key itself.
|
|
240
|
+
"""
|
|
241
|
+
source = series.get("data_source")
|
|
242
|
+
if source is None:
|
|
243
|
+
return InlineData()
|
|
244
|
+
return source
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def is_inline(series: Mapping[str, Any]) -> bool:
|
|
248
|
+
"""True if ``series`` carries its own arrays (the scripting-API default)."""
|
|
249
|
+
source = source_of(series)
|
|
250
|
+
return not (isinstance(source, DataSource) and source.is_reference())
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# -- the provider side --------------------------------------------------------
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class ProviderTable(Protocol):
|
|
257
|
+
"""The shape :class:`DataProvider` hands back for a ``table_id``.
|
|
258
|
+
|
|
259
|
+
Deliberately behavioural rather than structural: a GLEstudio table is a
|
|
260
|
+
live, editable spreadsheet model with undo and column metadata, and
|
|
261
|
+
nothing is gained by forcing it to expose gleplot's field names. Four
|
|
262
|
+
methods is the whole contract.
|
|
263
|
+
"""
|
|
264
|
+
|
|
265
|
+
def column_keys(self) -> Sequence[ColumnKey]:
|
|
266
|
+
"""Stable keys of every column, in table order."""
|
|
267
|
+
... # pragma: no cover
|
|
268
|
+
|
|
269
|
+
def has_column(self, key: ColumnKey) -> bool:
|
|
270
|
+
"""Whether ``key`` names a column that currently exists."""
|
|
271
|
+
... # pragma: no cover
|
|
272
|
+
|
|
273
|
+
def column_name(self, key: ColumnKey) -> str:
|
|
274
|
+
"""The column's *display* name -- used only for sidecar headers."""
|
|
275
|
+
... # pragma: no cover
|
|
276
|
+
|
|
277
|
+
def column_values(self, key: ColumnKey) -> np.ndarray:
|
|
278
|
+
"""The column's values as a 1-D float array."""
|
|
279
|
+
... # pragma: no cover
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class DataProvider(Protocol):
|
|
283
|
+
"""Supplies the tables that :class:`ColumnRef`/:class:`GridRef` name.
|
|
284
|
+
|
|
285
|
+
One method. A provider is passed **at write time**
|
|
286
|
+
(``Figure.savefig(..., data_provider=...)``) and is never stored on the
|
|
287
|
+
figure: the figure is a serializable document and the provider is a live
|
|
288
|
+
application object, so binding them would make ``to_dict()`` either lossy
|
|
289
|
+
or impossible, and would stop the same figure being rendered against
|
|
290
|
+
different tables (preview vs export, or a what-if dataset).
|
|
291
|
+
"""
|
|
292
|
+
|
|
293
|
+
def get_table(self, table_id: str) -> Optional[ProviderTable]:
|
|
294
|
+
"""The table with this id, or ``None`` if there is no such table."""
|
|
295
|
+
... # pragma: no cover
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class TableData:
|
|
299
|
+
"""A concrete, in-memory :class:`ProviderTable`.
|
|
300
|
+
|
|
301
|
+
Keeps the three parallel lists a table needs: stable ``keys``, display
|
|
302
|
+
``names``, and the column ``columns`` themselves. Renaming a column means
|
|
303
|
+
changing ``names`` and leaves every reference to it intact -- which is the
|
|
304
|
+
property the whole reference model rests on, made testable here.
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
def __init__(
|
|
308
|
+
self,
|
|
309
|
+
keys: Sequence[ColumnKey],
|
|
310
|
+
names: Sequence[str],
|
|
311
|
+
columns: Sequence[Sequence[float]],
|
|
312
|
+
) -> None:
|
|
313
|
+
if not (len(keys) == len(names) == len(columns)):
|
|
314
|
+
raise ValueError(
|
|
315
|
+
f"TableData needs one name and one column per key: got "
|
|
316
|
+
f"{len(keys)} keys, {len(names)} names, {len(columns)} columns"
|
|
317
|
+
)
|
|
318
|
+
arrays = [np.asarray(col, dtype=float) for col in columns]
|
|
319
|
+
lengths = {len(col) for col in arrays}
|
|
320
|
+
if len(lengths) > 1:
|
|
321
|
+
raise ValueError(
|
|
322
|
+
f"TableData columns must all have the same length; got {sorted(lengths)}"
|
|
323
|
+
)
|
|
324
|
+
self.keys: List[ColumnKey] = [str(k) for k in keys]
|
|
325
|
+
self.names: List[str] = [str(n) for n in names]
|
|
326
|
+
self.columns: List[np.ndarray] = arrays
|
|
327
|
+
self._by_key = dict(zip(self.keys, range(len(self.keys))))
|
|
328
|
+
|
|
329
|
+
@classmethod
|
|
330
|
+
def from_mapping(cls, mapping: Mapping[str, Sequence[float]]) -> "TableData":
|
|
331
|
+
"""Build a table whose column keys *are* their display names.
|
|
332
|
+
|
|
333
|
+
The convenient form for scripts and tests, where there is no rename
|
|
334
|
+
story to model.
|
|
335
|
+
"""
|
|
336
|
+
keys = list(mapping)
|
|
337
|
+
return cls(keys, keys, [mapping[k] for k in keys])
|
|
338
|
+
|
|
339
|
+
@classmethod
|
|
340
|
+
def from_data_table(cls, table: Any) -> "TableData":
|
|
341
|
+
"""Adapt a :class:`gleplot.dataio.DataTable` (a loaded ``.dat`` file).
|
|
342
|
+
|
|
343
|
+
Column keys are positional (``c0``, ``c1``, ...) because a loaded
|
|
344
|
+
file's header names are display text that an edit may change, while
|
|
345
|
+
position is what the file itself is keyed by. Non-numeric columns are
|
|
346
|
+
dropped: they cannot be plotted, and offering them as referenceable
|
|
347
|
+
would only produce dangling references later.
|
|
348
|
+
"""
|
|
349
|
+
keys, names, columns = [], [], []
|
|
350
|
+
for idx, (name, column) in enumerate(zip(table.column_names, table.columns)):
|
|
351
|
+
if table.is_numeric and not table.is_numeric[idx]:
|
|
352
|
+
continue
|
|
353
|
+
keys.append(f"c{idx}")
|
|
354
|
+
names.append(name)
|
|
355
|
+
columns.append(column)
|
|
356
|
+
return cls(keys, names, columns)
|
|
357
|
+
|
|
358
|
+
# -- ProviderTable ------------------------------------------------------
|
|
359
|
+
|
|
360
|
+
def column_keys(self) -> List[ColumnKey]:
|
|
361
|
+
return list(self.keys)
|
|
362
|
+
|
|
363
|
+
def has_column(self, key: ColumnKey) -> bool:
|
|
364
|
+
return key in self._by_key
|
|
365
|
+
|
|
366
|
+
def column_name(self, key: ColumnKey) -> str:
|
|
367
|
+
return self.names[self._by_key[key]]
|
|
368
|
+
|
|
369
|
+
def column_values(self, key: ColumnKey) -> np.ndarray:
|
|
370
|
+
return self.columns[self._by_key[key]]
|
|
371
|
+
|
|
372
|
+
def __repr__(self) -> str:
|
|
373
|
+
return f"TableData(keys={self.keys!r}, rows={len(self.columns[0]) if self.columns else 0})"
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
class DictDataProvider:
|
|
377
|
+
"""A :class:`DataProvider` over a plain ``{table_id: table}`` mapping.
|
|
378
|
+
|
|
379
|
+
Enough for scripts, tests and simple embedders; GLEstudio supplies its own
|
|
380
|
+
provider backed by the project's live tables.
|
|
381
|
+
"""
|
|
382
|
+
|
|
383
|
+
def __init__(self, tables: Optional[Mapping[str, ProviderTable]] = None) -> None:
|
|
384
|
+
self.tables: Dict[str, ProviderTable] = dict(tables or {})
|
|
385
|
+
|
|
386
|
+
def get_table(self, table_id: str) -> Optional[ProviderTable]:
|
|
387
|
+
return self.tables.get(table_id)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
# -- the dangling-reference record --------------------------------------------
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
class DanglingSourceWarning(UserWarning):
|
|
394
|
+
"""Warning category for a series skipped because its source is dangling.
|
|
395
|
+
|
|
396
|
+
Carries the structured record on ``.ref`` so a caller that installs a
|
|
397
|
+
``warnings`` filter still gets the inspectable object rather than only
|
|
398
|
+
the rendered message.
|
|
399
|
+
"""
|
|
400
|
+
|
|
401
|
+
def __init__(self, ref: "DanglingSourceRef") -> None:
|
|
402
|
+
super().__init__(str(ref))
|
|
403
|
+
self.ref = ref
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
class DanglingSourceRef:
|
|
407
|
+
"""A reference that could not be resolved, and the series it belonged to.
|
|
408
|
+
|
|
409
|
+
Deliberately an object rather than a formatted string: GLEstudio shows
|
|
410
|
+
these in the structure tree with retarget/remove actions, so it needs the
|
|
411
|
+
identity of the series (which axes, which list, which index) and of the
|
|
412
|
+
missing thing (which table, which columns) separately from any wording.
|
|
413
|
+
``str()`` renders the human-readable form for CLI use.
|
|
414
|
+
|
|
415
|
+
Attributes
|
|
416
|
+
----------
|
|
417
|
+
axes_index : int
|
|
418
|
+
Index of the axes in ``figure.axes_list``.
|
|
419
|
+
series_attr : str
|
|
420
|
+
The axes list the series lives in (``'lines'``, ``'heatmaps'``, ...).
|
|
421
|
+
series_index : int
|
|
422
|
+
Index within that list.
|
|
423
|
+
label : str or None
|
|
424
|
+
The series' label, when it has one -- the only user-facing name a
|
|
425
|
+
series has.
|
|
426
|
+
table_id : str
|
|
427
|
+
The ``table_id`` the reference names (``''`` for a source whose kind
|
|
428
|
+
this build does not understand).
|
|
429
|
+
missing_columns : tuple of str
|
|
430
|
+
The column keys that could not be resolved. Empty when the whole
|
|
431
|
+
table is missing.
|
|
432
|
+
reason : str
|
|
433
|
+
One of ``'no-provider'``, ``'unknown-table'``, ``'missing-column'``,
|
|
434
|
+
``'unknown-kind'``, ``'unusable-data'``.
|
|
435
|
+
"""
|
|
436
|
+
|
|
437
|
+
__slots__ = (
|
|
438
|
+
"axes_index",
|
|
439
|
+
"series_attr",
|
|
440
|
+
"series_index",
|
|
441
|
+
"label",
|
|
442
|
+
"table_id",
|
|
443
|
+
"missing_columns",
|
|
444
|
+
"reason",
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
#: Every value ``reason`` can take, with its wording.
|
|
448
|
+
#:
|
|
449
|
+
#: ``'unusable-data'`` is the one reason where the *reference* resolved
|
|
450
|
+
#: fine and the numbers behind it did not: a grid series whose extent (or
|
|
451
|
+
#: auto colorbar range) is computed at write time from the resolved
|
|
452
|
+
#: arrays (SPEC 14.5) cannot be drawn when those arrays are empty or
|
|
453
|
+
#: degenerate. It is reported like any other skip rather than raised,
|
|
454
|
+
#: because "nothing about a write raises" -- see :func:`gleplot.writer.resolve_figure`.
|
|
455
|
+
REASONS = {
|
|
456
|
+
"no-provider": "no data provider was supplied for this write",
|
|
457
|
+
"unknown-table": "no table with that id",
|
|
458
|
+
"missing-column": "column(s) not found in the table",
|
|
459
|
+
"unknown-kind": "unrecognized data-source kind",
|
|
460
|
+
"unusable-data": "the resolved data cannot be plotted (empty or degenerate)",
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
def __init__(
|
|
464
|
+
self,
|
|
465
|
+
axes_index: int,
|
|
466
|
+
series_attr: str,
|
|
467
|
+
series_index: int,
|
|
468
|
+
label: Optional[str],
|
|
469
|
+
table_id: str,
|
|
470
|
+
reason: str,
|
|
471
|
+
missing_columns: Iterable[str] = (),
|
|
472
|
+
) -> None:
|
|
473
|
+
self.axes_index = int(axes_index)
|
|
474
|
+
self.series_attr = series_attr
|
|
475
|
+
self.series_index = int(series_index)
|
|
476
|
+
self.label = label
|
|
477
|
+
self.table_id = table_id
|
|
478
|
+
self.reason = reason
|
|
479
|
+
self.missing_columns: Tuple[str, ...] = tuple(missing_columns)
|
|
480
|
+
|
|
481
|
+
@property
|
|
482
|
+
def series_id(self) -> str:
|
|
483
|
+
"""A stable, printable identifier: ``axes[0].lines[2]``."""
|
|
484
|
+
return f"axes[{self.axes_index}].{self.series_attr}[{self.series_index}]"
|
|
485
|
+
|
|
486
|
+
@property
|
|
487
|
+
def message(self) -> str:
|
|
488
|
+
"""The rendered, human-readable form (also what ``str()`` returns)."""
|
|
489
|
+
who = self.series_id
|
|
490
|
+
if self.label:
|
|
491
|
+
who += f" ({self.label!r})"
|
|
492
|
+
detail = self.REASONS.get(self.reason, self.reason)
|
|
493
|
+
if self.missing_columns:
|
|
494
|
+
detail += ": " + ", ".join(repr(c) for c in self.missing_columns)
|
|
495
|
+
return (
|
|
496
|
+
f"{who} was skipped: its data source references table "
|
|
497
|
+
f"{self.table_id!r} but {detail}"
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
def __str__(self) -> str:
|
|
501
|
+
return self.message
|
|
502
|
+
|
|
503
|
+
def __repr__(self) -> str:
|
|
504
|
+
return (
|
|
505
|
+
f"DanglingSourceRef({self.series_id}, table_id={self.table_id!r}, "
|
|
506
|
+
f"reason={self.reason!r}, missing_columns={self.missing_columns!r})"
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
def __eq__(self, other: object) -> bool:
|
|
510
|
+
if not isinstance(other, DanglingSourceRef):
|
|
511
|
+
return NotImplemented
|
|
512
|
+
return all(
|
|
513
|
+
getattr(self, name) == getattr(other, name) for name in self.__slots__
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
def __hash__(self) -> int:
|
|
517
|
+
return hash(tuple(getattr(self, name) for name in self.__slots__))
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
# -- resolution ---------------------------------------------------------------
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
class ResolvedReference:
|
|
524
|
+
"""The arrays a reference resolved to, plus what they came from.
|
|
525
|
+
|
|
526
|
+
``values`` is what gets written into the series copy the writer emits;
|
|
527
|
+
``column_keys`` and ``display_names`` are what the sidecar layer needs to
|
|
528
|
+
build a shared ``.dat`` (which physical column each role landed in, and
|
|
529
|
+
what to call it in the header row).
|
|
530
|
+
"""
|
|
531
|
+
|
|
532
|
+
__slots__ = ("table_id", "values", "column_keys", "display_names")
|
|
533
|
+
|
|
534
|
+
def __init__(
|
|
535
|
+
self,
|
|
536
|
+
table_id: str,
|
|
537
|
+
values: Dict[str, np.ndarray],
|
|
538
|
+
column_keys: Dict[str, RoleSpec],
|
|
539
|
+
display_names: Dict[str, str],
|
|
540
|
+
) -> None:
|
|
541
|
+
self.table_id = table_id
|
|
542
|
+
self.values = values
|
|
543
|
+
self.column_keys = column_keys
|
|
544
|
+
self.display_names = display_names
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def resolve_reference(
|
|
548
|
+
source: Any,
|
|
549
|
+
provider: Optional[DataProvider],
|
|
550
|
+
roles: Sequence[str],
|
|
551
|
+
) -> Tuple[Optional[ResolvedReference], Optional[str], Tuple[str, ...]]:
|
|
552
|
+
"""Resolve one reference against a provider.
|
|
553
|
+
|
|
554
|
+
Parameters
|
|
555
|
+
----------
|
|
556
|
+
source : DataSource
|
|
557
|
+
A :class:`ColumnRef` or :class:`GridRef` (inline sources never reach
|
|
558
|
+
here), or an unrecognized payload from a newer gleplot.
|
|
559
|
+
provider : DataProvider or None
|
|
560
|
+
``None`` is not an error here; it is the ``'no-provider'`` failure,
|
|
561
|
+
reported like any other so the caller has one code path.
|
|
562
|
+
roles : sequence of str
|
|
563
|
+
The series class's ``ARRAY_FIELDS``. Roles the reference does not
|
|
564
|
+
mention are skipped, and mentioned roles the class does not declare
|
|
565
|
+
are ignored -- a reference written by a newer gleplot for a field
|
|
566
|
+
this build lacks degrades to "that field keeps its inline value"
|
|
567
|
+
rather than to an error.
|
|
568
|
+
|
|
569
|
+
Returns
|
|
570
|
+
-------
|
|
571
|
+
(resolved, reason, missing)
|
|
572
|
+
Exactly one of ``resolved`` / ``reason`` is set. ``missing`` lists the
|
|
573
|
+
offending column keys when ``reason`` is ``'missing-column'``.
|
|
574
|
+
"""
|
|
575
|
+
if not isinstance(source, _TableRef):
|
|
576
|
+
return None, "unknown-kind", ()
|
|
577
|
+
|
|
578
|
+
table_id = source["table_id"]
|
|
579
|
+
if provider is None:
|
|
580
|
+
return None, "no-provider", ()
|
|
581
|
+
|
|
582
|
+
table = provider.get_table(table_id)
|
|
583
|
+
if table is None:
|
|
584
|
+
return None, "unknown-table", ()
|
|
585
|
+
|
|
586
|
+
wanted = {
|
|
587
|
+
role: spec for role, spec in source["columns"].items() if role in set(roles)
|
|
588
|
+
}
|
|
589
|
+
missing = [
|
|
590
|
+
key
|
|
591
|
+
for key in source.column_keys()
|
|
592
|
+
if not table.has_column(key)
|
|
593
|
+
# only complain about keys this build actually needs
|
|
594
|
+
and any(
|
|
595
|
+
key in (spec if isinstance(spec, list) else [spec])
|
|
596
|
+
for spec in wanted.values()
|
|
597
|
+
)
|
|
598
|
+
]
|
|
599
|
+
if missing:
|
|
600
|
+
return None, "missing-column", tuple(missing)
|
|
601
|
+
|
|
602
|
+
values: Dict[str, np.ndarray] = {}
|
|
603
|
+
display_names: Dict[str, str] = {}
|
|
604
|
+
for role, spec in wanted.items():
|
|
605
|
+
if isinstance(spec, list):
|
|
606
|
+
# A ``z`` grid: stack the listed columns left-to-right. Column j
|
|
607
|
+
# of the grid is column ``spec[j]`` of the table, so the array's
|
|
608
|
+
# shape is (n_rows, n_listed_columns) -- the same orientation the
|
|
609
|
+
# ``.z`` sidecar writer expects.
|
|
610
|
+
values[role] = np.column_stack(
|
|
611
|
+
[np.asarray(table.column_values(k), dtype=float) for k in spec]
|
|
612
|
+
)
|
|
613
|
+
for key in spec:
|
|
614
|
+
display_names[key] = table.column_name(key)
|
|
615
|
+
else:
|
|
616
|
+
values[role] = np.asarray(table.column_values(spec), dtype=float)
|
|
617
|
+
display_names[spec] = table.column_name(spec)
|
|
618
|
+
|
|
619
|
+
return (
|
|
620
|
+
ResolvedReference(table_id, values, dict(wanted), display_names),
|
|
621
|
+
None,
|
|
622
|
+
(),
|
|
623
|
+
)
|