Exemplo n.º 1
0
def draw_tree(robot_env, start, goal, tree, vertex=True, save_gif=True, fname='rrt_tree'):
    """Draw the tree built by the planner
    Args:
        robot_env (rl_planner.env.base_env.BaseEnv): the robot gym env
        start (numpy.ndarray)
        goal (numpy.ndarray)
        tree (list): list of nodes
        vertex (bool): nodes will be plotted if vertex is True 
        fname (str)
    """
    fig, ax = plt.subplots(figsize=(6,6))
    plt.axis([-22,22,-22,22])
    plt.xticks([])
    plt.yticks([])
    collection_list = [] # each entry is a collection
    tmp = plot_problem_definition(ax, robot_env.obs_list, robot_env.rigid_robot, start, goal)
    collection_list.append(tmp)
    for node in tree:
        if node.parent:
            tmp = tmp.copy()
            path = np.array(node.path[:])
            ax_path, = plt.plot(path[:,0], path[:,1], "-g", linewidth=0.6)
            tmp.append(ax_path)
            if vertex:   
                ax_node, = plt.plot(node.state[0], node.state[1], 'x', c='black', markersize=1.0)
                tmp.append(ax_node)
            collection_list.append(tmp)
            # plt.pause(2)   
    plt.savefig(fname+'.png')
    # plt.show()
    gif = anim.ArtistAnimation(fig, collection_list, interval=50)
    if save_gif:
        gif.save(fname+'.gif', writer = anim.PillowWriter(fps=4))
Exemplo n.º 2
0
def animate_frames(frames,
                   jupyter=True,
                   save_gif=False,
                   path='./tmp_results/animation.gif'):
    """ Animate frames from array (with ipython HTML extension for jupyter) and optionally save as gif.

    @param frames: list of frames
    @param jupyter: (bool), for using jupyter notebook extension to display animation
    @param save_gif: (bool), indicator if frames should be saved as gif
    @param path: path to save gif to
    """
    fig, ax = plt.subplots(figsize=(12, 10))
    plt.axis('off')
    cmap = None if len(frames[0].shape) == 3 else 'Greys'
    patch = plt.imshow(frames[0], cmap=cmap)

    anim = animation.FuncAnimation(plt.gcf(),
                                   lambda x: patch.set_data(frames[x]),
                                   frames=len(frames),
                                   interval=30)

    if save_gif:
        writer = animation.PillowWriter(fps=25)
        anim.save(path, writer=writer)

    if jupyter:
        display(HTML(anim.to_jshtml()))  # ipython extension
    else:
        plt.show()
    plt.close()
Exemplo n.º 3
0
    def scatter3d_module(x,
                         y,
                         z,
                         cs,
                         tag,
                         title=None,
                         vtx=None,
                         sym_z=True,
                         colorsMap='jet',
                         savegif=False):
        cm = plt.get_cmap(colorsMap)
        cNorm = matplotlib.colors.Normalize(vmin=min(cs), vmax=max(cs))
        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')

        ax.scatter(
            x[1:-1],
            y[1:-1],
            z[1:-1],
            s=1,
            c=scalarMap.to_rgba(cs)[1:-1],
        )

        start = np.rint(np.array([x[0], y[0], z[0]]) * 2) / 2
        end = np.rint(np.array([x[-1], y[-1], z[-1]]) * 2) / 2

        # if vtx is None:
        #     ax.text(x[0], y[0], z[0], f'Start: {tuple(start)}', size=10, zorder=1, color='k')
        #     ax.text(x[-1], y[-1], z[-1], f'End: {tuple(end)}', size=10, zorder=1, color='k')
        #     ax.scatter(x[0], y[0], z[0], s=3, c='red',)
        #     ax.scatter(x[-1], y[-1], z[-1], s=3, c='red',)
        # else:
        #     ax.text(vtx[0], vtx[1], vtx[2], f'Vertex: {tuple(vtx.astype(int))}', size=10, zorder=1, color='k')
        #     ax.scatter(x[0], y[0], z[0], s=3, c='red',)

        ax.set_xlim(x_range[0], x_range[1])
        ax.set_ylim(y_range[0], y_range[1])
        ax.set_zlim(z_range[0], z_range[1])

        ax.set_xlabel('X[cm]')
        ax.set_ylabel('Y[cm]')
        ax.set_zlabel('Z[cm]')
        if title:
            ax.set_title(title)
        scalarMap.set_array(cs)

        if not savegif:
            plt.savefig(EVENT_WRITE_DIR + f"event{tag}.png")
            plt.close()
            return

        def animate(frame):
            ax.view_init(30, frame / 4)
            return fig

        anim = animation.FuncAnimation(fig, animate, frames=200, interval=50)
        anim.save(EVENT_WRITE_DIR + f"event{tag}.gif",
                  writer=animation.PillowWriter(fps=10))
        plt.close()
