Esempio n. 1
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. 2
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. 3
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. 4
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()
Esempio n. 5
0
    def add_figure(self, fig=None):
        """adds the figure `fig` as a frame to the current movie

        Args:
            fig (:class:`~matplotlib.figures.Figure`):
                The plot figure that is added to the movie
        """
        if fig is None:
            import matplotlib.pyplot as plt

            fig = plt.gcf()

        if self._writer is None:
            # initialize a new writer
            from matplotlib.animation import FFMpegWriter

            self._writer = FFMpegWriter(self.framerate, **self.kwargs)
            self._writer.setup(fig, self.filename, dpi=self.dpi)

        else:
            # update the figure reference on a given writer, since it might have
            # changed from the last call. In particular, this will happen when
            # figures are shown using the `inline` backend.
            self._writer.fig = fig

        # we need to impose a white background to get reasonable antialiasing
        self._writer.grab_frame(facecolor="white")
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 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()
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. 9
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. 10
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. 11
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)
Esempio n. 12
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. 13
0
 def __init__(self, figNumber, outfile):
     #self.fig = plt.gcf()    #assuming we are focused on 1 plt
     self.fig = plt.figure(figNumber)
     metadata = dict(title='Movie Test',
                     artist='Matplotlib',
                     comment='Movie support!')
     self.writer = FFMpegWriter(fps=15, metadata=metadata)
     self.writer.setup(self.fig, outfile, dpi=100)
Esempio n. 14
0
    def setup_movie(self, fig):
        # create moviewriter
        # then setup
        # self.movieopt.pop()

        # fps=5, codec=None, bitrate=None, extra_args=None, metadata
        self.moviewriter = FFMpegWriter(**self.movieopt)
        self.moviewriter.setup(fig, self.outfile, self.dpi)
Esempio n. 15
0
class Video:
    ''' Writer for a video recording of the real time plot. '''
    def __init__(self, name='recording.mp4', fps=10):
        self.name = name
        self.writer = FFMpegWriter(fps=fps)

    def setup(self, fig):
        self.writer.setup(fig, self.name)
Esempio n. 16
0
    def save_animation(self, filename: str = None):
        if self._animation is None:
            return
        self._animation.pause()
        if filename is None:
            filename, format_str = QtWidgets.QFileDialog.getSaveFileName(
                self,
                self.
                tr("Choose a filename to save the animation of this SSU result"
                   ), ".",
                "MPEG-4 Video File (*.mp4);;Html Animation (*.html);;Graphics Interchange Format (*.gif)"
            )
        if filename is None or filename == "":
            return
        progress_dialog = QtWidgets.QProgressDialog(
            self.tr("Saving Animation Frames..."), self.tr("Cancel"), 0, 100,
            self)
        progress_dialog.setWindowTitle("QGrain")
        progress_dialog.setWindowModality(QtCore.Qt.WindowModal)

        def callback(frame_number, total_frames):
            if progress_dialog.wasCanceled():
                raise StopIteration()
            progress_dialog.setValue(int(frame_number / total_frames * 100))
            QtCore.QCoreApplication.processEvents()

        try:
            if filename[-5:] == ".html":
                if not FFMpegWriter.isAvailable():
                    self.show_error(self.tr("FFMpeg is not installed."))
                else:
                    self.show_info(
                        self.
                        tr("Rendering the animation to a html5 video, it will take several minutes."
                           ))
                    html = self._animation.to_html5_video()
                    with open(filename, "w") as f:
                        f.write(html)
            elif filename[-4:] == ".gif":
                if not ImageMagickWriter.isAvailable():
                    self.show_error(self.tr("ImageMagick is not installed."))
                else:
                    self._animation.save(filename,
                                         writer="imagemagick",
                                         fps=10,
                                         progress_callback=callback)
            elif filename[-4:] == ".mp4":
                if not FFMpegWriter.isAvailable():
                    self.show_error(self.tr("FFMpeg is not installed."))
                else:
                    self._animation.save(filename,
                                         writer="ffmpeg",
                                         fps=10,
                                         progress_callback=callback)
        except StopIteration:
            self.logger.info("The saving task was canceled.")
        finally:
            progress_dialog.close()
Esempio n. 17
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. 18
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. 19
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. 20
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. 21
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. 22
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. 23
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')
    def __init__(self,
                 env,
                 fps=1000,
                 by_episode=False,
                 save_video=False,
                 directory=''):
        self.env = env
        self.fps = fps
        self.by_episode = by_episode
        self.rewards = np.zeros(self.env.num_players)
        # Num_players + 1 for the average reward:
        self.rewards_data = [[[], [], []]
                             for _ in range(self.env.num_players + 1)]

        # Fig 1 = env map
        # Fig 2 = players rewards
        self.fig = plt.figure(figsize=(self.UNIT_SIZE,
                                       self.UNIT_SIZE * self.ROWS))
        # self.fig.subplots_adjust(
        # left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)

        self.save_video = save_video
        if self.save_video:
            self.dir = directory
            self.metadata = dict(title='Movie Test',
                                 artist='Matplotlib',
                                 comment='Movie support!')
            self.writer = FFMpegWriter(fps=10, metadata=self.metadata)
            self.writer.setup(self.fig, self.dir + 'game.mp4', 300)

        # player colors for plot:
        self.average_color = (0, 0, 0)
        self.players_colors = []
        for player_name in self.env.players_order:
            player_color = [(255 + c) / (2 * 255)
                            for c in self.env.players[player_name].color]
            self.players_colors.append(player_color)

        self._init_game()
        self._init_rewards()

        self._eps = 0.1
        self._min = 0
        self._max = 0

        self.env_episodes = 0
        self.freq = 1 / self.fps

        self.fig.tight_layout()
        plt.ion()
        plt.show(block=False)
