Exemple #1
0
def pred_animation(y_test, y_pred, is_save=False):
    fig = plt.figure(figsize=(15, 10))
    ims = []
    plt.imshow(room_image, extent=(0, 7.8, 0, 8.8))
    # Plot antenna position
    plt.scatter(7.25, 1.5, color='green', marker=7, s=500)
    plt.scatter(7.2, 7.1, color='green', marker=7, s=500)
    for m in range(3):
        plt.scatter(0.6, 2.763 - m * 0.063, color='cyan', marker=7, s=500)
    # Plot true position and predicted position (Animation)
    for i in range(len(y_test)):
        im_test = [
            plt.scatter(y_test[i, 0],
                        y_test[i, 1],
                        color='black',
                        marker='X',
                        s=1200)
        ]
        im_pred = [
            plt.scatter(y_pred[i, 0],
                        y_pred[i, 1],
                        color='blue',
                        s=1200,
                        alpha=0.7)
        ]
        ims.append(im_test + im_pred)
    plt.xlim(0, 7.8)
    plt.ylim(0, 8.8)
    ani = ArtistAnimation(fig, ims, interval=500)
    if is_save:
        ani.save(os.path.join(FIGURE_SAVE_PATH, 'pred_anim.mp4'),
                 writer="ffmpeg")
    plt.show()
def animate(theta1s, AB, AD, BC, CD, variation=0):

    rA, rD = 0, AD
    fig, ax = plt.subplots()
    container = []

    for theta1 in theta1s:
        rB, rC = pos(theta1, AB, AD, BC, CD)[variation]
        link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-')
        link2, = ax.plot(np.real([rB, rC]), np.imag([rB, rC]), 'go-')
        link3, = ax.plot(np.real([rD, rC]), np.imag([rD, rC]), 'bo-')
        A = ax.text(np.real(rA), np.imag(rA) + .01, r'$A$')
        B = ax.text(np.real(rB), np.imag(rB) + .01, r'$B$')
        C = ax.text(np.real(rC), np.imag(rC) + .01, r'$C$')
        D = ax.text(np.real(rD), np.imag(rD) + .01, r'$D$')
        container.append([link1, link2, link3, A, B, C, D])

    from matplotlib.animation import ArtistAnimation

    ani = ArtistAnimation(fig, container, interval=20, blit=True)
    ax.set_ylim(ymax=CD + .05)
    ax.grid()
    ax.set_aspect('equal')
    ani.save('mechanism_1_{0:d}.mp4'.format(variation),
             fps=60,
             bitrate=5000,
             dpi=400)
Exemple #3
0
def plot_paths(layout, paths):
    images = []

    cmap = colors.ListedColormap(['white', 'black', 'red', 'green', 'blue'])

    lengths = [len(path) for path in paths]
    lengths.sort()
    longest_path = lengths[-1]

    fig = plt.figure()

    for i in range(longest_path):

        steps = []
        for path in paths:
            if path.get(i) != None:
                steps.append(path.get(i))

        # print(steps)
        layout_arr = transform_array_to_int(layout, steps)

        img = plt.pcolor(layout_arr[::-1],
                         cmap=cmap,
                         edgecolors='k',
                         linewidths=1)
        images.append([img])
        if i == 0:
            plt.savefig('pics/start.png')

    images.insert(0, images[1])
    images.append(images[-1])

    animation = ArtistAnimation(fig, images, interval=250)
    print('Animation steps:', len(images))
    animation.save('video/anim.mp4', dpi=800)
def animate(case):

    from matplotlib.animation import ArtistAnimation

    phi1s = np.linspace(0, 2 * np.pi, 300)
    fig, ax = plt.subplots()
    rA, container = 0, []

    for phi in phi1s:
        rB, rC, rD, rE, rF = pos(phi, case)

        link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-')
        link2, = ax.plot(np.real([rB, rC]), np.imag([rB, rC]), 'go-')
        link3, = ax.plot(np.real([rC, rE]), np.imag([rC, rE]), 'bo-')
        link4, = ax.plot(np.real([rE, rF]), np.imag([rE, rF]), 'ko-')
        ax.plot(np.real(rD), np.imag(rD), 'bo-')
        ax.plot(np.real(rF), np.imag(rF), 'b,-')

        A = ax.text(np.real(rA), np.imag(rA) + .002, r'$A$')
        B = ax.text(np.real(rB), np.imag(rB) + .002, r'$B$')
        C = ax.text(np.real(rC), np.imag(rC) + .002, r'$C$')
        D = ax.text(np.real(rD), np.imag(rD) + .002, r'$D$')
        E = ax.text(np.real(rE), np.imag(rE) + .002, r'$E$')
        F = ax.text(np.real(rF), np.imag(rF) + .002, r'$F$')

        container.append([link1, link2, link3, link4, A, B, C, D, E, F])

    ani = ArtistAnimation(fig, container, interval=20, blit=True)
    ax.set_aspect('equal')
    ax.set_ylim(ymax=case[1] + .02)
    ax.grid()
    plt.show()

    ani.save('mechanism_3.mp4', fps=60, bitrate=5000, dpi=400)