Exemplo n.º 4
0
def gif2Animation(gifPath, label="none"):
    #pdb.set_trace()
    # *png path
    gifs = glob.glob(gifPath)

    fig = plt.figure()

    # animationの体裁を整える
    ax = plt.subplot()
    ax.spines['right'].set_color('None')
    ax.spines['left'].set_color('None')
    ax.spines['top'].set_color('None')
    ax.spines['bottom'].set_color('None')
    ax.tick_params(axis='x',
                   which='both',
                   top='off',
                   bottom='off',
                   labelbottom='off')
    ax.tick_params(axis='y',
                   which='both',
                   left='off',
                   right='off',
                   labelleft='off')

    imgs = []
    for gif in gifs:
        img = Image.open(gif)
        imgs.append([plt.imshow(img)])

    # making animation
    myAnima = animation.ArtistAnimation(fig, imgs, repeat_delay=10000)
    #plt.show()
    pw = animation.PillowWriter(fps=20)
    myAnima.save(os.path.join(imgPath, "animaPF", f"{label}.gif"), writer=pw)
Exemplo n.º 5
0
def plotCcgPerf_anim(byCCG, map_df, timeperiod, column='quantity'):
    fig, ax = plt.subplots(1, figsize=(10, 10))

    def plotMap(i):
        n = 0
        while n < 5:
            ax.clear()
            ax.axis('off')
            map_df[column] = map_df['ccgid'].map(lambda x: byCCG[x][i])
            ax.set_title(str("CCG " + column + ' ' + timeperiod[i]))
            map_df.plot(column=column,
                        cmap='Blues',
                        scheme='QUANTILES',
                        k=5,
                        linewidth=0.5,
                        ax=ax,
                        edgecolor='0.1',
                        legend=True)
            n += 1

    animator = ani.FuncAnimation(fig,
                                 plotMap,
                                 frames=len(timeperiod) * 5,
                                 repeat=False)

    writergif = ani.PillowWriter(fps=5)
    save_path = '2 geographical variation/'
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    filename = os.path.join(save_path, str(column + '.gif'))
    animator.save(filename, writer=writergif)
Exemplo n.º 6
0
def tsne_3d(tsne_data, mpath, df):
    fig = plt.figure(figsize=(10, 10))
    ax = Axes3D(fig)
    colors = 'g', 'r'
    labels = '1', '0'

    for i, mcolor, mlabel in zip(range(len(labels)), colors, labels):
        ax.scatter(tsne_data[df[df.columns[-1]] == i, 0],
                   tsne_data[df[df.columns[-1]] == i, 1],
                   tsne_data[df[df.columns[-1]] == i, 2],
                   s=30,
                   c=mcolor,
                   label=mlabel,
                   alpha=0.5)
    fig.legend()

    def rotate(angle):
        ax.view_init(azim=angle)

    angle = 1
    ani = animation.FuncAnimation(fig,
                                  rotate,
                                  frames=np.arange(0, 360, angle),
                                  interval=100)
    ani.save(mpath, writer=animation.PillowWriter(fps=20))
Exemplo n.º 7
0
    def Animation(self, filename):
        x, y, z = self.Vr[0], self.Vr[1], self.Vr[2]
        plt.close('All')
        fig, ax = plt.figure(1), plt.axes(xlim=(0, 40), ylim=(-20, 10))
        plt.grid(linestyle='-')
        plt.xlabel('x')
        plt.ylabel('z')

        [line] = ax.plot([], [], 'ro', lw=30 * self.R)

        def init():
            line.set_data([], [])
            return ([line])

        def animate(i):
            line.set_data([x[i - 1]], [y[i - 1]])  #(x[:i], y[:i])
            return ([line])

        animation = anim.FuncAnimation(fig,
                                       animate,
                                       init_func=init,
                                       frames=len(x) + 1,
                                       interval=1000,
                                       blit=True)
        animation.save(filename, writer=anim.PillowWriter(fps=10))
