umbruch-matplotlib 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: umbruch-matplotlib
3
+ Version: 0.1.0
4
+ Summary: Matplotlib backend that renders PDF, text and math through umbruch
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/manuel-rhdt/umbruch-matplotlib
7
+ Project-URL: Repository, https://github.com/manuel-rhdt/umbruch-matplotlib
8
+ Project-URL: Issues, https://github.com/manuel-rhdt/umbruch-matplotlib/issues
9
+ Keywords: matplotlib,backend,pdf,png,typography,mathml
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Printing
16
+ Classifier: Topic :: Scientific/Engineering :: Visualization
17
+ Requires-Python: >=3.12
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: matplotlib>=3.9
21
+ Requires-Dist: umbruch>=0.8.0
22
+ Provides-Extra: math
23
+ Requires-Dist: latex2mathml>=3.77; extra == "math"
24
+ Dynamic: license-file
25
+
26
+ # umbruch-matplotlib
27
+
28
+ A Matplotlib backend that renders plots to PDF or PNG using with
29
+ [umbruch](https://github.com/manuel-rhdt/umbruch) as the backend. Text and math are laid out by umbruch:
30
+ labels may contain rich text (`rich("<i>t</i><sub>0</sub>")`) and `$...$` math is converted to
31
+ MathML. It talks to umbruch through the `umbruch` package (`umbruch.Server`, version 0.8.0 or later); the executable comes with the package, and `$UMBRUCH` or `PATH` override it.
32
+
33
+ ```python
34
+ import matplotlib
35
+ matplotlib.use("module://umbruch_matplotlib")
36
+ import matplotlib.pyplot as plt
37
+ from umbruch_matplotlib import rich
38
+
39
+ fig, ax = plt.subplots()
40
+ ax.set_xlabel(rich("time <i>t</i> (ms)"))
41
+ ax.set_title(r"$\hat\rho_{ij}=\frac{a}{b}$")
42
+ fig.savefig("fig.pdf")
43
+ ```
44
+
45
+ Install with `pip install .[math]` (the `math` extra pulls in `latex2mathml`).
46
+
47
+ `savefig("fig.png")` is rasterized by umbruch as well: the same laid-out page as the PDF, painted
48
+ at the figure's `dpi` (96 dpi is only umbruch's default, Matplotlib's is used), so the image has the
49
+ same layout, the same rich text and the same math as the PDF and nothing falls back to Matplotlib's
50
+ Agg. The page background is the figure's facecolor, so a transparent figure comes out with an alpha
51
+ channel. One page per file — a figure is one page — and a `dpi` that needs more than 16.7 million
52
+ pixels in total (the raster backend's limit) is an error.
53
+
54
+ The backend builds on parts of Matplotlib's SVG renderer that are not public API. It is tested with Matplotlib 3.9, 3.10 and 3.11 (CI runs the oldest and the newest), and on import it checks that the parts it needs are there, naming what is missing otherwise.
55
+
56
+ Unsupported features raise instead of falling back to Matplotlib's own text rendering:
57
+ `text.usetex`, and TeX that cannot be converted to MathML.
58
+
59
+ Fonts come from Matplotlib: for every text, the font file that `font_manager.findfont` picks (including fonts added with `fontManager.addfont`) is sent to umbruch as an `@font-face` with a `data:` URI, so the PDF uses the face Matplotlib measured, with real italic and bold faces, and nothing depends on umbruch seeing the system's fonts. Styled markup inside a `rich()` string (`<b>`, `<strong>`, `<i>`, `<em>`) is set in the bold and italic faces of the *same* family: when a text has any, the family's bold, italic and bold-italic faces are sent along and all of them carry one `@font-face` family name, which is what CSS font matching needs (it never leaves the first family). The families of the text follow as CSS fallbacks. Measuring sends each face once, as the style sheet that umbruch remembers (`Server.set_stylesheet`, which needs umbruch 0.5.3). The SVG that is rendered to PDF still carries its own `@font-face` rules, because it is the same SVG that `savefig("x.svg")` writes. Variable fonts are drawn in their default instance, and from a `.ttc` only the first face is read.
60
+
61
+ Tick labels with exponents (`10^3`, `1×10^-4`) are set as text with superscripts in the label font, not as math. Math in `$...$` is converted to MathML and set in STIX Two Math by default. `mathtext.fontset = "cm"` selects Latin Modern Math, and `umbruch_matplotlib.config.math_font` takes the family of any OpenType math font that Matplotlib finds (for example `"Libertinus Math"`, sent to umbruch like the text fonts) or the path of a font file; it needs a font with an OpenType MATH table. Gouraud triangles (`pcolormesh`/`tripcolor` with `shading="gouraud"`) are written as one compact `<g data-umbruch-mesh="gouraud">` element with shared vertices that umbruch paints as a single native shading (an umbruch extension of SVG that nothing else draws; it needs a umbruch that reports `mesh_gouraud`). `config.gouraud = "subdivide"` draws them as flat triangles and `"stock"` uses Matplotlib's gradient emulation, for other renderers, and `"auto"` picks the native mesh when it is possible. A native mesh needs one alpha for the whole mesh (otherwise it raises), and no Gouraud mode works in a wide colour space yet, see below.
62
+
63
+ ### Wide-gamut colours
64
+
65
+ Matplotlib has no colour management: every RGB value (colours, colormaps, image pixels) is three numbers in [0, 1]. Say which space they are in, and umbruch writes the PDF in that space:
66
+
67
+ ```python
68
+ umbruch_matplotlib.config.color_space = "display-p3" # or fig.savefig(..., color_space="display-p3")
69
+ ax.plot(x, y, color=(0.1, 0.9, 0.3)) # these numbers are Display P3
70
+ ```
71
+
72
+ The spaces are those of CSS Color 4: `srgb` (the default), `display-p3`, `a98-rgb`, `prophoto-rgb` and `rec2020`. Painted colours (fill, stroke, text, hatches) are written as `color(display-p3 r g b)` from Matplotlib's float values, without the rounding to 1/255 of stock SVG; no hex colour is left in the SVG. Raster images are 8 bits per channel as Matplotlib makes them. (Matplotlib's own gradient emulation for Gouraud triangles, `config.gouraud = "stock"`, is gone: it only wrote hex colours.)
73
+
74
+ Everything Matplotlib itself supplies as sRGB (names like `"red"`, hex colours, the default colour cycle, the built-in colormaps) is then misread as P3 numbers. Convert it: `convert_color("tab:blue", dst="display-p3")` and `convert_cmap("viridis", dst="display-p3")` return values in the target space, clipped to its gamut.
75
+
76
+ Raster images (`imshow`, rasterised artists) get an ICC profile of the space in their PNG, which umbruch uses as the colour space of the image. Gouraud shading (`shading="gouraud"`) raises `NotImplementedError` in a wide space for now, because umbruch paints meshes in sRGB; use `shading="flat"` or `"nearest"`.
77
+
78
+ ## Examples
79
+
80
+ Rich text through `rich()`: inline markup for italics, bold, sub- and superscripts, colour and size, in titles, labels, tick labels and annotations.
81
+
82
+ ![Rich text](docs/rich_text.png)
83
+
84
+ Math is laid out as MathML with STIX Two Math, with correct operator spacing and function application, and can be mixed with rich text.
85
+
86
+ ![Math](docs/math.png)
87
+
88
+ A larger figure with hatching, gradients, colour bars, annotations, and math and rich text in titles, labels and legends. The output is a vector PDF whose text stays selectable.
89
+
90
+ ![Showcase](docs/showcase.png)
91
+
92
+ The scripts are in `examples/`. `python examples/make_images.py` re-renders the PNGs (needs `pdftoppm` and an `umbruch` binary on `$UMBRUCH` or the path).
93
+
94
+ Tests: `pytest tests`.
95
+
96
+ ## License
97
+
98
+ MIT, see `LICENSE`.
@@ -0,0 +1,6 @@
1
+ umbruch_matplotlib.py,sha256=bjDnIc9tSQcnBw5z8AaZPr5JnGda9_7OyUco55Pu1dI,48735
2
+ umbruch_matplotlib-0.1.0.dist-info/licenses/LICENSE,sha256=Ua4qpZaR09MHFAYp6a9NmdmEcyXWjD4PnGUD6LuAG4Y,1073
3
+ umbruch_matplotlib-0.1.0.dist-info/METADATA,sha256=pLK3nkIhKAjZIBC7it9oC44wxqmLDL-2Gt3Dh2mLYNg,7376
4
+ umbruch_matplotlib-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ umbruch_matplotlib-0.1.0.dist-info/top_level.txt,sha256=CWzrYGwZy_q0__ia8UvExqf9lT4pLYrp8OUDDN-vSAc,19
6
+ umbruch_matplotlib-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Manuel Reinhardt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ umbruch_matplotlib
umbruch_matplotlib.py ADDED
@@ -0,0 +1,1085 @@
1
+ """Matplotlib backend that hands text layout and PDF writing to umbruch.
2
+
3
+ Pipeline
4
+ --------
5
+ Matplotlib draws into a subclass of its SVG renderer, which already handles
6
+ paths, markers, clipping, hatches, images and collections. Three things
7
+ differ from stock SVG output:
8
+
9
+ * Text (plain, rich, and math) is written as an XHTML/MathML fragment inside a
10
+ <foreignObject>, which umbruch lays out and draws (it supports HTML and MathML
11
+ there). Measuring goes through umbruch too, so Matplotlib's layout (tick
12
+ labels, legends, constrained/tight layout, bbox_inches="tight") sees the
13
+ widths umbruch will produce. Heights and descents are the ink extents of the
14
+ plain text, as with stock Matplotlib, plus what markup adds to the line box
15
+ (sub/superscripts, fractions); the line box itself is used only to place the
16
+ text on its baseline.
17
+ * Gouraud triangles (``config.gouraud == "native"``, the default) are one compact
18
+ ``<g data-umbruch-mesh="gouraud" data-vertices=... data-triangles=...>`` element, which
19
+ umbruch paints as a single type 4 shading. This is an umbruch extension of SVG that no
20
+ other renderer draws, and it needs one alpha per mesh. ``"subdivide"`` (flat
21
+ sub-triangles) and ``"stock"`` (Matplotlib's gradient emulation) are polyfills for
22
+ other renderers. None works in a wide color space yet: that raises.
23
+ * Fonts: the file that Matplotlib's font manager picks for each text is sent to
24
+ umbruch as an @font-face with a data: URI (in the SVG, and in measure requests),
25
+ under a name derived from the file; the font's own family list follows as fallback.
26
+ The font of math (``config.math_font``, or ``mathtext.fontset``) is set by a style
27
+ attribute on each <math>, since a style sheet would not reach the probes of a measure.
28
+ * The finished SVG is rendered to PDF by ``umbruch figure.svg figure.pdf``.
29
+
30
+ Usage
31
+ -----
32
+ import matplotlib
33
+ matplotlib.use("module://umbruch_matplotlib") # or savefig(..., backend=...)
34
+ import umbruch_matplotlib as hb
35
+ ax.set_title(hb.rich("<i>Rate</i> r<sub>0</sub> in <b>Hz</b>"))
36
+ ax.set_xlabel(r"$\alpha^2$ (needs the latex2mathml package)")
37
+ fig.savefig("out.pdf")
38
+
39
+ The ``umbruch`` executable is taken from $UMBRUCH, the ``umbruch`` package or PATH. Rich text is marked by
40
+ a leading U+FEFF (see ``rich``), which survives Matplotlib's string handling.
41
+ The markup must be well-formed XML (numeric entities, not &nbsp;), and a newline
42
+ splits lines as for any Matplotlib text. ``$...$`` in a plain or rich string is
43
+ converted to MathML by ``config.tex_to_mathml`` (default: latex2mathml). Math
44
+ that cannot be converted raises, as does ``text.usetex``; there is no fallback to
45
+ Matplotlib's own text rendering.
46
+
47
+ Tested against Matplotlib 3.11 and umbruch 0.5; it uses a few private attributes of
48
+ the SVG renderer.
49
+ """
50
+ import base64
51
+ import functools
52
+ import hashlib
53
+ import io
54
+ import os
55
+ import re
56
+ import logging
57
+ import struct
58
+ import zlib
59
+ import xml.etree.ElementTree as ET
60
+ from xml.sax.saxutils import escape
61
+
62
+ import numpy as np
63
+
64
+ import umbruch
65
+
66
+ import matplotlib as mpl
67
+ from matplotlib import cbook, font_manager as fm
68
+ from matplotlib.backend_bases import FigureManagerBase
69
+ from matplotlib.backends.backend_mixed import MixedModeRenderer
70
+ from matplotlib.backends import backend_svg as _backend_svg
71
+ from matplotlib.backends.backend_svg import FigureCanvasSVG, RendererSVG
72
+
73
+ # This backend builds on parts of Matplotlib's SVG backend that are not public API.
74
+ # Before 3.11 the XML writer is called XMLWriter; check the rest, so that a Matplotlib
75
+ # that changed them fails here with a message rather than somewhere in a drawing.
76
+ _XMLWriter = getattr(_backend_svg, "_XMLWriter", None) or _backend_svg.XMLWriter
77
+ _generate_css = getattr(_backend_svg, "_generate_css", None)
78
+ _PRIVATE = {
79
+ "RendererSVG": [(RendererSVG, n) for n in (
80
+ "_get_clip_attrs", "_make_flip_transform", "_convert_path", "_get_style_dict",
81
+ "_write_hatches", "_get_hatch", "_make_id", "draw_gouraud_triangles")],
82
+ "the XML writer": [(_XMLWriter, n) for n in (
83
+ "_XMLWriter__flush", "start", "end", "element", "data")],
84
+ "backend_svg": [(_backend_svg, "_generate_css")],
85
+ }
86
+ _missing = [f"{where}.{name}" for where, items in _PRIVATE.items()
87
+ for obj, name in items if not hasattr(obj, name)]
88
+ if _missing:
89
+ raise ImportError(
90
+ f"umbruch_matplotlib needs parts of Matplotlib's SVG backend that Matplotlib "
91
+ f"{mpl.__version__} does not have ({', '.join(_missing)}); it is tested with "
92
+ "Matplotlib 3.9 to 3.11")
93
+ from matplotlib.colors import rgb2hex
94
+ from matplotlib.transforms import Affine2D
95
+
96
+ log = logging.getLogger(__name__)
97
+
98
+ XHTML = "http://www.w3.org/1999/xhtml"
99
+ RICH_MARK = ""
100
+
101
+ FigureManager = FigureManagerBase
102
+
103
+
104
+ def rich(markup):
105
+ """Mark *markup* (an XHTML fragment, optionally containing $math$) as rich text."""
106
+ return RICH_MARK + markup
107
+
108
+
109
+ def _fmt(v):
110
+ return f"{v:.3f}".rstrip("0").rstrip(".") or "0"
111
+
112
+
113
+ _ARITY = {"mfrac": 2, "mroot": 2, "msub": 2, "msup": 2, "munder": 2, "mover": 2,
114
+ "msubsup": 3, "munderover": 3}
115
+ _MATHML_NS = "http://www.w3.org/1998/Math/MathML"
116
+ ET.register_namespace("", _MATHML_NS)
117
+ #: operators TeX sets as functions: upright name, thin space, then the argument
118
+ _FUNCTIONS = {"sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan",
119
+ "sinh", "cosh", "tanh", "coth", "log", "ln", "lg", "exp", "det", "dim",
120
+ "ker", "deg", "arg", "gcd", "hom", "Pr", "sgn"}
121
+ #: mathematical symbols that stay identifiers (everything else in Sm is an operator)
122
+ _NOT_OPERATORS = {"\u2202", "\u2207", "\u221e"}
123
+
124
+
125
+ def _fix_mathml(ml):
126
+ """Validate and repair what latex2mathml writes.
127
+
128
+ It is lenient: an unknown macro becomes the literal text ``\\name`` and a malformed
129
+ ``\\frac`` becomes an <mfrac> with one child; both raise ValueError. It also marks
130
+ up things MathML needs marked for correct spacing: binary and relation symbols such
131
+ as \\pm come out as <mi> (no operator spacing), function names as \\sin have no
132
+ function application (no space before the argument), and the periods in
133
+ ``\\mathrm{a.u.}`` are operators (spaced). These are repaired.
134
+ """
135
+ import re
136
+ import unicodedata
137
+ # latex2mathml drops the upright style of a single-letter \mathrm{s}; it is the only
138
+ # input that yields the zero-padded ASCII entity, so mark exactly those as upright.
139
+ ml = re.sub(r"<mi>(&#x000[0-9A-Fa-f]{2};)</mi>", r'<mi mathvariant="normal">\1</mi>', ml)
140
+ ns = "{%s}" % _MATHML_NS
141
+ root = ET.fromstring(ml)
142
+ for el in root.iter():
143
+ tag = el.tag.rsplit("}", 1)[-1]
144
+ if el.text and "\\" in el.text:
145
+ raise ValueError(f"unknown TeX command in {el.text.strip()!r}")
146
+ if tag in _ARITY and len(el) != _ARITY[tag]:
147
+ raise ValueError(f"<{tag}> needs {_ARITY[tag]} arguments, got {len(el)}")
148
+ txt = el.text or ""
149
+ if tag == "mi" and len(txt) == 1 and unicodedata.category(txt) == "Sm" \
150
+ and txt not in _NOT_OPERATORS:
151
+ el.tag = ns + "mo"
152
+ elif tag == "mo" and txt == ".":
153
+ el.tag = ns + "mi"
154
+ # Function application goes after the function, which for \sin^2 means after the
155
+ # whole <msup>: inside it, the script would get three children.
156
+ parents = {child: parent for parent in root.iter() for child in parent}
157
+ local = lambda e: e.tag.rsplit("}", 1)[-1]
158
+ funcs = [el for el in root.iter() if local(el) == "mi" and (el.text or "") in _FUNCTIONS]
159
+ for el in reversed(funcs):
160
+ target = el
161
+ while target in parents and local(parents[target]) in _ARITY \
162
+ and parents[target][0] is target:
163
+ target = parents[target]
164
+ parent = parents.get(target)
165
+ if parent is None:
166
+ continue
167
+ i = list(parent).index(target)
168
+ if i + 1 < len(parent) and local(parent[i + 1]) != "mo":
169
+ fa = ET.Element(ns + "mo")
170
+ fa.text = "\u2061"
171
+ parent.insert(i + 1, fa)
172
+ return ET.tostring(root, encoding="unicode")
173
+
174
+
175
+ def _default_tex_to_mathml(tex):
176
+ try:
177
+ from latex2mathml.converter import convert
178
+ except ImportError:
179
+ raise RuntimeError("math needs the latex2mathml package (pip install latex2mathml) "
180
+ "or config.tex_to_mathml") from None
181
+ return _fix_mathml(convert(tex))
182
+
183
+
184
+ class _Config:
185
+ #: UmbruchBridge instance; if None, one is created for the umbruch executable
186
+ #: found by ``umbruch.Server``.
187
+ bridge = None
188
+ #: callable(tex: str) -> MathML string, or None to use latex2mathml (an error
189
+ #: if that is not installed).
190
+ tex_to_mathml = None
191
+ #: "native" (default): the mesh is one compact ``<g data-umbruch-mesh="gouraud">``
192
+ #: element that umbruch writes as a single type 4 shading. This is an umbruch
193
+ #: extension of SVG and nothing else draws it; it needs an umbruch that reports
194
+ #: the mesh_gouraud capability, and one alpha for the whole mesh (otherwise it
195
+ #: raises). The alternatives are polyfills for other renderers: "subdivide": flat
196
+ #: sub-triangles (works with any renderer); "stock": Matplotlib's three-gradient
197
+ #: filter emulation; "auto": "native" if that is possible, else "subdivide". None
198
+ #: of them works in a wide ``color_space`` yet (umbruch paints meshes in sRGB).
199
+ gouraud = "native"
200
+ gouraud_max_level = 8
201
+ #: Font of ``$...$`` math: a family name (umbruch's own "STIX Two Math" and "Latin
202
+ #: Modern Math", or any OpenType math font Matplotlib finds) or the path of a font
203
+ #: file. None follows ``mathtext.fontset``: "cm" is Latin Modern Math, anything
204
+ #: else STIX Two Math.
205
+ math_font = None
206
+ #: The color space of the numbers Matplotlib works with, one of "srgb" (the
207
+ #: default), "display-p3", "a98-rgb", "prophoto-rgb" and "rec2020". Matplotlib
208
+ #: has no color management, so every RGB value of a figure (colors, colormaps,
209
+ #: image pixels) is just three numbers in [0, 1]; this says which space they are
210
+ #: in. Painted colors are written as CSS ``color(<space> r g b)`` and raster
211
+ #: images get a matching ICC profile. ``savefig(..., color_space=...)`` overrides
212
+ #: it for one file. Colors given as sRGB (hex, names, the default cycle and
213
+ #: colormaps) are only right if converted: see ``convert_color``.
214
+ color_space = None
215
+
216
+
217
+ config = _Config()
218
+
219
+
220
+ # -- color spaces ----------------------------------------------------------------------
221
+
222
+ _D50 = np.array([0.9642, 1.0, 0.8249])
223
+ _D65_XY = (0.3127, 0.3290)
224
+ #: primaries (xy), white point (xy) and transfer function ("srgb" or a gamma) of the
225
+ #: predefined spaces of CSS Color 4 (rec2020 as umbruch sets it: a gamma of 2.4)
226
+ _SPACES = {
227
+ "srgb": ((0.640, 0.330), (0.300, 0.600), (0.150, 0.060), _D65_XY, "srgb"),
228
+ "display-p3": ((0.680, 0.320), (0.265, 0.690), (0.150, 0.060), _D65_XY, "srgb"),
229
+ "a98-rgb": ((0.640, 0.330), (0.210, 0.710), (0.150, 0.060), _D65_XY, 563 / 256),
230
+ "prophoto-rgb": ((0.7347, 0.2653), (0.1596, 0.8404), (0.0366, 0.0001),
231
+ (0.3457, 0.3585), 1.8),
232
+ "rec2020": ((0.708, 0.292), (0.170, 0.797), (0.131, 0.046), _D65_XY, 2.4),
233
+ }
234
+ _BRADFORD = np.array([[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367],
235
+ [0.0389, -0.0685, 1.0296]])
236
+
237
+
238
+ def _space(name):
239
+ try:
240
+ return _SPACES[name]
241
+ except KeyError:
242
+ raise ValueError(f"unknown color space {name!r}: one of "
243
+ f"{', '.join(_SPACES)}") from None
244
+
245
+
246
+ def _xy_to_xyz(xy):
247
+ x, y = xy
248
+ return np.array([x / y, 1.0, (1 - x - y) / y])
249
+
250
+
251
+ @functools.lru_cache(maxsize=None)
252
+ def _to_xyz_d50(name):
253
+ """Matrix from linear RGB of *name* to XYZ with a D50 white (the ICC connection space)."""
254
+ *primaries, white_xy, _ = _space(name)
255
+ P = np.array([_xy_to_xyz(p) for p in primaries]).T
256
+ white = _xy_to_xyz(white_xy)
257
+ M = P * np.linalg.solve(P, white)
258
+ gain = np.diag((_BRADFORD @ _D50) / (_BRADFORD @ white))
259
+ return np.linalg.inv(_BRADFORD) @ gain @ _BRADFORD @ M
260
+
261
+
262
+ def _decode(v, trc):
263
+ v = np.asarray(v, dtype=float)
264
+ a = np.abs(v)
265
+ lin = np.where(a <= 0.04045, a / 12.92, ((a + 0.055) / 1.055) ** 2.4) \
266
+ if trc == "srgb" else a ** trc
267
+ return np.sign(v) * lin
268
+
269
+
270
+ def _encode(v, trc):
271
+ v = np.asarray(v, dtype=float)
272
+ a = np.abs(v)
273
+ enc = np.where(a <= 0.0031308, a * 12.92, 1.055 * a ** (1 / 2.4) - 0.055) \
274
+ if trc == "srgb" else a ** (1 / trc)
275
+ return np.sign(v) * enc
276
+
277
+
278
+ def convert_color(color, src="srgb", dst=None):
279
+ """*color* (any Matplotlib color, or an array of RGB(A) rows) given in the color
280
+ space *src*, as RGB(A) numbers in *dst* (default: ``config.color_space``), clipped
281
+ to the gamut of *dst*. Use it for the colors that Matplotlib supplies as sRGB
282
+ (names, hex, the default colors) when the figure is in another space."""
283
+ dst = dst or config.color_space or "srgb"
284
+ single = isinstance(color, str) or (np.ndim(color) == 1 and len(color) in (3, 4)
285
+ and not isinstance(color[0], str))
286
+ rgba = mpl.colors.to_rgba_array(color)
287
+ if src != dst:
288
+ lin = _decode(rgba[:, :3], _space(src)[4]) @ _to_xyz_d50(src).T
289
+ out = _encode(np.linalg.solve(_to_xyz_d50(dst), lin.T).T, _space(dst)[4])
290
+ rgba = np.concatenate([np.clip(out, 0, 1), rgba[:, 3:]], axis=1)
291
+ return tuple(rgba[0]) if single else rgba
292
+
293
+
294
+ def convert_cmap(cmap, src="srgb", dst=None, N=256):
295
+ """A colormap (a name or a Colormap) whose colors are given in *src*, as a
296
+ ListedColormap of *N* colors in *dst* (see ``convert_color``)."""
297
+ cmap = mpl.colormaps[cmap] if isinstance(cmap, str) else cmap
298
+ colors = convert_color(cmap(np.linspace(0, 1, N)), src, dst)
299
+ return mpl.colors.ListedColormap(colors, name=f"{cmap.name}_{dst or config.color_space}")
300
+
301
+
302
+ def _icc_profile(name):
303
+ """A matrix/TRC ICC profile (version 2) of the color space *name*."""
304
+ *_, trc = _space(name)
305
+ s15 = lambda v: struct.pack(">i", int(round(v * 65536)))
306
+ xyz = lambda v: b"XYZ \0\0\0\0" + b"".join(s15(c) for c in v)
307
+ x = np.linspace(0, 1, 1024)
308
+ curve = b"curv\0\0\0\0" + struct.pack(">I", len(x)) + np.round(
309
+ _decode(x, trc) * 65535).astype(">u2").tobytes()
310
+ text = name.encode("ascii") + b"\0"
311
+ desc = (b"desc\0\0\0\0" + struct.pack(">I", len(text)) + text + b"\0" * 8 + b"\0\0\0"
312
+ + b"\0" * 67)
313
+ M = _to_xyz_d50(name)
314
+ tags = {b"desc": desc, b"cprt": b"text\0\0\0\0" + b"public domain\0",
315
+ b"wtpt": xyz(_D50), b"rXYZ": xyz(M[:, 0]), b"gXYZ": xyz(M[:, 1]),
316
+ b"bXYZ": xyz(M[:, 2]), b"rTRC": curve, b"gTRC": curve, b"bTRC": curve}
317
+ offset = 128 + 4 + 12 * len(tags)
318
+ table, body = b"", b""
319
+ for sig, data in tags.items():
320
+ data += b"\0" * (-len(data) % 4)
321
+ table += sig + struct.pack(">II", offset + len(body), len(data))
322
+ body += data
323
+ size = offset + len(body)
324
+ header = (struct.pack(">I", size) + b"\0\0\0\0" + b"\x02\x40\x00\x00" + b"mntrRGB XYZ "
325
+ + b"\x07\xea\x00\x01\x00\x01\x00\x00\x00\x00\x00\x00" + b"acsp" + b"\0" * 24
326
+ + b"\0\0\0\0" + b"".join(s15(c) for c in _D50) + b"\0" * 4 + b"\0" * 16
327
+ + b"\0" * 28)
328
+ return header + struct.pack(">I", len(tags)) + table + body
329
+
330
+
331
+ def _png_chunk(kind, data):
332
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(
333
+ ">I", zlib.crc32(kind + data))
334
+
335
+
336
+ def _tag_png_uri(uri, space):
337
+ """The ``data:image/png;base64,...`` URI *uri* with the ICC profile of *space* in
338
+ the PNG (after the IHDR chunk), unless it has one already."""
339
+ head, _, data = uri.partition("base64,")
340
+ png = base64.b64decode(data)
341
+ end = 8 + 12 + 13 # the signature and the IHDR chunk
342
+ if png[:8] != b"\x89PNG\r\n\x1a\n" or b"iCCP" in png[:end + 64]:
343
+ return uri
344
+ iccp = _png_chunk(b"iCCP", space.encode() + b"\0\0" + zlib.compress(_icc_profile(space)))
345
+ return head + "base64," + base64.b64encode(png[:end] + iccp + png[end:]).decode("ascii")
346
+
347
+
348
+ class UmbruchBridge:
349
+ """What the backend needs from a renderer. Units are SVG user units, which are
350
+ CSS px inside a foreignObject and, in Matplotlib's SVG, points."""
351
+
352
+ def __init__(self):
353
+ self._cache = {} # key -> (w, h, d) as Matplotlib should see it
354
+ self._ascent = {} # key -> distance from the top of the line box to the baseline
355
+ self._collect = None
356
+ #: what the renderer can do beyond the basics, e.g. {"mesh_gouraud"}
357
+ self.capabilities = frozenset()
358
+
359
+ # to implement -----------------------------------------------------------
360
+ def measure_many(self, items):
361
+ """Measure [(markup, font), ...]; must fill ``self._cache`` for every item."""
362
+ raise NotImplementedError
363
+
364
+ def render(self, svg, width, height):
365
+ """Return PDF bytes for the intermediate document."""
366
+ raise NotImplementedError
367
+
368
+ def render_png(self, svg, width, height, dpi=96):
369
+ """Return the PNG of one page of the intermediate document at *dpi*."""
370
+ raise NotImplementedError
371
+
372
+ # provided ---------------------------------------------------------------
373
+ @staticmethod
374
+ def key(markup, font):
375
+ return (markup, font["css"])
376
+
377
+ def measure(self, markup, font):
378
+ """(width, height, descent) of *markup* set in *font*; the first baseline is
379
+ ``height - descent`` below the top."""
380
+ if markup == "":
381
+ return (0.0, 0.0, 0.0)
382
+ key = self.key(markup, font)
383
+ hit = self._cache.get(key)
384
+ if hit is not None:
385
+ return hit
386
+ if self._collect is not None:
387
+ # a prefetch pass: remember what is missing, answer roughly
388
+ self._collect[key] = (markup, font)
389
+ n = len(_TAG_RE.sub("", markup))
390
+ return (0.6 * font["size"] * n, 1.4 * font["size"], 0.35 * font["size"])
391
+ self.measure_many([(markup, font)])
392
+ return self._cache[key]
393
+
394
+ def ascent(self, markup, font):
395
+ """(ascent, height) of the renderer's own line box: this is where the text is
396
+ placed, not what Matplotlib is told."""
397
+ key = self.key(markup, font)
398
+ if key not in self._ascent:
399
+ self.measure(markup, font)
400
+ return self._ascent.get(key, (1.1 * font["size"], 1.4 * font["size"]))
401
+
402
+ def close(self):
403
+ pass
404
+
405
+
406
+ class UmbruchServer(UmbruchBridge):
407
+ """The bridge to umbruch: an ``umbruch.Server`` (one long-lived ``umbruch --serve``
408
+ process; the executable is ``$UMBRUCH``, the one installed with the package or the
409
+ one on PATH). It sees only the fonts built into umbruch, so that the output does
410
+ not depend on the machine: the fonts of the text are sent along as @font-face.
411
+ ``umbruch.Error`` is raised if it cannot be found or started."""
412
+
413
+ BATCH = 2000
414
+
415
+ def __init__(self, server=None):
416
+ super().__init__()
417
+ self.server = server or umbruch.Server(system_fonts=False)
418
+ self.server.measure([]) # starts the process now, so that errors surface here
419
+ self.capabilities = self.server.capabilities
420
+ missing = {"measure", "render", "stylesheet"} - self.capabilities
421
+ if missing:
422
+ raise umbruch.Error("server", f"umbruch --serve lacks {sorted(missing)}")
423
+ # The @font-face rules of the fonts measured so far, by alias. They are sent once
424
+ # with set_stylesheet and only grow (an alias names one file), so what was measured
425
+ # stays valid.
426
+ self._rules = {}
427
+
428
+ def reset_stylesheet(self):
429
+ """Forgets every @font-face rule, here and in the server: the sheet is per process
430
+ and only grows over a run, so a reset has to empty both sides together."""
431
+ self._rules.clear()
432
+ self.server.set_stylesheet("")
433
+
434
+ def measure_many(self, items):
435
+ items = [it for it in dict((self.key(m, f), (m, f)) for m, f in items).values()
436
+ if self.key(*it) not in self._cache]
437
+ for start in range(0, len(items), self.BATCH):
438
+ chunk = items[start:start + self.BATCH]
439
+ self._send_font_faces(chunk)
440
+ metrics = self.server.measure([
441
+ {"markup": m, "css": f["css"]} for m, f in chunk])
442
+ for (markup, font), m in zip(chunk, metrics):
443
+ if "error" in m:
444
+ raise RuntimeError(f"umbruch could not measure {markup!r}: {m['error']}")
445
+ ink = m["ink"]
446
+ if ink is None: # nothing painted (spaces)
447
+ h = d = 0.0
448
+ else:
449
+ d = max(ink["bottom"], 0.0)
450
+ h = ink["bottom"] - ink["top"]
451
+ key = self.key(markup, font)
452
+ self._cache[key] = (m["width"], h, d)
453
+ self._ascent[key] = (m["ascent"], m["height"])
454
+ if m.get("missing_glyphs"):
455
+ log.warning("no font has %s (in %r)", ", ".join(m["missing_glyphs"]),
456
+ markup[:40])
457
+
458
+ def _send_font_faces(self, chunk):
459
+ """Makes the @font-face rules for *chunk* known to the server (once per face)."""
460
+ styled = any(_STYLED.search(m) for m, _ in chunk)
461
+ faces = _faces_of((f for _, f in chunk), math=any("<math" in m for m, _ in chunk),
462
+ styled=styled)
463
+ keys = [(f["alias"], f["weight"], f["style"]) for f in faces]
464
+ new = {k: _face_css([f]) for k, f in zip(keys, faces) if k not in self._rules}
465
+ if new:
466
+ self._rules.update(new)
467
+ for warning in self.server.set_stylesheet("".join(self._rules.values())):
468
+ log.warning("umbruch: %s", warning)
469
+
470
+ def render(self, svg, width, height):
471
+ rendered = umbruch.HTML(svg, xml=True, server=self.server).render()
472
+ for w in rendered.warnings:
473
+ if "PDF/UA" not in str(w): # not a goal of a plot
474
+ log.warning("umbruch: %s", w)
475
+ return rendered.pdf
476
+
477
+ def render_png(self, svg, width, height, dpi=96):
478
+ if "png" not in self.capabilities:
479
+ raise umbruch.Error("server", "this umbruch has no PNG output (the `png-output` feature)")
480
+ rendered = umbruch.HTML(svg, xml=True, server=self.server).render_png(dpi=dpi)
481
+ for w in rendered.warnings:
482
+ if "PDF/UA" not in str(w):
483
+ log.warning("umbruch: %s", w)
484
+ return rendered.png
485
+
486
+ def close(self):
487
+ self.server.close()
488
+
489
+
490
+ def get_bridge():
491
+ """The bridge to umbruch (started on first use); raises ``umbruch.Error`` if umbruch
492
+ cannot be found or started. There is no fallback to another way of running it."""
493
+ if config.bridge is None:
494
+ config.bridge = UmbruchServer()
495
+ return config.bridge
496
+
497
+
498
+ @functools.lru_cache(maxsize=None)
499
+ def _font_data_uri(path):
500
+ with open(path, "rb") as fh:
501
+ data = base64.b64encode(fh.read()).decode("ascii")
502
+ return f"data:{'font/otf' if path.lower().endswith('.otf') else 'font/ttf'};base64,{data}"
503
+
504
+
505
+ @functools.lru_cache(maxsize=None)
506
+ def _face_of(path):
507
+ """The face Matplotlib found at *path*, as a description for @font-face.
508
+
509
+ The alias is the **family's**, not the file's: CSS font matching stays inside the first
510
+ family that has the feature at all, so a ``<b>`` or ``<i>`` inside a ``rich()`` string can
511
+ only find a bold or italic face if it is a face of the same family name. Faces of one
512
+ family therefore share the alias and differ in ``weight`` and ``style``."""
513
+ entry = next((e for e in fm.fontManager.ttflist if e.fname == path), None)
514
+ if entry is None: # a file Matplotlib has no entry for: a family of its own
515
+ ident = f"{path}:{os.path.getmtime(path)}"
516
+ return {"alias": "mpl-" + hashlib.sha1(ident.encode()).hexdigest()[:12], "path": path,
517
+ "weight": None, "style": None, "family": None}
518
+ family = entry.name
519
+ return {"alias": "mpl-" + hashlib.sha1(family.encode()).hexdigest()[:12], "path": path,
520
+ "weight": int(fm.weight_dict.get(entry.weight, entry.weight)),
521
+ "style": entry.style, "family": family}
522
+
523
+
524
+ def _face_css(faces):
525
+ return "".join(
526
+ f"@font-face{{font-family:'{f['alias']}';font-weight:{f['weight']};"
527
+ f"font-style:{f['style']};src:url({_font_data_uri(f['path'])})}}"
528
+ for f in {(f["alias"], f["weight"], f["style"]): f for f in faces}.values())
529
+
530
+
531
+ #: markup that asks for another face of the same family
532
+ _STYLED = re.compile(r"<(b|strong|i|em)[\s>/]", re.IGNORECASE)
533
+
534
+
535
+ def _family_faces(face):
536
+ """*face* and the faces of its family that styled markup can ask for: bold, italic and
537
+ bold italic, when Matplotlib finds them."""
538
+ if not face or not face.get("family"):
539
+ return (face,) if face else ()
540
+ found = [face]
541
+ for weight, style in (("bold", "normal"), ("normal", "italic"), ("bold", "italic")):
542
+ try:
543
+ path = fm.findfont(fm.FontProperties(family=face["family"], weight=weight, style=style),
544
+ fallback_to_default=False)
545
+ except (ValueError, OSError):
546
+ continue
547
+ other = _face_of(path)
548
+ if other["family"] != face["family"]:
549
+ continue
550
+ found.append(other)
551
+ return tuple(found)
552
+
553
+
554
+ def _faces_of(fonts, math=False, styled=False):
555
+ """The faces of *fonts* (those that are files) — with the bold and italic faces of their
556
+ families when the text has styled markup — and of the math font if *math*."""
557
+ faces = []
558
+ for f in fonts:
559
+ if f.get("face"):
560
+ faces.extend(_family_faces(f["face"]) if styled else (f["face"],))
561
+ if math:
562
+ faces.append(_math_font()[1])
563
+ return [f for f in faces if f]
564
+
565
+
566
+ def _font_face_css(fonts, math=False, styled=False):
567
+ """@font-face rules (the font files as data: URIs) for the fonts of *fonts*, and for
568
+ the math font if *math* and it is a file."""
569
+ return _face_css(_faces_of(fonts, math, styled))
570
+
571
+
572
+ _MATH_BUNDLED = {"stix two math", "latin modern math"}
573
+
574
+
575
+ def _math_font():
576
+ """(CSS font-family value, face to embed or None) of the math font."""
577
+ value = config.math_font
578
+ if value is None:
579
+ value = "Latin Modern Math" if mpl.rcParams["mathtext.fontset"] == "cm" else None
580
+ return _math_font_for(value)
581
+
582
+
583
+ @functools.lru_cache(maxsize=None)
584
+ def _math_font_for(value):
585
+ if value is None:
586
+ return None, None
587
+ if value.lower() in _MATH_BUNDLED:
588
+ return repr(value), None
589
+ path = value if os.path.isfile(value) else None
590
+ if path is None:
591
+ try:
592
+ path = fm.findfont(fm.FontProperties(family=value), fallback_to_default=False)
593
+ except ValueError:
594
+ raise ValueError(f"math font {value!r} not found: give the family of an "
595
+ "OpenType math font Matplotlib can find, or a file") from None
596
+ ident = f"{path}:{os.path.getmtime(path)}"
597
+ face = {"alias": "mpl-math-" + hashlib.sha1(ident.encode()).hexdigest()[:12],
598
+ "path": path, "weight": 400, "style": "normal"}
599
+ return repr(face["alias"]), face
600
+
601
+
602
+ def _style_math(ml):
603
+ """Set the math font on the <math> elements of *ml* (a rule in a style sheet would
604
+ not reach the probes of a measure request, a style attribute does)."""
605
+ family = _math_font()[0]
606
+ if family is None:
607
+ return ml
608
+ return re.sub(r"<math\b", f'<math style="font-family:{family}"', ml)
609
+
610
+
611
+ def _font_spec(prop):
612
+ """What the renderer needs to set text in *prop*: the CSS, and the font file that
613
+ Matplotlib itself would use, which is sent along as an @font-face (umbruch cannot
614
+ see the system's fonts, and this way it sets exactly the face Matplotlib measured
615
+ for). The families of *prop* follow as fallbacks."""
616
+ weight = prop.get_weight()
617
+ weight = fm.weight_dict.get(weight, weight)
618
+ try:
619
+ face = _face_of(fm.findfont(prop))
620
+ except (ValueError, OSError):
621
+ face = None
622
+ if face and face["weight"] is not None:
623
+ weight, style = face["weight"], face["style"]
624
+ else:
625
+ face, style = None, prop.get_style()
626
+ names = []
627
+ for entry in prop.get_family():
628
+ entry = "sans-serif" if entry in ("sans", "sans serif") else entry
629
+ if entry in fm.font_family_aliases:
630
+ names += ["sans-serif" if n in ("sans", "sans serif") else n
631
+ for n in fm.FontManager._expand_aliases(entry)]
632
+ names.append(entry)
633
+ names = list(dict.fromkeys(names))
634
+ quoted = [n if n in fm.font_family_aliases or n == "sans-serif" else repr(n)
635
+ for n in names]
636
+ if face:
637
+ quoted.insert(0, repr(face["alias"]))
638
+ return {"prop": prop, "family": names, "size": float(prop.get_size()), "weight": int(weight),
639
+ "face": face, "style": style, "variant": prop.get_variant(),
640
+ "stretch": prop.get_stretch(),
641
+ "css": (f"font-family:{', '.join(quoted)};font-size:{_fmt(prop.get_size())}px;"
642
+ f"font-weight:{int(weight)};font-style:{style};"
643
+ f"font-variant:{prop.get_variant()}"
644
+ + ("" if prop.get_stretch() == "normal" else
645
+ f";font-stretch:{prop.get_stretch()}"))}
646
+
647
+
648
+ _TEXT_MACROS = {"times": "\u00d7", "cdot": "\u00b7", "pm": "\u00b1", ",": "\u2009",
649
+ ";": "\u2005", " ": " ", "%": "%", "_": "_", "{": "{", "}": "}",
650
+ "$": "$", "#": "#", "&": "&"}
651
+
652
+
653
+ def _mathdefault_html(tex):
654
+ """Matplotlib wraps tick labels in ``\\mathdefault{...}`` to say "set this in the
655
+ regular text font" (``10^{3}``, ``1\\times10^{-2}``). That is text with scripts,
656
+ not math, so it becomes inline XHTML in the surrounding font. Anything beyond that
657
+ small subset raises ValueError."""
658
+ def group(i, closing):
659
+ out = []
660
+ while i < len(tex):
661
+ c = tex[i]
662
+ if c == "}":
663
+ if closing:
664
+ return "".join(out), i + 1
665
+ raise ValueError(f"unbalanced '}}' in {tex!r}")
666
+ if c == "\\":
667
+ j = i + 1
668
+ if j < len(tex) and tex[j].isalpha():
669
+ while j < len(tex) and tex[j].isalpha():
670
+ j += 1
671
+ name = tex[i + 1:j]
672
+ else:
673
+ name, j = tex[i + 1:j + 1], j + 1
674
+ if name == "mathdefault":
675
+ if j >= len(tex) or tex[j] != "{":
676
+ raise ValueError(f"\\mathdefault needs a braced argument in {tex!r}")
677
+ inner, i = group(j + 1, True)
678
+ out.append(inner)
679
+ elif name in _TEXT_MACROS:
680
+ out.append(escape(_TEXT_MACROS[name]))
681
+ i = j
682
+ else:
683
+ raise ValueError(f"\\{name} is not supported in \\mathdefault text "
684
+ f"{tex!r}")
685
+ elif c in "^_":
686
+ tag = "sup" if c == "^" else "sub"
687
+ i += 1
688
+ if i >= len(tex):
689
+ raise ValueError(f"dangling {c!r} in {tex!r}")
690
+ if tex[i] == "{":
691
+ inner, i = group(i + 1, True)
692
+ else:
693
+ inner, i = group_one(i)
694
+ out.append(f"<{tag}>{inner}</{tag}>")
695
+ elif c == "{":
696
+ inner, i = group(i + 1, True)
697
+ out.append(inner)
698
+ else:
699
+ out.append(escape("\u2212" if c == "-" else c))
700
+ i += 1
701
+ if closing:
702
+ raise ValueError(f"unbalanced '{{' in {tex!r}")
703
+ return "".join(out), i
704
+
705
+ def group_one(i):
706
+ # a single character or macro as script argument
707
+ if tex[i] == "\\":
708
+ j = i + 2 if not tex[i + 1:i + 2].isalpha() else i + 1
709
+ while j < len(tex) and tex[i + 1:i + 2].isalpha() and tex[j].isalpha():
710
+ j += 1
711
+ return group_sub(tex[i:j]), j
712
+ return escape("\u2212" if tex[i] == "-" else tex[i]), i + 1
713
+
714
+ def group_sub(piece):
715
+ return _mathdefault_html(piece)
716
+
717
+ return group(0, False)[0]
718
+
719
+
720
+ _MATH_RE = re.compile(r"(?<!\\)\$(.+?)(?<!\\)\$", re.S)
721
+ _TAG_RE = re.compile(r"<[^>]+>")
722
+
723
+
724
+ _MATH_EL_RE = re.compile(r"<math\b.*?</math>", re.S)
725
+
726
+
727
+ def _plain_text(markup):
728
+ """The text of a markup fragment, without tags and without math (as XML text)."""
729
+ import html
730
+ text = html.unescape(_TAG_RE.sub("", _MATH_EL_RE.sub("", markup)))
731
+ return text if text.strip() else "x"
732
+
733
+
734
+ def _ink_height_descent(text, font):
735
+ from matplotlib.textpath import TextToPath
736
+ _, h, d = TextToPath().get_text_width_height_descent(text, font["prop"], False)
737
+ return h, d
738
+
739
+
740
+ def _check_xml(fragment):
741
+ try:
742
+ ET.fromstring(f'<div xmlns="{XHTML}">{fragment}</div>')
743
+ except ET.ParseError as e:
744
+ raise ValueError(f"rich text is not well-formed XML ({e}): {fragment!r}") from None
745
+
746
+
747
+ class _RawWriter(_XMLWriter):
748
+ #: the color space of the figure: PNG images are written with its ICC profile
749
+ color_space = None
750
+
751
+ def element(self, tag, text="", attrib={}, **extra):
752
+ href = attrib.get("xlink:href", "")
753
+ if tag == "image" and self.color_space not in (None, "srgb") \
754
+ and href.startswith("data:image/png;base64,"):
755
+ attrib = {**attrib, "xlink:href": _tag_png_uri(href, self.color_space)}
756
+ super().element(tag, text, attrib, **extra)
757
+
758
+ def raw(self, s):
759
+ # Pretty-printing would insert whitespace between inline elements.
760
+ self._XMLWriter__flush()
761
+ self._XMLWriter__write(s)
762
+
763
+
764
+ class RendererUmbruch(RendererSVG):
765
+ def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,
766
+ *, metadata=None, bridge, color_space=None):
767
+ super().__init__(width, height, svgwriter, basename, image_dpi,
768
+ metadata=metadata)
769
+ self.writer.__class__ = _RawWriter
770
+ self.bridge = bridge
771
+ self.color_space = color_space
772
+ self.writer.color_space = color_space
773
+ self._fonts = {}
774
+ self._math = False
775
+ self._styled = False
776
+
777
+ # -- colors -------------------------------------------------------------
778
+
779
+ def _css_color(self, rgb):
780
+ """*rgb* as a CSS color: in the figure's color space at full precision (stock
781
+ SVG writes hex, which rounds to 1/255), or as hex for sRGB."""
782
+ if self.color_space in (None, "srgb"):
783
+ return rgb2hex(rgb)
784
+ return "color({} {})".format(self.color_space,
785
+ " ".join(f"{float(v):.6g}" for v in rgb[:3]))
786
+
787
+ def _get_style_dict(self, gc, rgbFace):
788
+ attrib = super()._get_style_dict(gc, rgbFace)
789
+ if self.color_space not in (None, "srgb"):
790
+ if attrib.get("fill", "").startswith("#"):
791
+ attrib["fill"] = self._css_color(rgbFace)
792
+ if attrib.get("stroke", "").startswith("#"):
793
+ attrib["stroke"] = self._css_color(gc.get_rgb())
794
+ return attrib
795
+
796
+ def _write_hatches(self):
797
+ """As stock SVG, with the colors of the pattern in the figure's color space."""
798
+ if self.color_space in (None, "srgb"):
799
+ return super()._write_hatches()
800
+ if not len(self._hatchd):
801
+ return
802
+ size = 72
803
+ wr = self.writer
804
+ wr.start("defs")
805
+ for (path, face, stroke, *lw), oid in self._hatchd.values():
806
+ # the line width is part of the key since Matplotlib 3.11
807
+ lw = lw[0] if lw else mpl.rcParams["hatch.linewidth"]
808
+ wr.start("pattern", id=oid, patternUnits="userSpaceOnUse", x="0", y="0",
809
+ width=str(size), height=str(size))
810
+ path_data = self._convert_path(
811
+ path, Affine2D().scale(size).scale(1.0, -1.0).translate(0, size),
812
+ simplify=False)
813
+ wr.element("rect", x="0", y="0", width=str(size + 1), height=str(size + 1),
814
+ fill="none" if face is None else self._css_color(face))
815
+ style = {"fill": self._css_color(stroke), "stroke": self._css_color(stroke),
816
+ "stroke-width": str(lw), "stroke-linecap": "butt",
817
+ "stroke-linejoin": "miter"}
818
+ if stroke[3] < 1:
819
+ style["stroke-opacity"] = str(stroke[3])
820
+ wr.element("path", d=path_data, style=_generate_css(style))
821
+ wr.end("pattern")
822
+ wr.end("defs")
823
+
824
+ # -- text ---------------------------------------------------------------
825
+
826
+ def _markup(self, s, ismath):
827
+ """Inline XHTML/MathML for *s*. What umbruch cannot set is an error: there is
828
+ no quiet fallback to Matplotlib's own mathtext or usetex rendering."""
829
+ if ismath == "TeX":
830
+ raise NotImplementedError(
831
+ "text.usetex is not supported by the umbruch backend; use mathtext "
832
+ "($...$), which is converted to MathML, or rich()")
833
+ is_rich = s.startswith(RICH_MARK)
834
+ if is_rich:
835
+ s = s[1:]
836
+ esc = (lambda t: t) if is_rich else escape
837
+ if not ismath:
838
+ return esc(s)
839
+ conv = config.tex_to_mathml or _default_tex_to_mathml
840
+ out, pos = [], 0
841
+ for m in _MATH_RE.finditer(s):
842
+ if m.group(1).lstrip().startswith("\\mathdefault{"):
843
+ out.append(esc(s[pos:m.start()]).replace(r"\$", "$"))
844
+ out.append(_mathdefault_html(m.group(1).strip()))
845
+ pos = m.end()
846
+ continue
847
+ try:
848
+ ml = conv(m.group(1))
849
+ except Exception as e: # a converter that cannot read this TeX
850
+ raise RuntimeError(f"cannot convert math {m.group(1)!r} to MathML: {e}") from e
851
+ if ml is None:
852
+ raise RuntimeError(f"cannot convert math {m.group(1)!r} to MathML: the "
853
+ "converter returned None")
854
+ out.append(esc(s[pos:m.start()]).replace(r"\$", "$"))
855
+ out.append(_style_math(ml))
856
+ pos = m.end()
857
+ out.append(esc(s[pos:]).replace(r"\$", "$"))
858
+ return "".join(out)
859
+
860
+ def get_text_width_height_descent(self, s, prop, ismath):
861
+ return self.bridge.measure(self._markup(s, ismath), _font_spec(prop))
862
+
863
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
864
+ markup = self._markup(s, ismath)
865
+ font = _font_spec(prop)
866
+ if font["face"]:
867
+ self._fonts[font["face"]["alias"]] = font
868
+ self._math = self._math or "<math" in markup
869
+ self._styled = self._styled or bool(_STYLED.search(markup))
870
+ w, h, d = self.bridge.measure(markup, font)
871
+ asc, box_h = self.bridge.ascent(markup, font)
872
+ alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3]
873
+ # the same declarations as the probes of the measure op, plus paint
874
+ pad = 0.25 * font["size"]
875
+ style = (f"margin:{_fmt(pad)}px 0 0 {_fmt(pad)}px;padding:0;"
876
+ f"white-space:pre;line-height:normal;"
877
+ f"{font['css']};color:{self._css_color(gc.get_rgb())}")
878
+ if alpha != 1:
879
+ style += f";opacity:{_fmt(alpha)}"
880
+ div = f'<div xmlns="{XHTML}" style="{style}">{markup}</div>'
881
+ _check_xml(markup)
882
+ clip = self._get_clip_attrs(gc)
883
+ wr = self.writer
884
+ if clip:
885
+ wr.start("g", **clip)
886
+ tf = f"translate({_fmt(x)} {_fmt(y)})"
887
+ if angle:
888
+ tf += f" rotate({_fmt(-angle)})"
889
+ wr.start("g", transform=tf)
890
+ # The box top is one ascent above the baseline origin. The island is clipped
891
+ # to its box, so it gets a little room for overhanging glyphs.
892
+ wr.start("foreignObject", x=_fmt(-pad), y=_fmt(-asc - pad),
893
+ width=_fmt(w + 2 * pad), height=_fmt(box_h + 2 * pad))
894
+ wr.raw(div)
895
+ wr.end("foreignObject", indent=False)
896
+ wr.end("g")
897
+ if clip:
898
+ wr.end("g")
899
+
900
+ def finalize(self):
901
+ rules = _font_face_css(self._fonts.values(), math=self._math, styled=self._styled)
902
+ if rules:
903
+ self.writer.start("style")
904
+ self.writer.data(rules)
905
+ self.writer.end("style")
906
+ super().finalize()
907
+
908
+ # -- meshes -------------------------------------------------------------
909
+
910
+ def draw_gouraud_triangles(self, gc, triangles_array, colors_array, transform):
911
+ mode = config.gouraud
912
+ if mode not in ("native", "auto", "subdivide", "stock"):
913
+ raise ValueError(f"config.gouraud must be 'native', 'auto', 'subdivide' or "
914
+ f"'stock', not {mode!r}")
915
+ if self.color_space not in (None, "srgb"):
916
+ raise NotImplementedError(
917
+ f"Gouraud shading is not supported in the {self.color_space} color space "
918
+ "yet (umbruch paints meshes in sRGB): use shading='flat' or 'nearest', "
919
+ "or color_space='srgb'")
920
+ if mode == "stock":
921
+ return super().draw_gouraud_triangles(gc, triangles_array, colors_array,
922
+ transform)
923
+ if (mode == "native" and self.bridge.capabilities
924
+ and "mesh_gouraud" not in self.bridge.capabilities):
925
+ log.warning("this umbruch lacks the mesh_gouraud capability: its Gouraud "
926
+ "meshes are not drawn; update umbruch or set "
927
+ "config.gouraud = 'subdivide'")
928
+ cols = np.asarray(colors_array, dtype=float)
929
+ if cols.shape[-1] == 1:
930
+ cols = np.repeat(cols, 3, axis=-1)
931
+ if cols.shape[-1] == 3:
932
+ cols = np.concatenate([cols, np.ones(cols.shape[:-1] + (1,))], axis=-1)
933
+ # umbruch paints a mesh as one shading, which has one alpha
934
+ problem = None
935
+ if mode == "auto" and "mesh_gouraud" not in self.bridge.capabilities:
936
+ problem = "this umbruch cannot paint meshes"
937
+ elif np.ptp(cols[..., 3]) > 1 / 512:
938
+ problem = "the alpha changes between the vertices"
939
+ if mode == "native" and problem:
940
+ raise ValueError(f"config.gouraud = 'native' is not possible: {problem}; "
941
+ "use config.gouraud = 'subdivide'")
942
+ native = mode == "native" or (mode == "auto" and not problem)
943
+
944
+ wr = self.writer
945
+ trans = self._make_flip_transform(transform.frozen())
946
+ wr.start("g", **self._get_clip_attrs(gc))
947
+ if native:
948
+ self._native_mesh(trans, np.asarray(triangles_array, dtype=float), cols)
949
+ else:
950
+ wr.start("g")
951
+ for pts, c in zip(triangles_array, cols):
952
+ self._subdivided(trans.transform(pts), c)
953
+ wr.end("g")
954
+ wr.end("g")
955
+
956
+ def _native_mesh(self, trans, triangles, cols):
957
+ """The mesh as one element: the distinct vertices (x, y, r, g, b, a) and the
958
+ triangles as indices into them. A mesh of a grid shares most of its vertices
959
+ between triangles, and one element is much faster for umbruch to read than a
960
+ path per triangle."""
961
+ p = trans.transform(triangles.reshape(-1, 2))
962
+ rows = np.concatenate([np.round(p, 3), np.round(cols.reshape(-1, 4), 4)], axis=1)
963
+ rows = np.nan_to_num(rows, nan=0.0, posinf=0.0, neginf=0.0)
964
+ vertices, index = np.unique(rows, axis=0, return_inverse=True)
965
+ self.writer.element("g", attrib={
966
+ "data-umbruch-mesh": "gouraud",
967
+ "data-vertices": " ".join(map(repr, vertices.ravel().tolist())),
968
+ "data-triangles": " ".join(map(str, index.ravel().tolist()))})
969
+
970
+ def _tri(self, p, rgba, seam=False):
971
+ attrib = {"fill-opacity": _fmt(rgba[3])}
972
+ if seam and rgba[3] >= 1:
973
+ # a hairline of the same color hides the seams that antialiasing leaves
974
+ # between flat neighbours
975
+ attrib.update({"stroke": self._css_color(rgba[:3]), "stroke-width": "0.4",
976
+ "stroke-linejoin": "round"})
977
+ else:
978
+ attrib["stroke"] = "none"
979
+ self.writer.element(
980
+ "path", d="M{} {}L{} {}L{} {}Z".format(*(_fmt(v) for v in p.ravel())),
981
+ fill=self._css_color(rgba[:3]), attrib=attrib)
982
+
983
+ def _subdivided(self, p, c):
984
+ """Approximate a Gouraud triangle by flat ones: n*n sub-triangles, each in the
985
+ color of its centroid. n follows the color range and the size, so smooth
986
+ large triangles get many and tiny or flat ones few."""
987
+ span = float((c.max(axis=0) - c.min(axis=0))[:3].max())
988
+ edge = max(np.hypot(*(p[i] - p[(i + 1) % 3])) for i in range(3))
989
+ n = int(min(config.gouraud_max_level, max(1, np.ceil(span * 24)),
990
+ max(1, np.ceil(edge / 2.0))))
991
+ if n == 1:
992
+ return self._tri(p, c.mean(axis=0), seam=True)
993
+
994
+ def pt(i, j): # barycentric weights (n-i-j, i, j)/n
995
+ w = np.array([n - i - j, i, j]) / n
996
+ return w @ p, w @ c
997
+
998
+ for i in range(n):
999
+ for j in range(n - i):
1000
+ up = [pt(i, j), pt(i + 1, j), pt(i, j + 1)]
1001
+ self._tri(np.array([q[0] for q in up]),
1002
+ np.mean([q[1] for q in up], axis=0), seam=True)
1003
+ if i + j < n - 1:
1004
+ dn = [pt(i + 1, j), pt(i + 1, j + 1), pt(i, j + 1)]
1005
+ self._tri(np.array([q[0] for q in dn]),
1006
+ np.mean([q[1] for q in dn], axis=0), seam=True)
1007
+
1008
+
1009
+ class FigureCanvasUmbruch(FigureCanvasSVG):
1010
+ filetypes = {"pdf": "Portable Document Format (umbruch)",
1011
+ "svg": "SVG with umbruch extensions",
1012
+ "png": "Portable Network Graphics (umbruch)"}
1013
+
1014
+ def get_default_filetype(self):
1015
+ return "pdf"
1016
+
1017
+ def _draw_to(self, fh, bridge, bbox_inches_restore, metadata, color_space=None):
1018
+ dpi = self.figure.dpi
1019
+ self.figure.dpi = 72
1020
+ width, height = self.figure.get_size_inches()
1021
+ w, h = width * 72, height * 72
1022
+ renderer = MixedModeRenderer(
1023
+ self.figure, width, height, dpi,
1024
+ RendererUmbruch(w, h, fh, image_dpi=dpi, metadata=metadata, bridge=bridge,
1025
+ color_space=color_space),
1026
+ bbox_inches_restore=bbox_inches_restore)
1027
+ self.figure.draw(renderer)
1028
+ renderer.finalize()
1029
+ return w, h
1030
+
1031
+ def _prefetch(self, bridge):
1032
+ """Draw to nowhere to collect the strings, measure them in one batch, repeat
1033
+ until a drawing needs nothing new (layout can change the strings, e.g. ticks)."""
1034
+ for _ in range(4):
1035
+ bridge._collect = {}
1036
+ try:
1037
+ self._draw_to(io.StringIO(), bridge, None, None)
1038
+ finally:
1039
+ pending, bridge._collect = bridge._collect, None
1040
+ if not pending:
1041
+ return
1042
+ bridge.measure_many(list(pending.values()))
1043
+
1044
+ def _svg_text(self, bridge, bbox_inches_restore, metadata, color_space):
1045
+ space = color_space or config.color_space
1046
+ if space is not None:
1047
+ _space(space)
1048
+ buf = io.StringIO()
1049
+ size = self._draw_to(buf, bridge, bbox_inches_restore, metadata, space)
1050
+ return buf.getvalue(), size
1051
+
1052
+ def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None,
1053
+ color_space=None, **kwargs):
1054
+ bridge = get_bridge()
1055
+ self._prefetch(bridge)
1056
+ text, _ = self._svg_text(bridge, bbox_inches_restore, metadata, color_space)
1057
+ with cbook.open_file_cm(filename, "w", encoding="utf-8") as fh:
1058
+ if not cbook.file_requires_unicode(fh):
1059
+ import codecs
1060
+ fh = codecs.getwriter("utf-8")(fh)
1061
+ fh.write(text)
1062
+
1063
+ def print_pdf(self, filename, *, bbox_inches_restore=None, metadata=None,
1064
+ color_space=None, **kwargs):
1065
+ bridge = get_bridge()
1066
+ self._prefetch(bridge)
1067
+ svg, (w, h) = self._svg_text(bridge, bbox_inches_restore, None, color_space)
1068
+ data = bridge.render(svg, w, h)
1069
+ with cbook.open_file_cm(filename, "wb") as fh:
1070
+ fh.write(data)
1071
+
1072
+ def print_png(self, filename, *, bbox_inches_restore=None, metadata=None,
1073
+ color_space=None, **kwargs):
1074
+ """The same page as :meth:`print_pdf`, rasterized by umbruch at the figure's dpi
1075
+ (Matplotlib has set it to the `dpi` of the `savefig` before this is called)."""
1076
+ bridge = get_bridge()
1077
+ dpi = int(round(self.figure.dpi))
1078
+ self._prefetch(bridge)
1079
+ svg, (w, h) = self._svg_text(bridge, bbox_inches_restore, metadata, color_space)
1080
+ data = bridge.render_png(svg, w, h, dpi=dpi)
1081
+ with cbook.open_file_cm(filename, "wb") as fh:
1082
+ fh.write(data)
1083
+
1084
+
1085
+ FigureCanvas = FigureCanvasUmbruch