def animate(phi1s, variation=0, fps=60, AB=1, BC=1):
    """
    Animate movement of the mechanism
    """

    rA = 0
    fig, ax = plt.subplots()
    container = []

    for phi in phi1s:
        rB, rC, rBC = pos(phi, AB, BC)[variation]
        link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-')
        link2, = ax.plot(np.real([rB, rC]), np.imag([rB, rC]), 'go-')
        A = ax.text(np.real(rA), np.imag(rA) + .07, 'A')
        B = ax.text(np.real(rB), np.imag(rB) + .07, 'B')
        C = ax.text(np.real(rC), np.imag(rC) + .07, 'C')
        container.append([link1, link2, A, B, C])

        ax.plot(np.real(rC), np.imag(rC), 'b,-')

    from matplotlib.animation import ArtistAnimation
    ani = ArtistAnimation(fig, container, interval=fps, blit=True)
    ax.grid()
    ax.set_aspect('equal')
    ani.save('R_RRT.mp4', fps=60, bitrate=5000, dpi=400)
Exemple #6
0
def animate(case):
    
    from matplotlib.animation import ArtistAnimation
    
    theta1s = np.linspace(0, 2*np.pi, 300)
    fig, ax = plt.subplots()
    rA, container = 0, []
    
    for theta1 in theta1s:
        rB, rC, rD, rE, rD2 = pos(theta1, case)
        
        link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-')
        link31, = ax.plot(np.real([rC, rD]), np.imag([rC, rD]), 'go-')
        link32, = ax.plot(np.real([rC, rD2]), np.imag([rC, rD2]), 'g-')
        
        link4, = ax.plot(np.real([rD, rE]), np.imag([rD, rE]), 'bo-')
        ax.plot(np.real(rE), np.imag(rE), 'b,-')
        
        A = ax.text(np.real(rA), np.imag(rA)+.02, r'$A$')
        B = ax.text(np.real(rB), np.imag(rB)+.02, r'$B$')
        C = ax.text(np.real(rC), np.imag(rC)+.02, r'$C$')
        D1 = ax.text(np.real(rD), np.imag(rD)+.02, r'$D_1$')
        D2 = ax.text(np.real(rD2), np.imag(rD2)+.02, r'$D_2$')
        E = ax.text(np.real(rE), np.imag(rE)+.02, r'$E$')
        
        container.append([link1, link31, link32, link4, A, B, D2, C, D1, E])
    link3, = ax.plot(np.real(rC), np.imag(rC), 'ro')
    ani = ArtistAnimation(fig, container, interval=20, blit=True)
    ax.set_aspect('equal')
    ax.grid()
    plt.show()
    ani.save('mechanism_9.mp4', fps=60, bitrate=5000, dpi=400)
Exemple #7
0
    def animate_vibration_mode_stress(self, k, alpha=1, l=1, show=None, savename=None, 
                                      playtime=5, fps=60, repeat_delay=0, title=None):
        if k > self.num_eigenpairs - 1:
            raise ValueError(f"Too high an eigen-number. Have only solved for {self.num_eigenpairs} eigenpairs.")

        displacement_vec = self.retrieve_vibration_eigenvector(k)

        N_frames = int(playtime * fps)
        ts = np.linspace(0, 2*np.pi, N_frames)

        max_stretch = self.find_max_stress(displacement=displacement_vec*alpha)

        # Set a bigger font size for text:
        plt.rcParams.update({'font.size': 20})
        norm = mpl.colors.Normalize(vmin=-max_stretch, vmax=max_stretch)

        fig, ax = plt.subplots(figsize=(1.5*16,1.5*9))
        
        plt.subplots_adjust(left=0.05, bottom=0.05, right=0.99, top=0.94)
        ax.set_xlabel("x [m]")
        ax.set_ylabel("y [m]")

        if title is None:
            fig.suptitle(f"Vibration mode {k} for {self.area} with {len(self.triang)} Elements")
        elif type(title) is str:
            fig.suptitle(title)
        else:
            pass

        artists = [self.display_mesh_stress(displacement=alpha*np.sin(l*t)*displacement_vec,
                    norm=norm, show=False, ax=ax).findobj() for t in ts]

        ani = ArtistAnimation(fig, artists, interval=1000//fps, repeat_delay=repeat_delay, repeat=True, blit=True)
        cbar = fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=None), ax=ax)
        cbar.ax.get_yaxis().labelpad = 50
        cbar.set_label(r"Mean Total Stress $\sigma$ [Pa]", rotation=270, fontsize=24)

        if savename is not None:
            ani.save(f"root/project_2/animations/{savename}.mp4")

        if show is None:
            if savename is None:
                show = True
            else:
                show = False
        
        if show:
            plt.show()
            return 
        
        # Clean up memory
        fig.clear()
        plt.close(fig)
        del fig, ax, artists, ani, norm, cbar
        import gc
        gc.collect()

        return