Exemplo n.º 8
0
def saveDataAnimation(data):
    fig = plt.figure()
    data_size = len(data[0])
    ax = plt.axes(xlim=(0, data_size),
                  ylim=(torch.min(data[1]) * 1.5, torch.max(data[1]) * 1.5))
    scatter_plot = ax.scatter([], [], s=1)

    def init():
        print('Saving gifs')
        scatter_plot.set_offsets([])
        return scatter_plot,

    def animate(i):
        x = np.arange(data_size)
        y = data[i].numpy()
        offsets = np.stack((x, y)).T
        scatter_plot.set_offsets(offsets)
        if (i % 64 == 0):
            print('{}%'.format(round(100 * i / len(data))))
        return scatter_plot,

    anim = animation.FuncAnimation(fig,
                                   animate,
                                   init_func=init,
                                   frames=len(data),
                                   interval=20,
                                   blit=False)
    writergif = animation.PillowWriter(fps=60)
    anim.save('weights.gif', writer=writergif)
    plt.close(fig)
def display_frames_as_gif(frames, episode):
    try:
        pylab.figure(figsize=(frames[0].shape[1] / 72.0,
                              frames[0].shape[0] / 72.0),
                     dpi=72)
        patch = pylab.imshow(frames[0])
        pylab.axis('off')
        pylab.subplots_adjust(left=0, right=1, top=1, bottom=0)

        def animate(i):
            patch.set_data(frames[i])

        anim = animation.FuncAnimation(pylab.gcf(),
                                       animate,
                                       frames=len(frames),
                                       interval=33)
        anim.save(str(episode) + '_gameplay.gif')
    except:
        pylab.figure(figsize=(frames[0].shape[1] / 72.0,
                              frames[0].shape[0] / 72.0),
                     dpi=72)
        patch = pylab.imshow(frames[0])
        pylab.axis('off')
        pylab.subplots_adjust(left=0, right=1, top=1, bottom=0)

        def animate(i):
            patch.set_data(frames[i])

        anim = animation.FuncAnimation(pylab.gcf(),
                                       animate,
                                       frames=len(frames),
                                       interval=33)
        anim.save(str(episode) + '_gameplay.gif',
                  writer=animation.PillowWriter(fps=40))
Exemplo n.º 10
0
    def _create_animation(self, i, outputarray):
        fig = plt.figure()
        ax = plt.axes(xlim=(np.nanmin(outputarray.real)-1, np.nanmax(outputarray.real)+1),
                      ylim=(np.nanmin(outputarray.imag)-1, np.nanmax(outputarray.imag)+1))
        # ax.plot(inputarray.real, inputarray.imag)
        function, = ax.plot([], [], lw=2)
        arrows = []

        def init():
            function.set_data([], [])
            for ii in range(i):
                arrows.append(Arrow(0, 0, 0, 0))
                ax.add_patch(arrows[ii])
            return function,

        def animate(n):
            function.set_data(outputarray.real[:n:2, -1], outputarray.imag[:n:2, -1])
            for ii in range(i):
                arrows[ii].remove()
            for ii in range(i):
                if ii == 0:
                    arrows[ii] = Arrow(0, 0, outputarray.real[n, 0], outputarray.imag[n, 1], color='k', lw=1)
                else:
                    arrows[ii] = Arrow(outputarray.real[n, ii-1], outputarray.imag[n, ii-1],
                                        outputarray.real[n, ii], outputarray.imag[n, ii], color='k', lw=1)
                ax.add_patch(arrows[ii])
            return function,

        anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(outputarray), blit=True,
                                       interval=100)
        gifwriter = animation.PillowWriter(fps=60)
        anim.save(self.save_path + os.sep + 'fourier_series.gif', writer=gifwriter)
        return
Exemplo n.º 11
0
    def plot_animal_attributes(self):
        """
        Plot animal attributes
        """

        #Create graph
        self.animal_fig, self.animal_ax = plt.subplots(figsize=(5, 5))

        #Set labels and axis for graph
        self.animal_ax.set_xlabel("Speed")
        self.animal_ax.set_ylabel("Range")
        self.animal_ax.set_xlim(-1, 11)
        self.animal_ax.set_ylim(-1, 11)

        x_data = []
        y_data = []
        sizes = []

        scatter = self.animal_ax.scatter(-2, -2, c="#ff0000")

        #Create (x, y) coordinates
        def create_coordinates(x, y):
            coordinates = []
            for n, x_coor in enumerate(x):
                coor = (x_coor, y[n])
                coordinates.append(coor)
            return coordinates

        #Create sizes for points
        def create_sizes(coordinates):
            sizes = []
            for point in coordinates:
                size = coordinates.count(point) * 80
                sizes.append(size)
            return sizes

        def animate(i):
            data = self.data[i]
            x_data = data["animals"]["speed"]
            y_data = data["animals"]["range"]
            plt.title(f"Cycle: {data['cycle']}      Population: {data['pop']}")
            points = create_coordinates(x_data, y_data)
            sizes = create_sizes(points)

            #Update the graph
            scatter.set_offsets(points)
            scatter.set_sizes(sizes)
            return scatter,

        line_animation = animation.FuncAnimation(self.animal_fig,
                                                 animate,
                                                 frames=np.arange(
                                                     0, len(self.data), 1),
                                                 interval=0.05 * 1000,
                                                 blit=True,
                                                 save_count=len(self.data))

        writergif = animation.PillowWriter(fps=5)
        line_animation.save('animals.gif', writer=writergif)
        plt.close(self.animal_fig)
