-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathtest_backends_rendering.py
More file actions
333 lines (252 loc) · 12.4 KB
/
Copy pathtest_backends_rendering.py
File metadata and controls
333 lines (252 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
from io import StringIO
from operator import attrgetter
import numpy as np
import pytest
import matplotlib.pyplot as plt
from matplotlib.artist import Artist, BlendMode
from matplotlib.backends.backend_agg import RendererAgg
from matplotlib.backends.backend_pdf import RendererPdf
from matplotlib.backends.backend_pgf import RendererPgf
from matplotlib.backends.backend_svg import RendererSVG
from matplotlib.figure import Figure
from matplotlib.patches import Circle, PathPatch, Polygon, Rectangle
from matplotlib.path import Path
from matplotlib.testing._markers import needs_pgf_pdflatex
from matplotlib.testing.decorators import image_comparison
try:
# Import the same cairo (pycairo or cairocffi) that is used by the backend
from matplotlib.backends.backend_cairo import RendererCairo, cairo
cairo_version = cairo.cairo_version()
except ImportError:
RendererCairo = None
cairo_version = None
def plot_blend_mode_gallery(text=True, gouraud=True, rasterize=False):
N = 10
data = np.arange(N**2).reshape((N, N)) % (N-1)
fig, axs = plt.subplots(3, 8, figsize=(10, 5.5), dpi=80, layout="tight")
axs = axs.flatten()
fig.set_facecolor("none")
for ax in axs:
if rasterize:
ax.set_rasterization_zorder(6)
ax.set_facecolor("none")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1.2)
ax.set_axis_off()
for i, blend_mode in enumerate(BlendMode):
axs[i].imshow(data, cmap='Reds', alpha=0.75, extent=(0, 0.8, 0, 0.8))
axs[i].imshow(data[::-1, :], cmap='Blues', alpha=0.75,
extent=(0.2, 1, 0.4, 1.2), blend_mode=blend_mode)
if gouraud:
axs[i].pcolormesh(*np.meshgrid(np.linspace(0.6, 0.9, 5),
np.linspace(0.7, 1, 5)),
data[:5, :5], cmap='Spectral', alpha=0.75,
shading='gouraud', blend_mode=blend_mode)
if text:
axs[i].text(0.05, 0.15, "Test", weight="bold", color="c",
blend_mode=blend_mode)
axs[i].text(0.35, 0.10, "Tilted", weight="bold", color="m", rotation=45,
blend_mode=blend_mode)
axs[i].plot([0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2],
[0.7, 0.8, 0.9, 1, 0.7, 0.8, 0.9, 1],
'p', markersize=15, markeredgecolor="orange",
markerfacecolor="purple", alpha=0.75, blend_mode=blend_mode)
axs[i].plot([0, 1], [1.2, 0], color="y",
blend_mode=blend_mode)
circ = Circle((.65, 0.5), .3, facecolor='g', alpha=0.5,
blend_mode=blend_mode, zorder=2)
axs[i].add_artist(circ)
rect = Rectangle((0, 1.2), 1, .3, facecolor='lightgray', clip_on=False)
axs[i].add_artist(rect)
if text:
axs[i].set_title(blend_mode)
class ArtistGroup(Artist):
def __init__(self, artists, *, group_blend_mode=None, group_alpha=1,
knockout=False):
self._artists = artists
self._group_blend_mode = group_blend_mode
self._group_alpha = group_alpha
self._knockout = knockout
super().__init__()
def draw(self, renderer):
renderer.open_blend_group(self._group_blend_mode, alpha=self._group_alpha,
knockout=self._knockout)
for a in sorted(self._artists, key=attrgetter('zorder')):
if not a.is_transform_set():
a.set_transform(self.get_transform())
a.draw(renderer)
renderer.close_blend_group()
def plot_blend_group_types(rasterize=False):
# Rows: top row is non-isolated, bottom row is isolated
# Columns: left column is non-knockout, right column is knockout
fig, axs = plt.subplots(2, 2, figsize=(3, 3), dpi=80, layout='constrained')
for i, group_blend_mode in enumerate([None, "normal"]):
for j, knockout in enumerate([False, True]):
if rasterize:
axs[i, j].set_rasterization_zorder(6)
axs[i, j].set_xlim(-1, 1)
axs[i, j].set_ylim(-1, 1)
axs[i, j].set_aspect("equal")
axs[i, j].set_axis_off()
axs[i, j].imshow(np.arange(20*20).reshape((20, 20)) % 19,
cmap='Spectral', extent=[-1, 1, -1, 1])
cyan = Circle((-0.25, 0.2), 0.6, fc='c', alpha=0.75,
blend_mode='multiply', zorder=1)
magenta = Circle((0.25, 0.2), 0.6, fc='m', alpha=0.75,
blend_mode='multiply', zorder=2)
yellow = Circle((0, -0.25), 0.6, fc='y', alpha=0.75,
blend_mode='multiply', zorder=1)
# Test that zorder is respected within ArtistGroup by intentionally
# providing the input list in a different order from zorder
both = ArtistGroup([cyan, magenta, yellow],
group_blend_mode=group_blend_mode, knockout=knockout)
axs[i, j].add_artist(both)
# Test that the above ArtistGroup is all drawn at zorder=0 as far as the
# overall axes is concerned despite the zorder values of its elements
both.set_zorder(0)
gray = Circle((0, 0), 0.1, fc='gray', zorder=0)
axs[i, j].add_artist(gray)
@image_comparison(['blend_modes_agg.png'], style='mpl20')
def test_blend_modes_agg():
plot_blend_mode_gallery()
@pytest.mark.backend('cairo')
@image_comparison(['blend_modes_cairo.png'], style='mpl20',
tol=3 if cairo_version is not None and cairo_version < 11804 else 0)
def test_blend_modes_cairo():
# The test image used cairo 1.18.4, so loosen the tolerance for older cairo
# Disable text because text rendering varies too much with environment
plot_blend_mode_gallery(text=False)
@image_comparison(['blend_modes_svg.svg'], style='mpl20')
def test_blend_modes_svg():
# The bottom row of six Porter-Duff compositing operators is not supported, so will
# be rendered like the "normal" panel in the upper left
# Disable the Gouraud component because its implementation increases the image file
# size by an order of magnitude, plus the implementation is actually not supported
# by typical SVG viewers
plot_blend_mode_gallery(gouraud=False)
@image_comparison(['blend_modes_pdf.pdf'], style='mpl20')
def test_blend_modes_pdf():
# The bottom row of six Porter-Duff compositing operators is not supported, so will
# be rendered like the "normal" panel in the upper left
plot_blend_mode_gallery()
@image_comparison(['blend_modes_pdf_rasterized.pdf'], style='mpl20')
def test_blend_modes_pdf_rasterized():
plot_blend_mode_gallery(rasterize=True)
@needs_pgf_pdflatex
@pytest.mark.backend('pgf')
@image_comparison(['blend_modes_pgf.pdf'], style='mpl20')
def test_blend_modes_pgf():
# The bottom row of six Porter-Duff compositing operators is not supported, so will
# be rendered like the "normal" panel in the upper left
# Disable the Gouraud component because it is not supported by the PGF backend
plot_blend_mode_gallery(gouraud=False)
@image_comparison(['blend_groups_agg.png'], style='mpl20')
def test_blend_groups_agg():
# The top-right panel (knockout but not isolated) is not supported, so will be
# rendered like the top-left panel (neither knockout nor isolated)
plot_blend_group_types()
@pytest.mark.backend('cairo')
@image_comparison(['blend_groups_cairo.png'], style='mpl20')
def test_blend_groups_cairo():
# The top-right panel (knockout but not isolated) is not supported, so will be
# rendered like the top-left panel (neither knockout nor isolated)
plot_blend_group_types()
@image_comparison(['blend_groups_svg.svg'], style='mpl20')
def test_blend_groups_svg():
# The right-side panels (knockout versions) are not supported, so will be rendered
# like the corresponding left-side panels (non-knockout versions)
plot_blend_group_types()
@image_comparison(['blend_groups_svg_rasterized.svg'], style='mpl20')
def test_blend_groups_svg_rasterized():
# The top-right panel (knockout but not isolated) is not supported, so will be
# rendered like the top-left panel (neither knockout nor isolated)
plot_blend_group_types(rasterize=True)
@image_comparison(['blend_groups_pdf.pdf'], style='mpl20')
def test_blend_groups_pdf():
plot_blend_group_types()
@needs_pgf_pdflatex
@pytest.mark.backend('pgf')
@image_comparison(['blend_groups_pgf.pdf'], style='mpl20')
def test_blend_groups_pgf():
plot_blend_group_types()
@pytest.mark.backend('Agg')
def test_interleaved_groups_agg():
fig = plt.figure()
fig.canvas.draw()
# Try to stop an overarching filter without closing a contained blend group
fig.canvas.renderer.start_filter()
fig.canvas.renderer.open_blend_group(None)
with pytest.raises(RuntimeError, match="Cannot stop filtering"):
fig.canvas.renderer.stop_filter(lambda image, dpi: (image, 0, 0))
# Try to close an overarching blend group without stopping a contained filter
fig.canvas.renderer.open_blend_group(None)
fig.canvas.renderer.start_filter()
with pytest.raises(RuntimeError, match="Cannot close the blend group"):
fig.canvas.renderer.close_blend_group()
def test_interleaved_groups_svg():
# The SVG renderer is normally instantiated on the fly just for writing an SVG, so
# for this test we need to manually instantiate a renderer instead of using a figure
renderer = RendererSVG(1, 1, StringIO())
# Try to close an overarching group element without closing a contained blend group
renderer.open_group("bleh")
renderer.open_blend_group(None)
with pytest.raises(RuntimeError, match="Cannot close group element 'bleh'"):
renderer.close_group("bleh")
# Try to close an overarching blend group without closing a contained group element
renderer.open_blend_group(None)
renderer.open_group("bleh")
with pytest.raises(RuntimeError, match="Cannot close the blend group"):
renderer.close_blend_group()
_renderers = [RendererAgg, RendererPdf, RendererPgf, RendererSVG]
# Cairo may not be installed
if RendererCairo is not None:
_renderers += [RendererCairo]
@pytest.mark.parametrize('renderer', _renderers)
def test_group_invalid_blend_mode(renderer):
# Each renderer has a different instantiation signature
args = {RendererAgg: (1, 1, 1),
RendererCairo: (1,),
RendererPdf: (StringIO(), 1, 1, 1),
RendererPgf: (Figure(), StringIO()),
RendererSVG: (1, 1, StringIO())}
renderer_instance = renderer(*args[renderer])
with pytest.raises(ValueError, match="not a valid value for blend_mode"):
renderer_instance.open_blend_group("invalid_blend_mode")
def plot_fill_rule_comparison():
deg = np.arange(6) * 144
x = np.sin(deg * np.pi / 180)
y = np.cos(deg * np.pi / 180)
star = np.stack([x, y], axis=1)
square_vertices = np.array([[-1, -1], [-1, 1], [1, 1], [1, -1], [-1, -1]])
square_codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO]
fig, axs = plt.subplots(1, 2, figsize=(4, 5))
for ax, fill_rule in zip(axs, ['nonzero', 'evenodd']):
stroked_star = Polygon(star + [0, 4], closed=False,
ec='b', lw=5, ls=(0, (5, 1)),
fc='r', hatch='xx', fill_rule=fill_rule)
ax.add_patch(stroked_star)
nonstroked_star = Polygon(star + [0, 2], closed=False, ec='none',
fc='r', hatch='xx', fill_rule=fill_rule)
ax.add_patch(nonstroked_star)
squares = Path(np.vstack([square_vertices * 0.9,
square_vertices / 3 + [0, 0.5],
square_vertices / 3 + [0.3, 0],
(square_vertices / 3)[::-1, :] + [0, -0.5]]),
square_codes * 4)
ax.add_patch(PathPatch(squares, fc='g', ec='m', fill_rule=fill_rule))
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 5.1)
ax.set_aspect('equal')
ax.set_axis_off()
@image_comparison(['fill_rules'], extensions=['png', 'svg', 'pdf'], style='mpl20')
def test_fill_rules():
plot_fill_rule_comparison()
@pytest.mark.backend('cairo')
@image_comparison(['fill_rules_cairo.png'], style='mpl20')
def test_fill_rules_cairo():
plot_fill_rule_comparison()
@needs_pgf_pdflatex
@pytest.mark.backend('pgf')
@image_comparison(['fill_rules_pgf.pdf'], style='mpl20')
def test_fill_rules_pgf():
plot_fill_rule_comparison()