Debian Codegraph @

src/fabio/qt/matplotlib.py

raw
1 # /*##########################################################################
2 #
3 # Copyright (c) 2016-2024 European Synchrotron Radiation Facility
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
13 # all 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
21 # THE SOFTWARE.
22 #
23 # ###########################################################################*/
24
25 """This module initializes matplotlib and sets-up the backend to use.
26
27 It MUST be imported prior to any other import of matplotlib.
28
29 It provides the matplotlib :class:`FigureCanvasQTAgg` class corresponding
30 to the used backend.
31 """
32
33 from __future__ import annotations
34
35
36 __authors__ = ["T. Vincent"]
37 __license__ = "MIT"
38 __date__ = "12/03/2026"
39
40
41 import io
42 import matplotlib
43 import numpy
44
45 from qtpy import API as BINDING
46 from qtpy.QtGui import QFont
47
48 # This must be performed before any import from matplotlib
49 if BINDING in ("pyside6", "pyqt6"):
50 matplotlib.use("QtAgg", force=False)
51 from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg # noqa
52 from matplotlib.backends.backend_qtagg import NavigationToolbar2QT # noqa
53 elif BINDING =="pyqt5":
54 matplotlib.use("Qt5Agg", force=False)
55 from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg # noqa
56 from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT # noqa
57 else:
58 raise ImportError("Unsupported Qt binding: %s" % BINDING)
59
60
61 from matplotlib.font_manager import FontProperties
62 from matplotlib.mathtext import MathTextParser
63 from matplotlib.ticker import ScalarFormatter as _ScalarFormatter
64 from matplotlib import figure, font_manager
65 from packaging.version import Version
66
67 _MATPLOTLIB_VERSION = Version(matplotlib.__version__)
68
69
70 class DefaultTickFormatter(_ScalarFormatter):
71 """Tick label formatter"""
72
73 def __init__(self):
74 super().__init__(useOffset=True, useMathText=True)
75 self.set_scientific(True)
76 self.create_dummy_axis()
77
78 if _MATPLOTLIB_VERSION < Version("3.1.0"):
79
80 def format_ticks(self, values):
81 self.set_locs(values)
82 return [self(value, i) for i, value in enumerate(values)]
83
84
85 _FONT_STYLES = {
86 QFont.StyleNormal: "normal",
87 QFont.StyleItalic: "italic",
88 QFont.StyleOblique: "oblique",
89 }
90
91
92 def qFontToFontProperties(font: QFont):
93 """Convert a QFont to a matplotlib FontProperties"""
94 weightFactor = 10 if BINDING == "PyQt5" else 1
95 families = [font.family(), font.defaultFamily()]
96 if _MATPLOTLIB_VERSION >= Version("3.6.0"):
97 # Prevent 'Font family not found' warnings
98 availableNames = font_manager.get_font_names()
99 families = [f for f in families if f in availableNames]
100 families.append(font_manager.fontManager.defaultFamily["ttf"])
101
102 if "Sans" in font.family():
103 families.insert(0, "sans-serif")
104
105 return FontProperties(
106 family=families,
107 style=_FONT_STYLES[font.style()],
108 weight=weightFactor * font.weight(),
109 size=font.pointSizeF(),
110 )
111
112
113 def rasterMathText(
114 text: str,
115 font: QFont,
116 dotsPerInch: float = 96.0,
117 ) -> tuple[numpy.ndarray, float]:
118 """Raster text using matplotlib supporting latex-like math syntax.
119
120 It supports multiple lines.
121
122 :param text: The text to raster
123 :param font: Font to use
124 :param dotsPerInch: The DPI resolution of the created image
125 :return: Corresponding image in gray scale and baseline offset from top
126 """
127 # Implementation adapted from:
128 # https://github.com/matplotlib/matplotlib/blob/d624571a19aec7c7d4a24123643288fc27db17e7/lib/matplotlib/mathtext.py#L264
129
130 stripped_text = text.strip("\n")
131 font_prop = qFontToFontProperties(font)
132
133 parser = MathTextParser("path")
134 lines_info = [
135 parser.parse(line, prop=font_prop, dpi=dotsPerInch)
136 for line in stripped_text.split("\n")
137 ]
138 max_line_width = max(info[0] for info in lines_info)
139 # Use lp string as minimum height/ascent
140 ref_info = parser.parse("lp", prop=font_prop, dpi=dotsPerInch)
141 line_height = max(
142 ref_info[1],
143 *(info[1] for info in lines_info),
144 )
145 first_line_ascent = max(
146 ref_info[1] - ref_info[2], lines_info[0][1] - lines_info[0][2]
147 )
148
149 linespacing = 1.2
150
151 figure_height = numpy.ceil(line_height * len(lines_info) * linespacing) + 2
152 fig = figure.Figure(
153 figsize=(
154 (max_line_width + 1) / dotsPerInch,
155 figure_height / dotsPerInch,
156 )
157 )
158 fig.set_dpi(dotsPerInch)
159 text = fig.text(
160 0,
161 1,
162 stripped_text,
163 fontproperties=font_prop,
164 verticalalignment="top",
165 )
166 text.set_linespacing(linespacing)
167 with io.BytesIO() as buffer:
168 fig.savefig(buffer, dpi=dotsPerInch, format="raw")
169 canvas_width, canvas_height = fig.get_window_extent().max
170 buffer.seek(0)
171 image = numpy.frombuffer(buffer.read(), dtype=numpy.uint8).reshape(
172 int(canvas_height), int(canvas_width), 4
173 )
174
175 # RGB to inverted R channel
176 array = 255 - image[:, :, 0]
177
178 # Remove leading/trailing empty columns and trailing rows but one on each side
179 filled_rows = numpy.nonzero(numpy.sum(array, axis=1))[0]
180 filled_columns = numpy.nonzero(numpy.sum(array, axis=0))[0]
181 if len(filled_rows) == 0 or len(filled_columns) == 0:
182 return array, first_line_ascent
183 return (
184 numpy.ascontiguousarray(
185 array[
186 0 : filled_rows[-1] + 2,
187 max(0, filled_columns[0] - 1) : filled_columns[-1] + 2,
188 ]
189 ),
190 first_line_ascent,
191 )