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/config.py ADDED
@@ -0,0 +1,491 @@
1
+ """Configuration and style settings for gleplot."""
2
+
3
+ import math
4
+ import numbers
5
+ from dataclasses import asdict, dataclass
6
+ from typing import Any, Dict, Optional
7
+
8
+ from ._warn import warn_external
9
+ from .colors import _gle_color, _rgba_parts, _stored_color
10
+
11
+ #: GLE's ``set cap`` and ``set join`` words, in GLE's own numbering order, so
12
+ #: the first is GLE's default.
13
+ LINE_CAPS = ("butt", "round", "square")
14
+ LINE_JOINS = ("mitre", "round", "bevel")
15
+
16
+ #: ``GLEGraphConfig.scale_mode`` values; 'fixed' is accepted and warns.
17
+ _SCALE_MODES = ("auto", "fullsize", "fixed")
18
+
19
+ _LINE_WORDS = {
20
+ "line_cap": (LINE_CAPS, "matplotlib's 'projecting' is 'square'."),
21
+ "line_join": (LINE_JOINS, "matplotlib's 'miter' is 'mitre'."),
22
+ }
23
+
24
+
25
+ @dataclass
26
+ class GLEStyleConfig:
27
+ """GLE rendering style configuration.
28
+
29
+ Attributes
30
+ ----------
31
+ font : str or None
32
+ GLE font name (e.g., 'texcmr', 'ss', 'psh'), not a family name such
33
+ as 'helvetica', which GLE rejects. If None or empty string, uses
34
+ GLE's default font. Default: ''
35
+
36
+ fontsize : float
37
+ Font size in points. Default: 12 (optimized for GLE/PDF readability)
38
+
39
+ default_linewidth : float
40
+ Default line width in points (unit: 1/72 inch).
41
+ Default: 1.5 points ≈ 0.053 cm (increased for visibility in PDFs)
42
+
43
+ default_color : str or None
44
+ Colour every series that takes its colour from the line cycle
45
+ (:meth:`gleplot.Axes.plot`, :meth:`~gleplot.Axes.step`,
46
+ :meth:`~gleplot.Axes.stem`, :meth:`~gleplot.Axes.errorbar`,
47
+ :meth:`~gleplot.Axes.hist`, the function and file series) takes
48
+ instead when the call passes no ``color``. Any spelling
49
+ :func:`gleplot.colors.rgb_to_gle` accepts. Default: None, which
50
+ uses each axes' colour cycle, as matplotlib does (see the Notes).
51
+
52
+ default_marker_color : str or None
53
+ Same, for a marker-only series -- what :meth:`gleplot.Axes.scatter`
54
+ produces, and :meth:`~gleplot.Axes.plot` with a marker and no line.
55
+ Default: None, the colour cycle.
56
+
57
+ line_style_solid : int
58
+ GLE line style for solid lines. Default: 1
59
+
60
+ line_style_dashed : int
61
+ GLE line style for dashed lines (--). Default: 3
62
+
63
+ line_style_dotted : int
64
+ GLE line style for dotted lines (:). Default: 2
65
+
66
+ line_style_dashdot : int
67
+ GLE line style for dash-dot lines (-.). Default: 6
68
+
69
+ line_cap : {'butt', 'round', 'square'} or None
70
+ How every line in the figure ends (GLE ``set cap``). ``'square'`` is
71
+ matplotlib's ``'projecting'``. None (the default) writes nothing and
72
+ leaves GLE's own ``butt``.
73
+
74
+ line_join : {'mitre', 'round', 'bevel'} or None
75
+ How every line in the figure turns a corner (GLE ``set join``).
76
+ ``'mitre'`` is matplotlib's ``'miter'``. None (the default) writes
77
+ nothing and leaves GLE's own ``mitre``.
78
+
79
+ dashlen : float or None
80
+ Length in cm of the shortest dash in every line style (GLE ``set
81
+ dashlen``). The ``lstyle`` digits are multiples of it, so a larger
82
+ value stretches dashes and gaps alike. GLE does not scale dashes
83
+ with the line width, so a thick dashed line can read as dotted;
84
+ raise ``dashlen`` to open it up. None (the default) writes nothing
85
+ and leaves GLE's own 0.04 cm.
86
+
87
+ usetex : bool
88
+ Typeset every label with LaTeX (GLE ``set texlabels 1``), as
89
+ matplotlib's ``text.usetex`` does: titles, axis labels, tick labels,
90
+ legend entries and text annotations. Strings reach LaTeX as written,
91
+ so ``$...$`` is LaTeX math rather than gleplot's mathtext translation,
92
+ and text outside it must be valid LaTeX (``\\_`` for an underscore).
93
+ Labels already set keep their GLE markup, so set this when creating
94
+ the figure. Compiling needs a LaTeX installation; SVG output is not
95
+ available. Default: False
96
+
97
+ Notes
98
+ -----
99
+ With ``default_color`` and ``default_marker_color`` left at None, a series given
100
+ no colour takes the next of matplotlib's ``'C0'`` to ``'C9'``, per axes, exactly
101
+ where matplotlib would: :meth:`~gleplot.Axes.plot`, :meth:`~gleplot.Axes.step`,
102
+ :meth:`~gleplot.Axes.errorbar`, :meth:`~gleplot.Axes.hist` (one colour per data
103
+ set) and :meth:`~gleplot.Axes.stackplot` (one per layer) advance the line cycle;
104
+ :meth:`~gleplot.Axes.scatter`, :meth:`~gleplot.Axes.bar`,
105
+ :meth:`~gleplot.Axes.barh`, :meth:`~gleplot.Axes.fill`,
106
+ :meth:`~gleplot.Axes.fill_between` and :meth:`~gleplot.Axes.fill_betweenx`
107
+ advance a separate patch cycle; :meth:`~gleplot.Axes.stem`,
108
+ :meth:`~gleplot.Axes.hlines` and :meth:`~gleplot.Axes.vlines` draw in ``'C0'``
109
+ without advancing either. An axes made by ``twinx``/``twiny`` has cycles of its
110
+ own.
111
+
112
+ A ``default_linewidth``, ``default_color`` or ``default_marker_color``
113
+ other than its default is recorded in a saved file's metadata, so a
114
+ figure opened with :func:`gleplot.open_gle` gives new series the same
115
+ defaults. A colour is recorded as the GLE colour it draws. A figure
116
+ opened that way continues each cycle after the series whose colours
117
+ follow it.
118
+
119
+ The ``line_style_*`` defaults are the GLE ``lstyle`` numbers that actually
120
+ render as their names say, measured by compiling a ruler of ``set lstyle
121
+ 1..9`` strokes with GLE 4.3.10 and looking at the result:
122
+
123
+ ========== ==================
124
+ ``lstyle`` renders as
125
+ ========== ==================
126
+ 1 solid
127
+ 2 dotted (dense)
128
+ 3 dashed
129
+ 4 dotted (sparse)
130
+ 5 dashed (long)
131
+ 6 dash-dot
132
+ 7 dash-dot (sparse)
133
+ 8 dash-dot (dense)
134
+ 9 dashed (long, sparse)
135
+ ========== ==================
136
+
137
+ Any GLE ``lstyle`` code is accepted, not only 1-9. GLE reads a code of
138
+ more than one digit as alternating run lengths, black then white: ``42``
139
+ is a dash four units long followed by a gap two units long.
140
+
141
+ gleplot previously defaulted to dashed=2 / dotted=3 / dashdot=4, i.e.
142
+ ``linestyle='--'`` drew a dotted line and ``':'`` drew a dashed one. Do
143
+ not "restore" those numbers: they were transposed, and dashed-vs-dotted
144
+ is load-bearing in publication figures where a dashed curve conventionally
145
+ means a fit.
146
+ """
147
+
148
+ font: str = "" # Empty string = GLE default font
149
+ fontsize: float = 12 # Increased from 10 for better readability in GLE/PDF output
150
+ default_linewidth: float = 1.5 # Increased from 1.0 for visibility
151
+ default_color: Optional[str] = None
152
+ default_marker_color: Optional[str] = None
153
+ # See the "Notes" section above: these are GLE's real style numbers, not
154
+ # a sequential 1/2/3/4 guess.
155
+ line_style_solid: int = 1
156
+ line_style_dashed: int = 3
157
+ line_style_dotted: int = 2
158
+ line_style_dashdot: int = 6
159
+ line_cap: Optional[str] = None
160
+ line_join: Optional[str] = None
161
+ dashlen: Optional[float] = None
162
+ usetex: bool = False
163
+
164
+ def __setattr__(self, name: str, value: Any) -> None:
165
+ # Checked on every assignment, not only at construction:
166
+ # ``fig.style.line_cap = ...`` is a documented way to restyle.
167
+ if value is not None and name in _LINE_WORDS:
168
+ words, hint = _LINE_WORDS[name]
169
+ if not isinstance(value, str):
170
+ raise TypeError(
171
+ f"{name} must be a string or None; got {value!r}. "
172
+ f"Accepted: {list(words)}."
173
+ )
174
+ if value not in words:
175
+ raise ValueError(
176
+ f"{name} must be one of {list(words)} or None; got "
177
+ f"{value!r}. {hint}"
178
+ )
179
+ if value is not None and name == "dashlen":
180
+ if not isinstance(value, numbers.Real) or isinstance(value, bool):
181
+ raise TypeError(
182
+ f"dashlen must be a number of cm or None; got {value!r}."
183
+ )
184
+ # GLE's g_set_line_styled ignores 0; a negative dash is no dash.
185
+ if not (math.isfinite(value) and float(value) > 0):
186
+ raise ValueError(
187
+ f"dashlen must be a positive length in cm or None; got "
188
+ f"{value!r}. None keeps GLE's own 0.04 cm."
189
+ )
190
+ if value is not None and name in ("default_color", "default_marker_color"):
191
+ value = _stored_color(value)
192
+ _gle_color(_rgba_parts(value)[0], name) # raises for an unknown colour
193
+ if name == "usetex" and not isinstance(value, bool):
194
+ raise TypeError(
195
+ f"usetex must be True or False; got {value!r} of type "
196
+ f"{type(value).__name__}."
197
+ )
198
+ super().__setattr__(name, value)
199
+
200
+ def to_dict(self) -> Dict[str, Any]:
201
+ """Convert config to dictionary."""
202
+ return asdict(self)
203
+
204
+
205
+ @dataclass
206
+ class GLEGraphConfig:
207
+ """GLE graph configuration.
208
+
209
+ Attributes
210
+ ----------
211
+ scale_mode : str
212
+ Who sizes the graph. 'auto' (the default): gleplot places each axes
213
+ frame from its subplot cell or ``add_axes`` rect, with margins for
214
+ labels. 'fullsize': a figure with a single axes, other than one made
215
+ with ``add_axes``, is written with GLE's ``fullsize``, filling the
216
+ page with no margins; figures with several axes keep gleplot's
217
+ layout. 'fixed': no effect, and warns; the figure is written as under
218
+ 'auto'. Any other value raises ``ValueError``.
219
+
220
+ title_distance : float or None
221
+ Figure-wide default for ``Axes.title_dist`` -- the ``dist`` option of
222
+ GLE's ``title`` command, in cm. A per-axes ``title_dist`` wins over
223
+ it. ``None`` (the default) emits no ``dist`` at all, leaving GLE's
224
+ own spacing.
225
+
226
+ .. versionchanged:: 2.4
227
+ Was an inert ``0.1`` that nothing read. It is now the default for
228
+ the per-axes distance, and its default is ``None`` so that
229
+ figures which never set it emit exactly the GLE they always did.
230
+ A project serialized with the old inert ``0.1`` will, once
231
+ reloaded, actually emit ``dist 0.1``.
232
+
233
+ xlabel_distance : float or None
234
+ Same, for ``Axes.xlabel_dist`` -- the ``dist`` option of GLE's
235
+ ``xtitle`` command (distance between the axis title and the tick
236
+ labels), in cm. Default: None.
237
+
238
+ ylabel_distance : float or None
239
+ Same, for ``Axes.ylabel_dist`` (GLE ``ytitle ... dist``) and, when
240
+ the axes sets no distance of its own, ``Axes.y2label_dist``
241
+ (``y2title ... dist``). Default: None.
242
+
243
+ legend_position : str
244
+ Default legend position: 'tl', 'tr', 'bl', 'br', 'tc', 'bc', 'lc', 'rc', 'cc'.
245
+ Options: 'top right', 'top left', 'bottom right', 'bottom left', 'center'.
246
+ Default: 'tr' (top right)
247
+
248
+ legend_offset_x : float
249
+ Figure-wide default legend x-offset from its anchor (cm), used by
250
+ every axes whose own ``legend_offset`` is None. Default: 0.0.
251
+
252
+ legend_offset_y : float
253
+ The y half of the same default (cm). Default: 0.0.
254
+
255
+ ``(0.0, 0.0)`` means "no offset", and emits no ``offset`` clause --
256
+ so the defaults leave GLE output unchanged.
257
+
258
+ smooth_curves : bool
259
+ Draw line series as a fitted spline through the points (GLE's
260
+ ``smooth`` keyword) instead of as a polyline joining them.
261
+ **Opt-in**: a smoothed curve is an interpolation, not the data, so
262
+ it must never be applied without being asked for. Applies to
263
+ :meth:`~gleplot.Axes.plot`, :meth:`~gleplot.Axes.line_from_file` and
264
+ the line drawn by :meth:`~gleplot.Axes.errorbar`. Fills, contour
265
+ lines, step, stem and histogram lines, and a ``plot`` line broken by
266
+ NaN (which warns) are never smoothed.
267
+ Default: False
268
+
269
+ show_grid : bool
270
+ Figure-wide default grid: when True, every axes that has not called
271
+ :meth:`gleplot.Axes.grid` itself gets a main-tick grid on both axes
272
+ (GLE ``xaxis grid`` / ``yaxis grid``). An axes that HAS called
273
+ ``grid()`` -- including ``grid(False)`` -- keeps its own answer.
274
+ Default: False
275
+
276
+ default_cmap : str
277
+ Default colour map used by ``imshow``/``tripcolor`` when ``cmap`` is
278
+ not passed. One of the names in :data:`gleplot.palettes.SUPPORTED_CMAPS`,
279
+ or one with ``_r`` appended for its reversed form.
280
+ Default: 'viridis'
281
+
282
+ colormap_pixels : int
283
+ Default bitmap resolution (pixels per side) for ``colormap`` rendering
284
+ when ``imshow(pixels=...)`` is not given. Default: 200
285
+ """
286
+
287
+ scale_mode: str = "auto" # 'auto' or 'fullsize' ('fixed' has no effect)
288
+ # None = emit no 'dist' option (GLE's atitledist/titlescale spacing).
289
+ # See the class docstring for why these are no longer 0.1.
290
+ title_distance: Optional[float] = None
291
+ xlabel_distance: Optional[float] = None
292
+ ylabel_distance: Optional[float] = None
293
+ legend_position: str = "tr"
294
+ legend_offset_x: float = 0.0
295
+ legend_offset_y: float = 0.0
296
+ smooth_curves: bool = False
297
+ show_grid: bool = False
298
+ default_cmap: str = "viridis"
299
+ colormap_pixels: int = 200
300
+
301
+ def __setattr__(self, name: str, value: Any) -> None:
302
+ # Checked on every assignment, as GLEStyleConfig's words are.
303
+ if name == "scale_mode":
304
+ if not isinstance(value, str):
305
+ raise TypeError(
306
+ f"scale_mode must be 'auto' or 'fullsize'; got {value!r}."
307
+ )
308
+ if value not in _SCALE_MODES:
309
+ raise ValueError(
310
+ f"scale_mode must be 'auto' or 'fullsize' ('fixed' is "
311
+ f"accepted but has no effect); got {value!r}."
312
+ )
313
+ if value == "fixed":
314
+ warn_external(
315
+ "scale_mode='fixed' has no effect: gleplot places every "
316
+ "axes frame itself, as under 'auto'. Use 'auto', or "
317
+ "'fullsize' to let GLE size a single graph."
318
+ )
319
+ super().__setattr__(name, value)
320
+
321
+ def to_dict(self) -> Dict[str, Any]:
322
+ """Convert config to dictionary."""
323
+ return asdict(self)
324
+
325
+
326
+ @dataclass
327
+ class GLEMarkerConfig:
328
+ """Marker style configuration.
329
+
330
+ Attributes
331
+ ----------
332
+ default_marker : str
333
+ Default marker type when creating scatter plots.
334
+ Options: 'circle', 'square', 'triangle', 'diamond', 'cross',
335
+ 'fcircle', 'fsquare', 'ftriangle', 'fdiamond' (filled variants).
336
+ Default: 'fcircle' (filled circle)
337
+
338
+ msize_scale : float
339
+ Scaling factor for marker sizes. Multiplies the msize value.
340
+ Default: 1.0
341
+
342
+ mdist : Optional[float]
343
+ Default marker distance in cm along a line that has markers: GLE's
344
+ ``mdist``, written on each marked line that does not pass its own
345
+ ``mdist`` to ``plot``. If None, markers appear at every point.
346
+ Default: None
347
+ """
348
+
349
+ default_marker: str = "fcircle"
350
+ msize_scale: float = 1.0
351
+ mdist: Optional[float] = None
352
+
353
+ def __post_init__(self) -> None:
354
+ # GLE's marker loop (graph2.cpp drawMarkers) never ends on a
355
+ # negative mdist, and 0 is its own "every point".
356
+ if self.mdist is not None and not (
357
+ isinstance(self.mdist, (int, float))
358
+ and not isinstance(self.mdist, bool)
359
+ and math.isfinite(self.mdist)
360
+ and self.mdist > 0
361
+ ):
362
+ raise ValueError(
363
+ f"mdist must be a positive distance in cm or None; got "
364
+ f"{self.mdist!r}. None draws a marker on every point."
365
+ )
366
+
367
+ def to_dict(self) -> Dict[str, Any]:
368
+ """Convert config to dictionary."""
369
+ return asdict(self)
370
+
371
+
372
+ class GlobalConfigMeta(type):
373
+ """Metaclass for GlobalConfig to provide attribute access."""
374
+
375
+ _instance = None
376
+
377
+ @property
378
+ def style(cls) -> GLEStyleConfig:
379
+ """Get global style configuration."""
380
+ if cls._instance is None:
381
+ cls._instance = cls()
382
+ return cls._instance.style
383
+
384
+ @property
385
+ def graph(cls) -> GLEGraphConfig:
386
+ """Get global graph configuration."""
387
+ if cls._instance is None:
388
+ cls._instance = cls()
389
+ return cls._instance.graph
390
+
391
+ @property
392
+ def marker(cls) -> GLEMarkerConfig:
393
+ """Get global marker configuration."""
394
+ if cls._instance is None:
395
+ cls._instance = cls()
396
+ return cls._instance.marker
397
+
398
+
399
+ class GlobalConfig(metaclass=GlobalConfigMeta):
400
+ """Global gleplot configuration.
401
+
402
+ Provides singleton-like access to default configuration settings
403
+ that apply to all new figures created.
404
+
405
+ Access style, graph, and marker configurations directly as class attributes:
406
+
407
+ Examples
408
+ --------
409
+ >>> from gleplot.config import GlobalConfig
410
+ >>> # Change default font globally
411
+ >>> GlobalConfig.style.font = 'texcmss' # TeX Computer Modern Sans Serif
412
+ >>> # All new figures will use this font
413
+
414
+ >>> # Or reset to defaults
415
+ >>> GlobalConfig.reset()
416
+
417
+ Notes
418
+ -----
419
+ **Copy-at-construction, not shared-by-reference.** ``GlobalConfig.style``
420
+ (and ``.graph``, ``.marker``) really is one shared, mutable instance --
421
+ editing it here, before any figure exists, is exactly how you change the
422
+ default for every figure created afterwards. But :class:`gleplot.figure.Figure`
423
+ and :class:`gleplot.writer.GLEWriter` each take an independent COPY of
424
+ the current value at construction time (when their own ``style``/
425
+ ``graph``/``marker`` argument is omitted), not a reference to this
426
+ singleton. So:
427
+
428
+ - ``GlobalConfig.style.font = 'x'`` then ``fig = Figure()`` -- ``fig``
429
+ gets ``'x'`` (the default was read at construction time).
430
+ - ``fig = Figure()`` then ``fig.style.font = 'x'`` -- only ``fig``
431
+ changes; ``GlobalConfig.style.font`` and every other figure are
432
+ unaffected. Before this was fixed, this in-place edit silently
433
+ mutated ``GlobalConfig.style`` itself (since ``fig.style`` and
434
+ ``GlobalConfig.style`` were the same object), leaking into every
435
+ figure created afterwards in the process.
436
+ """
437
+
438
+ _instance = None
439
+
440
+ def __new__(cls):
441
+ if cls._instance is None:
442
+ cls._instance = super().__new__(cls)
443
+ cls._instance._initialized = False
444
+ return cls._instance
445
+
446
+ def __init__(self):
447
+ if self._initialized:
448
+ return
449
+
450
+ self.style = GLEStyleConfig()
451
+ self.graph = GLEGraphConfig()
452
+ self.marker = GLEMarkerConfig()
453
+ self._initialized = True
454
+
455
+ @classmethod
456
+ def reset(cls):
457
+ """Reset all configurations to defaults."""
458
+ instance = cls()
459
+ instance.style = GLEStyleConfig()
460
+ instance.graph = GLEGraphConfig()
461
+ instance.marker = GLEMarkerConfig()
462
+
463
+ @classmethod
464
+ def get_style(cls) -> GLEStyleConfig:
465
+ """Get global style configuration."""
466
+ return cls.style
467
+
468
+ @classmethod
469
+ def get_graph(cls) -> GLEGraphConfig:
470
+ """Get global graph configuration."""
471
+ return cls.graph
472
+
473
+ @classmethod
474
+ def get_marker(cls) -> GLEMarkerConfig:
475
+ """Get global marker configuration."""
476
+ return cls.marker
477
+
478
+ @classmethod
479
+ def to_dict(cls) -> Dict[str, Dict[str, Any]]:
480
+ """Export all configurations as dictionary."""
481
+ return {
482
+ "style": cls.style.to_dict(),
483
+ "graph": cls.graph.to_dict(),
484
+ "marker": cls.marker.to_dict(),
485
+ }
486
+
487
+
488
+ # Module-level convenience access
489
+ style = GlobalConfig.get_style
490
+ graph = GlobalConfig.get_graph
491
+ marker = GlobalConfig.get_marker