def pred_evolution_gif(fig,
                       frames_list,
                       interval=300,
                       save_dir='',
                       save=True,
                       no_margins=True,
                       show=False):

    print("\n\n\n\n=================")
    print("checking for ffmpeg...")
    if not os.path.isfile('./../../../opt/conda/bin/ffmpeg'):
        print("please 'pip install ffmpeg' to create gif")
        print("gif not created")

    else:
        print("ffmpeg found")
        print("creating the gif ...\n")
        gif = ArtistAnimation(fig, frames_list, interval,
                              repeat=True)  # create gif

        if save:
            if no_margins:
                plt.tight_layout()
                plt.gca().set_axis_off()
                plt.subplots_adjust(top=1,
                                    bottom=0,
                                    right=1,
                                    left=0,
                                    hspace=0,
                                    wspace=0)
                plt.margins(0, 0)
                plt.gca().xaxis.set_major_locator(plt.NullLocator())
                plt.gca().yaxis.set_major_locator(plt.NullLocator())

            if save_dir == '':
                time = datetime.now().strftime("%Y%m%d-%H%M%S")
                save_dir = 'results/gif' + time + '.gif'

            plt.rcParams[
                'animation.ffmpeg_path'] = r'//opt//conda//bin//ffmpeg'  # set directory of ffmpeg binary file
            Writer = animation.writers['ffmpeg']
            ffmwriter = Writer(fps=1000 // interval,
                               metadata=dict(artist='Me'),
                               bitrate=1800)  #set the save writer
            gif.save('results/temp_video.mp4', writer=ffmwriter)

            codeBASH = f"ffmpeg -i 'results/temp_video.mp4' -loop 0 {save_dir}"  #convert mp4 to gif
            os.system(codeBASH)
            os.remove("results/temp_video.mp4")

            plt.close('all')

        if show:
            plt.show()
            plt.close('all')

        print("\n\n=================")
        print('done\n\n')
    def save(self, filename, fps: float = 10):
        """
        Save Gif.

        Args:
            filename: Filename of the Gif
            fps: Frames per second
        """
        animation = ArtistAnimation(self.fig, self.images)
        animation.save(filename, writer="imagemagick", fps=fps)
Exemple #10
0
def gif_from_path(
    path=None,
    figsize=(10, 10),
    fps=0.5,
    interval=500,
    repeat_delay=1000,
    filename=None,
    dpi=400,
):
    """
    Create an animated gif from a director of image files.

    Parameters
    ----------
    path :str, required
        path to directory of images
    figsize : tuple, optional
        output figure size passed to matplotlib.pyplot
    fps : float, optional
        frames per second
    interval : int, optional
        interval between frames in miliseconds, default 500
    repeat_delay : int, optional
        time before animation repeats in miliseconds, default 1000
    filename : str, required
        output file name
    dpi : int, optional
        image dpi passed to matplotlib writer
    """
    assert filename, "You must provide an output filename ending in .gif"
    imgs = os.listdir(path)
    imgs.sort(key=lambda var: [
        int(x) if x.isdigit() else x
        for x in re.findall(r"[^0-9]|[0-9]+", var)
    ])

    fig, ax = plt.subplots(figsize=figsize)
    ax.axis("off")
    ims = []

    for i in imgs:
        c = plt.imread(str(PurePath(path, i)))
        im = plt.imshow(c, animated=True)
        ims.append([im])

    writer = PillowWriter(fps=fps)

    ani = ArtistAnimation(fig,
                          ims,
                          interval=interval,
                          blit=True,
                          repeat_delay=repeat_delay)

    plt.tight_layout()
    ani.save(filename, writer=writer, dpi=dpi)
Exemple #11
0
def save_gif(images, n=0, fname=None):
    """saves a series of images as a gif"""
    fig = plt.figure()
    plt.axis('off')
    ims = []
    for img in images:
        im = plt.imshow(img, animated=True, vmin=0., vmax=1.)
        ims.append([im])
    anim = ArtistAnimation(fig, ims, interval=100, repeat=False)
    fname = fname if fname is not None else 'figs/cav_transition/test{}.gif'.format(n)
    anim.save(fname)
 def __init__(self, plots, interval=200, repeat_delay=None,
              repeat=True, blit=False):
     figure, artists = self._draw_plots(plots)
     ArtistAnimation.__init__(
         self,
         figure,
         artists,
         interval=interval,
         repeat_delay=repeat_delay,
         repeat=repeat,
         blit=blit
     )
Exemple #13
0
    def show_animation(self) -> None:
        """Displays the animation in a pop-up. Optionally saves the animation."""
        use("TkAgg")
        fig = plt.figure()
        ims = self._generate_images()
        ani = ArtistAnimation(fig, ims, interval=50, blit=True)

        should_save = input('Do you want to save the animation? [Y/N]\n')
        if should_save == 'y' or should_save == 'Y':
            ani.save('julia_sets.mp4', writer="ffmpeg")

        plt.title(f'Animated Julia sets with c = {self.anim_constant}*e^(i*a)')
        plt.show()
def gen_visualisation():
    """
    Generates an .mp4 movies representing the restructuring
    of the initial graph based on output files from spring.cpp
    """
    fig = plt.figure()
    try:
        center = sys.argv[1]  # ensure test_file specified
    except IndexError:
        print('Usage: genvis.py test_file')
        sys.exit(1)
    nodes = 0
    frames = 0
    data = []
    images = []
    # load the initial graph as the first frame
    with open(center, 'r') as f:
        for i, l in enumerate(f):
            if i == 0:
                frames = int(l.strip('\n'))
            elif i == 1:
                nodes = int(l.strip('\n'))
            elif 1 < i <= nodes + 1:
                x, y = map(float, l.strip('\n').split(' '))
                data.append([x, y])
            elif i > nodes + 1:
                break

    scat = plt.scatter(*zip(*data), s=10)
    # add the frame to list
    images.append([scat])

    # loop over all other output files and generate frames
    for i in range(frames):
        data = []
        with open(str(i) + '.out', 'r') as f:
            for l in f:
                x, y = map(float, l.strip('\n').split(' '))
                data.append([x, y])
        scat = plt.scatter(*zip(*data), s=10)
        images.append([scat])

    # create animation
    line_anim = ArtistAnimation(fig, images, interval=50, blit=True)
    line_anim.save('graph_layout.mp4')
    # plt.show()

    # cleanup output files
    files = [f for f in os.listdir(".") if f.endswith(".out")]
    for f in files:
        os.remove(f)