Exemplo n.º 12
0
def scatter_plot_animation_new(time_ani, frequency_ani, parameters):

    cut_time = [_.flatten()[:110] / _.max() for _ in time_ani]
    cut_frequency = [_.flatten()[:110] / _.max() for _ in frequency_ani]

    writer = ani.PillowWriter()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel("Time domain cost")
    ax.set_ylabel("Frequency domain cost")
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    sctr, = ax.plot(cut_time[0], cut_frequency[0], '.b')

    def chart(i):
        # time_data = (time_ani[i]) / (time_ani[i].max()).flatten()
        # frequency_data = (frequency_ani[i] / frequency_ani[i].max()).flatten()
        sctr.set_data(cut_time[i], cut_frequency[i])
        ax.set_title(
            "Comparision of frequency and time domain costs $a = {:.3f}$".
            format(1 + (1 / 11) * i))

    animator = ani.FuncAnimation(fig, chart, frames=100, repeat=False)
    plt.show()
    animator.save("./GridAnalysisData/ScatterAnimationExperiment" +
                  parameters + ".gif",
                  writer=writer)
    plt.close(fig)
Exemplo n.º 13
0
	def animate_evolution(self):

		try:
			no_snaps = len([name for name in os.listdir(snap_dir) if os.path.isfile(os.path.join(snap_dir, name))])

			plt.clf()

			fig = plt.figure(figsize = (30,30))

			images = []

			print('Recomposing animation ({} snapshots found)'.format(no_snaps), flush = True)
			
			files = glob.glob(snap_dir + '/*')
			for file in files:
				im = plt.imread(file)
				images.append([plt.imshow(im)])

			ani = animation.ArtistAnimation(fig, images, interval=100, repeat_delay=0)
			plt.axis('off')

			writergif = animation.PillowWriter(fps=5) 
			ani.save(gif_file, writer = writergif)
			
			#plt.show()
		except:
			pass
Exemplo n.º 14
0
def main():
    U, F = load_problem(DEFAULT_FILE)
    N = U.shape[0]
    cycle = PoissonCycle(F, 1, 0, 1, 0)
    ims = []
    fig = plt.figure()
    ax = fig.gca(projection="3d")
    x = np.linspace(0, 1, 1024)
    X, Y = np.meshgrid(x, x)
    for i in range(100):
        #im = plt.imshow(U, cmap='RdBu_r', interpolation='nearest')
        im = ax.plot_surface(
            X[1: -1, 1: -1],
            Y[1: -1, 1: -1],
            U[1: -1, 1: -1],
            alpha=0.7, cmap='magma')
        t = ax.annotate(i, (0.1, 0.1), xycoords='figure fraction')
        norm = cycle.norm(U)
        n = ax.annotate(norm, (0.7, 0.1), xycoords='figure fraction')
        ims.append([im, t, n])

        if norm <= 1e-6 * N * N:
            break
        U = cycle(U)

    fig.colorbar(ims[0][0], shrink=0.5, aspect=10, pad=0.1)
    ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat=True)
    writer = animation.PillowWriter(fps=2)
    ani.save('../graphs/wave.gif', writer=writer)
def save_animation_as_gif_image(write_animation, animation_name):
    """
    use animation.writers.list() to list writer current machine supported
    """

    write_animation.save(''.join((animation_name, '.gif')),
                         writer=animation.PillowWriter(fps=40))
