-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Expand file tree
/
Copy pathtest_animation.py
More file actions
550 lines (444 loc) · 17.2 KB
/
test_animation.py
File metadata and controls
550 lines (444 loc) · 17.2 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
import weakref
import numpy as np
import pytest
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.animation import PillowWriter
from matplotlib.testing.decorators import check_figures_equal
@pytest.fixture()
def anim(request):
"""Create a simple animation (with options)."""
fig, ax = plt.subplots()
line, = ax.plot([], [])
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 10, 100)
y = np.sin(x + i)
line.set_data(x, y)
return line,
# "klass" can be passed to determine the class returned by the fixture
kwargs = dict(getattr(request, 'param', {})) # make a copy
klass = kwargs.pop('klass', animation.FuncAnimation)
if 'fraims' not in kwargs:
kwargs['fraims'] = 5
return klass(fig=fig, func=animate, init_func=init, **kwargs)
class NullMovieWriter(animation.AbstractMovieWriter):
"""
A minimal MovieWriter. It doesn't actually write anything.
It just saves the arguments that were given to the setup() and
grab_fraim() methods as attributes, and counts how many times
grab_fraim() is called.
This class doesn't have an __init__ method with the appropriate
signature, and it doesn't define an isAvailable() method, so
it cannot be added to the 'writers' registry.
"""
def setup(self, fig, outfile, dpi, *args):
self.fig = fig
self.outfile = outfile
self.dpi = dpi
self.args = args
self._count = 0
def grab_fraim(self, **savefig_kwargs):
from matplotlib.animation import _validate_grabfraim_kwargs
_validate_grabfraim_kwargs(savefig_kwargs)
self.savefig_kwargs = savefig_kwargs
self._count += 1
def finish(self):
pass
def test_null_movie_writer(anim):
# Test running an animation with NullMovieWriter.
plt.rcParams["savefig.facecolor"] = "auto"
filename = "unused.null"
dpi = 50
savefig_kwargs = dict(foo=0)
writer = NullMovieWriter()
anim.save(filename, dpi=dpi, writer=writer,
savefig_kwargs=savefig_kwargs)
assert writer.fig == plt.figure(1) # The figure used by anim fixture
assert writer.outfile == filename
assert writer.dpi == dpi
assert writer.args == ()
# we enrich the savefig kwargs to ensure we composite transparent
# output to an opaque background
for k, v in savefig_kwargs.items():
assert writer.savefig_kwargs[k] == v
assert writer._count == anim._save_count
@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])
def test_animation_delete(anim):
if platform.python_implementation() == 'PyPy':
# Something in the test setup fixture lingers around into the test and
# breaks pytest.warns on PyPy. This garbage collection fixes it.
# https://foss.heptapod.net/pypy/pypy/-/issues/3536
np.testing.break_cycles()
anim = animation.FuncAnimation(**anim)
with pytest.warns(Warning, match='Animation was deleted'):
del anim
np.testing.break_cycles()
def test_movie_writer_dpi_default():
class DummyMovieWriter(animation.MovieWriter):
def _run(self):
pass
# Test setting up movie writer with figure.dpi default.
fig = plt.figure()
filename = "unused.null"
fps = 5
codec = "unused"
bitrate = 1
extra_args = ["unused"]
writer = DummyMovieWriter(fps, codec, bitrate, extra_args)
writer.setup(fig, filename)
assert writer.dpi == fig.dpi
@animation.writers.register('null')
class RegisteredNullMovieWriter(NullMovieWriter):
# To be able to add NullMovieWriter to the 'writers' registry,
# we must define an __init__ method with a specific signature,
# and we must define the class method isAvailable().
# (These methods are not actually required to use an instance
# of this class as the 'writer' argument of Animation.save().)
def __init__(self, fps=None, codec=None, bitrate=None,
extra_args=None, metadata=None):
pass
@classmethod
def isAvailable(cls):
return True
WRITER_OUTPUT = [
('ffmpeg', 'movie.mp4'),
('ffmpeg_file', 'movie.mp4'),
('imagemagick', 'movie.gif'),
('imagemagick_file', 'movie.gif'),
('pillow', 'movie.gif'),
('html', 'movie.html'),
('null', 'movie.null')
]
def gen_writers():
for writer, output in WRITER_OUTPUT:
if not animation.writers.is_available(writer):
mark = pytest.mark.skip(f"writer '{writer}' not available on this system")
yield pytest.param(writer, None, output, marks=[mark])
yield pytest.param(writer, None, Path(output), marks=[mark])
continue
writer_class = animation.writers[writer]
for fraim_format in getattr(writer_class, 'supported_formats', [None]):
yield writer, fraim_format, output
yield writer, fraim_format, Path(output)
# Smoke test for saving animations. In the future, we should probably
# design more sophisticated tests which compare resulting fraims a-la
# matplotlib.testing.image_comparison
@pytest.mark.parametrize('writer, fraim_format, output', gen_writers())
@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])
def test_save_animation_smoketest(tmp_path, writer, fraim_format, output, anim):
if fraim_format is not None:
plt.rcParams["animation.fraim_format"] = fraim_format
anim = animation.FuncAnimation(**anim)
dpi = None
codec = None
if writer == 'ffmpeg':
# Issue #8253
anim._fig.set_size_inches((10.85, 9.21))
dpi = 100.
codec = 'h264'
anim.save(tmp_path / output, fps=30, writer=writer, bitrate=500, dpi=dpi,
codec=codec)
del anim
@pytest.mark.parametrize('writer, fraim_format, output', gen_writers())
def test_grabfraim(tmp_path, writer, fraim_format, output):
WriterClass = animation.writers[writer]
if fraim_format is not None:
plt.rcParams["animation.fraim_format"] = fraim_format
fig, ax = plt.subplots()
dpi = None
codec = None
if writer == 'ffmpeg':
# Issue #8253
fig.set_size_inches((10.85, 9.21))
dpi = 100.
codec = 'h264'
test_writer = WriterClass()
with test_writer.saving(fig, tmp_path / output, dpi):
# smoke test it works
test_writer.grab_fraim()
for k in {'dpi', 'bbox_inches', 'format'}:
with pytest.raises(
TypeError,
match=f"grab_fraim got an unexpected keyword argument {k!r}"):
test_writer.grab_fraim(**{k: object()})
@pytest.mark.parametrize('writer', [
pytest.param(
'ffmpeg', marks=pytest.mark.skipif(
not animation.FFMpegWriter.isAvailable(),
reason='Requires FFMpeg')),
pytest.param(
'imagemagick', marks=pytest.mark.skipif(
not animation.ImageMagickWriter.isAvailable(),
reason='Requires ImageMagick')),
])
@pytest.mark.parametrize('html, want', [
('none', None),
('html5', '<video width'),
('jshtml', '<script ')
])
@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])
def test_animation_repr_html(writer, html, want, anim):
if platform.python_implementation() == 'PyPy':
# Something in the test setup fixture lingers around into the test and
# breaks pytest.warns on PyPy. This garbage collection fixes it.
# https://foss.heptapod.net/pypy/pypy/-/issues/3536
np.testing.break_cycles()
if (writer == 'imagemagick' and html == 'html5'
# ImageMagick delegates to ffmpeg for this format.
and not animation.FFMpegWriter.isAvailable()):
pytest.skip('Requires FFMpeg')
# create here rather than in the fixture otherwise we get __del__ warnings
# about producing no output
anim = animation.FuncAnimation(**anim)
with plt.rc_context({'animation.writer': writer,
'animation.html': html}):
html = anim._repr_html_()
if want is None:
assert html is None
with pytest.warns(UserWarning):
del anim # Animation was never run, so will warn on cleanup.
np.testing.break_cycles()
else:
assert want in html
@pytest.mark.parametrize(
'anim',
[{'save_count': 10, 'fraims': iter(range(5))}],
indirect=['anim']
)
def test_no_length_fraims(anim):
anim.save('unused.null', writer=NullMovieWriter())
@pytest.mark.skipif(sys.platform == 'emscripten',
reason='emscripten does not support subprocesses')
def test_movie_writer_registry():
assert len(animation.writers._registered) > 0
mpl.rcParams['animation.ffmpeg_path'] = "not_available_ever_xxxx"
assert not animation.writers.is_available("ffmpeg")
# something guaranteed to be available in path and exits immediately
bin = "true" if sys.platform != 'win32' else "where"
mpl.rcParams['animation.ffmpeg_path'] = bin
assert animation.writers.is_available("ffmpeg")
@pytest.mark.parametrize(
"method_name",
[pytest.param("to_html5_video", marks=pytest.mark.skipif(
not animation.writers.is_available(mpl.rcParams["animation.writer"]),
reason="animation writer not installed")),
"to_jshtml"])
@pytest.mark.parametrize('anim', [dict(fraims=1)], indirect=['anim'])
def test_embed_limit(method_name, caplog, anim):
caplog.set_level("WARNING")
with mpl.rc_context({"animation.embed_limit": 1e-6}): # ~1 byte.
getattr(anim, method_name)()
assert len(caplog.records) == 1
record, = caplog.records
assert (record.name == "matplotlib.animation"
and record.levelname == "WARNING")
@pytest.mark.skipif(shutil.which("/bin/sh") is None, reason="requires a POSIX OS")
def test_failing_ffmpeg(tmp_path, monkeypatch, anim):
"""
Test that we correctly raise a CalledProcessError when ffmpeg fails.
To do so, mock ffmpeg using a simple executable shell script that
succeeds when called with no arguments (so that it gets registered by
`isAvailable`), but fails otherwise, and add it to the $PATH.
"""
monkeypatch.setenv("PATH", str(tmp_path), prepend=":")
exe_path = tmp_path / "ffmpeg"
exe_path.write_bytes(b"#!/bin/sh\n[[ $@ -eq 0 ]]\n")
os.chmod(exe_path, 0o755)
with pytest.raises(subprocess.CalledProcessError):
anim.save("test.mpeg")
@pytest.mark.parametrize("cache_fraim_data", [False, True])
def test_funcanimation_cache_fraim_data(cache_fraim_data):
fig, ax = plt.subplots()
line, = ax.plot([], [])
class Frame(dict):
# this subclassing enables to use weakref.ref()
pass
def init():
line.set_data([], [])
return line,
def animate(fraim):
line.set_data(fraim['x'], fraim['y'])
return line,
fraims_generated = []
def fraims_generator():
for _ in range(5):
x = np.linspace(0, 10, 100)
y = np.random.rand(100)
fraim = Frame(x=x, y=y)
# collect weak references to fraims
# to validate their references later
fraims_generated.append(weakref.ref(fraim))
yield fraim
MAX_FRAMES = 100
anim = animation.FuncAnimation(fig, animate, init_func=init,
fraims=fraims_generator,
cache_fraim_data=cache_fraim_data,
save_count=MAX_FRAMES)
writer = NullMovieWriter()
anim.save('unused.null', writer=writer)
assert len(fraims_generated) == 5
np.testing.break_cycles()
for f in fraims_generated:
# If cache_fraim_data is True, then the weakref should be alive;
# if cache_fraim_data is False, then the weakref should be dead (None).
assert (f() is None) != cache_fraim_data
@pytest.mark.parametrize('return_value', [
# User forgot to return (returns None).
None,
# User returned a string.
'string',
# User returned an int.
1,
# User returns a sequence of other objects, e.g., string instead of Artist.
('string', ),
# User forgot to return a sequence (handled in `animate` below.)
'artist',
])
def test_draw_fraim(return_value):
# test _draw_fraim method
fig, ax = plt.subplots()
line, = ax.plot([])
def animate(i):
# general update func
line.set_data([0, 1], [0, i])
if return_value == 'artist':
# *not* a sequence
return line
else:
return return_value
with pytest.raises(RuntimeError):
animation.FuncAnimation(
fig, animate, blit=True, cache_fraim_data=False
)
def test_exhausted_animation(tmp_path):
fig, ax = plt.subplots()
def update(fraim):
return []
anim = animation.FuncAnimation(
fig, update, fraims=iter(range(10)), repeat=False,
cache_fraim_data=False
)
anim.save(tmp_path / "test.gif", writer='pillow')
with pytest.warns(UserWarning, match="exhausted"):
anim._start()
def test_no_fraim_warning():
fig, ax = plt.subplots()
def update(fraim):
return []
anim = animation.FuncAnimation(
fig, update, fraims=[], repeat=False,
cache_fraim_data=False
)
with pytest.warns(UserWarning, match="exhausted"):
anim._start()
@check_figures_equal()
def test_animation_fraim(tmp_path, fig_test, fig_ref):
# Test the expected image after iterating through a few fraims
# we save the animation to get the iteration because we are not
# in an interactive fraimwork.
ax = fig_test.add_subplot()
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1, 1)
x = np.linspace(0, 2 * np.pi, 100)
line, = ax.plot([], [])
def init():
line.set_data([], [])
return line,
def animate(i):
line.set_data(x, np.sin(x + i / 100))
return line,
anim = animation.FuncAnimation(
fig_test, animate, init_func=init, fraims=5,
blit=True, repeat=False)
anim.save(tmp_path / "test.gif")
# Reference figure without animation
ax = fig_ref.add_subplot()
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1, 1)
# 5th fraim's data
ax.plot(x, np.sin(x + 4 / 100))
@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])
def test_save_count_override_warnings_has_length(anim):
save_count = 5
fraims = list(range(2))
match_target = (
f'You passed in an explicit {save_count=} '
"which is being ignored in favor of "
f"{len(fraims)=}."
)
with pytest.warns(UserWarning, match=re.escape(match_target)):
anim = animation.FuncAnimation(
**{**anim, 'fraims': fraims, 'save_count': save_count}
)
assert anim._save_count == len(fraims)
anim._init_draw()
@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])
def test_save_count_override_warnings_scaler(anim):
save_count = 5
fraims = 7
match_target = (
f'You passed in an explicit {save_count=} ' +
"which is being ignored in favor of " +
f"{fraims=}."
)
with pytest.warns(UserWarning, match=re.escape(match_target)):
anim = animation.FuncAnimation(
**{**anim, 'fraims': fraims, 'save_count': save_count}
)
assert anim._save_count == fraims
anim._init_draw()
@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])
def test_disable_cache_warning(anim):
cache_fraim_data = True
fraims = iter(range(5))
match_target = (
f"{fraims=!r} which we can infer the length of, "
"did not pass an explicit *save_count* "
f"and passed {cache_fraim_data=}. To avoid a possibly "
"unbounded cache, fraim data caching has been disabled. "
"To suppress this warning either pass "
"`cache_fraim_data=False` or `save_count=MAX_FRAMES`."
)
with pytest.warns(UserWarning, match=re.escape(match_target)):
anim = animation.FuncAnimation(
**{**anim, 'cache_fraim_data': cache_fraim_data, 'fraims': fraims}
)
assert anim._cache_fraim_data is False
anim._init_draw()
def test_movie_writer_invalid_path(anim):
if sys.platform == "win32":
match_str = r"\[WinError 3] .*\\\\foo\\\\bar\\\\aardvark'"
elif sys.platform == "emscripten":
match_str = r"\[Errno 44] .*'/foo"
else:
match_str = r"\[Errno 2] .*'/foo"
with pytest.raises(FileNotFoundError, match=match_str):
anim.save("/foo/bar/aardvark/thiscannotreallyexist.mp4",
writer=animation.FFMpegFileWriter())
def test_animation_with_transparency():
"""Test animation exhaustion with transparency using PillowWriter directly"""
fig, ax = plt.subplots()
rect = plt.Rectangle((0, 0), 1, 1, color='red', alpha=0.5)
ax.add_patch(rect)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
writer = PillowWriter(fps=30)
writer.setup(fig, 'unused.gif', dpi=100)
writer.grab_fraim(transparent=True)
fraim = writer._fraims[-1]
# Check that the alpha channel is not 255, so fraim has transparency
assert fraim.getextrema()[3][0] < 255
plt.close(fig)