Exemple #15
0
    def demo(self, performance, limit, defaultPause=0.1, interval=0.1):
        import matplotlib.pyplot as plt
        from matplotlib.animation import ArtistAnimation
        figure = plt.figure()
        artists = []
        timer = 0.0
        self.leds.clear()
        action = performance(self.leds)
        while timer < limit:
            try:
                pause = next(action)
            except StopIteration:
                break
            if pause is None:
                pause = defaultPause
            art = self.leds.plot(show=False)
            num = int((pause) / interval)
            if num == 0:
                continue
            artists += [[art]] * num
            timer += pause

        ani = ArtistAnimation(figure,
                              artists,
                              interval=interval * 1000,
                              repeat=False,
                              blit=True)  # noqa
        plt.show()
def animate(phi1s):
    
    from matplotlib.animation import ArtistAnimation
    
    fig, ax = plt.subplots()
    
    container = []
    for phi in phi1s:
        
        rB, rD, rF, rG = pos(phi)
        
        pinA, = ax.plot(rA[0], rA[1], 'bo')
        pinC, = ax.plot(rC[0], rC[1], 'bo')
        link1, = ax.plot([rA[0], rB[0]], [rA[1], rB[1]], 'ro-')
        link3, = ax.plot([rF[0], rD[0]], [rF[1], rD[1]], 'go-')
        link5, = ax.plot([rA[0], rG[0]], [rA[1], rG[1]], 'bo-')
        A = ax.text(rA[0]+.05, rA[1]+.05, 'A', fontsize=12)
        B = ax.text(rB[0]+.05, rB[1]+.05, 'B', fontsize=12)
        C = ax.text(rC[0]+.05, rC[1]+.05, 'C', fontsize=12)
        D = ax.text(rD[0]+.05, rD[1]+.05, 'D', fontsize=12)
        F = ax.text(rF[0]+.05, rF[1]+.05, 'F', fontsize=12)
        G = ax.text(rG[0]+.05, rG[1]+.05, 'G', fontsize=12)
        
        container.append([pinA, pinC, link1, link3, link5, A, B, C, D, F, G])

    ax.grid()
    ax.set_aspect('equal')
    ani = ArtistAnimation(fig, container, interval=20, blit=True)
Exemple #17
0
def show_anim(set_num, anim_num):
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import ArtistAnimation

    anims = _read_hdr()
    s = anims.sets[set_num]
    anim = s.animations[anim_num]

    images = [anims.render_pixelmap(frame) for frame in anim.frames]
    fps = anim.fps

    borders = np.array([[x, x + w, -y - h, -y] for frame in anim.frames
                        for x, y, w, h in [frame.origin + frame.shape]])
    extremes = ((borders[:, 0].min(), borders[:, 1].max()),
                (borders[:, 2].min(), borders[:, 3].max()))

    fig, ax = plt.subplots()
    artists = [[plt.imshow(image, animated=True, extent=borders[i])]
               for i, image in enumerate(images)]
    ani = ArtistAnimation(fig, artists, interval=1000.0 / fps, blit=True)
    ax.axis("off")
    ax.set_xlim(extremes[0])
    ax.set_ylim(extremes[1])
    plt.show()
Exemple #18
0
def animation(*args, **kwargs):
    """
    Artist animation wrapper to avoid another import
    
    """

    return ArtistAnimation(*args, **kwargs)
Exemple #19
0
 def animate(self, *args, **kwargs) -> ArtistAnimation:
     """Animate the snapshots taken.
     Uses matplotlib.animation.ArtistAnimation
     Returns
     -------
     ArtistAnimation
     """
     return ArtistAnimation(self._figure, self._photos, *args, **kwargs)
Exemple #20
0
def run_oned_linear_convection(method, nx, nt, x_min, x_max, dx, dt, c):
    # Generate figure for animation
    fig = pyplot.figure()
    ax = fig.add_subplot()

    frames = []
    # Generate initial data
    u = get_oned_data(InitialDataType.SQUARE, nx=nx, dx=dx)
    # Apply `method` for `nt` times
    # and save each frame to create an animation
    for i in range(nt):
        oned_linear_convection(u=u, nx=nx, dx=dx, dt=dt, c=c)
        frames.append(ax.plot(np.linspace(x_min, x_max, nx), u, "r"))
    # Now create the animation at 1 frame every 25 milliseconds
    animation = ArtistAnimation(fig, frames, repeat=False, interval=25)
    # And render to an mp4
    animation.save(f"{method.__name__}.mp4")
