Exemple #1
0
    def to_jshtml(self, fps=5, loop=True, embed_limit=20):
        """
        Generate HTML representation of the animation.

        Parameters
        ----------
        fps : int
            Frames per second of movie.
        loop : bool
            Whether the video should loop or not.
        embed_limit : int, optional
            Limit, in MB, of size of encoded animation in HTML.

        Returns
        -------
        html : str
            HTML representation of video.
        """
        default_mode = 'loop' if loop else 'once'

        writer = animation.HTMLWriter(fps=fps,
                                      embed_frames=True,
                                      default_mode=default_mode,
                                      embed_limit=embed_limit)

        # Can't open a second time while opened on windows. So we avoid
        # deleting when closed, and delete manually later.
        with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as f:
            with writer.saving(self.fig, f.name, self._dpi):
                for i in range(self.N):
                    self._draw_frame(i)
                    writer.grab_frame()

        with open(f.name) as fobj:
            html = fobj.read()

        os.remove(f.name)

        return html
## Use simulation to calculate the average distance over which the fire
## spreads before getting stuck, and the proportion of the time that the
## fire reaches the edge of the forest.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import colors
import os
from sys import platform
import shlex
import pandas as pd
from openpyxl import load_workbook

filename = "dynamic_images.html"
# change the fps to speed up or slow down the animation
writer = animation.HTMLWriter(fps=12)
# ensure matrix and data frame are not truncated
np.set_printoptions(threshold=np.inf)
#pd.set_option('display.max_columns', None)
#pd.set_option('display.max_rows', None)
fig = plt.figure()
# array of images
ims = []


def simulation(p, ny, nx, nrep, animate, separate):
    if separate == True:
        # empties animation array after each change in density of mud in the forest.
        global ims
        ims = []
Exemple #3
0
    img += plt.plot(xl,
                    psi2l,
                    color='green',
                    linestyle='solid',
                    linewidth=3.0,
                    label='E_2')
    img += plt.plot(xl,
                    psi3l,
                    color='blue',
                    linestyle='solid',
                    linewidth=3.0,
                    label='E_3')
    ims.append(img)

#グラフタイトルの設定
plt.title("Plane wave")
#x軸ラベル・y軸ラベルの設定
plt.xlabel("Position")
plt.ylabel("Real part of Wave fanction")
#描画範囲を設定
plt.xlim([-2.0, 2.0])
plt.ylim([-1.2, 1.2])
#アニメーションの生成
ani = animation.ArtistAnimation(fig, ims, interval=10)
#アニメーションの保存
ani.save("output.html", writer=animation.HTMLWriter())
#ani.save("output.gif", writer="imagemagick")
#ani.save("output.mp4", writer="ffmpeg", dpi=300)
#グラフの表示
plt.show()
Exemple #4
0
     default_fn = stype_str + '-' + dtype + '-animation'
     fn = input('Please input a filename(%s): ' % default_fn)
     if fn == '':
         fn = default_fn
     try:
         fps = int(input('Please set the fps(25): '))
     except:
         fps = 25
     _, anim = draw_all_charts(od, 100) if stype == -1 else draw_chart(
         stype, od, 100)
     print('Please wait...')
     anim.save(fn + '.mp4',
               writer=animation.FFMpegWriter(
                   fps=fps, extra_args=['-vcodec', 'libx264']))
     print('The file has been successfully saved in %s' %
           os.path.abspath(fn + '.mp4'))
 elif sys.argv[1] == 'save-html':
     default_fn = stype_str + '-' + dtype + '-animation'
     fn = input('Please input a filename(%s): ' % default_fn)
     if fn == '':
         fn = default_fn
     try:
         fps = int(input('Please set the fps(25): '))
     except:
         fps = 25
     _, anim = draw_all_charts(od, 100) if stype == -1 else draw_chart(
         stype, od, 100)
     print('Please wait...')
     anim.save(fn + '.html', writer=animation.HTMLWriter(fps=fps))
     print('The file has been successfully saved in %s' %
           os.path.abspath(fn + '.html'))
if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='You can try all sorting algorithm found on wikipedia.')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-v', '--visualize', choices=('play', 'mp4', 'html'))
    group.add_argument('-p', '--performance')
    parser.add_argument('-a', '--algorithm', nargs='*', default='all')
    parser.add_argument('--target', default='random', choices=(
        'random', 'sorted', 'reversed', 'almost-sorted', 'sorted-roughly',
        'few-unique'))
    parser.add_argument('--size', type=int, default=32)
    parser.add_argument('-o', '--outfile', default='result')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--interval', default=100, type=int)
    group.add_argument('--fps', default=25, type=int)
    args = parser.parse_args()

    target = generate_target(args.target, args.size)

    if args.visualize:
        ChartElement.max = args.size
        anim = draw_charts(args.algorithm, target, args.interval)
        if args.visualize == 'play':
            plt.show()
        elif args.visualize == 'mp4':
            anim.save(args.outfile+'.mp4', animation.FFMpegWriter(
                args.fps, extra_args=['-vcodec', 'libx264', '-tune',
                                      'stillimage']))
        elif args.visualize == 'html':
            anim.save(args.outfile+'.html', animation.HTMLWriter(args.fps))