Exemplo n.º 16
0
def animateSolution(x, time, sol_list, gif_name='pipe_flow_simulation'):
    fig = plt.figure()
    ax = plt.axes(xlim=(x[0], x[-1]),
                  ylim=(np.min(sol_list), np.max(sol_list)))
    #ax = plt.axes(xlim=(x[0], x[-1]), ylim=(-1,1))

    #ax = plt.axes(xlim=(x[0], x[-1]), ylim=(np.min(sol_list),1003))

    plt.grid(True)
    line, = ax.plot([], [], lw=2)

    # initialization function: plot the background of each frame
    def init():
        line.set_data([], [])
        return line,

    def animate(i):
        plt.title(str(time[i]))
        y = sol_list[i]
        line.set_data(x, y)
        return line,

    writergif = animation.PillowWriter(fps=5)

    anim = animation.FuncAnimation(fig,
                                   animate,
                                   init_func=init,
                                   frames=len(sol_list),
                                   interval=20,
                                   blit=True)

    # save the animation as mp4 video file
    anim.save(gif_name + '.gif', writer=writergif)
Exemplo n.º 17
0
def draw_path(robot_env, start, goal, path, fname='rrt_path'):
    """Draw the planned path.
    Args:
        robot_env (rl_planner.env.base_env.BaseEnv): the robot gym env
        start (numpy.ndarray)
        goal (numpy.ndarray)
        path (list): the planned path
        fname (str)
    """
    fig, ax = plt.subplots(figsize=(6,6))
    plt.axis([-22,22,-22,22])
    plt.xticks([])
    plt.yticks([])
    collection_list = [] # each entry is a collection
    tmp = plot_problem_definition(ax, robot_env.obs_list, robot_env.rigid_robot, start, goal)
    array_path = np.array([state[:2] for state in path])
    plt.plot(array_path[:,0], array_path[:,1], c='k', linewidth=1.0)
    collection_list.append(tmp)

    for state in path:
        tmp_ = tmp.copy()
        robot_marker = plot_robot(ax, robot_env.rigid_robot, state[:3])
        tmp_ += robot_marker
        collection_list.append(tmp_)
    gif = anim.ArtistAnimation(fig, collection_list, interval=200)
    gif.save(fname+'.gif', writer = anim.PillowWriter(fps=5))
Exemplo n.º 18
0
    def animate_sim(self, path, exited_maze, T):
        " Animate a game and save as a GIF"
        pathx = [path[i][0] for i in range(len(path))]
        pathy = [path[i][1] for i in range(len(path))]
        mino_pathx = [path[i][2] for i in range(len(path))]
        mino_pathy = [path[i][3] for i in range(len(path))]

        wall = [(6, 4)]
        for i in range(4):
            wall.append((i, 2))
        for i in range(3):
            wall.append((i + 1, 5))
            wall.append((2, 5 + i))
        for j in range(1, 7):
            wall.append((5, j))

        A = (0, 0)
        B = (6, 5)

        f = plt.figure(0)
        plt.scatter(*zip(*[(s[1], s[0]) for s in wall]),
                    1000,
                    c="r",
                    marker="x")
        plt.scatter(*A[::-1], c=0, cmap='winter', s=300, marker='o')
        plt.scatter(*B[::-1], c='palegreen', s=300, marker='D')
        plt.gca().invert_yaxis()

        scat = plt.scatter(x=[pathx[0], mino_pathx[0]],
                           y=[pathy[0], mino_pathy[0]],
                           c=['b', 'r'],
                           s=[100, 200],
                           zorder=100)

        def animationUpdate(t):
            '''anim update function'''
            plt.plot(mino_pathx[:t + 1],
                     mino_pathy[:t + 1],
                     c='r',
                     linewidth=3)
            plt.plot(pathx[:t + 1], pathy[:t + 1], c='b')
            x = [pathx[t], mino_pathx[t]]
            y = [pathy[t], mino_pathy[t]]
            scat.set_offsets(np.c_[x, y])
            #plt.title(f'seed = {seed}; t = {t}; Win = {not dead}')
            # plt.savefig(f'{seed}a{t}.png')
            return scat,

        anim = FuncAnimation(f,
                             animationUpdate,
                             frames=T + 1,
                             interval=100,
                             blit=False)

        writergif = animation.PillowWriter(fps=5)
        anim.save(f'p1_{self.seed}.gif', writer=writergif)
        plt.clf()
        print(f'Saved video as p1_{self.seed}.gif')
        self.seed += 1
Exemplo n.º 19
0
def exportFig(fig, updateFunc, frameNum, new_file_path):
    anim = FuncAnimation(fig, updateFunc,
                        frames=frameNum, interval=50, blit=True)

    fig.set_size_inches(16, 9, True)
    anim.save(new_file_path, writer = animation.PillowWriter(fps = 30))

    return new_file_path 