Exemple #21
0
def create_animation(df, img, include_backwards=True, fps=24, n_seconds=2, figsize=(8, 8), repeat=True):
    """Create animation from a displacement field.

    Parameters
    ----------
    df : DisplacementField
        Instance of the ``DisplacementField`` representing the coordinate transformation.

    img : np.ndarray
        Image.

    include_backwards : bool
        If True, then animation also played backwards after its played forwards.

    fps : int
        Frames per second.

    n_seconds : int
        Number of seconds to play the animation forwards.

    figsize : tuple
        Size of the figure.

    repeat : bool
        If True, then animation always replayed at the end.

    Returns
    -------
    ani : matplotlib.animation.ArtistAnimation
        Animation showing the transformation.

    Notes
    -----
    To enable animation viewing in a jupyter notebook write:
    ```
    from matplotlib import rc
    rc('animation', html='html5')
    ```

    """
    n_frames = int(n_seconds * fps)
    interval = (1 / fps) * 1000
    frames = []

    fig = plt.figure(figsize=figsize)
    plt.axis('off')

    for i in range(n_frames + 1):
        df_new = df * (i / n_frames)
        warped_img = df_new.warp(img)
        frames.append([plt.imshow(warped_img, cmap='gray')])

    if include_backwards:
        frames += frames[::-1]

    ani = ArtistAnimation(fig, frames, interval=interval, repeat=repeat)

    return ani
Exemple #22
0
    def sim_show(self):
        fig = plt.figure()
        artists = []
        for config in self.config_history:
            plot = plt.imshow(config)
            artists.append([plot])

        anima = ArtistAnimation(fig, artists, interval=200, repeat=False)
        plt.show(anima)
    def create_animation(self):
        """
        Upper function. Calls other functions and creates the animation object
        :return: None
        """
        self.init_subplots()

        self.ln = []
        self.ln.extend(self.draw_network())
        self.ln.extend(self.plot_node_ids())
        self.ln.extend(self.plot_delay())

        self.artists = [self.ln]
        self.artists.extend(self.create_artists())
        self.animation = ArtistAnimation(self.fig,
                                         self.artists,
                                         interval=self.interval,
                                         repeat=False)
def main():
    fig = plt.figure()
    plt.axis([0, SIZE, 0, SIZE])  #xmin xmax ymin ymax
    plt.xticks([])
    plt.yticks([])
    x, y, z = random_direction(math.floor(SIZE / 2), math.floor(SIZE / 2),
                               random_step_size())
    while z != 1:
        x, y, z = random_direction(x, y, random_step_size())
    animation = ArtistAnimation(fig, images, interval=100, repeat=0)
    plt.show()
