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)
Beispiel #2
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()
Beispiel #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)
Beispiel #4
0
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)
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)
Beispiel #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)
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')
Beispiel #8
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 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)
Beispiel #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)
Beispiel #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)
Beispiel #12
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)
Beispiel #14
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")
Beispiel #15
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
Beispiel #16
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 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
Beispiel #19
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')
Beispiel #20
0
def animate(phi1s=np.linspace(0, 360, 300) * np.pi / 180,
            AB=0.15,
            AC=0.1,
            CD=0.15,
            DF=0.4,
            AG=0.3):

    from matplotlib.animation import ArtistAnimation

    fig, ax = plt.subplots()

    container = []
    for phi in phi1s:

        rA, rB, rC, rD, rF, rG = pos(phi, AB, AC, CD, DF, AG)

        pinA, = ax.plot(np.real(rC), np.imag(rC), 'bo')
        pinC, = ax.plot(np.real(rC), np.imag(rC), 'bo')
        link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-')
        link3, = ax.plot(np.real([rD, rF]), np.imag([rD, rF]), 'go-')
        link5, = ax.plot(np.real([rA, rG]), np.imag([rA, rG]), 'bo-')
        A = ax.text(np.real(rA) * 1.05, np.imag(rA) * 1.05, 'A', fontsize=12)
        B = ax.text(np.real(rB) * 1.05, np.imag(rB) * 1.05, 'B', fontsize=12)
        C = ax.text(np.real(rC) * 1.05, np.imag(rC) * 1.05, 'C', fontsize=12)
        D = ax.text(np.real(rD) * 1.05, np.imag(rD) * 1.05, 'D', fontsize=12)
        F = ax.text(np.real(rF) * 1.05, np.imag(rF) * 1.05, 'F', fontsize=12)
        G = ax.text(np.real(rG) * 1.05, np.imag(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')
    ax.set_xlim(xmin=-np.max([AG, DF]), xmax=np.max([AG, DF]))
    ax.set_ylim(ymin=-np.max([AG, DF]), ymax=np.max([AG, DF]))
    ani = ArtistAnimation(fig, container, interval=15, blit=True)
    ani.save('R_RTR_RTR.mp4', fps=60, bitrate=5000, dpi=400)
Beispiel #21
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()
start_idx = 100
substring_len = 10
longest_sequence = max(valid_datasets, key=lambda dataset: dataset.length)
starting_substring = longest_sequence.sequence[start_idx:start_idx +
                                               substring_len]
valid_datasets = [
    start_from_substring(dataset, starting_substring)
    for dataset in valid_datasets
]
valid_datasets = [
    dataset for dataset in valid_datasets if len(dataset.sequence) > MIN_LENGTH
]

# Sort the accessions
sorted_datasets = sorted(valid_datasets, key=lambda data: data.date)

# Create the animation.
fig, ax = plt.subplots()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
frames = [d.frame(ax) for d in sorted_datasets]
base_pairs = ["A", "C", "T", "G"]

patches = [
    mpatches.Patch(color=base_rgb_map[bp], label=bp) for bp in base_pairs
]
plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
ani = ArtistAnimation(fig, frames, interval=100, blit=False)
ani.save(ANIMATION_NAME)
plt.show()
Beispiel #23
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()
Beispiel #24
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")

Beispiel #25
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")

# * mencoder
# 
# In matplotlib git master, the movie writing support has undergone a substantial internal refactor. As a result, it is much easier to pass custom encoding options to control the codec and quality used for the resulting movie. Also, unix pipes are employed by default when using the ffmpeg/mencoder utility, drastically speeding up the write process.
# 
# However, we will demonstrate saving files with the Matplotlib 1.1 code, whose API for the most part has only been extended.

# <codecell>

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ims = []
for i in range(50):
    ims.append([ax.imshow(np.random.randn(20, 20))])

anim = ArtistAnimation(fig, ims, interval=500, repeat=False)
anim.save('images.mp4', fps=15)

# <headingcell level=2>

# Blitting

# <markdowncell>

# Blitting is a technique for increasing animation performance by only drawing things that have changed. However, this requires:
# 
# * An init_func for creating a clean slate (for erasing between frames)
# * Knowledge of what artists change in a frame so that only those are drawn
# 
# As a result, blitting is not enabled by default.

# <codecell>
Beispiel #27
0
m2 = 0.6*1.98847*10**30

m3 = 0.3*1.98847*10**30

G = 6.67*10**(-11)

sol = odeint(move_func,s0,t)

fig = plt.figure()
bodys = []

for i in range(0, len(t), 1):
    body1, = plt.plot(sol[:i,0],sol[:i,2],'-', color= 'y')
    body1_line, = plt.plot(sol[i,0],sol[i,2],'o', color= 'y')

    body2, = plt.plot(sol[:i,4],sol[:i,6],'-', color= 'g')
    body2_line, = plt.plot(sol[i,4],sol[i,6],'o', color= 'g')

    body3, = plt.plot(sol[:i,8],sol[:i,10],'-', color= 'r')
    body3_line, = plt.plot(sol[i,8],sol[i,10],'o', color= 'r')
    
    bodys.append([body1,body1_line,body2,body2_line,body3,body3_line])

ani = ArtistAnimation(fig,bodys, interval=100)
plt.axis('equal')
ani.save('N_body_G.gif')



Beispiel #28
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()
Beispiel #29
0
s0 = (x10, v_x10, y10, v_y10,
x20, v_x20, y20, v_y20,
x30, v_x30, y30, v_y30)

m1 = 2.10777 * 10**30
m2 = 1.193 * 10**30
m3 = 0.596 *10**30
G = 6.67 * 10**(-11)

sol = odeint(move_func, s0, t)
fig = plt.figure()
bodys = []

for i in range (0, len(t), 1):
    body1, = plt.plot(sol[:i,0], sol[:i,2], '-', color='r')
    body1_line, = plt.plot(sol[i, 0], sol[i,2], 'o', color='r')

    body2, = plt.plot(sol[:i,4], sol[:i,6], '-', color='g')
    body2_line, = plt.plot(sol[i, 4], sol[i,6], 'o', color='g')

    body3, = plt.plot(sol[:i,8], sol[:i,10], '-', color='b')
    body3_line, = plt.plot(sol[i, 8], sol[i,10], 'o', color='b')

    bodys.append([body1, body1_line, body2, body2_line, body3, body3_line])

ani = ArtistAnimation(fig, bodys, interval=50)
plt.axis('equal')
ani.save('N_body_G+K.gif')

Beispiel #30
0
    def animated_plot(self):

        """

        creates two plots :
        one representing voltage/t
        the other one being input current/t

        """

        X = odeint(self.dALLdt, [-65, 0.05, 0.6, 0.32], self.t, args=(self,))
        V = X[:, 0]
        m = X[:, 1]
        h = X[:, 2]
        n = X[:, 3]

        images = {
            "current_line": [],
            "voltage_line": [],
            "gating": []
        }

        # ----------------------------------- #

        fig1 = plt.figure()

        print("Saving animation voltage_line")

        for i in tqdm(self.t):

            if not i % 10:

                # plot a frame of the graph
                voltage_line = plt.plot(self.t[:i + 1], V[:i + 1], color="b")
                plt.title('Hodgkin-Huxley Neuron firing')
                plt.ylabel('V (mV)')
                plt.xlabel('t (ms)')

                images["voltage_line"].append(voltage_line)

        anim = ArtistAnimation(fig1, images["voltage_line"], interval=40, blit=True)
        anim.save("voltage_line.mp4", dpi=200, extra_args=['-vcodec', 'libx264'])

        plt.close()

        # ----------------------------------- #

        fig2 = plt.figure()

        print("Saving animation current_line")
        for i in tqdm(self.t):

            if not i % 10:

                current_line = plt.plot(
                    self.t[:i + 1],
                    list(map(self.I_inj, self.t[:i + 1])),
                    color="red"
                )

                plt.title('Injected current')
                plt.xlabel('t (ms)')
                plt.ylabel('$I_{inj}$ ($\\mu{A}/cm^2$)')
                plt.ylim(-1, 40)

                images["current_line"].append(current_line)

        anim = ArtistAnimation(fig2, images["current_line"], interval=40, blit=True)
        anim.save("current_line.mp4", dpi=200, extra_args=['-vcodec', 'libx264'])

        plt.close()

        # ----------------------------------- #

        fig3 = plt.figure()

        print("Saving animation gating channels")
        for i in tqdm(self.t):

            if not i % 10:

                m1, h1, n1 = plt.plot(
                    self.t[:i + 1], m[:i + 1], 'r',
                    self.t[:i + 1], h[:i + 1], 'g',
                    self.t[:i + 1], n[:i + 1], 'b'
                )

                plt.title('Channels activity')
                plt.ylabel('Gating Value')
                plt.xlabel('t (ms)')
                plt.legend()

                images["gating"].append((m1, h1, n1))

        anim = ArtistAnimation(fig3, images["gating"], interval=40, blit=True)
        anim.save("gating.mp4", dpi=200, extra_args=['-vcodec', 'libx264'])

        plt.close()

        for i in ["voltage_line.mp4", "current_line.mp4", "gating.mp4"]:
            convertFile(i, TargetFormat.GIF)
Beispiel #31
0
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")
s0 = (x10, v_x10, y10, v_y10, x10, v_x20, y20, v_y20, x10, v_x30, y30, v_y30)
m1 = 1.1 * 10**(30)

m2 = 2.1 * 10**(30)

m3 = 3.6 * 10**(30)

G = 6.67 * 10**(-11)

sol = odeint(move_func, s0, t)

fig = plt.figure()
bodys = []

for i in range(0, len(t), 1):
    body1, = plt.plot(sol[:i, 0], sol[:i, 2], '-', color='r')
    body1_line, = plt.plot(sol[i, 0], sol[i, 2], 'o', color='r')

    body2, = plt.plot(sol[:i, 4], sol[:i, 6], '-', color='g')
    body2_line, = plt.plot(sol[i, 4], sol[i, 6], 'o', color='g')

    body3, = plt.plot(sol[:i, 8], sol[:i, 10], '-', color='b')
    body2_line, = plt.plot(sol[i, 8], sol[i, 10], '-', color='b')

    bodys.append(
        [body1, body1_line, body2, body2, body2_line, body3, body3_line])

ani = ArtistAnimation(fig, bodys, interval=50)
plt.axis('equal')
ani.save('N_body_G+K.Gif')
Beispiel #34
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()
Beispiel #35
0
            if k == pos:
                x, y = k * 10 + j, 0
            elif pos < k < i:
                x, y = k * 10 + 10, 0
            elif k == i:
                x, y = pos * 10 + 10 - j, 10
            else:
                x, y = k * 10, 0
            patches.append(Rectangle((x, y), 9, 9))
            annotations.append(
                gca().annotate(val if k == i else (tab[k + 1] if pos < k < i else v), (x, y), (x + 4.5, y + 4.5),
                               color='w',
                               weight='bold', fontsize=20,
                               ha='center',
                               va='center'))
        collection = gca().add_collection(PatchCollection(patches))
        colors = ['red' if k == i else 'blue' for k in range(len(tab))]
        collection.set_color(colors)
        frames.append((collection, *annotations))


tab = permutation(10)
frames = []
fig = figure(figsize=(len(tab), 3))
axis('off')
gca().axis('equal')
gca().axis([0, len(tab) * 10, 0, 10])
tri_insertion(tab)
ani = ArtistAnimation(fig, frames, interval=100, repeat_delay=3000)
ani.save('_images/tri_insertion.gif', dpi=80, writer='imagemagick', )
    #     else:
    #         mox = (mox_max - mox_min)/(t12-t11)*(t-t11) + mox_min
    #     return mox

# %%  Generate instance of simulation, excete calculation and output all of the results
    inst = Main(PARAM_EXCOND, PARAM_CALCOND, PARAM_MODELCONST, FUNCLIST_CEA, PARAM_PLOT)
    FIG = plt.figure(figsize=(28,16))
    inst.exe(FUNC_MOX)
    print("CFL = {}".format(inst.cond_cal["CFL"]))
    DIC_RESULT  = {"t": inst.t_history,
                  "Pc": inst.Pc_history,
                  "Vox": inst.Vox_history,
                  "Vf": inst.Vf_history,
                  "mox": inst.mox_history,
                  "mf": inst.mf_history,
                  "of": inst.of_history,
                  "cstr": inst.cstr_history
                  }
    DF_RESULT = pd.DataFrame(DIC_RESULT)
    DF_RESULT.to_csv(os.path.join(inst.fld_name, "result.csv"))
    DF_R_RESULT = pd.DataFrame(inst.r_history, index=inst.t_history, columns=inst.x)
    DF_R_RESULT.to_csv(os.path.join(inst.fld_name, "result_r.csv"))
    DF_RDOT_RESULT = pd.DataFrame(inst.rdot_history, index=inst.t_history, columns=inst.x)
    DF_RDOT_RESULT.to_csv(os.path.join(inst.fld_name, "result_rdot.csv"))

# %% Generate animation.
    inst.gen_img_list(FIG)
    print("Now generating animation...")
    anim = ArtistAnimation(FIG, inst.img_list, interval=PARAM_CALCOND["dt"]*1e+3)
    anim.save(os.path.join(inst.fld_name, "animation.mp4"), writer="ffmpeg", fps=1/PARAM_PLOT["interval"])
    print("Completed!")
Beispiel #37
0
    update_Y.append(tf.assign(v, v * beta1 + (1 - beta1) * (grad**2)))
    m_hat = m / (1 - beta1)
    v_hat = v / (1 - beta2)
    adam = lr / (tf.sqrt(v_hat) + adam_e)
    update_Y.append(tf.assign(Y, Y - adam * m_hat))

    with tf.Session() as sess:
        fig = plt.figure(figsize=(8, 8))
        images = []
        sess.run(init_op)
        X, y = sess.run(next_element)
        pp = p_joint(X, PERPLEXITY)
        sess.run(tf.initialize_all_variables())

        for i in range(1000):
            sess.run(init_op)
            X, y = sess.run(next_element)
            b, c, qq = sess.run([update_Y, C, Q], feed_dict={P: pp})
            xx, yy = b[-1].T
            print("iteration %d -- KL_Loss %f" % (i, c))

            if i % 10 == 0:
                plt.title('KL_loss: {}'.format(c))
                img = [plt.scatter(b[-1][:, 0], b[-1][:, 1], c=y)]

                images.append(img)

        ani = ArtistAnimation(fig, images, interval=500)
        ani.save("class.mp4")
        plt.close('all')
Beispiel #38
0
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation

from matplotlib import animation

import numpy as np
fig, ax = plt.subplots(figsize=(19.2, 10.8), dpi=100)
artists = []
x = np.arange(10)
for i in range(10):
    y = np.random.rand(10)
    im = ax.scatter(x, y)
    artists.append([im])
print(artists)

anim = ArtistAnimation(fig, artists, interval=1000)

mp4writer = animation.FFMpegWriter(fps=1, metadata=dict(artist='kshibata'), bitrate=1800)
anim.save('test3.mp4', writer=mp4writer)
Beispiel #39
0
pair = 0
iscf_pair = iscfs[repeat, pair, ...]

fig, ax = plt.subplots()

iscf_anim = []
for t in np.arange(iscf_pair.shape[0]):
    mat = ax.imshow(iscf_pair[t], cmap='RdYlBu_r', vmin=-5, vmax=5)
    if t == 0:
        ax.imshow(iscf_pair[t], cmap='RdYlBu_r', vmin=-5, vmax=5)
        ax.axis('off')
        fig.colorbar(mat, ax=ax)
    iscf_anim.append([mat])

ani = ArtistAnimation(fig, iscf_anim, interval=67, blit=True)
ani.save(f'results/iscf_lstm_tanh-z_pca-k{k}_m{matchup}_r{r}_p{pair}_ani.mp4')
plt.show()

matchup, repeat = 0, 0
n_players = 4
n_units = 512
n_pairs = n_players * (n_players - 1) // 2
n_samples = 4501
width = 150
onsets = np.arange(n_samples - width)
n_windows = len(onsets)

win_isfc_results = np.load((f'results/isfc_win-{width}_lstm_pca-k{k}_ica_'
                            f'matchup-{matchup}_repeat-{repeat}_results.npy'))

# Vectorize square ISFC matrices first