Exemplo n.º 20
0
def animate_trajectory(traj_file, action="play", filename=""):
    def animation_init():  # only required for blitting to give a clean slate.
        line.set_ydata([np.nan] * len(x))
        return line,

    def animate(i):
        if i < len(raw_points.x):
            if raw_points.pressure[i] != 0:
                xdata.append(raw_points.x[i])
                ydata.append(raw_points.y[i])
                line.set_data(xdata, ydata)
        return line,

    fields = ['x', 'y', 'pressure', 'time']
    try:
        raw_points = pd.read_csv(traj_file, usecols=fields)
    except (IOError, FileNotFoundError):
        QMessageBox().critical(
            None, "Warning! file access error",
            "WriTracker couldn't load the trajectory file.", QMessageBox.Ok)
        return False
    fig, ax = plt.subplots()
    xmargin = 100
    ymargin = 100
    maxx = raw_points.x.max() + xmargin
    minx = raw_points.x.min() - xmargin
    maxy = raw_points.y.max() + ymargin
    miny = raw_points.y.min() - ymargin
    x = np.arange(0, max(maxx, maxy), 1)
    y = np.arange(0, max(maxx, maxy), 1)
    line, = ax.plot(x, y, 'o', markersize=1)
    ax.set(xlim=(minx, maxx), ylim=(max(0, miny), maxy))
    xdata, ydata = [], []

    if action == "play":
        # When using plt.show, 'interval' controls the speed of the animation
        anim = animation.FuncAnimation(fig,
                                       animate,
                                       init_func=animation_init,
                                       interval=10,
                                       blit=True)
        plt.show()  # to display "live" the animation
        return anim  # required when calling from inside a function
    elif action == "save":
        print("WriTracker Plotter: Saving GIF, please wait")
        f = filename + ".gif"
        # save_count > 1000 might cause memory error.
        ani = animation.FuncAnimation(fig,
                                      animate,
                                      init_func=animation_init,
                                      blit=True,
                                      save_count=1000)
        writergif = animation.PillowWriter(
            fps=40
        )  # fps > 60  | fps < 15 caused very very slow output. 30-40 fits.
        ani.save(f, writer=writergif)
Exemplo n.º 21
0
def export_frames_as_gif(frames, filename):
    patch = plt.imshow(frames[0])
    plt.axis('off')
    def animate(i):
        patch.set_data(frames[i])
        
    anim = animation.FuncAnimation(plt.gcf(), animate, frames = len(frames), interval=3)
    print('Saving gif...')
    #anim.save('images/{}.gif'.format(filename), fps=30)
    anim.save('images/{}.gif'.format(filename), writer=animation.PillowWriter(fps=30))
Exemplo n.º 22
0
def main():
    total_time = 20e-9
    n_frames = 250
    dx = 0.01
    grid = Grid1D(dx, 2.0)
    grid.set_material(1.0, 1.5, er=4.0, cond=0.0)
    # grid = create_shield(0.25e-3, 1.0, 11.6e8)
    print(grid)
    src_z = 0.1
    source = Gaussian(src_z, 'Gaussian', 1.0, 40 * grid.dt, 12 * grid.dt)
    # source = Sinusoid(src_z, 'Sine', 1.0, 200e6)
    # source = SinusoidalGauss(src_z, 'Sine-Gauss', 1e7, 1e9)
    grid.add_source(source)
    grid.add_probe(Probe(1.9, 'Transmitted'))
    grid.solve(total_time, n_frames)

    fig, axes = plt.subplots(2, 1, sharex=True)
    axes[0].plot(grid.x, grid.ez)
    axes[0].set_ylabel('Ez')
    axes[1].plot(grid.x, grid.hy)
    axes[1].set_ylabel('Hy')
    axes[1].set_xlabel('x (m)')

    fig2, ax2 = plt.subplots()
    ax2.set_ylim(-2, 2)
    eline, = ax2.plot(grid.x, grid.ez)
    ax2.set_ylabel('Ez')
    ax2.set_xlabel('x (m)')
    collection = collections.BrokenBarHCollection.span_where(
        grid.x,
        ymin=-2,
        ymax=2,
        where=grid.cb < 0.5,
        facecolor='red',
        alpha=0.5)
    ax2.add_collection(collection)
    ani = animation.FuncAnimation(fig2,
                                  animate,
                                  fargs=(eline, grid.data),
                                  interval=40,
                                  blit=True,
                                  frames=len(grid.data))

    f = r"fdtd_1d.gif"
    print('Saving', f, '...', end='')
    writergif = animation.PillowWriter(fps=25)
    ani.save(f, writer=writergif)
    print(' done.')
    source_data = source.solve(grid.t)
    plot_time_freq(source_data, grid.t, grid.dt, 'Source')
    for probe in grid.probes:
        plot_time_freq(probe.data, grid.t, grid.dt, probe.label)
    plot_response(source_data, probe.data, grid.t, grid.dt, 'Response')
    plt.show()
