def test_animate(): import unittest from matplotlib.animation import writers import warnings from ase.build import bulk, molecule, fcc111 from ase.io.animation import write_animation if 'html' not in writers.list(): raise unittest.SkipTest('matplotlib html writer not present') images = [molecule('H2O'), bulk('Cu'), fcc111('Au', size=(1, 1, 1))] # gif and mp4 writers may not be available. Easiest solution is to only # test this using the html writer because it always exists whenever # matplotlib exists: with warnings.catch_warnings(): try: from matplotlib import MatplotlibDeprecationWarning except ImportError: pass else: warnings.simplefilter('ignore', MatplotlibDeprecationWarning) write_animation('things.html', images, writer='html')
from matplotlib.animation import writers from ase.test.testsuite import NotAvailable from ase.build import bulk, molecule, fcc111 from ase.io.animation import write_animation import warnings if 'html' not in writers.list(): raise NotAvailable('matplotlib html writer not present') images = [molecule('H2O'), bulk('Cu'), fcc111('Au', size=(1, 1, 1))] # gif and mp4 writers may not be available. Easiest solution is to only # test this using the html writer because it always exists whenever # matplotlib exists: with warnings.catch_warnings(): try: from matplotlib import MatplotlibDeprecationWarning except ImportError: pass else: warnings.simplefilter('ignore', MatplotlibDeprecationWarning) write_animation('things.html', images, writer='html')
def test_matplotlib_example(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") progs = ["ffmpeg"] if not sys.platform.startswith("win"): progs.append("avconv") errs = [] prog = None for prog in progs: out, err = run_cmd(prog, wait=True, fLOG=fLOG) exps = "usage:" if (exps not in out and exps not in err) or err is None or len(err) == 0: errs.append((prog, err)) else: break if len(errs) >= len(progs): if sys.platform.startswith("win"): fLOG("download ffmpeg") add_missing_development_version( ["pyensae"], __file__, hide=True) from pyensae.datasource import download_data download_data("ffmpeg.zip", website="xd") else: raise FileNotFoundError( "Unable to find '{1}'.\nPATH='{0}'\n--------\n[OUT]\n{2}\n[ERR]\n{3}".format( os.environ["PATH"], prog, out, "\n----\n".join("{0}:\n{1}".format(*_) for _ in errs))) temp = get_temp_folder(__file__, "temp_example_example") fix_tkinter_issues_virtualenv() # update a distribution based on new data. import numpy as np import matplotlib.pyplot as plt import scipy.stats as ss from matplotlib.animation import FuncAnimation, writers # To get the list of available writers if not writers.is_available(prog): writers.register(prog) fLOG(writers.list()) class UpdateDist: def __init__(self, ax, prob=0.5): self.success = 0 self.prob = prob self.line, = ax.plot([], [], 'k-') self.x = np.linspace(0, 1, 200) self.ax = ax # Set up plot parameters self.ax.set_xlim(0, 1) self.ax.set_ylim(0, 15) self.ax.grid(True) # This vertical line represents the theoretical value, to # which the plotted distribution should converge. self.ax.axvline(prob, linestyle='--', color='black') def init(self): self.success = 0 self.line.set_data([], []) return self.line, def __call__(self, i): # This way the plot can continuously run and we just keep # watching new realizations of the process if i == 0: return self.init() # Choose success based on exceed a threshold with a uniform # pick if np.random.rand(1,) < self.prob: # pylint: disable=W0143 self.success += 1 y = ss.beta.pdf(self.x, self.success + 1, (i - self.success) + 1) self.line.set_data(self.x, y) return self.line, fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ud = UpdateDist(ax, prob=0.7) anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init, interval=100, blit=True) try: Writer = writers[prog] except KeyError as e: if prog == "avconv": from matplotlib.animation import AVConvWriter Writer = AVConvWriter else: raise e writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800) anim.save(os.path.join(temp, 'lines2.mp4'), writer=writer) plt.close('all') fLOG("end")
def prepare_save(self, filename, writer=None, fps=5, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, savefig_kwargs=None): """See https://matplotlib.org/_modules/matplotlib/animation.html#Animation save, except with fps not None for default""" if writer is None: writer = mpl.rcParams['animation.writer'] elif (not isinstance(writer, str) and any(arg is not None for arg in (fps, codec, bitrate, extra_args, metadata))): raise RuntimeError('Passing in values for arguments ' 'fps, codec, bitrate, extra_args, or metadata ' 'is not supported when writer is an existing ' 'MovieWriter instance. These should instead be ' 'passed as arguments when creating the ' 'MovieWriter instance.') if savefig_kwargs is None: savefig_kwargs = {} if dpi is None: dpi = mpl.rcParams['savefig.dpi'] if dpi == 'figure': dpi = self.fig.dpi if codec is None: codec = mpl.rcParams['animation.codec'] if bitrate is None: bitrate = mpl.rcParams['animation.bitrate'] # If we have the name of a writer, instantiate an instance of the # registered class. if isinstance(writer, str): if writer in writers.avail: writer = writers[writer](fps, codec, bitrate, extra_args=extra_args, metadata=metadata) else: _log.warning("MovieWriter {} unavailable. Trying to use {} " "instead.".format(writer, writers.list()[0])) try: writer = writers[writers.list()[0]](fps, codec, bitrate, extra_args=extra_args, metadata=metadata) except IndexError: raise ValueError("Cannot save animation: no writers are " "available. Please install ffmpeg to " "save animations.") _log.info('AsyncAnimation.save using %s', type(writer)) if 'bbox_inches' in savefig_kwargs: _log.warning("Warning: discarding the 'bbox_inches' argument in " "'savefig_kwargs' as it may cause frame size " "to vary, which is inappropriate for animation.") savefig_kwargs.pop('bbox_inches') self._my_rc_ctx = mpl.rc_context() self._my_rc_ctx.__enter__() if mpl.rcParams['savefig.bbox'] == 'tight': _log.info("Disabling savefig.bbox = 'tight', as it may cause " "frame size to vary, which is inappropriate for " "animation.") mpl.rcParams['savefig.bbox'] = None self._save_ctx = writer.saving(self.fig, filename, dpi) self._save_ctx.__enter__() self._writer = writer self._savefig_kwargs = savefig_kwargs