Esempio n. 25
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. 26
0
    def __init__(self, size):
        self.fig = plt.figure()
        self.ax = plt.subplot(111)
        self.ax.set_title('Ez')
        self.ax.set_xlabel('x (nm)')
        self.ax.set_ylabel('y (nm)')
        self.img = self.ax.imshow(np.zeros(size),
                                  extent=(0, 3000, 0, 3000),
                                  cmap='RdBu',
                                  vmin=-0.5,
                                  vmax=0.5,
                                  origin='lower')
        # self.fig.show()

        self.writer = FFMpegWriter(fps=60, bitrate=5000)
Esempio n. 27
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. 28
0
 def render(images, isColor, frame_rate, save, fileNameOut):
     """
     Render the given images, and either save the output or
     not based on the input parameter. If animation output is
     to be saved, it is named according to the input variable
     fileNameOut.
     :param images:
     :param isColor:
     :param frame_rate:
     :param save:
     :param fileNameOut:
     :return:
     """
     f = plt.figure()
     film = []
     for frame in images:
         if isColor:
             film.append([plt.imshow(frame)])
         else:
             film.append([plt.imshow(frame, 'gray_r')])
     a = animation.ArtistAnimation(f,
                                   film,
                                   interval=frame_rate,
                                   blit=True,
                                   repeat_delay=100)
     if save:
         writer = FFMpegWriter(fps=frame_rate,
                               metadata=dict(artist='Me'),
                               bitrate=1800)
         a.save(fileNameOut, writer=writer)
     plt.show()
Esempio n. 29
0
 def save_animation(self):
     if self.last_result is not None:
         filename, format_str = self.file_dialog.getSaveFileName(self, self.tr("Save the animation of this SSU result"), None, self.tr("MPEG-4 Video File (*.mp4);;Graphics Interchange Format (*.gif)"))
         if filename is None or filename == "":
             return
         progress = QProgressDialog(self)
         progress.setRange(0, 100)
         progress.setLabelText(self.tr("Saving Animation [{0} Frames]").format(self.last_result.n_iterations))
         canceled = False
         def save_callback(i, n):
             if progress.wasCanceled():
                 nonlocal canceled
                 canceled = True
                 raise StopIteration()
             progress.setValue((i+1)/n*100)
             QCoreApplication.processEvents()
         self.show_result(self.last_result)
         # plt.rcParams["savefig.dpi"] = 120.0
         if "*.gif" in format_str:
             if not ImageMagickWriter.isAvailable():
                 self.normal_msg.setWindowTitle(self.tr("Error"))
                 self.normal_msg.setText(self.tr("ImageMagick is not installed, please download and install it from its offical website (https://imagemagick.org/index.php)."))
                 self.normal_msg.exec_()
             else:
                 self.animation.save(filename, writer="imagemagick", fps=30, progress_callback=save_callback)
         elif "*.mp4" in format_str:
             if not FFMpegWriter.isAvailable():
                 self.normal_msg.setWindowTitle(self.tr("Error"))
                 self.normal_msg.setText(self.tr("FFMpeg is not installed, please download and install it from its offical website (https://ffmpeg.org/)."))
                 self.normal_msg.exec_()
             else:
                 self.animation.save(filename, writer="ffmpeg", fps=30, progress_callback=save_callback)
         # plt.rcParams["savefig.dpi"] = 300.0
         if not canceled:
             progress.setValue(100)
Esempio n. 30
0
def draw_walks_in_parallel(walk_data, state, erase, save):
    f = plt.figure()
    film = []

    nk = len(walk_data.keys())
    ns = len(walk_data[walk_data.keys().pop()])
    print "N Walkers: " + str(nk)
    print "N Steps: " + str(ns)

    for i in range(ns):
        for step in range(nk):
            if erase and i >= 1:
                try:
                    s = walk_data[step][i-1]
                    state[s[0], s[1]] = 0
                except IndexError:
                    continue
            try:
                step = walk_data[step][i]
                state[step[0], step[1]] = 1
            except IndexError:
                continue
        film.append([plt.imshow(state, 'gray')])
    a = animation.ArtistAnimation(f,film,interval=80,blit=True,repeat_delay=900)
    if save['do']:
        w = FFMpegWriter(fps=save['fps'],bitrate=1800)
        a.save(save['name'],w)
    plt.show()
    plt.close()
    return film
Esempio n. 31
0
    def __init__(self,
                 filename: str,
                 framerate: float = 30,
                 dpi: float = None,
                 **kwargs):
        r"""
        Args:
            filename (str):
                The filename where the movie is stored. The suffix of this path
                also determines the default movie codec.
            framerate (float):
                The number of frames per second, which determines how fast the
                movie will appear to run.
            dpi (float):
                The resolution of the resulting movie
            \**kwargs:
                Additional parameters are used to initialize
                :class:`matplotlib.animation.FFMpegWriter`.
        """
        self.filename = str(filename)
        self.framerate = framerate
        self.dpi = dpi
        self.kwargs = kwargs

        # test whether ffmpeg is available
        from matplotlib.animation import FFMpegWriter
        if not FFMpegWriter.isAvailable():
            raise RuntimeError('FFMpegWriter is not available. This is most '
                               'likely because a suitable installation of '
                               'FFMpeg was not found. See ffmpeg.org for how '
                               'to install it properly on your system.')

        self._writer = None
Esempio n. 32
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. 33
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. 34
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