/
animation.py
1782 lines (1504 loc) · 68.7 KB
/
animation.py
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# TODO:
# * Documentation -- this will need a new section of the User's Guide.
# Both for Animations and just timers.
# - Also need to update
# https://scipy-cookbook.readthedocs.io/items/Matplotlib_Animations.html
# * Blit
# * Currently broken with Qt4 for widgets that don't start on screen
# * Still a few edge cases that aren't working correctly
# * Can this integrate better with existing matplotlib animation artist flag?
# - If animated removes from default draw(), perhaps we could use this to
# simplify initial draw.
# * Example
# * Frameless animation - pure procedural with no loop
# * Need example that uses something like inotify or subprocess
# * Complex syncing examples
# * Movies
# * Can blit be enabled for movies?
# * Need to consider event sources to allow clicking through multiple figures
import abc
import base64
import contextlib
from io import BytesIO, TextIOWrapper
import itertools
import logging
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
import uuid
import warnings
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib._animation_data import (
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
from matplotlib import _api, cbook
import matplotlib.colors as mcolors
_log = logging.getLogger(__name__)
# Process creation flag for subprocess to prevent it raising a terminal
# window. See for example https://stackoverflow.com/q/24130623/
subprocess_creation_flags = (
subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0)
# Other potential writing methods:
# * http://pymedia.org/
# * libming (produces swf) python wrappers: https://github.com/libming/libming
# * Wrap x264 API:
# (https://stackoverflow.com/q/2940671/)
def adjusted_figsize(w, h, dpi, n):
"""
Compute figure size so that pixels are a multiple of n.
Parameters
----------
w, h : float
Size in inches.
dpi : float
The dpi.
n : int
The target multiple.
Returns
-------
wnew, hnew : float
The new figure size in inches.
"""
# this maybe simplified if / when we adopt consistent rounding for
# pixel size across the whole library
def correct_roundoff(x, dpi, n):
if int(x*dpi) % n != 0:
if int(np.nextafter(x, np.inf)*dpi) % n == 0:
x = np.nextafter(x, np.inf)
elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
x = np.nextafter(x, -np.inf)
return x
wnew = int(w * dpi / n) * n / dpi
hnew = int(h * dpi / n) * n / dpi
return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)
class MovieWriterRegistry:
"""Registry of available writer classes by human readable name."""
def __init__(self):
self._registered = dict()
def register(self, name):
"""
Decorator for registering a class under a name.
Example use::
@registry.register(name)
class Foo:
pass
"""
def wrapper(writer_cls):
self._registered[name] = writer_cls
return writer_cls
return wrapper
def is_available(self, name):
"""
Check if given writer is available by name.
Parameters
----------
name : str
Returns
-------
bool
"""
try:
cls = self._registered[name]
except KeyError:
return False
return cls.isAvailable()
def __iter__(self):
"""Iterate over names of available writer class."""
for name in self._registered:
if self.is_available(name):
yield name
def list(self):
"""Get a list of available MovieWriters."""
return [*self]
def __getitem__(self, name):
"""Get an available writer class from its name."""
if self.is_available(name):
return self._registered[name]
raise RuntimeError(f"Requested MovieWriter ({name}) not available")
writers = MovieWriterRegistry()
class AbstractMovieWriter(abc.ABC):
"""
Abstract base class for writing movies, providing a way to grab frames by
calling `~AbstractMovieWriter.grab_frame`.
`setup` is called to start the process and `finish` is called afterwards.
`saving` is provided as a context manager to facilitate this process as ::
with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
# Iterate over frames
moviewriter.grab_frame(**savefig_kwargs)
The use of the context manager ensures that `setup` and `finish` are
performed as necessary.
An instance of a concrete subclass of this class can be given as the
``writer`` argument of `Animation.save()`.
"""
def __init__(self, fps=5, metadata=None, codec=None, bitrate=None):
self.fps = fps
self.metadata = metadata if metadata is not None else {}
self.codec = (
mpl.rcParams['animation.codec'] if codec is None else codec)
self.bitrate = (
mpl.rcParams['animation.bitrate'] if bitrate is None else bitrate)
@abc.abstractmethod
def setup(self, fig, outfile, dpi=None):
"""
Setup for writing the movie file.
Parameters
----------
fig : `~matplotlib.figure.Figure`
The figure object that contains the information for frames.
outfile : str
The filename of the resulting movie file.
dpi : float, default: ``fig.dpi``
The DPI (or resolution) for the file. This controls the size
in pixels of the resulting movie file.
"""
self.outfile = outfile
self.fig = fig
if dpi is None:
dpi = self.fig.dpi
self.dpi = dpi
@property
def frame_size(self):
"""A tuple ``(width, height)`` in pixels of a movie frame."""
w, h = self.fig.get_size_inches()
return int(w * self.dpi), int(h * self.dpi)
@abc.abstractmethod
def grab_frame(self, **savefig_kwargs):
"""
Grab the image information from the figure and save as a movie frame.
All keyword arguments in *savefig_kwargs* are passed on to the
`~.Figure.savefig` call that saves the figure.
"""
@abc.abstractmethod
def finish(self):
"""Finish any processing for writing the movie."""
@contextlib.contextmanager
def saving(self, fig, outfile, dpi, *args, **kwargs):
"""
Context manager to facilitate writing the movie file.
``*args, **kw`` are any parameters that should be passed to `setup`.
"""
# This particular sequence is what contextlib.contextmanager wants
self.setup(fig, outfile, dpi, *args, **kwargs)
try:
yield self
finally:
self.finish()
class MovieWriter(AbstractMovieWriter):
"""
Base class for writing movies.
This is a base class for MovieWriter subclasses that write a movie frame
data to a pipe. You cannot instantiate this class directly.
See examples for how to use its subclasses.
Attributes
----------
frame_format : str
The format used in writing frame data, defaults to 'rgba'.
fig : `~matplotlib.figure.Figure`
The figure to capture data from.
This must be provided by the subclasses.
"""
# Builtin writer subclasses additionally define the _exec_key and _args_key
# attributes, which indicate the rcParams entries where the path to the
# executable and additional command-line arguments to the executable are
# stored. Third-party writers cannot meaningfully set these as they cannot
# extend rcParams with new keys.
# Pipe-based writers only support RGBA, but file-based ones support more
# formats.
supported_formats = ["rgba"]
def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
metadata=None):
"""
Parameters
----------
fps : int, default: 5
Movie frame rate (per second).
codec : str or None, default: :rc:`animation.codec`
The codec to use.
bitrate : int, default: :rc:`animation.bitrate`
The bitrate of the movie, in kilobits per second. Higher values
means higher quality movies, but increase the file size. A value
of -1 lets the underlying movie encoder select the bitrate.
extra_args : list of str or None, optional
Extra command-line arguments passed to the underlying movie
encoder. The default, None, means to use
:rc:`animation.[name-of-encoder]_args` for the builtin writers.
metadata : dict[str, str], default: {}
A dictionary of keys and values for metadata to include in the
output file. Some keys that may be of use include:
title, artist, genre, subject, copyright, srcform, comment.
"""
if type(self) is MovieWriter:
# TODO MovieWriter is still an abstract class and needs to be
# extended with a mixin. This should be clearer in naming
# and description. For now, just give a reasonable error
# message to users.
raise TypeError(
'MovieWriter cannot be instantiated directly. Please use one '
'of its subclasses.')
super().__init__(fps=fps, metadata=metadata, codec=codec,
bitrate=bitrate)
self.frame_format = self.supported_formats[0]
self.extra_args = extra_args
def _adjust_frame_size(self):
if self.codec == 'h264':
wo, ho = self.fig.get_size_inches()
w, h = adjusted_figsize(wo, ho, self.dpi, 2)
if (wo, ho) != (w, h):
self.fig.set_size_inches(w, h, forward=True)
_log.info('figure size in inches has been adjusted '
'from %s x %s to %s x %s', wo, ho, w, h)
else:
w, h = self.fig.get_size_inches()
_log.debug('frame size in pixels is %s x %s', *self.frame_size)
return w, h
def setup(self, fig, outfile, dpi=None):
# docstring inherited
super().setup(fig, outfile, dpi=dpi)
self._w, self._h = self._adjust_frame_size()
# Run here so that grab_frame() can write the data to a pipe. This
# eliminates the need for temp files.
self._run()
def _run(self):
# Uses subprocess to call the program for assembling frames into a
# movie file. *args* returns the sequence of command line arguments
# from a few configuration options.
command = self._args()
_log.info('MovieWriter._run: running command: %s',
cbook._pformat_subprocess(command))
PIPE = subprocess.PIPE
self._proc = subprocess.Popen(
command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
creationflags=subprocess_creation_flags)
def finish(self):
"""Finish any processing for writing the movie."""
out, err = self._proc.communicate()
# Use the encoding/errors that universal_newlines would use.
out = TextIOWrapper(BytesIO(out)).read()
err = TextIOWrapper(BytesIO(err)).read()
if out:
_log.log(
logging.WARNING if self._proc.returncode else logging.DEBUG,
"MovieWriter stdout:\n%s", out)
if err:
_log.log(
logging.WARNING if self._proc.returncode else logging.DEBUG,
"MovieWriter stderr:\n%s", err)
if self._proc.returncode:
raise subprocess.CalledProcessError(
self._proc.returncode, self._proc.args, out, err)
def grab_frame(self, **savefig_kwargs):
# docstring inherited
_log.debug('MovieWriter.grab_frame: Grabbing frame.')
# Readjust the figure size in case it has been changed by the user.
# All frames must have the same size to save the movie correctly.
self.fig.set_size_inches(self._w, self._h)
# Save the figure data to the sink, using the frame format and dpi.
self.fig.savefig(self._proc.stdin, format=self.frame_format,
dpi=self.dpi, **savefig_kwargs)
def _args(self):
"""Assemble list of encoder-specific command-line arguments."""
return NotImplementedError("args needs to be implemented by subclass.")
@classmethod
def bin_path(cls):
"""
Return the binary path to the commandline tool used by a specific
subclass. This is a class method so that the tool can be looked for
before making a particular MovieWriter subclass available.
"""
return str(mpl.rcParams[cls._exec_key])
@classmethod
def isAvailable(cls):
"""Return whether a MovieWriter subclass is actually available."""
return shutil.which(cls.bin_path()) is not None
class FileMovieWriter(MovieWriter):
"""
`MovieWriter` for writing to individual files and stitching at the end.
This must be sub-classed to be useful.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.frame_format = mpl.rcParams['animation.frame_format']
def setup(self, fig, outfile, dpi=None, frame_prefix=None):
"""
Setup for writing the movie file.
Parameters
----------
fig : `~matplotlib.figure.Figure`
The figure to grab the rendered frames from.
outfile : str
The filename of the resulting movie file.
dpi : float, default: ``fig.dpi``
The dpi of the output file. This, with the figure size,
controls the size in pixels of the resulting movie file.
frame_prefix : str, optional
The filename prefix to use for temporary files. If *None* (the
default), files are written to a temporary directory which is
deleted by `finish`; if not *None*, no temporary files are
deleted.
"""
self.fig = fig
self.outfile = outfile
if dpi is None:
dpi = self.fig.dpi
self.dpi = dpi
self._adjust_frame_size()
if frame_prefix is None:
self._tmpdir = TemporaryDirectory()
self.temp_prefix = str(Path(self._tmpdir.name, 'tmp'))
else:
self._tmpdir = None
self.temp_prefix = frame_prefix
self._frame_counter = 0 # used for generating sequential file names
self._temp_paths = list()
self.fname_format_str = '%s%%07d.%s'
def __del__(self):
if self._tmpdir:
self._tmpdir.cleanup()
@property
def frame_format(self):
"""
Format (png, jpeg, etc.) to use for saving the frames, which can be
decided by the individual subclasses.
"""
return self._frame_format
@frame_format.setter
def frame_format(self, frame_format):
if frame_format in self.supported_formats:
self._frame_format = frame_format
else:
_api.warn_external(
f"Ignoring file format {frame_format!r} which is not "
f"supported by {type(self).__name__}; using "
f"{self.supported_formats[0]} instead.")
self._frame_format = self.supported_formats[0]
def _base_temp_name(self):
# Generates a template name (without number) given the frame format
# for extension and the prefix.
return self.fname_format_str % (self.temp_prefix, self.frame_format)
def grab_frame(self, **savefig_kwargs):
# docstring inherited
# Creates a filename for saving using basename and counter.
path = Path(self._base_temp_name() % self._frame_counter)
self._temp_paths.append(path) # Record the filename for later use.
self._frame_counter += 1 # Ensures each created name is unique.
_log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s',
self._frame_counter, path)
with open(path, 'wb') as sink: # Save figure to the sink.
self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi,
**savefig_kwargs)
def finish(self):
# Call run here now that all frame grabbing is done. All temp files
# are available to be assembled.
try:
self._run()
super().finish()
finally:
if self._tmpdir:
_log.debug(
'MovieWriter: clearing temporary path=%s', self._tmpdir
)
self._tmpdir.cleanup()
@writers.register('pillow')
class PillowWriter(AbstractMovieWriter):
@classmethod
def isAvailable(cls):
return True
def setup(self, fig, outfile, dpi=None):
super().setup(fig, outfile, dpi=dpi)
self._frames = []
def grab_frame(self, **savefig_kwargs):
buf = BytesIO()
self.fig.savefig(
buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
self._frames.append(Image.frombuffer(
"RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1))
def finish(self):
self._frames[0].save(
self.outfile, save_all=True, append_images=self._frames[1:],
duration=int(1000 / self.fps), loop=0)
# Base class of ffmpeg information. Has the config keys and the common set
# of arguments that controls the *output* side of things.
class FFMpegBase:
"""
Mixin class for FFMpeg output.
This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter`
classes.
"""
_exec_key = 'animation.ffmpeg_path'
_args_key = 'animation.ffmpeg_args'
@property
def output_args(self):
args = []
if Path(self.outfile).suffix == '.gif':
self.codec = 'gif'
else:
args.extend(['-vcodec', self.codec])
extra_args = (self.extra_args if self.extra_args is not None
else mpl.rcParams[self._args_key])
# For h264, the default format is yuv444p, which is not compatible
# with quicktime (and others). Specifying yuv420p fixes playback on
# iOS, as well as HTML5 video in firefox and safari (on both Win and
# OSX). Also fixes internet explorer. This is as of 2015/10/29.
if self.codec == 'h264' and '-pix_fmt' not in extra_args:
args.extend(['-pix_fmt', 'yuv420p'])
# For GIF, we're telling FFMPEG to split the video stream, to generate
# a palette, and then use it for encoding.
elif self.codec == 'gif' and '-filter_complex' not in extra_args:
args.extend(['-filter_complex',
'split [a][b];[a] palettegen [p];[b][p] paletteuse'])
if self.bitrate > 0:
args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
args.extend(extra_args)
for k, v in self.metadata.items():
args.extend(['-metadata', '%s=%s' % (k, v)])
return args + ['-y', self.outfile]
# Combine FFMpeg options with pipe-based writing
@writers.register('ffmpeg')
class FFMpegWriter(FFMpegBase, MovieWriter):
"""
Pipe-based ffmpeg writer.
Frames are streamed directly to ffmpeg via a pipe and written in a single
pass.
"""
def _args(self):
# Returns the command line parameters for subprocess to use
# ffmpeg to create a movie using a pipe.
args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
'-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
'-r', str(self.fps)]
# Logging is quieted because subprocess.PIPE has limited buffer size.
# If you have a lot of frames in your animation and set logging to
# DEBUG, you will have a buffer overrun.
if _log.getEffectiveLevel() > logging.DEBUG:
args += ['-loglevel', 'error']
args += ['-i', 'pipe:'] + self.output_args
return args
# Combine FFMpeg options with temp file-based writing
@writers.register('ffmpeg_file')
class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
"""
File-based ffmpeg writer.
Frames are written to temporary files on disk and then stitched
together at the end.
"""
supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
def _args(self):
# Returns the command line parameters for subprocess to use
# ffmpeg to create a movie using a collection of temp images
args = []
# For raw frames, we need to explicitly tell ffmpeg the metadata.
if self.frame_format in {'raw', 'rgba'}:
args += [
'-f', 'image2', '-vcodec', 'rawvideo',
'-video_size', '%dx%d' % self.frame_size,
'-pixel_format', 'rgba',
'-framerate', str(self.fps),
]
args += ['-r', str(self.fps), '-i', self._base_temp_name(),
'-vframes', str(self._frame_counter)]
# Logging is quieted because subprocess.PIPE has limited buffer size.
# If you have a lot of frames in your animation and set logging to
# DEBUG, you will have a buffer overrun.
if _log.getEffectiveLevel() > logging.DEBUG:
args += ['-loglevel', 'error']
return [self.bin_path(), *args, *self.output_args]
# Base class for animated GIFs with ImageMagick
class ImageMagickBase:
"""
Mixin class for ImageMagick output.
This is a base class for the concrete `ImageMagickWriter` and
`ImageMagickFileWriter` classes, which define an ``input_names`` attribute
(or property) specifying the input names passed to ImageMagick.
"""
_exec_key = 'animation.convert_path'
_args_key = 'animation.convert_args'
@_api.deprecated("3.6")
@property
def delay(self):
return 100. / self.fps
@_api.deprecated("3.6")
@property
def output_args(self):
extra_args = (self.extra_args if self.extra_args is not None
else mpl.rcParams[self._args_key])
return [*extra_args, self.outfile]
def _args(self):
# ImageMagick does not recognize "raw".
fmt = "rgba" if self.frame_format == "raw" else self.frame_format
extra_args = (self.extra_args if self.extra_args is not None
else mpl.rcParams[self._args_key])
return [
self.bin_path(),
"-size", "%ix%i" % self.frame_size,
"-depth", "8",
"-delay", str(100 / self.fps),
"-loop", "0",
f"{fmt}:{self.input_names}",
*extra_args,
self.outfile,
]
@classmethod
def bin_path(cls):
binpath = super().bin_path()
if binpath == 'convert':
binpath = mpl._get_executable_info('magick').executable
return binpath
@classmethod
def isAvailable(cls):
try:
return super().isAvailable()
except mpl.ExecutableNotFoundError as _enf:
# May be raised by get_executable_info.
_log.debug('ImageMagick unavailable due to: %s', _enf)
return False
# Combine ImageMagick options with pipe-based writing
@writers.register('imagemagick')
class ImageMagickWriter(ImageMagickBase, MovieWriter):
"""
Pipe-based animated gif writer.
Frames are streamed directly to ImageMagick via a pipe and written
in a single pass.
"""
input_names = "-" # stdin
# Combine ImageMagick options with temp file-based writing
@writers.register('imagemagick_file')
class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
"""
File-based animated gif writer.
Frames are written to temporary files on disk and then stitched
together at the end.
"""
supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
input_names = property(
lambda self: f'{self.temp_prefix}*.{self.frame_format}')
# Taken directly from jakevdp's JSAnimation package at
# http://github.com/jakevdp/JSAnimation
def _included_frames(frame_count, frame_format, frame_dir):
return INCLUDED_FRAMES.format(Nframes=frame_count,
frame_dir=frame_dir,
frame_format=frame_format)
def _embedded_frames(frame_list, frame_format):
"""frame_list should be a list of base64-encoded png files"""
if frame_format == 'svg':
# Fix MIME type for svg
frame_format = 'svg+xml'
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
return "\n" + "".join(
template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
for i, frame_data in enumerate(frame_list))
@writers.register('html')
class HTMLWriter(FileMovieWriter):
"""Writer for JavaScript-based HTML movies."""
supported_formats = ['png', 'jpeg', 'tiff', 'svg']
@classmethod
def isAvailable(cls):
return True
def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
metadata=None, embed_frames=False, default_mode='loop',
embed_limit=None):
if extra_args:
_log.warning("HTMLWriter ignores 'extra_args'")
extra_args = () # Don't lookup nonexistent rcParam[args_key].
self.embed_frames = embed_frames
self.default_mode = default_mode.lower()
_api.check_in_list(['loop', 'once', 'reflect'],
default_mode=self.default_mode)
# Save embed limit, which is given in MB
if embed_limit is None:
self._bytes_limit = mpl.rcParams['animation.embed_limit']
else:
self._bytes_limit = embed_limit
# Convert from MB to bytes
self._bytes_limit *= 1024 * 1024
super().__init__(fps, codec, bitrate, extra_args, metadata)
def setup(self, fig, outfile, dpi=None, frame_dir=None):
outfile = Path(outfile)
_api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)
self._saved_frames = []
self._total_bytes = 0
self._hit_limit = False
if not self.embed_frames:
if frame_dir is None:
frame_dir = outfile.with_name(outfile.stem + '_frames')
frame_dir.mkdir(parents=True, exist_ok=True)
frame_prefix = frame_dir / 'frame'
else:
frame_prefix = None
super().setup(fig, outfile, dpi, frame_prefix)
self._clear_temp = False
def grab_frame(self, **savefig_kwargs):
if self.embed_frames:
# Just stop processing if we hit the limit
if self._hit_limit:
return
f = BytesIO()
self.fig.savefig(f, format=self.frame_format,
dpi=self.dpi, **savefig_kwargs)
imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
self._total_bytes += len(imgdata64)
if self._total_bytes >= self._bytes_limit:
_log.warning(
"Animation size has reached %s bytes, exceeding the limit "
"of %s. If you're sure you want a larger animation "
"embedded, set the animation.embed_limit rc parameter to "
"a larger value (in MB). This and further frames will be "
"dropped.", self._total_bytes, self._bytes_limit)
self._hit_limit = True
else:
self._saved_frames.append(imgdata64)
else:
return super().grab_frame(**savefig_kwargs)
def finish(self):
# save the frames to an html file
if self.embed_frames:
fill_frames = _embedded_frames(self._saved_frames,
self.frame_format)
frame_count = len(self._saved_frames)
else:
# temp names is filled by FileMovieWriter
frame_count = len(self._temp_paths)
fill_frames = _included_frames(
frame_count, self.frame_format,
self._temp_paths[0].parent.relative_to(self.outfile.parent))
mode_dict = dict(once_checked='',
loop_checked='',
reflect_checked='')
mode_dict[self.default_mode + '_checked'] = 'checked'
interval = 1000 // self.fps
with open(self.outfile, 'w') as of:
of.write(JS_INCLUDE + STYLE_INCLUDE)
of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
Nframes=frame_count,
fill_frames=fill_frames,
interval=interval,
**mode_dict))
# Duplicate the temporary file clean up logic from
# FileMovieWriter.finish. We can not call the inherited version of
# finish because it assumes that there is a subprocess that we either
# need to call to merge many frames together or that there is a
# subprocess call that we need to clean up.
if self._tmpdir:
_log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
self._tmpdir.cleanup()
class Animation:
"""
A base class for Animations.
This class is not usable as is, and should be subclassed to provide needed
behavior.
.. note::
You must store the created Animation in a variable that lives as long
as the animation should run. Otherwise, the Animation object will be
garbage-collected and the animation stops.
Parameters
----------
fig : `~matplotlib.figure.Figure`
The figure object used to get needed events, such as draw or resize.
event_source : object, optional
A class that can run a callback when desired events
are generated, as well as be stopped and started.
Examples include timers (see `TimedAnimation`) and file
system notifications.
blit : bool, default: False
Whether blitting is used to optimize drawing. If the backend does not
support blitting, then this parameter has no effect.
See Also
--------
FuncAnimation, ArtistAnimation
"""
def __init__(self, fig, event_source=None, blit=False):
self._draw_was_started = False
self._fig = fig
# Disables blitting for backends that don't support it. This
# allows users to request it if available, but still have a
# fallback that works if it is not.
self._blit = blit and fig.canvas.supports_blit
# These are the basics of the animation. The frame sequence represents
# information for each frame of the animation and depends on how the
# drawing is handled by the subclasses. The event source fires events
# that cause the frame sequence to be iterated.
self.frame_seq = self.new_frame_seq()
self.event_source = event_source
# Instead of starting the event source now, we connect to the figure's
# draw_event, so that we only start once the figure has been drawn.
self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
# Connect to the figure's close_event so that we don't continue to
# fire events and try to draw to a deleted figure.
self._close_id = self._fig.canvas.mpl_connect('close_event',
self._stop)
if self._blit:
self._setup_blit()
def __del__(self):
if not getattr(self, '_draw_was_started', True):
warnings.warn(
'Animation was deleted without rendering anything. This is '
'most likely not intended. To prevent deletion, assign the '
'Animation to a variable, e.g. `anim`, that exists until you '
'output the Animation using `plt.show()` or '
'`anim.save()`.'
)
def _start(self, *args):
"""
Starts interactive animation. Adds the draw frame command to the GUI
handler, calls show to start the event loop.
"""
# Do not start the event source if saving() it.
if self._fig.canvas.is_saving():
return
# First disconnect our draw event handler
self._fig.canvas.mpl_disconnect(self._first_draw_id)
# Now do any initial draw
self._init_draw()
# Add our callback for stepping the animation and
# actually start the event_source.
self.event_source.add_callback(self._step)
self.event_source.start()
def _stop(self, *args):
# On stop we disconnect all of our events.
if self._blit:
self._fig.canvas.mpl_disconnect(self._resize_id)
self._fig.canvas.mpl_disconnect(self._close_id)
self.event_source.remove_callback(self._step)
self.event_source = None
def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
bitrate=None, extra_args=None, metadata=None, extra_anim=None,
savefig_kwargs=None, *, progress_callback=None):
"""
Save the animation as a movie file by drawing every frame.
Parameters
----------
filename : str
The output filename, e.g., :file:`mymovie.mp4`.
writer : `MovieWriter` or str, default: :rc:`animation.writer`
A `MovieWriter` instance to use or a key that identifies a
class to use, such as 'ffmpeg'.
fps : int, optional
Movie frame rate (per second). If not set, the frame rate from the
animation's frame interval.
dpi : float, default: :rc:`savefig.dpi`
Controls the dots per inch for the movie frames. Together with
the figure's size in inches, this controls the size of the movie.
codec : str, default: :rc:`animation.codec`.
The video codec to use. Not all codecs are supported by a given
`MovieWriter`.
bitrate : int, default: :rc:`animation.bitrate`
The bitrate of the movie, in kilobits per second. Higher values
means higher quality movies, but increase the file size. A value
of -1 lets the underlying movie encoder select the bitrate.
extra_args : list of str or None, optional
Extra command-line arguments passed to the underlying movie
encoder. The default, None, means to use
:rc:`animation.[name-of-encoder]_args` for the builtin writers.
metadata : dict[str, str], default: {}
Dictionary of keys and values for metadata to include in
the output file. Some keys that may be of use include:
title, artist, genre, subject, copyright, srcform, comment.
extra_anim : list, default: []
Additional `Animation` objects that should be included
in the saved movie file. These need to be from the same
`.Figure` instance. Also, animation frames will
just be simply combined, so there should be a 1:1 correspondence
between the frames from the different animations.
savefig_kwargs : dict, default: {}
Keyword arguments passed to each `~.Figure.savefig` call used to
save the individual frames.
progress_callback : function, optional
A callback function that will be called for every frame to notify
the saving progress. It must have the signature ::
def func(current_frame: int, total_frames: int) -> Any
where *current_frame* is the current frame number and
*total_frames* is the total number of frames to be saved.
*total_frames* is set to None, if the total number of frames can
not be determined. Return values may exist but are ignored.
Example code to write the progress to stdout::
progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
Notes
-----
*fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
construct a `.MovieWriter` instance and can only be passed if
*writer* is a string. If they are passed as non-*None* and *writer*
is a `.MovieWriter`, a `RuntimeError` will be raised.
"""
if writer is None:
writer = mpl.rcParams['animation.writer']
elif (not isinstance(writer, str) and
any(arg is not None
for arg in (fps, codec, bitrate, extra_args, metadata))):
raise RuntimeError('Passing in values for arguments '
'fps, codec, bitrate, extra_args, or metadata '
'is not supported when writer is an existing '
'MovieWriter instance. These should instead be '
'passed as arguments when creating the '