Exemplo n.º 23
0
def plot_trends_dynamically(name, countries=[]):
    fig, ax = plt.subplots(figsize=(17, 9))
    leg = ax.legend()

    df_x_full = threshold_data(per_million(df_prevalence),
                               'cases',
                               'weekly',
                               countries,
                               reset=False)
    df_y_full = threshold_data(per_million(df_incidence_weekly),
                               'cases',
                               'weekly',
                               countries,
                               reset=False)

    def animate(i):
        ax.clear()

        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.xaxis.set_major_formatter(
            ticker.FuncFormatter(lambda y, pos: ('{{:.{:1d}f}}'.format(
                int(np.maximum(-np.log10(y), 0)))).format(y)))
        ax.yaxis.set_major_formatter(
            ticker.FuncFormatter(lambda y, pos: ('{{:.{:1d}f}}'.format(
                int(np.maximum(-np.log10(y), 0)))).format(y)))
        ax.set_xlabel('Prevalence (Cases per Million)')
        ax.set_ylabel('Incidence (New cases per million)')

        i += 1
        for country in countries:
            x = df_x_full.iloc[:i][country]
            y = df_y_full.iloc[:i][country]

            line, = ax.plot(x, y, '-o', markevery=[-1], label=country)
            plt.annotate(country, (x[-1], y[-1]),
                         textcoords="offset points",
                         xytext=(5, 10),
                         ha='right',
                         color=line.get_color())

        if i > len(df_x_full) - 1:
            i = len(df_x_full) - 1

        ax.annotate(df_x_full.index[i].date(),
                    xy=(0.85, 0.05),
                    xycoords='axes fraction',
                    fontsize=15)
        ax.legend(loc="upper left", frameon=False)
        ax.set_title('Trends (steps per week)')

    anim = animation.FuncAnimation(fig, animate, frames=20)
    anim.save('dynamic-trends/' + name + '.gif',
              writer=animation.PillowWriter(fps=2))
Exemplo n.º 24
0
    def animate(self):
        plt.axis('off')
        plt.tight_layout(pad=0)

        im_ani = animation.FuncAnimation(self.fig,
                                         self.update,
                                         frames=self.i_number,
                                         interval=200,
                                         repeat_delay=1000,
                                         blit=True)
        writer_gif = animation.PillowWriter(fps=3)
        im_ani.save('./assets/game-of-life.gif', writer=writer_gif)
Exemplo n.º 25
0
 def animate(self, f):
     anim = animation.FuncAnimation(self.fig,
                                    self._update,
                                    frames=self.number_of_steps,
                                    interval=1,
                                    blit=True)
     # If the keyword argument for show animation is true, show the plot
     if self.show_anim:
         plt.show()
     if self.save:
         writergif = animation.PillowWriter(fps=200)
         anim.save(f, writer=writergif)
Exemplo n.º 26
0
def save(animation, name, fps, ext=".gif"):
    """
    Save animation as either a .gif or .mp4 file.

    :param animation: matplotlib.animation.FuncAnimation object.
    :param name: name of the saved file.
    :param fps: frames per second.
    :param ext: extension of the saved file, either .gif or .mp4.
    """
    writer = anim.PillowWriter(fps) if ext == ".gif" else anim.FFMpegWriter(
        fps)
    animation.save("images/" + name + ext, writer)
Exemplo n.º 27
0
 def run(self, movie=False):
     ani = animation.FuncAnimation(self.fig,
                                   self.animate,
                                   frames=269,
                                   blit=True,
                                   init_func=self.initAnimate,
                                   repeat=False)
     if movie:
         pwriter = animation.PillowWriter(
             fps=60, metadata=dict(artist='Dr. Ryan Clement'))
         ani.save('../movies/pentagon_zombie_apocalypse.gif',
                  writer=pwriter)