Exemple #6
0
    def play_animation(self, save=False, filename='test_anim', as_gif=False):

        fig = plt.figure(figsize=(10, 8))
        gridspec = gs.GridSpec(1, 3, width_ratios=[1, 1, 0.05])

        S_ax = fig.add_subplot(gridspec[0],
                               projection='3d',
                               zlim=self.zlim_S,
                               xlabel="X",
                               ylabel="Y")
        I_ax = fig.add_subplot(gridspec[1],
                               projection='3d',
                               zlim=self.zlim_I,
                               xlabel="X",
                               ylabel="Y")
        color_ax = fig.add_subplot(gridspec[2])

        S_ax.set_title("S: Susceptible Population", pad=20, fontsize=16)
        I_ax.set_title("I: Infected Population", pad=20, fontsize=16)

        # Adding single color-bar:
        mappable = plt.cm.ScalarMappable(cmap=plt.cm.plasma)
        mappable.set_array(self.model.I_solver.u_n)
        mappable.set_clim(
            0.0,
            np.maximum(np.max(self.model.S_solver.u_n),
                       np.max(self.model.I_solver.u_n)))
        plt.colorbar(mappable, cax=color_ax, orientation="vertical")

        # Tighten up the entire figure:
        plt.tight_layout(rect=[0.0, 0.02, 1.0, 0.99])

        # Defining plot arguments to be sent to the
        plot_args = {
            'rstride': 1,
            'cstride': 1,
            'linewidth': 0.01,
            'cmap': mappable.cmap,
            'norm': mappable.norm,
            'antialiased': True,
            'shade': True
        }

        axes = [
            S_ax.plot_surface(self.X, self.Y, self.model.S_solver.u_n,
                              **plot_args),
            I_ax.plot_surface(self.X, self.Y, self.model.I_solver.u_n,
                              **plot_args)
        ]

        S_ax.view_init(**self.initial_view)
        time_text = plt.figtext(x=0.02,
                                y=0.94,
                                s=f"T: {0 * self.model.S_solver.k:.3f}")

        I_ax.view_init(**self.initial_view)

        def update_plot(i, axes, plot_args):
            self.model.perform_single_step(i)
            time_text.set_text(f"T: {i * self.model.S_solver.k:.3f}")

            axes[0].remove()
            axes[0] = S_ax.plot_surface(self.X, self.Y,
                                        self.model.S_solver.u_n, **plot_args)
            S_ax.elev += self.elev_rotation
            S_ax.azim += self.azim_rotation

            axes[1].remove()
            axes[1] = I_ax.plot_surface(self.X, self.Y,
                                        self.model.I_solver.u_n, **plot_args)
            I_ax.elev += self.elev_rotation
            I_ax.azim += self.azim_rotation
            return time_text,

        anim_obj = anim.FuncAnimation(fig=fig,
                                      func=update_plot,
                                      frames=self.frames,
                                      fargs=(axes, plot_args),
                                      interval=int(1000.0 / self.fps))

        # Otherwise:
        if save and as_gif:  # Needs 'imagemagick' installed:
            print("Saving animation as .gif.")
            anim_obj.save(filename=filename + '.gif', writer='imagemagick')
        elif save:
            print("Saving animation as html.")
            html_writer = anim.HTMLWriter(fps=self.fps)
            anim_obj.save(filename=filename + '.html', writer=html_writer)
        else:
            plt.show()
        return np.array([self.model.S_solver.u_n, self.model.I_solver.u_n])
Exemple #7
0
            if sys.argv[2] in stype_dic:
                showtype = stype_dic[sys.argv[2]]
            else:
                exit()

        # We want to show all sorting algorithm
        showtype_str = 'all'
        # The dataset if generated with rand
        datatype = 'random'
        dataset = list(range(1, Data.data_count + 1))
        random.shuffle(dataset)

        if sys.argv[1] == 'play':
            frameInterval = 100
            if showtype == 100:
                plt, _ = draw_all_charts(dataset, frameInterval)
            plt.show()

        elif sys.argv[1] == 'save-html':
            filename = "random-dataset-animation"
            fps = 25
            if showtype == 100:
                _, anim = draw_all_charts(dataset, 100)

            # save animation as html form
            anim.save(filename + '.html', writer=animation.HTMLWriter(fps=fps))
            print('The file has been successfully saved in %s' %
                  os.path.abspath(filename + '.html'))
    else:
        exit()
Exemple #8
0
# time of simulation (in seconds)
duration = int(input('Duration of time to simulate (in seconds): '))
frames_per_second = 60
n_frames = duration * frames_per_second

# initialize the Animator
animator = Animator(fig=graph.fig,
                    ax=graph.ax,
                    cars_object=cars,
                    lights_object=lights,
                    num=(1, 1),
                    n=N)
init = animator.reset
animate = animator.animate

print(f"{dt.now().strftime('%H:%M:%S')} Now running simulation... ")
# for creating HTML movies
ani = animation.FuncAnimation(graph.fig,
                              animate,
                              init_func=init,
                              frames=tqdm(range(n_frames), file=sys.stdout),
                              interval=30,
                              blit=True)
mywriter = animation.HTMLWriter(fps=frames_per_second)
ani.save(f'traffic_{dt.today().strftime("%Y_%m_%d")}.html', writer=mywriter)

# for creating mp4 movies
# ani = animation.FuncAnimation(fig, animate, init_func=init, frames=500)
# mywriter = animation.FFMpegWriter(fps=60)
# ani.save('movie.mp4', writer=mywriter)