Exemple #25
0
    def animate_vibration_mode(self, k, alpha=1, l=1, show=None, savename=None, playtime=5, fps=60, repeat_delay=0, title=None):
        if k > self.num_eigenpairs - 1:
            raise ValueError(f"Too high an eigen-number. Have only solved for {self.num_eigenpairs} eigenpairs.")

        displacement_vec = self.retrieve_vibration_eigenvector(k)

        N_frames = playtime * fps
        ts = np.linspace(0, 2*np.pi, N_frames)

        fig, ax = plt.subplots(figsize=(16, 16))
        if title is None:
            fig.suptitle(f"Eigen vibration mode {k}", fontsize=18)
        else:
            fig.suptitle(title, fontsize=18)

        artists = [self.display_mesh(displacement=alpha*np.sin(l*t)*displacement_vec,
                    show=False, ax=ax) for t in ts]

        ani = ArtistAnimation(fig, artists, interval=1000//fps, repeat_delay=repeat_delay, repeat=True, blit=True)

        if savename is not None:
            ani.save(f"root/project_2/animations/{savename}.mp4")

        if show is None:
            if savename is None:
                show = True
            else:
                show = False
        
        if show:
            plt.show()
            return

        # Clean up memory
        fig.clear()
        plt.close(fig)
        del fig, ax, artists, ani
        import gc
        gc.collect()

        return
Exemple #26
0
def draw_solver_progress(progress_mats,
                         display_with_ipython=True,
                         img_filename=None,
                         imagemagick_path=None,
                         imagemagick_extra_args=None):
    '''
    Produce a GIF of solution progress using matplotlib, requires imagemagick.

    Parameters
    ----------

    progress_mats: list of 2D arrays, required
        List of matrices showing progression of brute force solver. Produced by
        solve_nonogram when return_iterations is set to True

    display_with_ipython: bool, optional, default: True
        Whether or not to display image using IPython.display.Image (for jupyter
        notebook or console)

    img_filename: str or None, optional, default=None
        path to output GIF file. If not specified, a temporary file will be
        created for display.
    '''
    fig, ax = plt.subplots(figsize=(10, 10))
    ax.autoscale()
    imgs = [draw_solution_so_far(mat, ax) for mat in progress_mats]
    anim = ArtistAnimation(fig, imgs, interval=500, repeat_delay=1000)
    plt.axis('square')
    plt.axis('off')
    if img_filename is None:
        handle, img_filename = mkstemp(suffix='.gif')
        os.close(handle)
    if imagemagick_path:
        plt.rcParams["animation.convert_path"] = imagemagick_path
    anim.save(img_filename, writer='imagemagick', extra_args=imagemagick_extra_args)
    plt.close()
    if display_with_ipython:
        from IPython.display import Image, display
        shutil.copy2(img_filename, img_filename + '.png')
        display(Image(filename=img_filename + '.png'))
    def play_video(self, t_ini=0, t_final=np.inf, grayscale = True, save=False):
        """ Play a video of radar images between t_ini and t_final
            grayscale: if False automatic coloration of images is used
            save: if True, save the video as a .mp4
        """
        # Handling pause/resume event when clicking on the video
        anim_running = True
        def onClick(event):
            nonlocal anim_running
            if anim_running:
                ani.event_source.stop()
                anim_running = False
            else:
                ani.event_source.start()
                anim_running = True
                    
        times = self.get_timestamps(t_ini, t_final)
        images = []       
        fig = plt.figure(facecolor='black')
        fig.set_figwidth(8)
        fig.canvas.mpl_connect('button_press_event', onClick)
        ax = plt.axes()     
        [ax.spines[spine].set_color('white') for spine in ax.spines]
        ax.set_facecolor("black")
        ax.tick_params(colors='black')
                
        print("Creating video...")
        for t in times:
            if grayscale:              
                images.append([ax.imshow(Image.fromarray(self.heatmaps[t].img), cmap='gray', vmin=0, vmax=255), ax.text(0.6,0.8,str(round(t,2)), color='white')])
            else:
                images.append([ax.imshow(Image.fromarray(self.heatmaps[t].img)), ax.text(0.6,0.8,str(round(t,2)), color='white')])

        ani = ArtistAnimation(fig, images, interval=100, blit=False, repeat_delay=1000)
        if save:
            print("Saving video: "+str(self.src) + '.mp4')
            os.makedirs(os.path.dirname('Videos/' + str(self.src) + '.mp4'), exist_ok=True)
            ani.save('Videos/' + str(self.src) + '.mp4', fps=10, dpi=200, savefig_kwargs={'facecolor': 'black'})
        plt.show()
        return ani
def main():
    robotmap = robot_map(20, 20, 0.09, 0.9)
    robotmap.generate_map()
    row, col = robotmap.get_start_position()
    target_row, target_col = robotmap.get_target_position()
    
    ret, dfs_path, res_path = dijkstra_search(robotmap, row, col, target_row, target_col)
    print('start position:', row, col)
    print('target position:', target_row, target_col)

    dfs_path = np.array(dfs_path)
    res_path = np.array(res_path)

    if ret == False:
        print('can not find a path')
        sys.exit(0)
    else:
        print('success to find a path')

    fig = plt.figure()
    ax = plt.axes()
    ax.set_xlim([0, robotmap.shape[0]])
    ax.set_xlabel('X')
    ax.set_ylim([0, robotmap.shape[1]])
    ax.set_ylabel('Y')
    ax.set_title('maze')

    images = []
    image = robotmap.get_image()
    # draw start and target
    image[row, col] = 50
    image[target_row, target_col] = 200
    im = plt.imshow(image, cmap=plt.cm.get_cmap('jet'), animated=True, interpolation='nearest')
    images.append([im])
    # draw path
    for i in range(1, dfs_path.shape[0] - 1):
        image[dfs_path[i, 0], dfs_path[i, 1]] = 100
        im = plt.imshow(image, cmap=plt.cm.get_cmap('jet'), animated=True, interpolation='nearest')
        images.append([im])

    image = robotmap.get_image()
    image[row, col] = 50
    image[target_row, target_col] = 200
    for i in range(1, res_path.shape[0] - 1):
        image[res_path[i, 0], res_path[i, 1]] = 150
    for i in range(10):
        im = plt.imshow(image, cmap=plt.cm.get_cmap('jet'), animated=True, interpolation='nearest')
        images.append([im])
    ani = ArtistAnimation(fig, images, interval=len(images), blit=True,
                                    repeat_delay=100)
    # ani.save('dijkstra_search.gif', dpi=80, writer='imagemagick')
    plt.show()
Exemple #29
0
    def generate_gif(self, input_chord, output_file, framerate):
        """

        Parameters
        ----------
        input_chord: iterable
        output_file: str
        framerate: int

        Returns
        -------

        """
        img_matrices = self.play_chords(input_chord)

        fig = plt.figure(figsize=(20, 10))

        artists = [[plt.imshow(i, animated=True, cmap='gray')]
                   for i in img_matrices]

        ani = ArtistAnimation(fig, artists, interval=framerate, blit=True)
        ani.save(output_file, writer='imagemagick')
def save_ds_video_path(date, cube_list, dated, timed, path):

    #plt.ion()
    f1 = plt.figure(figsize=(3, 3))
    ax = f1.add_subplot(111)

    struct = extract_cube_path(date, cube_list)

    cube_ds = dark_subtract_cube(dated, timed, struct)

    cube_ds = cube_ds[400:, :, :]
    images = []
    texts = [
        "AO188 off, SCExAO off", "AO188 on, SCExAO off", "AO188 on, SCExAO on"
    ]

    for i in xrange(cube_ds.shape[0]):
        print i
        imtemp = cube_ds[i, 68:188, 100:220]
        imtemp = np.log10(imtemp)
        imtemp = np.nan_to_num(imtemp)
        im = ax.imshow(imtemp,
                       cmap=cmaps.inferno,
                       clim=(0.0, 4.0),
                       interpolation="bicubic")
        if i < 759:
            j = 0
        elif (i > 758) and (i < 1600):
            j = 1
        else:
            j = 2
        ax.annotate(texts[j], xy=(10, 110), xytext=(10, 110), color='white')

        images.append((im, ))

    anim = ArtistAnimation(f1, images, interval=25, blit=False)
    anim.save(path, dpi=150)

    return None
params.append((0.16, 0.08, 0.060, 0.062))  # Coral
params.append((0.19, 0.05, 0.060, 0.062))  # Fingerprint
params.append((0.10, 0.10, 0.018, 0.050))  # Spirals
params.append((0.12, 0.08, 0.020, 0.050))  # Spirals Dense
params.append((0.10, 0.16, 0.020, 0.050))  # Spirals Fast
params.append((0.16, 0.08, 0.020, 0.055))  # Unstable
params.append((0.16, 0.08, 0.050, 0.065))  # Worms 1
params.append((0.16, 0.08, 0.054, 0.063))  # Worms 2
params.append((0.16, 0.08, 0.035, 0.060))  # Zebrafish
(du, dv, f, k) = params[2]

dt = 1.

ims = []
fig = figure()
axis('off')

N = 20000
for ind in range(N):
    u, v = u + (du * laplace(u, mode='wrap') - u * v ** 2 + f * (1. - u)) * dt, v + (
        dv * laplace(v, mode='wrap') + u * v ** 2 - (k + f) * v) * dt
    if ind % 10 == 0:
        print(str(ind) + "/" + str(N))
        ims.append([imshow(v)])

ani = ArtistAnimation(fig, ims, interval=10, blit=True, repeat_delay=1000)
Writer = writers['ffmpeg']
writer = Writer(fps=100, metadata=dict(artist='Laurent Garcin'), bitrate=18000)
ani.save('morpho.mp4', writer=writer)
show()
fig = plt.figure(figsize=(5, 5))

for epoch in range(nb_epoch):
    # shuffle X_train and calculate P
    if epoch % shuffle_interval == 0:
        X = X_train[np.random.permutation(n)[:m]]
        P = calculate_P(X)

    # train
    loss = 0
    for i in xrange(0, n, batch_size):
        loss += model.train_on_batch(X[i:i+batch_size], P[i:i+batch_size])
    print "Epoch: {}/{}, loss: {}".format(epoch+1, nb_epoch, loss / batch_num)

    # visualize training process
    pred = model.predict(X_test)
    img = plt.scatter(pred[:, 0], pred[:, 1], c=y_test,
                      marker='o', s=3, edgecolor='')
    images.append([img])

ani = ArtistAnimation(fig, images, interval=100, repeat_delay=2000)
ani.save("mlp_process.mp4")

plt.clf()
fig = plt.figure(figsize=(5, 5))
pred = model.predict(X_test)
plt.scatter(pred[:, 0], pred[:, 1], c=y_test, marker='o', s=4, edgecolor='')
fig.tight_layout()

plt.savefig("mlp_result.png")
Exemple #33
0
 def _step(self, *a,**k):
     artists = self._framedata[0]
     self.updateArtists(artists)
     AA._step(self,*a,**k)
Exemple #34
0
nb = 10
z = uniform(-3, 3, nb) + 1j * uniform(-3, 3, nb)
a = 2 + 2j
b = 3 - 2j
Z = a * (z + normal(0, .01) + 1j * normal(0, .01)) + b
z0 = mean(z)
Z0 = mean(Z)
zz = z - z0
ZZ = Z - Z0
aa = sum(zz.conjugate() * ZZ) / sum(zz * zz.conjugate())
bb = Z0 - aa * z0

center = bb / (1 - aa)
mod = absolute(aa)
arg = angle(aa)

fig = figure()
ims = []
for t in linspace(0, 1, 100):
    m = (1 - t) + t * mod
    a = t * arg
    a_current = m * exp(1j * a)
    current = center + a_current * (z - center)
    # current = (1 - t) * z + t * (aa * z + bb)
    ims.append((scatter(z.real, z.imag, color='blue'), scatter(Z.real, Z.imag, color='red'),
                scatter(current.real, current.imag)))
im_ani = ArtistAnimation(fig, ims, interval=50, repeat_delay=3000, blit=True)
im_ani.save('test.mp4')
show()
Exemple #35
0
            # plot a frame of the graph
            voltageLine, currentLine = pylab.plot(timeLine[:i+1], axon.Vm[:i+1], 'b-', timeLine[:i+1], curr[:i+1], 'g-')
            if k == 1: # have only 1 legend
                pylab.legend([voltageLine, currentLine], ["Response from cell", "Impulse current"])
            pylab.title('Effective Current ' + "{:6.3f}".format(effectiveCurrent) + u' µA/cm$^2$')
            pylab.ylabel('Membrane Potential (mV)')
            pylab.xlabel('Time (ms)')
            pylab.ylim([-20,120])
            pylab.xlim([0,60])
            lines += [voltageLine, currentLine]

    if i % 25 == 0:
        # don't wanna print a lot cuz it slows things down
        print "Time: " + str(i*dt) + " ms"
        images.append(tuple(lines))

pylab.tight_layout()
anim = ArtistAnimation(animationFigure, images, interval = 40, blit = True)
print "Saving animation..."
anim.save("currentComparisons.mp4", extra_args=['-vcodec', 'libx264'])
pylab.show()

# pylab.figure()
# pylab.plot(timeLine, Vm, timeLine, I)
# pylab.title('Hodgkin-Huxley Example')
# pylab.ylabel('Membrane Potential (mV)')
# pylab.xlabel('timeLine (msec)')
# pylab.savefig("model.jpg")

Exemple #36
0
    sodiumCurrent = sodiumConductance * (Vm[i-1] - sodiumPotential)
    potassiumCurrent = potassiumConductance * (Vm[i-1] - potassiumPotential)
    leakageCurrent = leakageConductance * (Vm[i-1] - leakagePotential)
    Vm[i] = Vm[i-1] + (I[i-1] - sodiumCurrent - potassiumCurrent - leakageCurrent) * dt / Cm

    # update status
    if i % 25 == 0:
        # update status every 25 frames (about a second of video).
        # don't wanna print a lot cuz it slows things down
        print "Time: " + str(i*dt) + ", Saving frame " + str(i)

        # plot a frame of the graph
        voltageLine, currentLine = pylab.plot(timeLine[:i+1], Vm[:i+1], 'b-', timeLine[:i+1], I[:i+1], 'g-')
        pylab.legend([voltageLine, currentLine], ["Response from cell", "Impulse current"])
        pylab.title('Hodgkin-Huxley Model of Action Potentials')
        pylab.ylabel('Membrane Potential (mV)')
        pylab.xlabel('Time (ms)')
        images.append((voltageLine, currentLine))

anim = ArtistAnimation(animationFigure, images, interval = 50, blit = True)
print "Saving animation"
anim.save("model.mp4", dpi=200, extra_args=['-vcodec', 'libx264'])

pylab.figure()
pylab.plot(timeLine, Vm, timeLine, I)
pylab.title('Hodgkin-Huxley Example')
pylab.ylabel('Membrane Potential (mV)')
pylab.xlabel('timeLine (msec)')
pylab.savefig("model.jpg")

Exemple #37
0
a, b, c = random(size), random(size), random(size)
alpha, beta, gamma = 1., 1., 1.
Da, Db, Dc = .1, .1, .1

ims = []
fig = figure(figsize=(4, 4))
axis('off')

kernel = [[1, 1, 1], [1, -8, 1], [1, 1, 1]]


def constrain(v):
    v[v < 0.] = 0.
    v[v > 1.] = 1.
    return v


N = 500
for ind in range(N):
    a, b, c = constrain(a + Da * convolve(a, kernel) + a * (alpha * b - gamma * c)), \
              constrain(b + Db * convolve(b, kernel) + b * (beta * c - alpha * a)), \
              constrain(c + Dc * convolve(c, kernel) + c * (gamma * a - beta * b))
    print(str(ind) + "/" + str(N))
    ims.append([imshow(a, vmin=0., vmax=1.)])

ani = ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)
Writer = writers['ffmpeg']
writer = Writer(fps=20, metadata=dict(artist='Laurent Garcin'), bitrate=18000)
ani.save('bz.mp4', writer=writer)
show()
# <codecell>