def main(unused_argv):

    if not FLAGS.rollout_path:
        raise ValueError("A `rollout_path` must be passed.")
    with open(FLAGS.rollout_path, "rb") as file:
        rollout_data = pickle.load(file)
    writer = animation.PillowWriter(fps=30)

    fig, axes = plt.subplots(1, 2, figsize=(10, 5))

    plot_info = []
    for ax_i, (label, rollout_field) in enumerate([
        ("Ground truth", "ground_truth_rollout"),
        ("Prediction", "predicted_rollout")
    ]):
        # Append the initial positions to get the full trajectory.
        trajectory = np.concatenate(
            [rollout_data["initial_positions"], rollout_data[rollout_field]],
            axis=0)
        ax = axes[ax_i]
        ax.set_title(label)
        bounds = rollout_data["metadata"]["bounds"]
        ax.set_xlim(bounds[0][0] - 0.2, bounds[0][1] + 0.2)
        ax.set_ylim(bounds[1][0] - 0.2, bounds[1][1] + 0.2)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_aspect(1.)
        points = {
            particle_type: ax.plot([], [], "o", ms=2, color=color)[0]
            for particle_type, color in TYPE_TO_COLOR.items()
        }
        plot_info.append((ax, trajectory, points))

    num_steps = trajectory.shape[0]

    def update(step_i):
        outputs = []
        for _, trajectory, points in plot_info:
            for particle_type, line in points.items():
                mask = rollout_data["particle_types"] == particle_type
                line.set_data(trajectory[step_i, mask, 0], trajectory[step_i,
                                                                      mask, 1])
                outputs.append(line)
        return outputs

    unused_animation = animation.FuncAnimation(fig,
                                               update,
                                               frames=np.arange(
                                                   0, num_steps,
                                                   FLAGS.step_stride),
                                               interval=10)
    unused_animation.save("animation10000.gif", writer=writer)
Exemplo n.º 29
0
def saveSifGif(sif, ylo=0, yhi=10000, xlo=0, xhi=10000, **options):
    """Convert kinetic series to animated gif

    Saves files to <siffilebase>.gif
    The color range is scaled from min to max of the complete series. Other
    options will hopefully be implemented soon.

    Parameters:
        ylo/yhi: lower/higher row index
        xlo/xhi: lower/higher coloumn index
    Known keyword arguments:
        path: directory wherer to write images, default sif location
        fname: filename base to use <fname>_iii.png, default sif name
        figsize: tuple (w,h) for plt.set_size_inches(), default (4,4)
        norm: default is max in series; other options to be added
        extent: To be implemented, (xmin,xmax,ymin,ymax) axis limits, default px indices
        aspect: To be implemented, axis aspect ratio, default "auto" (->square image)
        transpose: (boolean) flip axis, default False
        reversex/reverssey: to be implemented
        reversex/reverssey: (boolean) invert data in x/y, default False
            -> Axis labelling is not inverted! (to be implemented)
        --- Further options kw-args are passed on to plt.imshow ---
    """

    try:
        fname = options.pop("fname", os.path.basename(sif.path)[:-3] + "gif")
        path = options.pop("path", os.path.dirname(sif.path))
        sifdata = sif.data
        if options.pop("transpose", False):
            sifdata = sif.data.transpose([0, 2, 1])
        yhi = np.min([yhi, sifdata.shape[-2]])
        xhi = np.min([xhi, sifdata.shape[-1]])
        sifdata = sifdata[:, ylo:yhi, xlo:xhi]
        extent = options.pop(
            "extent", (xlo, xhi, ylo, yhi))  # TODO: invert for reversexy
        if options.pop("reversex", False):
            sifdata = sifdata[:, :, ::-1]
        if options.pop("reversey", False):
            sifdata = sifdata[:, ::-1, :]
        outpath = os.path.join(path, fname)
        if not outpath.endswith(".gif"):
            outpath += ".gif"
        fig = plt.figure()
        mx = np.max(sifdata)
        mn = np.min(sifdata)
        arts = [[
            plt.imshow(sifdata[i, :, :], vmin=mn, vmax=mx, extent=extent)
        ] for i in range(sif.kineticlength)]
        anima = anim.ArtistAnimation(fig, arts)
        anima.save(outpath, writer=anim.PillowWriter())
    except:  # TODO
        raise ()  # TODO
Exemplo n.º 30
0
def display_frames_as_gif(frames, filename='animation.gif'):
    plt.figure(figsize=(frames[0].shape[1] / 72, frames[0].shape[0] / 72),
               dpi=72)
    patch = plt.imshow(frames[0])
    plt.axis('off')

    anim = animation.FuncAnimation(plt.gcf(),
                                   lambda x: patch.set_data(frames[x]),
                                   frames=len(frames),
                                   interval=50)

    writer = animation.PillowWriter(fps=30)
    anim.save(filename, writer=writer)