def _save_img_list(img_list, save_path, config): #_show_img_list(img_list) metadata = dict(title='generator images', artist='Matplotlib', comment='Movie support!') writer = ImageMagickWriter(fps=1,metadata=metadata) ims = [np.transpose(i, (1, 2, 0)) for i in img_list] fig, ax = plt.subplots() with writer.saving(fig, "%s/img_list.gif" % save_path,500): for i in range(len(ims)): ax.imshow(ims[i]) ax.set_title("step {}".format(i * config["save_every"])) writer.grab_frame()
class Visualization(object): """Helper class to visualize the progress of the GAN training procedure. """ def __init__(self, file_name, model_name, fps=15): """Initialize the helper class. :param fps: The number of frames per second when saving the gif animation. """ self.fps = fps self.figure, (self.ax2) = plt.subplots(1, 1, figsize=(5, 5)) self.figure.suptitle("{}".format(model_name)) sns.set(color_codes=True, style='white', palette='colorblind') sns.despine(self.figure) plt.show(block=False) self.real_data = Dataset() self.step = 0 self.writer = ImageMagickWriter(fps=self.fps) self.writer.setup(self.figure, file_name, dpi=100) def plot_progress(self, gen_net): """Plot the progress of the training procedure. This can be called back from the GAN fit method. :param gan: The GAN we are fitting. :param session: The current session of the GAN. :param data: The data object from which we are sampling the input data. """ real = self.real_data.next_batch(batch_size=10000) r1, r2 = self.ax2.get_xlim() x = np.linspace(r1, r2, 10000)[:, np.newaxis] g = gen_net(torch.FloatTensor(np.random.randn(10000, 1))) self.ax2.clear() self.ax2.set_ylim([0, 1]) self.ax2.set_xlim([0, 8]) sns.kdeplot(real.numpy().flatten(), shade=True, ax=self.ax2, label='Real data') sns.kdeplot(g.detach().numpy().flatten(), shade=True, ax=self.ax2, label='Generated data') self.ax2.set_title('Distributions') self.ax2.set_title('{} iterations'.format(self.step * 50)) self.ax2.set_xlabel('Input domain') self.ax2.set_ylabel('Probability density') self.ax2.legend(loc='upper left', frameon=True) self.figure.canvas.draw() self.figure.canvas.flush_events() self.writer.grab_frame() self.step += 1
def __init__(self, file_name, model_name, fps=15): """Initialize the helper class. :param fps: The number of frames per second when saving the gif animation. """ self.fps = fps self.figure, (self.ax2) = plt.subplots(1, 1, figsize=(5, 5)) self.figure.suptitle("{}".format(model_name)) sns.set(color_codes=True, style='white', palette='colorblind') sns.despine(self.figure) plt.show(block=False) self.real_data = Dataset() self.step = 0 self.writer = ImageMagickWriter(fps=self.fps) self.writer.setup(self.figure, file_name, dpi=100)
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)
def __init__(self, save_animation=False, fps=30): """Initialize the helper class. :param save_animation: Whether the animation should be saved as a gif. Requires the ImageMagick library. :param fps: The number of frames per second when saving the gif animation. """ self.save_animation = save_animation self.fps = fps self.figure, (self.ax1, self.ax2) = plt.subplots(1, 2, figsize=(8, 4)) self.figure.suptitle("1D GAAN") sns.set(color_codes=True, style='white', palette='colorblind') sns.despine(self.figure) plt.show(block=False) if self.save_animation: self.writer = ImageMagickWriter(fps=self.fps) self.writer.setup(self.figure, 'Toy_1D_GAAN.gif', dpi=100)
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()
def save_animation(self, fps=5, time=5, *, filename="robot_animation.gif"): original_position = self.theta number_of_frames = self.path.shape[1] frames_to_animate = fps * time if number_of_frames < frames_to_animate: step = 1 fps = max(1, time // number_of_frames) else: step = number_of_frames // frames_to_animate fig = plt.figure() robot_animation = ImageMagickWriter(fps=fps) with robot_animation.saving(fig, filename, dpi=150): for column in np.arange(start=0, stop=number_of_frames, step=step): self.theta = np.array(self.path[:, column]) self.plot(show=False) robot_animation.grab_frame() fig.clear() self._set_plot_options() self.theta = original_position # ?? plt.close()
def __init__(self, save_animation=False, fps=30): """Initialize the helper class. :param save_animation: Whether the animation should be saved as a gif. Requires the ImageMagick library. :param fps: The number of frames per second when saving the gif animation. """ self.save_animation = save_animation self.fps = fps self.figure, (self.ax1, self.ax2) = plt.subplots(1, 2, figsize=(8, 4)) self.figure.suptitle("1D GAAN") sns.set(color_codes=True, style='white', palette='colorblind') sns.despine(self.figure) plt.show(block=False) if self.save_animation: self.writer = ImageMagickWriter(fps=self.fps) self.writer.setup(self.figure, 'Toy_1D_GAAN.gif', dpi=100)
def _anim_rst(anim, image_path, gallery_conf): from matplotlib.animation import ImageMagickWriter # output the thumbnail as the image, as it will just be copied # if it's the file thumbnail fig = anim._fig image_path = image_path.replace('.png', '.gif') fig_size = fig.get_size_inches() thumb_size = gallery_conf['thumbnail_size'] use_dpi = round(min(t_s / f_s for t_s, f_s in zip(thumb_size, fig_size))) # FFmpeg is buggy for GIFs if ImageMagickWriter.isAvailable(): writer = 'imagemagick' else: writer = None anim.save(image_path, writer=writer, dpi=use_dpi) html = anim._repr_html_() if html is None: # plt.rcParams['animation.html'] == 'none' html = anim.to_jshtml() html = indent(html, ' ') return _ANIMATION_RST.format(html)
def display_frames_as_gif(dst_path, frames): """ Displays a list of frames as a gif, with controls """ plt.figure(figsize=(frames[0].shape[1] // 100, frames[0].shape[0] // 100)) patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) dst_path = Path(dst_path) ext = dst_path.suffix[1:] dst_path.parent.mkdir(parents=True, exist_ok=True) if ext == 'gif': writer = ImageMagickWriter() elif ext == 'mp4': writer = FFMpegWriter() else: raise ValueError anim = FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) anim.save(str(dst_path), writer=writer)
class Visualization(object): """Helper class to visualize the progress of the GAN training procedure. """ def __init__(self, save_animation=False, fps=30): """Initialize the helper class. :param save_animation: Whether the animation should be saved as a gif. Requires the ImageMagick library. :param fps: The number of frames per second when saving the gif animation. """ self.save_animation = save_animation self.fps = fps self.figure, (self.ax1, self.ax2) = plt.subplots(1, 2, figsize=(8, 4)) self.figure.suptitle("1D GAAN") sns.set(color_codes=True, style='white', palette='colorblind') sns.despine(self.figure) plt.show(block=False) if self.save_animation: self.writer = ImageMagickWriter(fps=self.fps) self.writer.setup(self.figure, 'Toy_1D_GAAN.gif', dpi=100) def plot_progress(self, gan, session, data): """Plot the progress of the training procedure. This can be called back from the GAN fit method. :param gan: The GAN we are fitting. :param session: The current session of the GAN. :param data: The data object from which we are sampling the input data. """ # Plot the training curve. steps = gan.log_interval * np.arange(len(gan.loss_d_curve)) self.ax1.clear() self.ax1.plot(steps, gan.loss_d_curve, label='D loss') self.ax1.plot(steps, gan.loss_g_curve, label='G loss') self.ax1.set_title('Learning curve') self.ax1.set_xlabel('Iteration') if gan.model == 'gan' or gan.model == 'rgan' or gan.model == 'mdgan' or gan.model == 'vaegan' or gan.model == 'gaan': title = 'Loss' elif gan.model == 'wgangp': title = 'Negative critic loss' self.ax1.set_ylabel(title) # Plot the generated and the input data distributions. g = gan.sample(session) r1, r2 = self.ax2.get_xlim() x = np.linspace(r1, r2, gan.n_sample)[:, np.newaxis] critic = gan.dreal(session, x) if gan.model == 'wgangp': # Normalize the critic to be in [0, 1] to make visualization easier. critic = (critic - critic.min()) / (critic.max() - critic.min()) d, _ = data.next_batch(gan.n_sample) if gan.model == 'gaan' or gan.model == 'rgan' or gan.model == 'mdgan': r = gan.reconstruct(session, d) e = gan.encode(session, d) self.ax2.clear() self.ax2.set_ylim([0, 1]) self.ax2.set_xlim([-8, 8]) if gan.model == 'gan' or gan.model == 'rgan' or gan.model == 'mdgan' or gan.model == 'gaan' or gan.model == 'vaegan': self.ax2.plot(x, critic, label='Decision boundary') elif gan.model == 'wgangp': self.ax2.plot(x, critic, label='Critic (normalized)') sns.kdeplot(d.flatten(), shade=True, ax=self.ax2, label='Real data') sns.kdeplot(g.flatten(), shade=True, ax=self.ax2, label='Generated data') self.ax2.set_title('Distributions') self.ax2.set_xlabel('Input domain') self.ax2.set_ylabel('Probability density') self.ax2.legend(loc='upper left', frameon=True) if len(steps) - 1 == gan.n_step // gan.log_interval: if self.save_animation: wait_seconds = 3 [ self.writer.grab_frame() for _ in range(wait_seconds * self.fps) ] self.writer.finish() plt.show() else: self.figure.canvas.draw() self.figure.canvas.flush_events() if self.save_animation: self.writer.grab_frame()
train_y = np.array(b) ax.scatter(train_x[:, 0], train_x[:, 1], train_x[:, 2], s=5, c=create_color_list(train_y)) scat = ax.scatter(weights[:, 0], weights[:, 1], weights[:, 2], c='k', marker='^') max_iterations = 100 learning_rate = 0.005 old_weights = np.zeros(weights.shape) writer = ImageMagickWriter(fps=4) file_name = "kohonens.gif" try: with writer.saving(fig, file_name, dpi=100): for k in range(max_iterations): neuron_class = 4 * np.ones(weight_size) print(k) random.shuffle(train_set) for x, y in train_set: d = np.zeros(weight_size) for i in range(weight_size): d[i] = np.linalg.norm(x - weights[i, :]) winner_index = np.argmin(d) neuron_class[winner_index] = y h = neighbor(k, winner_index) for j in range(weight_size):
def generate_rotating_pose(out_file, pose, joint_set, initial_func=None): """ Creates a gif that rotates the camera around `pose`. You might want to call ``plt.ioff()`` before using this function. Parameters: out_file: output file name pose: ndarray(nJoints,3), coordinates are in x, y, z order. Y grows downwards. joint_set: joint order of `pose` initial_func: if not None, a function that generates the initial plot that is going to be rotated. If provided, pose and joint_set must be NaN """ if initial_func is not None: assert pose is None, "if initial_func i set, pose must be None" assert joint_set is None, "if initial_func i set, joint_set must be None" start_azim = -190 end_azim = -0 azim_steps = 30 start_elev = 5 end_elev = 70 elev_steps = 15 total_steps = azim_steps * 2 + elev_steps * 2 def update(i): middle_azim = (start_azim + end_azim) / 2 middle_elev = (start_elev + end_elev) / 2 if i < azim_steps / 2: ax.view_init(azim=middle_azim + (start_azim - middle_azim) * i / azim_steps * 2, elev=middle_elev) if azim_steps / 2 <= i < azim_steps * 1.5: ax.view_init(azim=start_azim + (end_azim - start_azim) * (i - azim_steps / 2) / azim_steps, elev=middle_elev) elif azim_steps * 1.5 <= i < azim_steps * 2: ax.view_init(azim=end_azim + (middle_azim - end_azim) * (i - azim_steps * 1.5) / azim_steps * 2, elev=middle_elev) elif azim_steps * 2 <= i < azim_steps * 2 + elev_steps / 2: ax.view_init(azim=middle_azim, elev=middle_elev + (start_elev - middle_elev) * (i - azim_steps * 2) / elev_steps * 2) elif azim_steps * 2 + elev_steps / 2 <= i < azim_steps * 2 + elev_steps * 1.5: ax.view_init(azim=middle_azim, elev=start_elev + (end_elev - start_elev) * (i - azim_steps * 2 - elev_steps / 2) / elev_steps) elif azim_steps * 2 + elev_steps * 1.5 <= i: ax.view_init(azim=middle_azim, elev=end_elev + (middle_elev - end_elev) * (i - azim_steps * 2 - elev_steps * 1.5) / elev_steps * 2) def first_frame(): show3Dpose(pose, joint_set, ax, invert_vertical=True, linewidth=1, set_axis=False, hide_panes=False) RADIUS = 900 xroot, yroot, zroot = np.mean(pose[:, joint_set.index_of('hip'), :], axis=0) ax.set_xlim3d([-RADIUS + xroot, RADIUS + xroot]) ax.set_ylim3d([-RADIUS + zroot, RADIUS + zroot]) ax.set_zlim3d([-RADIUS + yroot, RADIUS + yroot]) ax.invert_zaxis() ax.set_aspect('equal') if initial_func is None: initial_func = first_frame ax = get_3d_axes() plt.tight_layout() fps = 10 anim = FuncAnimation(plt.gcf(), update, frames=total_steps, interval=1000 / fps, init_func=initial_func, repeat=False) writer = ImageMagickWriter(fps=fps) anim.save(out_file, writer=writer)
def animate(graphics, fig, n_steps=None, export_path='./', export_name='animation', overwrite=False, format='gif', fps=5, writer=None): """Animation helper function. Call this function with a configured :py:class:`Graphics` instance and the respective figure. This function will export an animation with the results from the :py:class:`do_mpc.data.Data` object. Either specify ``format`` and ``fps`` or supply a configured writer (e.g. ``ImageMagickWriter`` for gifs). :param graphics: Configured :py:class:`Graphics` instance. :type graphics: :py:class:`Graphics` :param fig: Matplotlib Figure. :type fig: Matplotlib Figure. :param n_steps: (Optional) number of time steps for the animation. :type n_steps: int :param export_path: (Optional) Path where to export the animation. Directory will be created if it doesn't exist. :type export_path: str :param export_name: (Optional) Name of the resulting animation (gif/mp4) file. :type export_name: str :param overwrite: (Optional) Check if export_name already exists in the supplied directory and overwrite or alter export_name. :type overwrite: bool :param format: (Optional) Choose between gif or mp4. :type format: str :param fps: (Optional) Frames per second for the resulting animation. :type fps: int :param writer: (Optional) If supplied, the ``fps`` and ``format`` argument are discarded. Use this to configure your own writer. :type writer: writer class :return: None """ if n_steps == None: n_steps = graphics.data['_time'].shape[0] def update(t_ind): print('Writing frame: {} of {}.'.format(t_ind, n_steps)) graphics.plot_results(t_ind=t_ind) graphics.plot_predictions(t_ind=t_ind) graphics.reset_axes() lines = graphics.result_lines.full + graphics.pred_lines.full return lines anim = FuncAnimation(fig, update, frames=n_steps, blit=True) if writer == None: if 'mp4' in format: writer = FFMpegWriter(fps=fps, extra_args=['-vcodec', 'libx264']) extension = 'mp4' elif 'gif' in format: writer = ImageMagickWriter(fps=fps) extension = 'gif' else: raise Exception( 'Invalid output format {}. Please choose mp4 or gif.'.format( format)) else: extension = '' if not os.path.exists(export_path): os.makedirs(export_path) # Dynamically generate new result name if name is already taken in result_path. if overwrite == False: ind = 1 ext_export_name = export_name while os.path.isfile(export_path + ext_export_name + '.pkl'): ext_export_name = '{ind:03d}_{name}'.format(ind=ind, name=export_name) ind += 1 export_name = ext_export_name anim.save('{}{}.{}'.format(export_path, export_name, extension), writer=writer)
class Visualization(object): """Helper class to visualize the progress of the GAN training procedure. """ def __init__(self, save_animation=False, fps=30): """Initialize the helper class. :param save_animation: Whether the animation should be saved as a gif. Requires the ImageMagick library. :param fps: The number of frames per second when saving the gif animation. """ self.save_animation = save_animation self.fps = fps self.figure, (self.ax1, self.ax2) = plt.subplots(1, 2, figsize=(8, 4)) self.figure.suptitle("1D GAAN") sns.set(color_codes=True, style='white', palette='colorblind') sns.despine(self.figure) plt.show(block=False) if self.save_animation: self.writer = ImageMagickWriter(fps=self.fps) self.writer.setup(self.figure, 'Toy_1D_GAAN.gif', dpi=100) def plot_progress(self, gan, session, data): """Plot the progress of the training procedure. This can be called back from the GAN fit method. :param gan: The GAN we are fitting. :param session: The current session of the GAN. :param data: The data object from which we are sampling the input data. """ # Plot the training curve. steps = gan.log_interval * np.arange(len(gan.loss_d_curve)) self.ax1.clear() self.ax1.plot(steps, gan.loss_d_curve, label='D loss') self.ax1.plot(steps, gan.loss_g_curve, label='G loss') self.ax1.set_title('Learning curve') self.ax1.set_xlabel('Iteration') if gan.model == 'gan' or gan.model == 'rgan' or gan.model == 'mdgan' or gan.model == 'vaegan' or gan.model == 'gaan': title = 'Loss' elif gan.model == 'wgangp': title = 'Negative critic loss' self.ax1.set_ylabel(title) # Plot the generated and the input data distributions. g = gan.sample(session) r1,r2 = self.ax2.get_xlim() x = np.linspace(r1, r2, gan.n_sample)[:, np.newaxis] critic = gan.dreal(session, x) if gan.model == 'wgangp': # Normalize the critic to be in [0, 1] to make visualization easier. critic = (critic - critic.min()) / (critic.max() - critic.min()) d, _ = data.next_batch(gan.n_sample) if gan.model == 'gaan' or gan.model == 'rgan' or gan.model == 'mdgan': r = gan.reconstruct(session, d) e = gan.encode(session, d) self.ax2.clear() self.ax2.set_ylim([0, 1]) self.ax2.set_xlim([-8, 8]) if gan.model == 'gan' or gan.model == 'rgan' or gan.model == 'mdgan' or gan.model == 'gaan' or gan.model == 'vaegan': self.ax2.plot(x, critic, label='Decision boundary') elif gan.model == 'wgangp': self.ax2.plot(x, critic, label='Critic (normalized)') sns.kdeplot(d.flatten(), shade=True, ax=self.ax2, label='Real data') sns.kdeplot(g.flatten(), shade=True, ax=self.ax2, label='Generated data') self.ax2.set_title('Distributions') self.ax2.set_xlabel('Input domain') self.ax2.set_ylabel('Probability density') self.ax2.legend(loc='upper left', frameon=True) if len(steps) - 1 == gan.n_step // gan.log_interval: if self.save_animation: wait_seconds = 3 [self.writer.grab_frame() for _ in range(wait_seconds * self.fps)] self.writer.finish() plt.show() else: self.figure.canvas.draw() self.figure.canvas.flush_events() if self.save_animation: self.writer.grab_frame()
ax.annotate( 'Source:Johns Hopkins School of Public Health\nCode:https://github.com/kriskirimi/Covid2019EA', fontsize=7.5, color='#6b6a6a', style='italic', xy=(0, 0), xycoords=('axes fraction'), textcoords=('offset points'), xytext=((00, -52))) def animate(i): line1.set_data(x[:i], y1[:i]) line2.set_data(x[:i], y2[:i]) line3.set_data(x[:i], y3[:i]) line4.set_data(x[:i], y4[:i]) line5.set_data(x[:i], y5[:i]) line6.set_data(x[:i], y6[:i]) line7.set_data(x[:i], y7[:i]) line8.set_data(x[:i], y8[:i]) return [line1, line2, line3, line4, line5, line6, line7, line8] ani = FuncAnimation(fig, animate, frames=len(x), interval=400) writer = ImageMagickWriter(fps=20) ani.save( r'C:\Users\KIRIMI\Documents\GitHub\Covid2019EA\EA Covid19 Confirmed Cases.gif', writer='imagemagick') plt.show() # plt.claose()
ax.set_yticks([]) im = ax.imshow(get_mode(modes, 0), animated=True) def update(frame): img = get_mode(modes, frame) vmin, vmax = get_data_range(img) im.set_clim(vmin, vmax) im.set_array(img) ax.collections = [] ax.contour(img, np.arange(-.01, .01, .0025), colors='black', linewidths=1) ax.add_artist(plt.Circle((49, 99), 25, color='black', zorder=10)) return im, ani = FuncAnimation(fig, update, modes.shape[1], blit=True) ani.save(OUTPUT_DIR + 'dmd_cylinder_modes.gif', ImageMagickWriter()) # %% Benchmarks PEViD NUM_WARMUPS = 3 NUM_RUNS = 3 NUM_STEPS = 3 resolutions = [(3840, 2160), (2560, 1440), (1920, 1080), (1280, 720), (960, 540), (640, 360)] widths = [120, 100, 80, 60, 40, 20] res_fixed = (1920, 1080) width_fixed = 80 fns = [lib.svd, lib.dmd, lib.bgs] fns_update = [lib.svd_update, lib.dmd_update, lib.bgs_update] idx = pd.MultiIndex.from_product([['svd', 'dmd', 'bgs'], ['cpu', 'gpu'], ['stat', 'strm'], range(NUM_RUNS + 1)]) def run_benchmark(x, times):
ax[1].legend(label_lines, ['T_R', 'T_K']) fig.align_ylabels() fig.tight_layout() output_format = 'gif' def update(t_ind): print('Writing frame: {}.'.format(t_ind)) mpc_graphics.plot_results(t_ind=t_ind) mpc_graphics.plot_predictions(t_ind=t_ind) mpc_graphics.reset_axes() lines = mpc_graphics.result_lines.full return lines n_steps = results['mpc']['_time'].shape[0] anim = FuncAnimation(fig, update, frames=n_steps, blit=True) if 'mp4' in output_format: FFWriter = FFMpegWriter(fps=5, extra_args=['-vcodec', 'libx264']) anim.save('anim.mp4', writer=FFWriter) elif 'gif' in output_format: gif_writer = ImageMagickWriter(fps=5, extra_args=['-MAGICK_MEMORY_LIMIT 4GiB']) anim.save('anim.gif', writer=gif_writer) else: plt.show()
line_i.set_linewidth(5) # Add labels label_lines = mpc_graphics.result_lines[ '_x', 'C_a'] + mpc_graphics.result_lines['_x', 'C_b'] ax[0].legend(label_lines, ['C_a', 'C_b']) label_lines = mpc_graphics.result_lines[ '_x', 'T_R'] + mpc_graphics.result_lines['_x', 'T_K'] ax[1].legend(label_lines, ['T_R', 'T_K']) fig.align_ylabels() from matplotlib.animation import FuncAnimation, ImageMagickWriter def update(t_ind): print('Writing frame: {}.'.format(t_ind), end='\r') mpc_graphics.plot_results(t_ind=t_ind) mpc_graphics.plot_predictions(t_ind=t_ind) mpc_graphics.reset_axes() lines = mpc_graphics.result_lines.full return lines n_steps = mpc.data['_time'].shape[0] anim = FuncAnimation(fig, update, frames=n_steps, blit=False) gif_writer = ImageMagickWriter(fps=5) anim.save('anim_CSTR.gif', writer="imagemagick")
# Load the model and an example model = LevelSetMachineLearning.load('./LSML-model.pkl') example = model.testing_data[13] # Set up plotting for the movie frames fig, ax = plt.subplots(1, 1, figsize=(2, 2)) ax.axis('off') ax.imshow(example.img, cmap=plt.cm.gray, interpolation='bilinear') lines = [] # Set up the movie writer and grab the frame at initialization writer = ImageMagickWriter(fps=5) writer.setup(fig, 'evolution.gif', 100) writer.grab_frame() # Define the callback function to be used during segmentation evolution def update_movie(i, u): if i % 10 != 0: return for line in lines: line.remove() lines.clear() lines.extend(