# Create an empty figure
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ims = [] # list for storing all of the created artists

# Generate a bunch of images with random data
for i in range(10):
    ims.append([ax.imshow(np.random.randn(20, 20))])

# Create an animation object, passing it the figure and a
# sequence of *collections* of Artists. In this case we are
# giving it a list of lists of images.
# Frames are displayed with a 500 millisecond delay
anim = ArtistAnimation(fig, ims, interval=500)

# <markdowncell>

# Same animation, but this time delaying between restarts of the animation.

# <codecell>

from matplotlib.animation import ArtistAnimation
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ims = []
for i in range(10):
    ims.append([ax.imshow(np.random.randn(20, 20))])

anim = ArtistAnimation(fig, ims, interval=500, repeat_delay=3000)
Exemple #39
0
while not array_equal(access, a):
    access = a.copy()
    a = logical_and(binary_dilation(a), grid)
    lines, colors = [], []
    for i in range(N - 1):
        for j in range(N):
            if access[i, j] and access[i + 1, j]:
                lines.append([(i, j), (i + 1, j)])
                colors.append([1, 0, 0, 1])
            elif grid[i, j] and grid[i + 1, j]:
                lines.append([(i, j), (i + 1, j)])
                colors.append([0, 0, 1, 1])
    for i in range(N):
        for j in range(N - 1):
            if access[i, j] and access[i, j + 1]:
                lines.append([(i, j), (i, j + 1)])
                colors.append([1, 0, 0, 1])
            elif grid[i, j] and grid[i, j + 1]:
                lines.append([(i, j), (i, j + 1)])
                colors.append([0, 0, 1, 1])
    ax.autoscale()
    ax.set_aspect('equal')
    ims.append([ax.add_collection(LineCollection(lines, colors=colors))])

ani = ArtistAnimation(fig, ims, interval=10, blit=True, repeat_delay=1000)
Writer = writers['ffmpeg']
writer = Writer(fps=10, metadata=dict(artist='Laurent Garcin'), bitrate=18000)
ani.save('perco_bond.mp4', writer=writer)
show()
Exemple #40
0
    C = 3


N = 7

config = {
    'iter': 0,
    Piquet.A: list(range(N, 0, -1)),
    Piquet.B: [],
    Piquet.C: []
}

fig = plt.figure()
plot_config(config)


def hanoi(n, A, B, C):
    if n > 0:
        hanoi(n - 1, A, C, B)
        config[A].pop()
        config[C].append(n)
        config['iter'] += 1
        plot_config(config)
        hanoi(n - 1, B, A, C)


hanoi(N, Piquet.A, Piquet.B, Piquet.C)
im_ani = ArtistAnimation(fig, ims, interval=50, repeat_delay=1000, blit=True)
im_ani.save('hanoi.mp4')
plt.show()