animation.py 66 KB

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