Esempio n. 1
0
def plot_contour_ani(x, y, z, xl=r"$X$", yl=r"$Y$", steps=100, fn="test.mp4"):
    metadata = dict(title='Movie Test',
                    artist='Matplotlib',
                    comment='Movie support!')
    writer = FFMpegWriter(fps=15, metadata=metadata)

    xx, yy = np.meshgrid(x, y)
    fig = plt.figure()
    plt.xlabel(xl)
    plt.ylabel(yl)
    plt.contourf(xx,
                 yy,
                 z[0, :, :].T,
                 cmap='seismic',
                 levels=np.linspace(-1.0, 1.0, 32),
                 extend='both')
    cb = plt.colorbar()
    cb.set_ticks([-1, -0.8, -0.6, -0.4, 0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
    cb.set_label(r'$\zeta$', rotation=0)

    with writer.saving(fig, fn, 100):
        for i in range(steps):
            if i % 10 == 0:
                plt.contourf(xx,
                             yy,
                             z[i, :, :].T,
                             cmap='seismic',
                             levels=np.linspace(-1.0, 1.0, 32),
                             extend='both')
                plt.title('t = {0:.1f} s'.format(i * 0.1))
                print("i = ", i)
                writer.grab_frame()

    plt.close()
Esempio n. 2
0
def save_history_as_video_file(x, n_components, history, save_video_file):
    fig, ax = plt.subplots(1, 1, figsize=(8, 8))

    ax.set_xlim(-2.0, 2.0)
    ax.set_ylim(-2.0, 2.0)

    def animate(t):
        nonlocal history, ax
        ax.clear()

        colors = list(BASE_COLORS)[:n_components]

        plot_gmm_confidence_ellipses(ax, history[t]['mean'], history[t]['cov'],
                                     colors=colors)
        plot_data_samples(ax, x, history[t]['gamma'], colors=colors)

        ax.set_title('iteration = {:02d}, log_likelihood = {:.3f}'.format(
            t, history[t]['log_likelihood']))

        return ax,

    writer = FFMpegWriter(fps=1)
    with writer.saving(fig, save_video_file, dpi=100):
        for t in range(len(history)):
            animate(t)
            writer.grab_frame()
Esempio n. 3
0
    def movie(self,
              variables=None,
              InOut=0.0,
              plotgroup=None,
              saveName='movie.mp4',
              resolution=10,
              figsize=(15, 8)):

        metadata = dict(title=self.meas_type, artist='Matplotlib', comment='')
        writer = FFMpegWriter(fps=15, metadata=metadata)

        fig = plt.figure(figsize=figsize)

        subset = self.GetDataSubset(inout=InOut, plotGroup=plotgroup)

        length = subset['Amp'].values.shape[1]

        limits = self.varlimits(variables=variables,
                                InOut=InOut,
                                plotgroup=plotgroup)

        with writer.saving(fig, saveName, 100):
            for k in np.arange(0, length, int(length / resolution)):
                # Create a new plot object
                self.imslice(variables=variables,
                             sliceNum=k,
                             InOut=InOut,
                             plotgroup=plotgroup,
                             limits=limits)
                writer.grab_frame()
Esempio n. 4
0
def main():
    power = int(sys.argv[1])
    height = 2**power
    width = int(height**0.5)
    sandpile = np.zeros((width, width), dtype=np.uint32)
    sandpile[width // 2, width // 2] = height
    my_cmap = colors.ListedColormap(["white", "green", "purple", "gold"])
    bounds = [-1, 0.5, 1.5, 2.5, 3.5]
    norm = colors.BoundaryNorm(bounds, my_cmap.N)
    writer = FFMpegWriter(fps=15,
                          metadata={
                              "title": "Abelian Sand",
                              "artist": "Matplotlib"
                          })
    fig, ax = plt.subplots()
    plt.axis("off")
    fig.subplots_adjust(left=0,
                        bottom=0,
                        right=1,
                        top=1,
                        wspace=None,
                        hspace=None)
    im = ax.imshow(sandpile, cmap=my_cmap, norm=norm)
    min_height = np.max(sandpile)
    with writer.saving(fig, f"sand-{power}.mp4", dpi=100):
        for i, _ in enumerate(apply_gravity(sandpile)):
            im.set_data(sandpile)
            min_height = min(min_height, np.max(sandpile))
            im.set_clim(0, 4)  # min_height)
            writer.grab_frame()
            np.save(f"video/frame-{power}-{i:09d}", sandpile)
    np.save(f"sand-{power}", sandpile)
    plt.imsave(f"sand-{power}.png", sandpile, cmap=my_cmap)
Esempio n. 5
0
def write_movie(pose_array,
                name='writer_test.mp4',
                fps=15,
                r_base=1000,
                color_shift_at=0,
                title=None):
    """
    Write a movie of ground truth and predicted outputs.
    :param pose_array: np.array [joints, 3dpoints, time]
    :param name: the name for the movie.
    """
    time = pose_array.shape[-1]
    metadata = dict(title='Movie Test',
                    artist='Matplotlib',
                    comment='Movie support!')
    writer = FFMpegWriter(fps=fps, metadata=metadata)

    fig = plt.figure()
    with writer.saving(fig, name, 100):
        ax = fig.add_subplot(111, projection='3d')
        gt_plotter = viz.Ax3DPose(ax, 'Human36', title=title)
        net_plotter = viz.Ax3DPose(ax,
                                   'Human36',
                                   lcolor='#e88d1e',
                                   rcolor='#3ce7ae',
                                   title=title)
        net_plotter.axes_set = True
        for i in range(time):
            if i > color_shift_at:
                net_plotter.update(pose_array[:, :, i].flatten(),
                                   r_base=r_base)
            else:
                gt_plotter.update(pose_array[:, :, i].flatten(), r_base=r_base)
            writer.grab_frame()
    plt.close()
def main():
    parser = ArgumentParser()
    parser.add_argument('--n_particles', type=int, default=50)
    parser.add_argument('--animation_command', type=str, default='show',
                        choices=('show', 'save'))
    args = parser.parse_args()

    n_states = 1
    transition_model = GaussianTransitionModel(np.eye(n_states),
                                               np.eye(n_states))
    observation_model = GaussianObservationModel(np.eye(n_states),
                                                 np.eye(n_states))
    particle_filter = MonteCarloFilter(args.n_particles, n_states,
                                       transition_model,
                                       observation_model)

    sim = ToySimulator(particle_filter)
    if args.animation_command == 'show':
        ani = FuncAnimation(sim.fig, sim.update)
        plt.show()
        return
    elif args.animation_command == 'save':
        n_steps = 50
        video_file_name = 'monte_carlo_filter_example'
        extensions = ['.mp4', '.h264']
        for ext in extensions:
            writer = FFMpegWriter()
            with writer.saving(sim.fig, video_file_name + ext, dpi=100):
                for t in range(n_steps):
                    sim.update(t)
                    writer.grab_frame()
Esempio n. 7
0
    def start(self, saved=False,  filename="visual.mp4"):
        fig = plt.figure()

        ax = fig.add_subplot(projection='3d')
        ax.view_init(60, 48)

        self.draw_func(ax, self.line_count, self.point_count)

        pointer, = ax.plot3D([], [], marker="8", linestyle='None', markersize=2, color='red')

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

        def update(fishes):
            x = np.array([fish.get("pos")[0] for fish in fishes], dtype=np.core.float64)
            y = np.array([fish.get("pos")[1] for fish in fishes], dtype=np.core.float64)
            z = np.array([fish.get("fitness_value") for fish in fishes], dtype=np.core.float64)
            pointer.set_data_3d(x, y, z)

            return pointer,

        if not saved:
            ani = FuncAnimation(fig, update, frames=self.history.get("steps"),
                                init_func=init, blit=True, interval=self.timeout)
            plt.show()
        else:
            metadata = dict(title='Visualization', artist='Matplotlib',
                            comment='')
            movie_writer = FFMpegWriter(fps=5, metadata=metadata)
            with movie_writer.saving(fig, outfile=filename, dpi=800):
                for step in self.history.get("steps"):
                    update(step)
                    movie_writer.grab_frame()
Esempio n. 8
0
class VideoWriter(object):
    def __init__(self,
                 frame_rate,
                 bit_rate=None,
                 dots_per_inch=200,
                 figure=None,
                 axes=None,
                 axis=True,
                 verbose=True,
                 **kwargs):
        self.fps = kwargs.get('fps', None)
        if self.fps is None:
            self.fps = frame_rate
        kwargs['fps'] = self.fps
        if 'bitrate' not in kwargs:
            kwargs['bitrate'] = bit_rate
        self.grab = FFMpegWriter(
            **{kw: arg
               for kw, arg in kwargs.items() if arg is not None})

        self.finally_close = False
        if figure is None:
            if axes is None:
                # always import pyplot as late as possible to allow for backend selection
                import matplotlib.pyplot as plt
                figure, axes = plt.subplots()
                self.finally_close = True
            else:
                figure = axes.get_figure()
        elif axes is None:
            axes = figure.gca()
        if axis in (False, 'off'):
            axes.set_axis_off()
        self.dpi = dots_per_inch
        self.figure = figure
        self.axes = axes
        self.verbose = verbose

    def saving(self, output_file):
        output_file = os.path.expanduser(output_file)
        if self.verbose and os.path.exists(
                output_file) and 0 < os.path.getsize(output_file):
            answer = input("overwrite file '{}': [N/y] ".format(output_file))
            if not (answer and answer[0].lower() == 'y'):
                raise Aborted
        return self.grab.saving(self.figure, output_file, self.dpi)

    def range(self, N):
        trange = range
        if self.verbose:
            try:
                import tqdm
            except ImportError:
                pass
            else:
                trange = tqdm.trange
        return trange(int(N))

    def grab_frame(self, *args, **kwargs):
        self.grab.grab_frame(*args, **kwargs)
def main():
    parser = ArgumentParser()
    parser.add_argument('--n_particles', type=int, default=50)
    parser.add_argument('--animation_command',
                        type=str,
                        default='show',
                        choices=('show', 'save'))
    args = parser.parse_args()

    n_states = 1
    transition_model = GaussianTransitionModel(np.eye(n_states),
                                               np.eye(n_states))
    observation_model = GaussianObservationModel(np.eye(n_states),
                                                 np.eye(n_states))
    particle_filter = MonteCarloFilter(args.n_particles, n_states,
                                       transition_model, observation_model)

    sim = ToySimulator(particle_filter)
    if args.animation_command == 'show':
        ani = FuncAnimation(sim.fig, sim.update)
        plt.show()
        return
    elif args.animation_command == 'save':
        n_steps = 50
        video_file_name = 'monte_carlo_filter_example'
        extensions = ['.mp4', '.h264']
        for ext in extensions:
            writer = FFMpegWriter()
            with writer.saving(sim.fig, video_file_name + ext, dpi=100):
                for t in range(n_steps):
                    sim.update(t)
                    writer.grab_frame()
Esempio n. 10
0
def exportDistributionSweep(distributions, fps=30, dpi=100, path=None):
    """
    Creates (and plays) a video of a sequence of distributions on the simplex.

    Parameters
    ----------
    distributions: an iterable containing the different distributions passed to the plot function
    fps: framerate of the video
    dpi: resolution of the video
    path: path to the video. If 'None', a temporary file is used.
    """
    # create temporary file
    if path is None:
        _, path = tempfile.mkstemp(suffix='.mp4')

    # create writer object and export frames to video
    writer = FFMpegWriter(fps=fps)
    fig = plt.figure()
    with writer.saving(fig, path, dpi=dpi):
        for param in distributions:
            fig.clear()
            plot(param)
            writer.grab_frame()

    # show video
    os.system('open ' + path)
Esempio n. 11
0
    def plot(self, measures_summary):
        os.makedirs('plots/', exist_ok=True)

        measures = measures_summary['measures_all_runs']
        activations_summary = measures_summary['activations_summary']
        self.get_specifications(measures)

        plt.set_cmap("hsv")
        fig, (ax_infoplane, ax_accuracy) = plt.subplots(
            2, 1, figsize=(6, 9), gridspec_kw={'height_ratios': [2, 1]})

        acc = []
        val_acc = []

        scatter, text = self.setup_infoplane_subplot(ax_infoplane)
        acc_line, val_acc_line = self.setup_accuracy_subplot(ax_accuracy)

        writer = FFMpegWriter(fps=7)
        with writer.saving(fig, self.filename, 600):
            for epoch_number, mi_epoch in measures.groupby(level=0):
                # Drop outer index level corresponding to the epoch.
                mi_epoch.index = mi_epoch.index.droplevel()

                scatter = self.fill_infoplane_subplot(scatter, mi_epoch)
                text.set_text(f'Epoch: {epoch_number}')

                acc, val_acc, acc_line, val_acc_line = self.fill_accuracy_subplot(
                    acc_line, val_acc_line, activations_summary, epoch_number,
                    acc, val_acc)

                writer.grab_frame()
Esempio n. 12
0
def ianimate(df,
             autoscale=True,
             ax=None,
             axis=0,
             filename=None,
             fps=5,
             kind=None,
             n=None,
             rx=None,
             ry=None,
             step=1,
             title=None):
    """ ianimate.

    Animate plots, output to jupyter notebook.

    :param df: pandas dataframe
    :param autoscale: bool, if True will adjust the scale as data is processed, else will pre-render full scale
    :param ax: matplotlib ax
    :param axis: 0 or 1 for horizontal or vertical data
    :param filename: file name to save the mp4 file to
    :param fps: frames per second - defaults to 5
    :param kind: pandas plot kind
    :param n: frame to render
    :param rx: remove x axis
    :param ry: remove y axis
    :param step: how many steps between frames
    :param title: optional, title for the plot
    :return: HTML video control widget for jupyter notebook
    """
    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.get_fig()

    if filename is None:
        filename = 'tmp.mp4'
    if n is None:
        n = df.shape[0]
    moviewriter = FFMpegWriter(fps=fps)
    with moviewriter.saving(fig, filename, dpi=100):
        for j in range(1, n, step):
            update_figure(df,
                          n=j,
                          ax=ax,
                          axis=axis,
                          autoscale=autoscale,
                          kind=kind,
                          rx=rx,
                          ry=ry,
                          title=title)
            moviewriter.grab_frame()
    return HTML("""
            <video width="640" height="480" controls loop>
              <source src="{}" type="video/mp4">
            </video>
        """.format(filename))
Esempio n. 13
0
def make_movie(fig, plot_fn, param_list, output='output.mp4'):
    from matplotlib.animation import FFMpegWriter
    writer = FFMpegWriter(fps=60)
    with writer.saving(fig, output, dpi=200):
        for n, param in enumerate(param_list):
            print(f'frame {n} / {len(param_list)}')
            plot_fn(fig, param)
            writer.grab_frame()
            fig.clf()
    print(f'writing {output}')
Esempio n. 14
0
def make_movie(fig, directories, output, plot_function, **kwargs):
    filename_lists = [directory_contents(d) for d in directories]
    writer = FFMpegWriter(fps=10)

    with writer.saving(fig, output, dpi=200):
        for filename_list in zip(*filename_lists):
            print(list(filename_list))
            plot_function(fig, filename_list, **kwargs)
            writer.grab_frame()
            fig.clf()
Esempio n. 15
0
def createVideo(hdf, videoIn, videoOut, minDuration, maxDuration):
    df = pd.read_hdf(hdf)
    if len(df) > minDuration - 1:
        scorer = df.columns.get_level_values(0)[0]
        bptsToPlot = [
            'proboscis1', 'proboscis2', 'head', 'thorax', 'abdomenC',
            'abdomenR', 'abdomenL', 'bottom', 'rightForeLeg1', 'rightForeLeg2',
            'rightForeLeg3', 'leftForeLeg1', 'leftForeLeg2', 'leftForeLeg3',
            'rightMidleg1', 'rightMidleg2', 'rightMidleg3', 'leftMidleg1',
            'leftMidleg2', 'leftMidleg3', 'rightHindleg1', 'rightHindleg2',
            'rightHindleg3', 'leftHindleg1', 'leftHindleg2', 'leftHindleg3'
        ]
        cmap = mpl.cm.get_cmap('plasma', len(bptsToPlot) + 2)
        start = df.first_valid_index()
        stop = df.last_valid_index()
        if stop - start > maxDuration:
            stop = start + maxDuration

        cap = cv2.VideoCapture(videoIn)
        fps = cap.get(cv2.CAP_PROP_FPS)
        cap.set(1, start)
        ret, frame = cap.read()
        (h, w) = frame.shape[:2]
        dpi = 100
        writer = FFMpegWriter(fps=fps, codec='h264')

        fig = plt.figure(frameon=False, figsize=(w / dpi, h / dpi))
        plt.set_cmap('plasma')

        with writer.saving(fig, videoOut, dpi=dpi):
            for i in tqdm(range(start, stop)):
                cap.set(1, i)
                ret, frame = cap.read()
                plt.imshow(frame)
                j = 0
                for ind in df.columns.get_level_values(1).unique():
                    for bp in bptsToPlot:
                        plt.scatter(df[scorer, ind, bp].x[i],
                                    df[scorer, ind, bp].y[i],
                                    color=cmap(j),
                                    alpha=0.75)
                        j += 1
                plt.axis('off')
                plt.subplots_adjust(left=0,
                                    bottom=0,
                                    right=1,
                                    top=1,
                                    wspace=0,
                                    hspace=0)
                writer.grab_frame()
                plt.clf()

        plt.close(fig)
Esempio n. 16
0
def tweening(df,
             filename,
             autoscale=True,
             axis=0,
             fps=5,
             kind=None,
             rx=None,
             ry=None,
             step=1,
             title=None,
             transitions=10):
    """ tweening.

    :param df: pandas dataframe, required
    :param filename: file name to save the mp4 file to, required
    :param autoscale: bool, if True will adjust the scale as data is processed, else will pre-render full scale
    :param axis: 0 or 1 for horizontal or vertical data
    :param fps: frames per second - defaults to 5
    :param kind: pandas plot kind
    :param rx: remove x axis
    :param ry: remove y axis
    :param step: how many steps between frames
    :param title: optional, title for the plot
    :param transitions: how many interimary values to generate
    :return: HTML video control widget for jupyter notebook
    """

    fig, ax = plt.subplots()
    nb_data_points = df.shape[0]
    moviewriter = FFMpegWriter(fps=fps)
    grayed = num_only(df)
    with moviewriter.saving(fig, filename, dpi=100):
        for j in range(0, nb_data_points - 1, step):
            dfj = df.iloc[j:]
            df_expanded = between_rows(dfj, n=transitions)
            for i in range(transitions):
                update_figure(df_expanded,
                              n=i,
                              ax=ax,
                              axis=axis,
                              autoscale=autoscale,
                              grayed=grayed,
                              j=j,
                              kind=kind,
                              rx=rx,
                              ry=ry,
                              title=title)
                moviewriter.grab_frame()
    return HTML("""
            <video width="640" height="480" controls loop>
              <source src="{}" type="video/mp4">
            </video>
        """.format(filename))
Esempio n. 17
0
def slice_vid(as_, points, slicer=_slicer3, iters=7, fname="slices of 3d.mp4"):
    '''Generate a 3D slicing video'''
    writer = FFMpegWriter(fps=4)
    fig = plt.figure()
    with writer.saving(fig, fname, 144):
        for a in as_:
            slice_ = slicer(points, iters, a)
            plt.imshow(slice_, cmap='inferno')
            plt.clim(0, iters - 1)
            plt.title(f"$\\Re(z) = {a}$")
            writer.grab_frame()
            plt.clf()
    print("\a")
Esempio n. 18
0
def make_movie(fig, plot_fn, args):
    from matplotlib.animation import FFMpegWriter

    writer = FFMpegWriter(fps=15)

    with writer.saving(fig, 'output.mp4', dpi=200):
        for filename in args.filenames:
            print(filename)
            plot_fn(fig, filename, args)
            writer.grab_frame()
            fig.clf()

    print('writing', 'output.mp4')
Esempio n. 19
0
def make_movie(filename):
    with h5py.File(filename, "r") as f:
        positions_t = np.array(f["positions_t"])
        theta_t = np.array(f["theta_t"])
        U_t = np.array(f["U_t"])
        alpha = np.array(f["alpha"])
        area_n = np.array(f["area_n"])[0]
        nrecord = np.array(f["nrecord"])[0]
        dt = np.array(f["dt"])[0]

    fbase = os.path.splitext(filename)[0]
    metadata = dict(title=fbase)
    writer = FFMpegWriter(fps=30, metadata=metadata)

    fig = plt.figure(figsize=[6.4, 6.4], dpi=100)
    with writer.saving(fig, fbase + ".mp4", 100):
        for i in range(0, positions_t.shape[0]):
            positions = positions_t[i, :, :]
            thetas = theta_t[i, :]
            U_n = U_t[i, :]

            normals = np.vstack([-np.sin(thetas), np.cos(thetas)]).T

            plt.plot(
                np.sqrt(area_n / np.pi) *
                np.hstack([np.cos(alpha), np.cos(alpha[0])]),
                np.sqrt(area_n / np.pi) *
                np.hstack([np.sin(alpha), np.sin(alpha[0])]),
                color="red",
            )
            plt.plot(
                np.hstack([positions[:, 0], positions[:, 0]]),
                np.hstack([positions[:, 1], positions[:, 1]]),
                color="blue",
            )
            plt.quiver(
                positions[:, 0],
                positions[:, 1],
                U_n * normals[:, 0],
                U_n * normals[:, 1],
                scale=2.5,
                color="blue",
                headwidth=1.5,
                headlength=2.5,
            )
            plt.xlim([-1.2, 1.2])
            plt.ylim([-1.2, 1.2])
            writer.grab_frame()

            plt.cla()
Esempio n. 20
0
def make_movie_impl(args, plot_fn, figsize=[16, 6]):
    from matplotlib.animation import FFMpegWriter

    dpi = 200
    res = 768

    writer = FFMpegWriter(fps=10)
    fig = plt.figure(figsize=figsize)

    with writer.saving(fig, args.output, dpi):
        for filename in args.filenames:
            print(filename)
            fig = plot_fn(fig, filename, edges=args.edges, depth=args.depth, **get_ranges(args))
            writer.grab_frame()
            fig.clf()
Esempio n. 21
0
 def writevideo(self):
     #print animation.writers.list()
     #matplotlib.rcParams['animation.ffmpeg_args'] = ['-report', '/tmp/ffmpeg.log']
     #FFMpegWriter = animation.writers['ffmpeg']
     metadata = dict(title='Github Data Projects',
                     artist='0x0FFF',
                     comment='Evolution of open source data projects')
     writer = FFMpegWriter(fps=30, bitrate=8000, metadata=metadata)
     i = 0
     #self.iters = 200
     with writer.saving(self.fig, "/projects/personal/writer_test.mp4",
                        120):
         while i < self.iters:
             self.update_animation(i)
             writer.grab_frame()
             i += 1
     return
Esempio n. 22
0
def plot_accuracy_development(history, _run):
    fig, ax = plt.subplots()
    writer = FFMpegWriter(fps=1)
    filename = "accuracy_movie.mp4"
    with writer.saving(fig, filename, 600):
        accuracy = history.history["accuracy"]
        x = list(range(1, len(accuracy) + 1))
        y = accuracy
        ax.set(xlim=[0.9, len(accuracy) + 0.1], ylim=[0, 1], xlabel="epoch", ylabel="accuracy")
        [acc_line] = ax.plot(x, y, "o-")

        for i in range(1, len(accuracy) + 1):
            acc_line.set_data(x[:i], y[:i])

            writer.grab_frame()

    _run.add_artifact(filename=filename, name="accuracy_movie")
Esempio n. 23
0
def make_movie(args):
    from matplotlib.animation import FFMpegWriter

    figsize = [15, 8]
    dpi = 200
    res = 768

    writer = FFMpegWriter(fps=10)
    fig = plt.figure(figsize=figsize)

    with writer.saving(fig, args.output, dpi):
        for filename in args.filenames:
            print(filename)
            # plot_single_file(args, fig, filename)
            plot_radial_profile(args, fig, filename)
            writer.grab_frame()
            fig.clf()
Esempio n. 24
0
 def writevideo(self):
     #print animation.writers.list()
     #matplotlib.rcParams['animation.ffmpeg_args'] = ['-report', '/tmp/ffmpeg.log']
     #FFMpegWriter = animation.writers['ffmpeg']
     metadata = dict(title='Github Data Projects', artist='0x0FFF',
                     comment='Evolution of open source data projects')
     writer = FFMpegWriter(fps=30,
                           bitrate=8000,
                           metadata=metadata
                          )
     i = 0
     #self.iters = 200
     with writer.saving(self.fig, "/projects/personal/writer_test.mp4", 120):
         while i < self.iters:
             self.update_animation(i)
             writer.grab_frame()
             i += 1
     return
Esempio n. 25
0
 def write_frames_from_log(self, logfile):
     stuff = np.load(logfile)
     filename = str(stuff['name']) + '.mp4'
     self.visualizer = Visualizer(int(stuff['ego_id']),
                                  stuff['LengthWidth'][:, 0],
                                  stuff['LengthWidth'][:, 1],
                                  int(stuff['num_cars']), self.road)
     metadata = dict(title=str(stuff['name']), artist='Pseudo', comment='')
     writer = FFMpegWriter(fps=2 * int(1. / Vehicle.DEL_T),
                           codec='libx264',
                           metadata=metadata,
                           extra_args=['-pix_fmt', 'yuv420p'])
     with writer.saving(self.visualizer.fig, filename,
                        self.visualizer.fig.dpi):
         for state in stuff['State_record']:
             self.visualizer.update(state[:, :3])
             writer.grab_frame()
     Scenario.flip_video(filename)
Esempio n. 26
0
def make_video_animation(num_frames, animation_function, output_name, fps=30):
    """
	fps: int 
	   frames per second for output video.
	animation_function:
		function that returs a frame given an index j.
	"""
    metadata = dict(title='Movie Test',
                    artist='IA',
                    comment='A.I. Dance Autotune')
    writer = FFMpegWriter(fps=fps, metadata=metadata)

    with writer.saving(fig, output_name + '.mp4', dpi=100):
        for j in tqdm(range(num_frames)):
            animation_function(j)
            writer.grab_frame()

    torch.cuda.empty_cache()
Esempio n. 27
0
def main():
    parser = ArgumentParser()
    # SVC hyper-parameters
    parser.add_argument('--C', type=float, default=10.0)
    parser.add_argument('--kernel',
                        type=str,
                        default='rbf',
                        choices=('linear', 'rbf'))
    parser.add_argument('--gamma', type=str, default='auto')
    # toy data config
    parser.add_argument('--n_samples_per_label', type=int, default=10)
    parser.add_argument('--seed', type=int, default=0)
    # Animation config
    parser.add_argument('--animation_command',
                        type=str,
                        default='save',
                        choices=('show', 'save'))
    parser.add_argument('--out_video_name', type=str, default='svc_smo.mp4')
    args = parser.parse_args()

    x, y = get_toy_data(n_features=2,
                        n_samples_per_label=args.n_samples_per_label,
                        seed=args.seed)

    clf = SVC(args.C, args.kernel, args.gamma)
    ani = SVCAnimator(clf, x, y)

    if args.animation_command == 'show':
        animation = FuncAnimation(ani.fig, ani.update)
        plt.show()
        return

    if args.animation_command == 'save':
        writer = FFMpegWriter()
        with writer.saving(ani.fig, args.out_video_name, dpi=100):
            t = 0
            while True:
                t += 1
                print(t)
                ani.update(t)
                writer.grab_frame()

                if ani.convergence:
                    break
    def animate(self, index, substance, time_idx):
        """create an mp4 movie for the substance for all time_idxteps (t)"""
        writer = FFMpegWriter(fps=15)
        assert (self.grids[index] != []), "No grids defined"
        substances = self.grids[index]['nc_file'].variables.keys()
        assert substance in substances, "Substance name not in: " + str(
            substances)

        lat = self.grids[index]['lat'][:]
        lon = self.grids[index]['lon'][:]
        # read variable substance from the file and get the array for depth_idx == 0
        substance_arr = self.grids[index]['nc_file'].variables[substance][
            time_idx, 0, :, :]
        img_info = self.create_image(lat, lon, substance_arr[0])

        with writer.saving(img_info['fig'], "%s.mp4" % (substance, ), 100):
            for idx in range(len(time_idx)):
                img_info['pcolor'].set_array(
                    substance_arr[idx, :-1, :-1].ravel())
                writer.grab_frame()
Esempio n. 29
0
def main():
    parser = ArgumentParser()
    parser.add_argument('--animation_command', type=str, default='show',
                        choices=('show', 'save'))
    args = parser.parse_args()

    gen = _data_generator(np.zeros(2), [2.2, 0.5], np.eye(2))
    kf = build_kf()
    sim = _ToySimulator(kf, gen)

    if args.animation_command == 'show':
        ani = FuncAnimation(sim.fig, sim.update)
        plt.show()
    elif args.animation_command == 'save':
        n_steps = 50
        video_file_name = 'kf.mp4'
        writer = FFMpegWriter()
        with writer.saving(sim.fig, video_file_name, dpi=100):
            for t in range(n_steps):
                sim.update(t)
                writer.grab_frame()
Esempio n. 30
0
def main():
    parser = ArgumentParser()
    # SVC hyper-parameters
    parser.add_argument('--C', type=float, default=10.0)
    parser.add_argument('--kernel', type=str, default='rbf',
                        choices=('linear', 'rbf'))
    parser.add_argument('--gamma', type=str, default='auto')
    # toy data config
    parser.add_argument('--n_samples_per_label', type=int, default=10)
    parser.add_argument('--seed', type=int, default=0)
    # Animation config
    parser.add_argument('--animation_command', type=str, default='save',
                        choices=('show', 'save'))
    parser.add_argument('--out_video_name', type=str, default='svc_smo.mp4')
    args = parser.parse_args()

    x, y = get_toy_data(n_features=2,
                        n_samples_per_label=args.n_samples_per_label,
                        seed=args.seed)

    clf = SVC(args.C, args.kernel, args.gamma)
    ani = SVCAnimator(clf, x, y)

    if args.animation_command == 'show':
        animation = FuncAnimation(ani.fig, ani.update)
        plt.show()
        return

    if args.animation_command == 'save':
        writer = FFMpegWriter()
        with writer.saving(ani.fig, args.out_video_name, dpi=100):
            t = 0
            while True:
                t += 1
                print(t)
                ani.update(t)
                writer.grab_frame()

                if ani.convergence:
                    break
Esempio n. 31
0
def run_agent(num_timesteps, record=False, title="recording_test.mp4"):
    done = False
    _ = env.reset()
    if record:
        print("recording a test run . . . ")
        fig = plt.figure()
        metadata = dict(title='Movie Test',
                        artist='Matplotlib',
                        comment='Movie support!')
        writer = FFMpegWriter(fps=15, metadata=metadata)
        with writer.saving(fig, title, 100):
            for i in range(num_timesteps):
                current_state = env.last_obs / 255
                action = int(q_func.get_best_action(current_state))
                obs, reward, done, _ = env.step(action)
                #next_state = obs/255
                #experience_replay.put((current_state, action, reward, next_state, done))
                plt.imshow(obs)
                writer.grab_frame()
                env.render(record=record)
                #i += 1
                if done:
                    _ = env.reset()

    else:
        for i in range(num_timesteps):
            current_state = env.last_obs / 255
            action = int(q_func.get_best_action(current_state))
            obs, reward, done, _ = env.step(action)
            next_state = obs / 255
            try:
                experience_replay.put(
                    (current_state, action, reward, next_state, done))
            except queue.Full as e:
                import pdb
                pdb.set_trace()
            env.render(record=record)
            #i += 1
            if done:
                _ = env.reset()
Esempio n. 32
0
class TwoDPlotter:
#TODO: Track real time between plots and maybe also loss?
    def __init__(self, x, y, saving=False):
        plt.ion()
        self.fig = plt.figure()
        self.real_ax = self.fig.subplots()
        self.real_ax.grid('both')
        plt.show()
        new_x = [i['x'] for i in x]
        self.real_ax.scatter(new_x,y, c='red', label='Training Data')
        self.points = self.real_ax.scatter([],[], c='green', label='Neural Net')
        self.fig.legend()
        
        self.cache = self.fig.canvas.copy_from_bbox(self.fig.bbox)
        self.fig.canvas.draw()

        self.saving = False
        if saving:
            self.writer = FFMpegWriter(fps=1)
            self.saving = True

    def __call__(self, new_x, new_y):
        new_x = [i['x'] for i in new_x]
        offsets = list(zip(new_x, new_y))
        self.points.set_offsets(offsets)
        self.update_blit()

        if self.saving:
            self.writer.grab_frame()

    def update_blit(self):
        self.fig.canvas.restore_region(self.cache)
        self.real_ax.draw_artist(self.points)
        self.fig.canvas.blit(self.fig.bbox)

    def save(self, filepath):
        if self.saving:
            return self.writer.saving(self.fig, filepath, 300)
        else:
            raise ValueError("Cannot save a plotter not configured to save")
    def plot(self, measures_summary):

        measures = measures_summary['measures_all_runs']

        os.makedirs('plots/', exist_ok=True)

        plt.set_cmap("hsv")
        fig, ax = plt.subplots()
        if self.dataset == 'datasets.mnist' or self.dataset == 'datasets.fashion_mnist':
            ax.set(xlim=[0, 14], ylim=[0, 3.5])
        else:
            ax.set(xlim=[0, 12], ylim=[0, 1])

        ax.set(xlabel='I(X;M)', ylabel='I(Y;M)')

        scatter = ax.scatter([], [], s=20, edgecolor='none')
        text = ax.text(0, 1.05, "", fontsize=12)

        num_layers = measures.index.get_level_values(1).nunique()
        layers_colors = np.linspace(0, 1, num_layers)

        writer = FFMpegWriter(fps=10)

        with writer.saving(fig, self.filename, 600):
            for epoch_number, mi_epoch in measures.groupby(level=0):
                # Drop outer index level corresponding to the epoch.
                mi_epoch.index = mi_epoch.index.droplevel()

                xmvals = mi_epoch['MI_XM']
                ymvals = mi_epoch['MI_YM']

                points = np.array([xmvals, ymvals]).transpose()
                colors = layers_colors[mi_epoch.index]

                scatter.set_offsets(points)
                scatter.set_array(colors)

                text.set_text(f"Epoch: {epoch_number}")

                writer.grab_frame()
Esempio n. 34
0
def animate_movie(db_fn: str, graph_movie_fn: str):
    # db_fn = r"E:\Simulations\CeramicBands\v7\pics\8X\history.db"
    movie_writer = ThisWriter(fps=30)

    sub_graph_flags = SubGraphs(force_disp=True,
                                surface_absolute=False,
                                surface_deviation=True,
                                columns_strain_x=True)
    fig, sub_graphs = create_subplots(sub_graph_flags)

    # fig.tight_layout()
    with movie_writer.saving(fig, graph_movie_fn, dpi=DPI_FIG):
        with history.DB(db_fn) as hist:
            top_nodes = _node_of_top_line(hist)

            if not top_nodes:
                # Empty DB - get out of here.
                return

            lims = get_limits_graphs(hist, top_nodes, sub_graphs)

            for db_res_case in sorted(hist.get_all(history.ResultCase)):
                print(db_res_case)

                graphed_something = compose_graphs(hist, top_nodes,
                                                   db_res_case.num, sub_graphs)

                # Set any global limits which have been assigned
                for ax in sub_graphs:
                    if ax and ax in lims:
                        x_lims, y_lims = lims[ax]

                        ax.set_xlim(x_lims)
                        ax.set_ylim(y_lims)

                fig.canvas.draw()
                fig.canvas.flush_events()
                if graphed_something:
                    movie_writer.grab_frame()