animation.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. # TODO:
  2. # * Documentation -- this will need a new section of the User's Guide.
  3. # Both for Animations and just timers.
  4. # - Also need to update http://www.scipy.org/Cookbook/Matplotlib/Animations
  5. # * Blit
  6. # * Currently broken with Qt4 for widgets that don't start on screen
  7. # * Still a few edge cases that aren't working correctly
  8. # * Can this integrate better with existing matplotlib animation artist flag?
  9. # - If animated removes from default draw(), perhaps we could use this to
  10. # simplify initial draw.
  11. # * Example
  12. # * Frameless animation - pure procedural with no loop
  13. # * Need example that uses something like inotify or subprocess
  14. # * Complex syncing examples
  15. # * Movies
  16. # * Can blit be enabled for movies?
  17. # * Need to consider event sources to allow clicking through multiple figures
  18. import abc
  19. import base64
  20. import contextlib
  21. from io import BytesIO, TextIOWrapper
  22. import itertools
  23. import logging
  24. from pathlib import Path
  25. import shutil
  26. import subprocess
  27. import sys
  28. from tempfile import TemporaryDirectory
  29. import uuid
  30. import numpy as np
  31. import matplotlib as mpl
  32. from matplotlib._animation_data import (
  33. DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
  34. from matplotlib import cbook
  35. _log = logging.getLogger(__name__)
  36. # Process creation flag for subprocess to prevent it raising a terminal
  37. # window. See for example:
  38. # https://stackoverflow.com/questions/24130623/using-python-subprocess-popen-cant-prevent-exe-stopped-working-prompt
  39. if sys.platform == 'win32':
  40. subprocess_creation_flags = CREATE_NO_WINDOW = 0x08000000
  41. else:
  42. # Apparently None won't work here
  43. subprocess_creation_flags = 0
  44. # Other potential writing methods:
  45. # * http://pymedia.org/
  46. # * libming (produces swf) python wrappers: https://github.com/libming/libming
  47. # * Wrap x264 API:
  48. # (http://stackoverflow.com/questions/2940671/
  49. # how-to-encode-series-of-images-into-h264-using-x264-api-c-c )
  50. def adjusted_figsize(w, h, dpi, n):
  51. """
  52. Compute figure size so that pixels are a multiple of n.
  53. Parameters
  54. ----------
  55. w, h : float
  56. Size in inches.
  57. dpi : float
  58. The dpi.
  59. n : int
  60. The target multiple.
  61. Returns
  62. -------
  63. wnew, hnew : float
  64. The new figure size in inches.
  65. """
  66. # this maybe simplified if / when we adopt consistent rounding for
  67. # pixel size across the whole library
  68. def correct_roundoff(x, dpi, n):
  69. if int(x*dpi) % n != 0:
  70. if int(np.nextafter(x, np.inf)*dpi) % n == 0:
  71. x = np.nextafter(x, np.inf)
  72. elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
  73. x = np.nextafter(x, -np.inf)
  74. return x
  75. wnew = int(w * dpi / n) * n / dpi
  76. hnew = int(h * dpi / n) * n / dpi
  77. return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)
  78. class MovieWriterRegistry:
  79. """Registry of available writer classes by human readable name."""
  80. def __init__(self):
  81. self._registered = dict()
  82. @cbook.deprecated("3.2")
  83. def set_dirty(self):
  84. """Sets a flag to re-setup the writers."""
  85. def register(self, name):
  86. """
  87. Decorator for registering a class under a name.
  88. Example use::
  89. @registry.register(name)
  90. class Foo:
  91. pass
  92. """
  93. def wrapper(writer_cls):
  94. self._registered[name] = writer_cls
  95. return writer_cls
  96. return wrapper
  97. @cbook.deprecated("3.2")
  98. def ensure_not_dirty(self):
  99. """If dirty, reasks the writers if they are available"""
  100. @cbook.deprecated("3.2")
  101. def reset_available_writers(self):
  102. """Reset the available state of all registered writers"""
  103. @cbook.deprecated("3.2")
  104. @property
  105. def avail(self):
  106. return {name: self._registered[name] for name in self.list()}
  107. def is_available(self, name):
  108. """
  109. Check if given writer is available by name.
  110. Parameters
  111. ----------
  112. name : str
  113. Returns
  114. -------
  115. bool
  116. """
  117. try:
  118. cls = self._registered[name]
  119. except KeyError:
  120. return False
  121. return cls.isAvailable()
  122. def __iter__(self):
  123. """Iterate over names of available writer class."""
  124. for name in self._registered:
  125. if self.is_available(name):
  126. yield name
  127. def list(self):
  128. """Get a list of available MovieWriters."""
  129. return [*self]
  130. def __getitem__(self, name):
  131. """Get an available writer class from its name."""
  132. if self.is_available(name):
  133. return self._registered[name]
  134. raise RuntimeError(f"Requested MovieWriter ({name}) not available")
  135. writers = MovieWriterRegistry()
  136. class AbstractMovieWriter(abc.ABC):
  137. """
  138. Abstract base class for writing movies. Fundamentally, what a MovieWriter
  139. does is provide is a way to grab frames by calling grab_frame().
  140. setup() is called to start the process and finish() is called afterwards.
  141. This class is set up to provide for writing movie frame data to a pipe.
  142. saving() is provided as a context manager to facilitate this process as::
  143. with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
  144. # Iterate over frames
  145. moviewriter.grab_frame(**savefig_kwargs)
  146. The use of the context manager ensures that setup() and finish() are
  147. performed as necessary.
  148. An instance of a concrete subclass of this class can be given as the
  149. ``writer`` argument of `Animation.save()`.
  150. """
  151. def __init__(self, fps=5, metadata=None, codec=None, bitrate=None):
  152. self.fps = fps
  153. self.metadata = metadata if metadata is not None else {}
  154. self.codec = (
  155. mpl.rcParams['animation.codec'] if codec is None else codec)
  156. self.bitrate = (
  157. mpl.rcParams['animation.bitrate'] if bitrate is None else bitrate)
  158. @abc.abstractmethod
  159. def setup(self, fig, outfile, dpi=None):
  160. """
  161. Setup for writing the movie file.
  162. Parameters
  163. ----------
  164. fig : `~matplotlib.figure.Figure`
  165. The figure object that contains the information for frames.
  166. outfile : str
  167. The filename of the resulting movie file.
  168. dpi : float, default: ``fig.dpi``
  169. The DPI (or resolution) for the file. This controls the size
  170. in pixels of the resulting movie file.
  171. """
  172. self.outfile = outfile
  173. self.fig = fig
  174. if dpi is None:
  175. dpi = self.fig.dpi
  176. self.dpi = dpi
  177. @property
  178. def frame_size(self):
  179. """A tuple ``(width, height)`` in pixels of a movie frame."""
  180. w, h = self.fig.get_size_inches()
  181. return int(w * self.dpi), int(h * self.dpi)
  182. @abc.abstractmethod
  183. def grab_frame(self, **savefig_kwargs):
  184. """
  185. Grab the image information from the figure and save as a movie frame.
  186. All keyword arguments in *savefig_kwargs* are passed on to the
  187. `~.Figure.savefig` call that saves the figure.
  188. """
  189. @abc.abstractmethod
  190. def finish(self):
  191. """Finish any processing for writing the movie."""
  192. @contextlib.contextmanager
  193. def saving(self, fig, outfile, dpi, *args, **kwargs):
  194. """
  195. Context manager to facilitate writing the movie file.
  196. ``*args, **kw`` are any parameters that should be passed to `setup`.
  197. """
  198. # This particular sequence is what contextlib.contextmanager wants
  199. self.setup(fig, outfile, dpi, *args, **kwargs)
  200. try:
  201. yield self
  202. finally:
  203. self.finish()
  204. class MovieWriter(AbstractMovieWriter):
  205. """
  206. Base class for writing movies.
  207. This is a base class for MovieWriter subclasses that write a movie frame
  208. data to a pipe. You cannot instantiate this class directly.
  209. See examples for how to use its subclasses.
  210. Attributes
  211. ----------
  212. frame_format : str
  213. The format used in writing frame data, defaults to 'rgba'.
  214. fig : `~matplotlib.figure.Figure`
  215. The figure to capture data from.
  216. This must be provided by the sub-classes.
  217. """
  218. # Builtin writer subclasses additionally define the _exec_key and _args_key
  219. # attributes, which indicate the rcParams entries where the path to the
  220. # executable and additional command-line arguments to the executable are
  221. # stored. Third-party writers cannot meaningfully set these as they cannot
  222. # extend rcParams with new keys.
  223. exec_key = cbook._deprecate_privatize_attribute("3.3")
  224. args_key = cbook._deprecate_privatize_attribute("3.3")
  225. def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
  226. metadata=None):
  227. """
  228. Parameters
  229. ----------
  230. fps : int, default: 5
  231. Movie frame rate (per second).
  232. codec : str or None, default: :rc:`animation.codec`
  233. The codec to use.
  234. bitrate : int, default: :rc:`animation.bitrate`
  235. The bitrate of the movie, in kilobits per second. Higher values
  236. means higher quality movies, but increase the file size. A value
  237. of -1 lets the underlying movie encoder select the bitrate.
  238. extra_args : list of str or None, optional
  239. Extra command-line arguments passed to the underlying movie
  240. encoder. The default, None, means to use
  241. :rc:`animation.[name-of-encoder]_args` for the builtin writers.
  242. metadata : Dict[str, str], default: {}
  243. A dictionary of keys and values for metadata to include in the
  244. output file. Some keys that may be of use include:
  245. title, artist, genre, subject, copyright, srcform, comment.
  246. """
  247. if type(self) is MovieWriter:
  248. # TODO MovieWriter is still an abstract class and needs to be
  249. # extended with a mixin. This should be clearer in naming
  250. # and description. For now, just give a reasonable error
  251. # message to users.
  252. raise TypeError(
  253. 'MovieWriter cannot be instantiated directly. Please use one '
  254. 'of its subclasses.')
  255. super().__init__(fps=fps, metadata=metadata, codec=codec,
  256. bitrate=bitrate)
  257. self.frame_format = 'rgba'
  258. self.extra_args = extra_args
  259. def _adjust_frame_size(self):
  260. if self.codec == 'h264':
  261. wo, ho = self.fig.get_size_inches()
  262. w, h = adjusted_figsize(wo, ho, self.dpi, 2)
  263. if (wo, ho) != (w, h):
  264. self.fig.set_size_inches(w, h, forward=True)
  265. _log.info('figure size in inches has been adjusted '
  266. 'from %s x %s to %s x %s', wo, ho, w, h)
  267. else:
  268. w, h = self.fig.get_size_inches()
  269. _log.debug('frame size in pixels is %s x %s', *self.frame_size)
  270. return w, h
  271. def setup(self, fig, outfile, dpi=None):
  272. # docstring inherited
  273. super().setup(fig, outfile, dpi=dpi)
  274. self._w, self._h = self._adjust_frame_size()
  275. # Run here so that grab_frame() can write the data to a pipe. This
  276. # eliminates the need for temp files.
  277. self._run()
  278. def _run(self):
  279. # Uses subprocess to call the program for assembling frames into a
  280. # movie file. *args* returns the sequence of command line arguments
  281. # from a few configuration options.
  282. command = self._args()
  283. _log.info('MovieWriter._run: running command: %s',
  284. cbook._pformat_subprocess(command))
  285. PIPE = subprocess.PIPE
  286. self._proc = subprocess.Popen(
  287. command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
  288. creationflags=subprocess_creation_flags)
  289. def finish(self):
  290. """Finish any processing for writing the movie."""
  291. self.cleanup()
  292. def grab_frame(self, **savefig_kwargs):
  293. # docstring inherited
  294. _log.debug('MovieWriter.grab_frame: Grabbing frame.')
  295. # Readjust the figure size in case it has been changed by the user.
  296. # All frames must have the same size to save the movie correctly.
  297. self.fig.set_size_inches(self._w, self._h)
  298. # Save the figure data to the sink, using the frame format and dpi.
  299. self.fig.savefig(self._frame_sink(), format=self.frame_format,
  300. dpi=self.dpi, **savefig_kwargs)
  301. def _frame_sink(self):
  302. """Return the place to which frames should be written."""
  303. return self._proc.stdin
  304. def _args(self):
  305. """Assemble list of encoder-specific command-line arguments."""
  306. return NotImplementedError("args needs to be implemented by subclass.")
  307. def cleanup(self):
  308. """Clean-up and collect the process used to write the movie file."""
  309. out, err = self._proc.communicate()
  310. self._frame_sink().close()
  311. # Use the encoding/errors that universal_newlines would use.
  312. out = TextIOWrapper(BytesIO(out)).read()
  313. err = TextIOWrapper(BytesIO(err)).read()
  314. if out:
  315. _log.log(
  316. logging.WARNING if self._proc.returncode else logging.DEBUG,
  317. "MovieWriter stdout:\n%s", out)
  318. if err:
  319. _log.log(
  320. logging.WARNING if self._proc.returncode else logging.DEBUG,
  321. "MovieWriter stderr:\n%s", err)
  322. if self._proc.returncode:
  323. raise subprocess.CalledProcessError(
  324. self._proc.returncode, self._proc.args, out, err)
  325. @classmethod
  326. def bin_path(cls):
  327. """
  328. Return the binary path to the commandline tool used by a specific
  329. subclass. This is a class method so that the tool can be looked for
  330. before making a particular MovieWriter subclass available.
  331. """
  332. return str(mpl.rcParams[cls._exec_key])
  333. @classmethod
  334. def isAvailable(cls):
  335. """Return whether a MovieWriter subclass is actually available."""
  336. return shutil.which(cls.bin_path()) is not None
  337. class FileMovieWriter(MovieWriter):
  338. """
  339. `MovieWriter` for writing to individual files and stitching at the end.
  340. This must be sub-classed to be useful.
  341. """
  342. def __init__(self, *args, **kwargs):
  343. MovieWriter.__init__(self, *args, **kwargs)
  344. self.frame_format = mpl.rcParams['animation.frame_format']
  345. @cbook._delete_parameter("3.3", "clear_temp")
  346. def setup(self, fig, outfile, dpi=None, frame_prefix=None,
  347. clear_temp=True):
  348. """
  349. Setup for writing the movie file.
  350. Parameters
  351. ----------
  352. fig : `~matplotlib.figure.Figure`
  353. The figure to grab the rendered frames from.
  354. outfile : str
  355. The filename of the resulting movie file.
  356. dpi : float, optional
  357. The dpi of the output file. This, with the figure size,
  358. controls the size in pixels of the resulting movie file.
  359. Default is ``fig.dpi``.
  360. frame_prefix : str, optional
  361. The filename prefix to use for temporary files. If None (the
  362. default), files are written to a temporary directory which is
  363. deleted by `cleanup` (regardless of the value of *clear_temp*).
  364. clear_temp : bool, optional
  365. If the temporary files should be deleted after stitching
  366. the final result. Setting this to ``False`` can be useful for
  367. debugging. Defaults to ``True``.
  368. """
  369. self.fig = fig
  370. self.outfile = outfile
  371. if dpi is None:
  372. dpi = self.fig.dpi
  373. self.dpi = dpi
  374. self._adjust_frame_size()
  375. if frame_prefix is None:
  376. self._tmpdir = TemporaryDirectory()
  377. self.temp_prefix = str(Path(self._tmpdir.name, 'tmp'))
  378. else:
  379. self._tmpdir = None
  380. self.temp_prefix = frame_prefix
  381. self._clear_temp = clear_temp
  382. self._frame_counter = 0 # used for generating sequential file names
  383. self._temp_paths = list()
  384. self.fname_format_str = '%s%%07d.%s'
  385. @cbook.deprecated("3.3")
  386. @property
  387. def clear_temp(self):
  388. return self._clear_temp
  389. @clear_temp.setter
  390. def clear_temp(self, value):
  391. self._clear_temp = value
  392. @property
  393. def frame_format(self):
  394. """
  395. Format (png, jpeg, etc.) to use for saving the frames, which can be
  396. decided by the individual subclasses.
  397. """
  398. return self._frame_format
  399. @frame_format.setter
  400. def frame_format(self, frame_format):
  401. if frame_format in self.supported_formats:
  402. self._frame_format = frame_format
  403. else:
  404. self._frame_format = self.supported_formats[0]
  405. def _base_temp_name(self):
  406. # Generates a template name (without number) given the frame format
  407. # for extension and the prefix.
  408. return self.fname_format_str % (self.temp_prefix, self.frame_format)
  409. def _frame_sink(self):
  410. # Creates a filename for saving using the basename and the current
  411. # counter.
  412. path = Path(self._base_temp_name() % self._frame_counter)
  413. # Save the filename so we can delete it later if necessary
  414. self._temp_paths.append(path)
  415. _log.debug('FileMovieWriter.frame_sink: saving frame %d to path=%s',
  416. self._frame_counter, path)
  417. self._frame_counter += 1 # Ensures each created name is 'unique'
  418. # This file returned here will be closed once it's used by savefig()
  419. # because it will no longer be referenced and will be gc-ed.
  420. return open(path, 'wb')
  421. def grab_frame(self, **savefig_kwargs):
  422. # docstring inherited
  423. # Overloaded to explicitly close temp file.
  424. _log.debug('MovieWriter.grab_frame: Grabbing frame.')
  425. # Tell the figure to save its data to the sink, using the
  426. # frame format and dpi.
  427. with self._frame_sink() as myframesink:
  428. self.fig.savefig(myframesink, format=self.frame_format,
  429. dpi=self.dpi, **savefig_kwargs)
  430. def finish(self):
  431. # Call run here now that all frame grabbing is done. All temp files
  432. # are available to be assembled.
  433. self._run()
  434. MovieWriter.finish(self) # Will call clean-up
  435. def cleanup(self):
  436. MovieWriter.cleanup(self)
  437. if self._tmpdir:
  438. _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
  439. self._tmpdir.cleanup()
  440. else:
  441. if self._clear_temp:
  442. _log.debug('MovieWriter: clearing temporary paths=%s',
  443. self._temp_paths)
  444. for path in self._temp_paths:
  445. path.unlink()
  446. @writers.register('pillow')
  447. class PillowWriter(AbstractMovieWriter):
  448. @classmethod
  449. def isAvailable(cls):
  450. return True
  451. def setup(self, fig, outfile, dpi=None):
  452. super().setup(fig, outfile, dpi=dpi)
  453. self._frames = []
  454. def grab_frame(self, **savefig_kwargs):
  455. from PIL import Image
  456. buf = BytesIO()
  457. self.fig.savefig(
  458. buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
  459. renderer = self.fig.canvas.get_renderer()
  460. self._frames.append(Image.frombuffer(
  461. "RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1))
  462. def finish(self):
  463. self._frames[0].save(
  464. self.outfile, save_all=True, append_images=self._frames[1:],
  465. duration=int(1000 / self.fps), loop=0)
  466. # Base class of ffmpeg information. Has the config keys and the common set
  467. # of arguments that controls the *output* side of things.
  468. class FFMpegBase:
  469. """
  470. Mixin class for FFMpeg output.
  471. To be useful this must be multiply-inherited from with a
  472. `MovieWriterBase` sub-class.
  473. """
  474. _exec_key = 'animation.ffmpeg_path'
  475. _args_key = 'animation.ffmpeg_args'
  476. @property
  477. def output_args(self):
  478. args = []
  479. if Path(self.outfile).suffix == '.gif':
  480. self.codec = 'gif'
  481. else:
  482. args.extend(['-vcodec', self.codec])
  483. extra_args = (self.extra_args if self.extra_args is not None
  484. else mpl.rcParams[self._args_key])
  485. # For h264, the default format is yuv444p, which is not compatible
  486. # with quicktime (and others). Specifying yuv420p fixes playback on
  487. # iOS, as well as HTML5 video in firefox and safari (on both Win and
  488. # OSX). Also fixes internet explorer. This is as of 2015/10/29.
  489. if self.codec == 'h264' and '-pix_fmt' not in extra_args:
  490. args.extend(['-pix_fmt', 'yuv420p'])
  491. # For GIF, we're telling FFMPEG to split the video stream, to generate
  492. # a palette, and then use it for encoding.
  493. elif self.codec == 'gif' and '-filter_complex' not in extra_args:
  494. args.extend(['-filter_complex',
  495. 'split [a][b];[a] palettegen [p];[b][p] paletteuse'])
  496. if self.bitrate > 0:
  497. args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
  498. args.extend(extra_args)
  499. for k, v in self.metadata.items():
  500. args.extend(['-metadata', '%s=%s' % (k, v)])
  501. return args + ['-y', self.outfile]
  502. @classmethod
  503. def isAvailable(cls):
  504. return (
  505. super().isAvailable()
  506. # Ubuntu 12.04 ships a broken ffmpeg binary which we shouldn't use.
  507. # NOTE: when removed, remove the same method in AVConvBase.
  508. and b'LibAv' not in subprocess.run(
  509. [cls.bin_path()], creationflags=subprocess_creation_flags,
  510. stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
  511. stderr=subprocess.PIPE).stderr)
  512. # Combine FFMpeg options with pipe-based writing
  513. @writers.register('ffmpeg')
  514. class FFMpegWriter(FFMpegBase, MovieWriter):
  515. """
  516. Pipe-based ffmpeg writer.
  517. Frames are streamed directly to ffmpeg via a pipe and written in a single
  518. pass.
  519. """
  520. def _args(self):
  521. # Returns the command line parameters for subprocess to use
  522. # ffmpeg to create a movie using a pipe.
  523. args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
  524. '-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
  525. '-r', str(self.fps)]
  526. # Logging is quieted because subprocess.PIPE has limited buffer size.
  527. # If you have a lot of frames in your animation and set logging to
  528. # DEBUG, you will have a buffer overrun.
  529. if _log.getEffectiveLevel() > logging.DEBUG:
  530. args += ['-loglevel', 'error']
  531. args += ['-i', 'pipe:'] + self.output_args
  532. return args
  533. # Combine FFMpeg options with temp file-based writing
  534. @writers.register('ffmpeg_file')
  535. class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
  536. """
  537. File-based ffmpeg writer.
  538. Frames are written to temporary files on disk and then stitched
  539. together at the end.
  540. """
  541. supported_formats = ['png', 'jpeg', 'ppm', 'tiff', 'sgi', 'bmp',
  542. 'pbm', 'raw', 'rgba']
  543. def _args(self):
  544. # Returns the command line parameters for subprocess to use
  545. # ffmpeg to create a movie using a collection of temp images
  546. return [self.bin_path(), '-r', str(self.fps),
  547. '-i', self._base_temp_name(),
  548. '-vframes', str(self._frame_counter)] + self.output_args
  549. # Base class of avconv information. AVConv has identical arguments to FFMpeg.
  550. @cbook.deprecated('3.3')
  551. class AVConvBase(FFMpegBase):
  552. """
  553. Mixin class for avconv output.
  554. To be useful this must be multiply-inherited from with a
  555. `MovieWriterBase` sub-class.
  556. """
  557. _exec_key = 'animation.avconv_path'
  558. _args_key = 'animation.avconv_args'
  559. # NOTE : should be removed when the same method is removed in FFMpegBase.
  560. isAvailable = classmethod(MovieWriter.isAvailable.__func__)
  561. # Combine AVConv options with pipe-based writing
  562. @writers.register('avconv')
  563. class AVConvWriter(AVConvBase, FFMpegWriter):
  564. """
  565. Pipe-based avconv writer.
  566. Frames are streamed directly to avconv via a pipe and written in a single
  567. pass.
  568. """
  569. # Combine AVConv options with file-based writing
  570. @writers.register('avconv_file')
  571. class AVConvFileWriter(AVConvBase, FFMpegFileWriter):
  572. """
  573. File-based avconv writer.
  574. Frames are written to temporary files on disk and then stitched
  575. together at the end.
  576. """
  577. # Base class for animated GIFs with ImageMagick
  578. class ImageMagickBase:
  579. """
  580. Mixin class for ImageMagick output.
  581. To be useful this must be multiply-inherited from with a
  582. `MovieWriterBase` sub-class.
  583. """
  584. _exec_key = 'animation.convert_path'
  585. _args_key = 'animation.convert_args'
  586. @property
  587. def delay(self):
  588. return 100. / self.fps
  589. @property
  590. def output_args(self):
  591. extra_args = (self.extra_args if self.extra_args is not None
  592. else mpl.rcParams[self._args_key])
  593. return [*extra_args, self.outfile]
  594. @classmethod
  595. def bin_path(cls):
  596. binpath = super().bin_path()
  597. if binpath == 'convert':
  598. binpath = mpl._get_executable_info('magick').executable
  599. return binpath
  600. @classmethod
  601. def isAvailable(cls):
  602. try:
  603. return super().isAvailable()
  604. except mpl.ExecutableNotFoundError as _enf:
  605. # May be raised by get_executable_info.
  606. _log.debug('ImageMagick unavailable due to: %s', _enf)
  607. return False
  608. # Combine ImageMagick options with pipe-based writing
  609. @writers.register('imagemagick')
  610. class ImageMagickWriter(ImageMagickBase, MovieWriter):
  611. """
  612. Pipe-based animated gif.
  613. Frames are streamed directly to ImageMagick via a pipe and written
  614. in a single pass.
  615. """
  616. def _args(self):
  617. return ([self.bin_path(),
  618. '-size', '%ix%i' % self.frame_size, '-depth', '8',
  619. '-delay', str(self.delay), '-loop', '0',
  620. '%s:-' % self.frame_format]
  621. + self.output_args)
  622. # Combine ImageMagick options with temp file-based writing
  623. @writers.register('imagemagick_file')
  624. class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
  625. """
  626. File-based animated gif writer.
  627. Frames are written to temporary files on disk and then stitched
  628. together at the end.
  629. """
  630. supported_formats = ['png', 'jpeg', 'ppm', 'tiff', 'sgi', 'bmp',
  631. 'pbm', 'raw', 'rgba']
  632. def _args(self):
  633. return ([self.bin_path(), '-delay', str(self.delay), '-loop', '0',
  634. '%s*.%s' % (self.temp_prefix, self.frame_format)]
  635. + self.output_args)
  636. # Taken directly from jakevdp's JSAnimation package at
  637. # http://github.com/jakevdp/JSAnimation
  638. def _included_frames(paths, frame_format):
  639. """paths should be a list of Paths"""
  640. return INCLUDED_FRAMES.format(Nframes=len(paths),
  641. frame_dir=paths[0].parent,
  642. frame_format=frame_format)
  643. def _embedded_frames(frame_list, frame_format):
  644. """frame_list should be a list of base64-encoded png files"""
  645. template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
  646. return "\n" + "".join(
  647. template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
  648. for i, frame_data in enumerate(frame_list))
  649. @writers.register('html')
  650. class HTMLWriter(FileMovieWriter):
  651. """Writer for JavaScript-based HTML movies."""
  652. supported_formats = ['png', 'jpeg', 'tiff', 'svg']
  653. @cbook.deprecated("3.3")
  654. @property
  655. def args_key(self):
  656. return 'animation.html_args'
  657. @classmethod
  658. def isAvailable(cls):
  659. return True
  660. def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
  661. metadata=None, embed_frames=False, default_mode='loop',
  662. embed_limit=None):
  663. if extra_args:
  664. _log.warning("HTMLWriter ignores 'extra_args'")
  665. extra_args = () # Don't lookup nonexistent rcParam[args_key].
  666. self.embed_frames = embed_frames
  667. self.default_mode = default_mode.lower()
  668. cbook._check_in_list(['loop', 'once', 'reflect'],
  669. default_mode=self.default_mode)
  670. # Save embed limit, which is given in MB
  671. if embed_limit is None:
  672. self._bytes_limit = mpl.rcParams['animation.embed_limit']
  673. else:
  674. self._bytes_limit = embed_limit
  675. # Convert from MB to bytes
  676. self._bytes_limit *= 1024 * 1024
  677. super().__init__(fps, codec, bitrate, extra_args, metadata)
  678. def setup(self, fig, outfile, dpi, frame_dir=None):
  679. outfile = Path(outfile)
  680. cbook._check_in_list(['.html', '.htm'],
  681. outfile_extension=outfile.suffix)
  682. self._saved_frames = []
  683. self._total_bytes = 0
  684. self._hit_limit = False
  685. if not self.embed_frames:
  686. if frame_dir is None:
  687. frame_dir = outfile.with_name(outfile.stem + '_frames')
  688. frame_dir.mkdir(parents=True, exist_ok=True)
  689. frame_prefix = frame_dir / 'frame'
  690. else:
  691. frame_prefix = None
  692. super().setup(fig, outfile, dpi, frame_prefix)
  693. self._clear_temp = False
  694. def grab_frame(self, **savefig_kwargs):
  695. if self.embed_frames:
  696. # Just stop processing if we hit the limit
  697. if self._hit_limit:
  698. return
  699. f = BytesIO()
  700. self.fig.savefig(f, format=self.frame_format,
  701. dpi=self.dpi, **savefig_kwargs)
  702. imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
  703. self._total_bytes += len(imgdata64)
  704. if self._total_bytes >= self._bytes_limit:
  705. _log.warning(
  706. "Animation size has reached %s bytes, exceeding the limit "
  707. "of %s. If you're sure you want a larger animation "
  708. "embedded, set the animation.embed_limit rc parameter to "
  709. "a larger value (in MB). This and further frames will be "
  710. "dropped.", self._total_bytes, self._bytes_limit)
  711. self._hit_limit = True
  712. else:
  713. self._saved_frames.append(imgdata64)
  714. else:
  715. return super().grab_frame(**savefig_kwargs)
  716. def finish(self):
  717. # save the frames to an html file
  718. if self.embed_frames:
  719. fill_frames = _embedded_frames(self._saved_frames,
  720. self.frame_format)
  721. Nframes = len(self._saved_frames)
  722. else:
  723. # temp names is filled by FileMovieWriter
  724. fill_frames = _included_frames(self._temp_paths, self.frame_format)
  725. Nframes = len(self._temp_paths)
  726. mode_dict = dict(once_checked='',
  727. loop_checked='',
  728. reflect_checked='')
  729. mode_dict[self.default_mode + '_checked'] = 'checked'
  730. interval = 1000 // self.fps
  731. with open(self.outfile, 'w') as of:
  732. of.write(JS_INCLUDE + STYLE_INCLUDE)
  733. of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
  734. Nframes=Nframes,
  735. fill_frames=fill_frames,
  736. interval=interval,
  737. **mode_dict))
  738. class Animation:
  739. """
  740. A base class for Animations.
  741. This class is not usable as is, and should be subclassed to provide needed
  742. behavior.
  743. Parameters
  744. ----------
  745. fig : `~matplotlib.figure.Figure`
  746. The figure object used to get needed events, such as draw or resize.
  747. event_source : object, optional
  748. A class that can run a callback when desired events
  749. are generated, as well as be stopped and started.
  750. Examples include timers (see `TimedAnimation`) and file
  751. system notifications.
  752. blit : bool, default: False
  753. Whether blitting is used to optimize drawing.
  754. See Also
  755. --------
  756. FuncAnimation, ArtistAnimation
  757. """
  758. def __init__(self, fig, event_source=None, blit=False):
  759. self._fig = fig
  760. # Disables blitting for backends that don't support it. This
  761. # allows users to request it if available, but still have a
  762. # fallback that works if it is not.
  763. self._blit = blit and fig.canvas.supports_blit
  764. # These are the basics of the animation. The frame sequence represents
  765. # information for each frame of the animation and depends on how the
  766. # drawing is handled by the subclasses. The event source fires events
  767. # that cause the frame sequence to be iterated.
  768. self.frame_seq = self.new_frame_seq()
  769. self.event_source = event_source
  770. # Instead of starting the event source now, we connect to the figure's
  771. # draw_event, so that we only start once the figure has been drawn.
  772. self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
  773. # Connect to the figure's close_event so that we don't continue to
  774. # fire events and try to draw to a deleted figure.
  775. self._close_id = self._fig.canvas.mpl_connect('close_event',
  776. self._stop)
  777. if self._blit:
  778. self._setup_blit()
  779. def _start(self, *args):
  780. """
  781. Starts interactive animation. Adds the draw frame command to the GUI
  782. handler, calls show to start the event loop.
  783. """
  784. # Do not start the event source if saving() it.
  785. if self._fig.canvas.is_saving():
  786. return
  787. # First disconnect our draw event handler
  788. self._fig.canvas.mpl_disconnect(self._first_draw_id)
  789. # Now do any initial draw
  790. self._init_draw()
  791. # Add our callback for stepping the animation and
  792. # actually start the event_source.
  793. self.event_source.add_callback(self._step)
  794. self.event_source.start()
  795. def _stop(self, *args):
  796. # On stop we disconnect all of our events.
  797. if self._blit:
  798. self._fig.canvas.mpl_disconnect(self._resize_id)
  799. self._fig.canvas.mpl_disconnect(self._close_id)
  800. self.event_source.remove_callback(self._step)
  801. self.event_source = None
  802. def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
  803. bitrate=None, extra_args=None, metadata=None, extra_anim=None,
  804. savefig_kwargs=None, *, progress_callback=None):
  805. """
  806. Save the animation as a movie file by drawing every frame.
  807. Parameters
  808. ----------
  809. filename : str
  810. The output filename, e.g., :file:`mymovie.mp4`.
  811. writer : `MovieWriter` or str, default: :rc:`animation.writer`
  812. A `MovieWriter` instance to use or a key that identifies a
  813. class to use, such as 'ffmpeg'.
  814. fps : int, optional
  815. Movie frame rate (per second). If not set, the frame rate from the
  816. animation's frame interval.
  817. dpi : float, default: :rc:`savefig.dpi`
  818. Controls the dots per inch for the movie frames. Together with
  819. the figure's size in inches, this controls the size of the movie.
  820. codec : str, default: :rc:`animation.codec`.
  821. The video codec to use. Not all codecs are supported by a given
  822. `MovieWriter`.
  823. bitrate : int, default: :rc:`animation.bitrate`
  824. The bitrate of the movie, in kilobits per second. Higher values
  825. means higher quality movies, but increase the file size. A value
  826. of -1 lets the underlying movie encoder select the bitrate.
  827. extra_args : list of str or None, optional
  828. Extra command-line arguments passed to the underlying movie
  829. encoder. The default, None, means to use
  830. :rc:`animation.[name-of-encoder]_args` for the builtin writers.
  831. metadata : Dict[str, str], default {}
  832. Dictionary of keys and values for metadata to include in
  833. the output file. Some keys that may be of use include:
  834. title, artist, genre, subject, copyright, srcform, comment.
  835. extra_anim : list, default: []
  836. Additional `Animation` objects that should be included
  837. in the saved movie file. These need to be from the same
  838. `matplotlib.figure.Figure` instance. Also, animation frames will
  839. just be simply combined, so there should be a 1:1 correspondence
  840. between the frames from the different animations.
  841. savefig_kwargs : dict, default: {}
  842. Keyword arguments passed to each `~.Figure.savefig` call used to
  843. save the individual frames.
  844. progress_callback : function, optional
  845. A callback function that will be called for every frame to notify
  846. the saving progress. It must have the signature ::
  847. def func(current_frame: int, total_frames: int) -> Any
  848. where *current_frame* is the current frame number and
  849. *total_frames* is the total number of frames to be saved.
  850. *total_frames* is set to None, if the total number of frames can
  851. not be determined. Return values may exist but are ignored.
  852. Example code to write the progress to stdout::
  853. progress_callback =\
  854. lambda i, n: print(f'Saving frame {i} of {n}')
  855. Notes
  856. -----
  857. *fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
  858. construct a `.MovieWriter` instance and can only be passed if
  859. *writer* is a string. If they are passed as non-*None* and *writer*
  860. is a `.MovieWriter`, a `RuntimeError` will be raised.
  861. """
  862. if writer is None:
  863. writer = mpl.rcParams['animation.writer']
  864. elif (not isinstance(writer, str) and
  865. any(arg is not None
  866. for arg in (fps, codec, bitrate, extra_args, metadata))):
  867. raise RuntimeError('Passing in values for arguments '
  868. 'fps, codec, bitrate, extra_args, or metadata '
  869. 'is not supported when writer is an existing '
  870. 'MovieWriter instance. These should instead be '
  871. 'passed as arguments when creating the '
  872. 'MovieWriter instance.')
  873. if savefig_kwargs is None:
  874. savefig_kwargs = {}
  875. if fps is None and hasattr(self, '_interval'):
  876. # Convert interval in ms to frames per second
  877. fps = 1000. / self._interval
  878. # Re-use the savefig DPI for ours if none is given
  879. if dpi is None:
  880. dpi = mpl.rcParams['savefig.dpi']
  881. if dpi == 'figure':
  882. dpi = self._fig.dpi
  883. writer_kwargs = {}
  884. if codec is not None:
  885. writer_kwargs['codec'] = codec
  886. if bitrate is not None:
  887. writer_kwargs['bitrate'] = bitrate
  888. if extra_args is not None:
  889. writer_kwargs['extra_args'] = extra_args
  890. if metadata is not None:
  891. writer_kwargs['metadata'] = metadata
  892. all_anim = [self]
  893. if extra_anim is not None:
  894. all_anim.extend(anim
  895. for anim
  896. in extra_anim if anim._fig is self._fig)
  897. # If we have the name of a writer, instantiate an instance of the
  898. # registered class.
  899. if isinstance(writer, str):
  900. try:
  901. writer_cls = writers[writer]
  902. except RuntimeError: # Raised if not available.
  903. writer_cls = PillowWriter # Always available.
  904. _log.warning("MovieWriter %s unavailable; using Pillow "
  905. "instead.", writer)
  906. writer = writer_cls(fps, **writer_kwargs)
  907. _log.info('Animation.save using %s', type(writer))
  908. if 'bbox_inches' in savefig_kwargs:
  909. _log.warning("Warning: discarding the 'bbox_inches' argument in "
  910. "'savefig_kwargs' as it may cause frame size "
  911. "to vary, which is inappropriate for animation.")
  912. savefig_kwargs.pop('bbox_inches')
  913. # Create a new sequence of frames for saved data. This is different
  914. # from new_frame_seq() to give the ability to save 'live' generated
  915. # frame information to be saved later.
  916. # TODO: Right now, after closing the figure, saving a movie won't work
  917. # since GUI widgets are gone. Either need to remove extra code to
  918. # allow for this non-existent use case or find a way to make it work.
  919. if mpl.rcParams['savefig.bbox'] == 'tight':
  920. _log.info("Disabling savefig.bbox = 'tight', as it may cause "
  921. "frame size to vary, which is inappropriate for "
  922. "animation.")
  923. # canvas._is_saving = True makes the draw_event animation-starting
  924. # callback a no-op; canvas.manager = None prevents resizing the GUI
  925. # widget (both are likewise done in savefig()).
  926. with mpl.rc_context({'savefig.bbox': None}), \
  927. writer.saving(self._fig, filename, dpi), \
  928. cbook._setattr_cm(self._fig.canvas,
  929. _is_saving=True, manager=None):
  930. for anim in all_anim:
  931. anim._init_draw() # Clear the initial frame
  932. frame_number = 0
  933. # TODO: Currently only FuncAnimation has a save_count
  934. # attribute. Can we generalize this to all Animations?
  935. save_count_list = [getattr(a, 'save_count', None)
  936. for a in all_anim]
  937. if None in save_count_list:
  938. total_frames = None
  939. else:
  940. total_frames = sum(save_count_list)
  941. for data in zip(*[a.new_saved_frame_seq() for a in all_anim]):
  942. for anim, d in zip(all_anim, data):
  943. # TODO: See if turning off blit is really necessary
  944. anim._draw_next_frame(d, blit=False)
  945. if progress_callback is not None:
  946. progress_callback(frame_number, total_frames)
  947. frame_number += 1
  948. writer.grab_frame(**savefig_kwargs)
  949. def _step(self, *args):
  950. """
  951. Handler for getting events. By default, gets the next frame in the
  952. sequence and hands the data off to be drawn.
  953. """
  954. # Returns True to indicate that the event source should continue to
  955. # call _step, until the frame sequence reaches the end of iteration,
  956. # at which point False will be returned.
  957. try:
  958. framedata = next(self.frame_seq)
  959. self._draw_next_frame(framedata, self._blit)
  960. return True
  961. except StopIteration:
  962. return False
  963. def new_frame_seq(self):
  964. """Return a new sequence of frame information."""
  965. # Default implementation is just an iterator over self._framedata
  966. return iter(self._framedata)
  967. def new_saved_frame_seq(self):
  968. """Return a new sequence of saved/cached frame information."""
  969. # Default is the same as the regular frame sequence
  970. return self.new_frame_seq()
  971. def _draw_next_frame(self, framedata, blit):
  972. # Breaks down the drawing of the next frame into steps of pre- and
  973. # post- draw, as well as the drawing of the frame itself.
  974. self._pre_draw(framedata, blit)
  975. self._draw_frame(framedata)
  976. self._post_draw(framedata, blit)
  977. def _init_draw(self):
  978. # Initial draw to clear the frame. Also used by the blitting code
  979. # when a clean base is required.
  980. pass
  981. def _pre_draw(self, framedata, blit):
  982. # Perform any cleaning or whatnot before the drawing of the frame.
  983. # This default implementation allows blit to clear the frame.
  984. if blit:
  985. self._blit_clear(self._drawn_artists)
  986. def _draw_frame(self, framedata):
  987. # Performs actual drawing of the frame.
  988. raise NotImplementedError('Needs to be implemented by subclasses to'
  989. ' actually make an animation.')
  990. def _post_draw(self, framedata, blit):
  991. # After the frame is rendered, this handles the actual flushing of
  992. # the draw, which can be a direct draw_idle() or make use of the
  993. # blitting.
  994. if blit and self._drawn_artists:
  995. self._blit_draw(self._drawn_artists)
  996. else:
  997. self._fig.canvas.draw_idle()
  998. # The rest of the code in this class is to facilitate easy blitting
  999. def _blit_draw(self, artists):
  1000. # Handles blitted drawing, which renders only the artists given instead
  1001. # of the entire figure.
  1002. updated_ax = {a.axes for a in artists}
  1003. # Enumerate artists to cache axes' backgrounds. We do not draw
  1004. # artists yet to not cache foreground from plots with shared axes
  1005. for ax in updated_ax:
  1006. # If we haven't cached the background for the current view of this
  1007. # axes object, do so now. This might not always be reliable, but
  1008. # it's an attempt to automate the process.
  1009. cur_view = ax._get_view()
  1010. view, bg = self._blit_cache.get(ax, (object(), None))
  1011. if cur_view != view:
  1012. self._blit_cache[ax] = (
  1013. cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox))
  1014. # Make a separate pass to draw foreground.
  1015. for a in artists:
  1016. a.axes.draw_artist(a)
  1017. # After rendering all the needed artists, blit each axes individually.
  1018. for ax in updated_ax:
  1019. ax.figure.canvas.blit(ax.bbox)
  1020. def _blit_clear(self, artists):
  1021. # Get a list of the axes that need clearing from the artists that
  1022. # have been drawn. Grab the appropriate saved background from the
  1023. # cache and restore.
  1024. axes = {a.axes for a in artists}
  1025. for ax in axes:
  1026. try:
  1027. view, bg = self._blit_cache[ax]
  1028. except KeyError:
  1029. continue
  1030. if ax._get_view() == view:
  1031. ax.figure.canvas.restore_region(bg)
  1032. else:
  1033. self._blit_cache.pop(ax)
  1034. def _setup_blit(self):
  1035. # Setting up the blit requires: a cache of the background for the
  1036. # axes
  1037. self._blit_cache = dict()
  1038. self._drawn_artists = []
  1039. self._resize_id = self._fig.canvas.mpl_connect('resize_event',
  1040. self._on_resize)
  1041. self._post_draw(None, self._blit)
  1042. def _on_resize(self, event):
  1043. # On resize, we need to disable the resize event handling so we don't
  1044. # get too many events. Also stop the animation events, so that
  1045. # we're paused. Reset the cache and re-init. Set up an event handler
  1046. # to catch once the draw has actually taken place.
  1047. self._fig.canvas.mpl_disconnect(self._resize_id)
  1048. self.event_source.stop()
  1049. self._blit_cache.clear()
  1050. self._init_draw()
  1051. self._resize_id = self._fig.canvas.mpl_connect('draw_event',
  1052. self._end_redraw)
  1053. def _end_redraw(self, event):
  1054. # Now that the redraw has happened, do the post draw flushing and
  1055. # blit handling. Then re-enable all of the original events.
  1056. self._post_draw(None, False)
  1057. self.event_source.start()
  1058. self._fig.canvas.mpl_disconnect(self._resize_id)
  1059. self._resize_id = self._fig.canvas.mpl_connect('resize_event',
  1060. self._on_resize)
  1061. def to_html5_video(self, embed_limit=None):
  1062. """
  1063. Convert the animation to an HTML5 ``<video>`` tag.
  1064. This saves the animation as an h264 video, encoded in base64
  1065. directly into the HTML5 video tag. This respects :rc:`animation.writer`
  1066. and :rc:`animation.bitrate`. This also makes use of the
  1067. ``interval`` to control the speed, and uses the ``repeat``
  1068. parameter to decide whether to loop.
  1069. Parameters
  1070. ----------
  1071. embed_limit : float, optional
  1072. Limit, in MB, of the returned animation. No animation is created
  1073. if the limit is exceeded.
  1074. Defaults to :rc:`animation.embed_limit` = 20.0.
  1075. Returns
  1076. -------
  1077. str
  1078. An HTML5 video tag with the animation embedded as base64 encoded
  1079. h264 video.
  1080. If the *embed_limit* is exceeded, this returns the string
  1081. "Video too large to embed."
  1082. """
  1083. VIDEO_TAG = r'''<video {size} {options}>
  1084. <source type="video/mp4" src="data:video/mp4;base64,{video}">
  1085. Your browser does not support the video tag.
  1086. </video>'''
  1087. # Cache the rendering of the video as HTML
  1088. if not hasattr(self, '_base64_video'):
  1089. # Save embed limit, which is given in MB
  1090. if embed_limit is None:
  1091. embed_limit = mpl.rcParams['animation.embed_limit']
  1092. # Convert from MB to bytes
  1093. embed_limit *= 1024 * 1024
  1094. # Can't open a NamedTemporaryFile twice on Windows, so use a
  1095. # TemporaryDirectory instead.
  1096. with TemporaryDirectory() as tmpdir:
  1097. path = Path(tmpdir, "temp.m4v")
  1098. # We create a writer manually so that we can get the
  1099. # appropriate size for the tag
  1100. Writer = writers[mpl.rcParams['animation.writer']]
  1101. writer = Writer(codec='h264',
  1102. bitrate=mpl.rcParams['animation.bitrate'],
  1103. fps=1000. / self._interval)
  1104. self.save(str(path), writer=writer)
  1105. # Now open and base64 encode.
  1106. vid64 = base64.encodebytes(path.read_bytes())
  1107. vid_len = len(vid64)
  1108. if vid_len >= embed_limit:
  1109. _log.warning(
  1110. "Animation movie is %s bytes, exceeding the limit of %s. "
  1111. "If you're sure you want a large animation embedded, set "
  1112. "the animation.embed_limit rc parameter to a larger value "
  1113. "(in MB).", vid_len, embed_limit)
  1114. else:
  1115. self._base64_video = vid64.decode('ascii')
  1116. self._video_size = 'width="{}" height="{}"'.format(
  1117. *writer.frame_size)
  1118. # If we exceeded the size, this attribute won't exist
  1119. if hasattr(self, '_base64_video'):
  1120. # Default HTML5 options are to autoplay and display video controls
  1121. options = ['controls', 'autoplay']
  1122. # If we're set to repeat, make it loop
  1123. if hasattr(self, 'repeat') and self.repeat:
  1124. options.append('loop')
  1125. return VIDEO_TAG.format(video=self._base64_video,
  1126. size=self._video_size,
  1127. options=' '.join(options))
  1128. else:
  1129. return 'Video too large to embed.'
  1130. def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
  1131. """Generate HTML representation of the animation"""
  1132. if fps is None and hasattr(self, '_interval'):
  1133. # Convert interval in ms to frames per second
  1134. fps = 1000 / self._interval
  1135. # If we're not given a default mode, choose one base on the value of
  1136. # the repeat attribute
  1137. if default_mode is None:
  1138. default_mode = 'loop' if self.repeat else 'once'
  1139. if not hasattr(self, "_html_representation"):
  1140. # Can't open a NamedTemporaryFile twice on Windows, so use a
  1141. # TemporaryDirectory instead.
  1142. with TemporaryDirectory() as tmpdir:
  1143. path = Path(tmpdir, "temp.html")
  1144. writer = HTMLWriter(fps=fps,
  1145. embed_frames=embed_frames,
  1146. default_mode=default_mode)
  1147. self.save(str(path), writer=writer)
  1148. self._html_representation = path.read_text()
  1149. return self._html_representation
  1150. def _repr_html_(self):
  1151. """IPython display hook for rendering."""
  1152. fmt = mpl.rcParams['animation.html']
  1153. if fmt == 'html5':
  1154. return self.to_html5_video()
  1155. elif fmt == 'jshtml':
  1156. return self.to_jshtml()
  1157. class TimedAnimation(Animation):
  1158. """
  1159. `Animation` subclass for time-based animation.
  1160. A new frame is drawn every *interval* milliseconds.
  1161. Parameters
  1162. ----------
  1163. fig : `~matplotlib.figure.Figure`
  1164. The figure object used to get needed events, such as draw or resize.
  1165. interval : int, default: 200
  1166. Delay between frames in milliseconds.
  1167. repeat_delay : int, default: 0
  1168. The delay in milliseconds between consecutive animation runs, if
  1169. *repeat* is True.
  1170. repeat : bool, default: True
  1171. Whether the animation repeats when the sequence of frames is completed.
  1172. blit : bool, default: False
  1173. Whether blitting is used to optimize drawing.
  1174. """
  1175. def __init__(self, fig, interval=200, repeat_delay=0, repeat=True,
  1176. event_source=None, *args, **kwargs):
  1177. self._interval = interval
  1178. # Undocumented support for repeat_delay = None as backcompat.
  1179. self._repeat_delay = repeat_delay if repeat_delay is not None else 0
  1180. self.repeat = repeat
  1181. # If we're not given an event source, create a new timer. This permits
  1182. # sharing timers between animation objects for syncing animations.
  1183. if event_source is None:
  1184. event_source = fig.canvas.new_timer(interval=self._interval)
  1185. Animation.__init__(self, fig, event_source=event_source,
  1186. *args, **kwargs)
  1187. def _step(self, *args):
  1188. """Handler for getting events."""
  1189. # Extends the _step() method for the Animation class. If
  1190. # Animation._step signals that it reached the end and we want to
  1191. # repeat, we refresh the frame sequence and return True. If
  1192. # _repeat_delay is set, change the event_source's interval to our loop
  1193. # delay and set the callback to one which will then set the interval
  1194. # back.
  1195. still_going = Animation._step(self, *args)
  1196. if not still_going and self.repeat:
  1197. self._init_draw()
  1198. self.frame_seq = self.new_frame_seq()
  1199. self.event_source.remove_callback(self._step)
  1200. self.event_source.add_callback(self._loop_delay)
  1201. self.event_source.interval = self._repeat_delay
  1202. return True
  1203. else:
  1204. return still_going
  1205. def _stop(self, *args):
  1206. # If we stop in the middle of a loop delay (which is relatively likely
  1207. # given the potential pause here), remove the loop_delay callback as
  1208. # well.
  1209. self.event_source.remove_callback(self._loop_delay)
  1210. Animation._stop(self)
  1211. def _loop_delay(self, *args):
  1212. # Reset the interval and change callbacks after the delay.
  1213. self.event_source.remove_callback(self._loop_delay)
  1214. self.event_source.interval = self._interval
  1215. self.event_source.add_callback(self._step)
  1216. Animation._step(self)
  1217. class ArtistAnimation(TimedAnimation):
  1218. """
  1219. Animation using a fixed set of `.Artist` objects.
  1220. Before creating an instance, all plotting should have taken place
  1221. and the relevant artists saved.
  1222. Parameters
  1223. ----------
  1224. fig : `~matplotlib.figure.Figure`
  1225. The figure object used to get needed events, such as draw or resize.
  1226. artists : list
  1227. Each list entry is a collection of artists that are made visible on
  1228. the corresponding frame. Other artists are made invisible.
  1229. interval : int, default: 200
  1230. Delay between frames in milliseconds.
  1231. repeat_delay : int, default: 0
  1232. The delay in milliseconds between consecutive animation runs, if
  1233. *repeat* is True.
  1234. repeat : bool, default: True
  1235. Whether the animation repeats when the sequence of frames is completed.
  1236. blit : bool, default: False
  1237. Whether blitting is used to optimize drawing.
  1238. """
  1239. def __init__(self, fig, artists, *args, **kwargs):
  1240. # Internal list of artists drawn in the most recent frame.
  1241. self._drawn_artists = []
  1242. # Use the list of artists as the framedata, which will be iterated
  1243. # over by the machinery.
  1244. self._framedata = artists
  1245. TimedAnimation.__init__(self, fig, *args, **kwargs)
  1246. def _init_draw(self):
  1247. # Make all the artists involved in *any* frame invisible
  1248. figs = set()
  1249. for f in self.new_frame_seq():
  1250. for artist in f:
  1251. artist.set_visible(False)
  1252. artist.set_animated(self._blit)
  1253. # Assemble a list of unique figures that need flushing
  1254. if artist.get_figure() not in figs:
  1255. figs.add(artist.get_figure())
  1256. # Flush the needed figures
  1257. for fig in figs:
  1258. fig.canvas.draw_idle()
  1259. def _pre_draw(self, framedata, blit):
  1260. """Clears artists from the last frame."""
  1261. if blit:
  1262. # Let blit handle clearing
  1263. self._blit_clear(self._drawn_artists)
  1264. else:
  1265. # Otherwise, make all the artists from the previous frame invisible
  1266. for artist in self._drawn_artists:
  1267. artist.set_visible(False)
  1268. def _draw_frame(self, artists):
  1269. # Save the artists that were passed in as framedata for the other
  1270. # steps (esp. blitting) to use.
  1271. self._drawn_artists = artists
  1272. # Make all the artists from the current frame visible
  1273. for artist in artists:
  1274. artist.set_visible(True)
  1275. class FuncAnimation(TimedAnimation):
  1276. """
  1277. Makes an animation by repeatedly calling a function *func*.
  1278. Parameters
  1279. ----------
  1280. fig : `~matplotlib.figure.Figure`
  1281. The figure object used to get needed events, such as draw or resize.
  1282. func : callable
  1283. The function to call at each frame. The first argument will
  1284. be the next value in *frames*. Any additional positional
  1285. arguments can be supplied via the *fargs* parameter.
  1286. The required signature is::
  1287. def func(frame, *fargs) -> iterable_of_artists
  1288. If ``blit == True``, *func* must return an iterable of all artists
  1289. that were modified or created. This information is used by the blitting
  1290. algorithm to determine which parts of the figure have to be updated.
  1291. The return value is unused if ``blit == False`` and may be omitted in
  1292. that case.
  1293. frames : iterable, int, generator function, or None, optional
  1294. Source of data to pass *func* and each frame of the animation
  1295. - If an iterable, then simply use the values provided. If the
  1296. iterable has a length, it will override the *save_count* kwarg.
  1297. - If an integer, then equivalent to passing ``range(frames)``
  1298. - If a generator function, then must have the signature::
  1299. def gen_function() -> obj
  1300. - If *None*, then equivalent to passing ``itertools.count``.
  1301. In all of these cases, the values in *frames* is simply passed through
  1302. to the user-supplied *func* and thus can be of any type.
  1303. init_func : callable, optional
  1304. A function used to draw a clear frame. If not given, the results of
  1305. drawing from the first item in the frames sequence will be used. This
  1306. function will be called once before the first frame.
  1307. The required signature is::
  1308. def init_func() -> iterable_of_artists
  1309. If ``blit == True``, *init_func* must return an iterable of artists
  1310. to be re-drawn. This information is used by the blitting algorithm to
  1311. determine which parts of the figure have to be updated. The return
  1312. value is unused if ``blit == False`` and may be omitted in that case.
  1313. fargs : tuple or None, optional
  1314. Additional arguments to pass to each call to *func*.
  1315. save_count : int, default: 100
  1316. Fallback for the number of values from *frames* to cache. This is
  1317. only used if the number of frames cannot be inferred from *frames*,
  1318. i.e. when it's an iterator without length or a generator.
  1319. interval : int, default: 200
  1320. Delay between frames in milliseconds.
  1321. repeat_delay : int, default: 0
  1322. The delay in milliseconds between consecutive animation runs, if
  1323. *repeat* is True.
  1324. repeat : bool, default: True
  1325. Whether the animation repeats when the sequence of frames is completed.
  1326. blit : bool, default: False
  1327. Whether blitting is used to optimize drawing. Note: when using
  1328. blitting, any animated artists will be drawn according to their zorder;
  1329. however, they will be drawn on top of any previous artists, regardless
  1330. of their zorder.
  1331. cache_frame_data : bool, default: True
  1332. Whether frame data is cached. Disabling cache might be helpful when
  1333. frames contain large objects.
  1334. """
  1335. def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
  1336. save_count=None, *, cache_frame_data=True, **kwargs):
  1337. if fargs:
  1338. self._args = fargs
  1339. else:
  1340. self._args = ()
  1341. self._func = func
  1342. self._init_func = init_func
  1343. # Amount of framedata to keep around for saving movies. This is only
  1344. # used if we don't know how many frames there will be: in the case
  1345. # of no generator or in the case of a callable.
  1346. self.save_count = save_count
  1347. # Set up a function that creates a new iterable when needed. If nothing
  1348. # is passed in for frames, just use itertools.count, which will just
  1349. # keep counting from 0. A callable passed in for frames is assumed to
  1350. # be a generator. An iterable will be used as is, and anything else
  1351. # will be treated as a number of frames.
  1352. if frames is None:
  1353. self._iter_gen = itertools.count
  1354. elif callable(frames):
  1355. self._iter_gen = frames
  1356. elif np.iterable(frames):
  1357. if kwargs.get('repeat', True):
  1358. def iter_frames(frames=frames):
  1359. while True:
  1360. this, frames = itertools.tee(frames, 2)
  1361. yield from this
  1362. self._iter_gen = iter_frames
  1363. else:
  1364. self._iter_gen = lambda: iter(frames)
  1365. if hasattr(frames, '__len__'):
  1366. self.save_count = len(frames)
  1367. else:
  1368. self._iter_gen = lambda: iter(range(frames))
  1369. self.save_count = frames
  1370. if self.save_count is None:
  1371. # If we're passed in and using the default, set save_count to 100.
  1372. self.save_count = 100
  1373. else:
  1374. # itertools.islice returns an error when passed a numpy int instead
  1375. # of a native python int (http://bugs.python.org/issue30537).
  1376. # As a workaround, convert save_count to a native python int.
  1377. self.save_count = int(self.save_count)
  1378. self._cache_frame_data = cache_frame_data
  1379. # Needs to be initialized so the draw functions work without checking
  1380. self._save_seq = []
  1381. TimedAnimation.__init__(self, fig, **kwargs)
  1382. # Need to reset the saved seq, since right now it will contain data
  1383. # for a single frame from init, which is not what we want.
  1384. self._save_seq = []
  1385. def new_frame_seq(self):
  1386. # Use the generating function to generate a new frame sequence
  1387. return self._iter_gen()
  1388. def new_saved_frame_seq(self):
  1389. # Generate an iterator for the sequence of saved data. If there are
  1390. # no saved frames, generate a new frame sequence and take the first
  1391. # save_count entries in it.
  1392. if self._save_seq:
  1393. # While iterating we are going to update _save_seq
  1394. # so make a copy to safely iterate over
  1395. self._old_saved_seq = list(self._save_seq)
  1396. return iter(self._old_saved_seq)
  1397. else:
  1398. if self.save_count is not None:
  1399. return itertools.islice(self.new_frame_seq(), self.save_count)
  1400. else:
  1401. frame_seq = self.new_frame_seq()
  1402. def gen():
  1403. try:
  1404. for _ in range(100):
  1405. yield next(frame_seq)
  1406. except StopIteration:
  1407. pass
  1408. else:
  1409. cbook.warn_deprecated(
  1410. "2.2", message="FuncAnimation.save has truncated "
  1411. "your animation to 100 frames. In the future, no "
  1412. "such truncation will occur; please pass "
  1413. "'save_count' accordingly.")
  1414. return gen()
  1415. def _init_draw(self):
  1416. # Initialize the drawing either using the given init_func or by
  1417. # calling the draw function with the first item of the frame sequence.
  1418. # For blitting, the init_func should return a sequence of modified
  1419. # artists.
  1420. if self._init_func is None:
  1421. self._draw_frame(next(self.new_frame_seq()))
  1422. else:
  1423. self._drawn_artists = self._init_func()
  1424. if self._blit:
  1425. if self._drawn_artists is None:
  1426. raise RuntimeError('The init_func must return a '
  1427. 'sequence of Artist objects.')
  1428. for a in self._drawn_artists:
  1429. a.set_animated(self._blit)
  1430. self._save_seq = []
  1431. def _draw_frame(self, framedata):
  1432. if self._cache_frame_data:
  1433. # Save the data for potential saving of movies.
  1434. self._save_seq.append(framedata)
  1435. # Make sure to respect save_count (keep only the last save_count
  1436. # around)
  1437. self._save_seq = self._save_seq[-self.save_count:]
  1438. # Call the func with framedata and args. If blitting is desired,
  1439. # func needs to return a sequence of any artists that were modified.
  1440. self._drawn_artists = self._func(framedata, *self._args)
  1441. if self._blit:
  1442. if self._drawn_artists is None:
  1443. raise RuntimeError('The animation function must return a '
  1444. 'sequence of Artist objects.')
  1445. self._drawn_artists = sorted(self._drawn_artists,
  1446. key=lambda x: x.get_zorder())
  1447. for a in self._drawn_artists:
  1448. a.set_animated(self._blit)