def _render_mst_complex(self, g: Graph, trace: Edges, gifpath=None): g_nx = self._converter.graph_to_nx_graph(g) g_weighthed_edges = self._converter.weighted_edges(g) pos = nx.spring_layout(g_nx, k=0.4) def _init(): self._ax.set_title(f'initial graph') nx.draw_networkx(g_nx, pos=pos, with_labels=True, node_color=GraphRenderer.NODE_COLOR) nx.draw_networkx_edges(g_nx, pos, edge_color=GraphRenderer.G_EDGE_COLOR, width=GraphRenderer.EDGE_WIDTH, arrows=False, ax=self._ax) nx.draw_networkx_edge_labels( g_nx, pos, edge_labels=g_weighthed_edges, font_color=GraphRenderer.G_EDGE_LABEL_COLOR, ax=self._ax) def _update(frame): self._ax.set_title( f'step {frame + 1}. - edge {trace[frame]} added to the tree') edgelist = [edge for edge, _ in trace[:frame + 1]] edge_labels = {edge: w for edge, w in trace[:frame + 1]} nx.draw_networkx_edges(g_nx, pos, edgelist=edgelist, edge_color=GraphRenderer.MST_EDGE_COLOR, width=GraphRenderer.EDGE_WIDTH, arrows=False, ax=self._ax) nx.draw_networkx_edge_labels( g_nx, pos, edge_labels=edge_labels, font_color=GraphRenderer.MST_EDGE_LABEL_COLOR, ax=self._ax) self.ani = FuncAnimation(self._fig, _update, frames=len(trace), init_func=_init, interval=GraphRenderer.FRAME_INTERVAL, repeat=False) if gifpath: writer = PillowWriter(fps=GraphRenderer.GIF_FPS) self.ani.save(gifpath, writer=writer) plt.axis('off') plt.show()
def animation(self, save_animation=True): """Function to create animation of evolution u matrix using the saved frames. Argumetns: ----------------- save_animation: bool - If true, save animation to gif file """ fig = plab.figure() plt.rcParams['figure.figsize'] = (10, 10) plab.pcolormesh(self.u_mat, cmap=plab.cm.RdBu) def animate(i): """Plotting function for animation""" if i < self.save_u_mat.shape[0]: plab.pcolormesh(np.squeeze(self.save_u_mat[i, :, :]), cmap=plab.cm.RdBu) anim = animation.FuncAnimation(fig, animate, frames=range(self.save_u_mat.shape[0]), blit=False) writer = PillowWriter(fps=20) filename_an = f'u_matrix_F={self.F}_k={self.k}.gif' plab.xlabel('u_1') plab.ylabel('u_2') plab.title( f'u matrix, F={self.F}, k={self.k} after {self.n_times} iterations.' ) if save_animation: anim.save(filename_an, writer=writer)
def predator_prey(n_gens, r, p, d, prop_prey, prop_pred, env_rows, env_cols): env = initial_env(env_rows, env_cols, prop_prey, prop_pred) prey_list = [] prey_list.append(count_species(env, 1)) pred_list = [] pred_list.append(count_species(env, 2)) for gen in range(n_gens): for i in range((env_rows * env_cols) // 3): reproduction(env, r) predation(env, p) starvation(env, d) prey_list.append(count_species(env, 1)) pred_list.append(count_species(env, 2)) # Display environment will save the resulting env into an image display_env(env) # Will contain the animation (GIF) based on the image generated at every generation ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=500) # Saves the GIF writer = PillowWriter(fps=20) ani.save("population.gif", writer=writer)
def cubetogif2(cube, gif_name, gsize, gap, nfps): fig = plt.figure(figsize=(gsize, gsize)) zsize = cube.shape[0] xsize = cube.shape[1] ysize = cube.shape[2] zv = zsize // gap frames = [] for i in range(zv): fn = i * gap data = cube[fn, :, :] im = plt.imshow(data, animated=True, cmap='gray') text = plt.text(xsize * 0.15, ysize * 0.85, '{:0>4d}'.format(fn), fontsize=18, style='italic', ha='left', va='bottom', wrap=True) frames.append([im, text]) ani = animation.ArtistAnimation(fig, frames, interval=100, blit=True, repeat_delay=1000) writer = PillowWriter(fps=nfps, metadata=dict(artist='Me'), bitrate=1800) ani.save(gif_name, writer=writer) return ani
def animate(self, speed, frames, save=False): self.fig = plt.figure(figsize=(8, 8)) self.anim = FuncAnimation(self.fig, self.update, frames=frames) if save == True: self.anim.save('lattice_animation.gif', writer=PillowWriter(fps=24)) plt.show()
def play_animation() -> None: """ Creates an animation or "slide show" of plotted results in the GUI """ ani = FuncAnimation(f, update, 19, interval=40, blit=True) writer = PillowWriter(fps=25) ani.save("test.gif", writer=writer)
def k_means(Laplacian, image, k, name, way): methods = ['random', 'k-means++'] images = [] fig = plt.figure() for method in methods: C, classification = initialization(Laplacian, k, method) iteration = 0 while True: prev_classification = classification iteration += 1 images = plot_result(classification, images) classification = classify(Laplacian, C, k) if np.array_equal(prev_classification, classification) or iteration >= 100: break C = update_C(Laplacian, classification, k) images = plot_result(classification, images) animate = animation.ArtistAnimation(fig, images, interval=500, repeat_delay=1000) animate.save(os.path.join(f'./{method}_{name}_{k}_{way}.gif'), writer=PillowWriter(fps=20)) plot_eigenspace(Laplacian, classification, k, method, way, name)
def HalfPlateExample(): n = 30 grid = None dE_func = lambda i, j: 2 * grid.grid[i][ j] if i < n // 2 else -2 * grid.grid[i][j] grid = ExternalGrid(n, t_func=2.0, dE_func=dE_func) ims = [] fig = plt.figure() for i in range(100): for j in range(1000): grid.metro() ims.append([plt.imshow(grid.grid, clim=(0, 1)), plt.text(0.9, 1.2, i)]) ani = animation.ArtistAnimation(fig, ims, interval=100, blit=True, repeat_delay=0) ani.save("series.gif", writer=PillowWriter(fps=10))
def dirfitstogif2(dirname, gif_name, gsize, gap, nfps): fig = plt.figure(figsize=(gsize, gsize)) files = file_search(dirname, ['.fits']) zsize = len(files) head = fits.getheader(files[0]) xsize = head['NAXIS1'] ysize = head['NAXIS2'] zv = zsize // gap frames = [] for i in range(zv): fn = i * gap data = fits.getdata(files[i]) im = plt.imshow(data, animated=True, cmap='gray') text = plt.text(xsize * 0.15, ysize * 0.85, '{:0>4d}'.format(fn), fontsize=18, style='italic', ha='left', va='bottom', wrap=True) frames.append([im, text]) ani = animation.ArtistAnimation(fig, frames, interval=100, blit=True, repeat_delay=1000) writer = PillowWriter(fps=nfps, metadata=dict(artist='Me'), bitrate=1800) ani.save(gif_name, writer=writer) return ani
def pressure_vis(start_hour=0, length=100, height=2): current_dir = os.path.dirname(os.path.realpath(__file__)) save_dir = os.path.join(current_dir, '../experiment/plot/wind', 'pressure.gif') data = xr.open_dataset(args['1grid_data']) lon = np.array(data['longitude'].values) lat = np.array(data['latitude'].values) lon_grid, lat_grid = np.meshgrid(lon, lat, ) geo = data['z'][start_hour, height].values fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={"projection": "3d"}) fig.set_tight_layout(True) surf = ax.plot_surface(lon_grid, lat_grid, geo, cmap=cm.coolwarm, linewidth=0, antialiased=False) fig.colorbar(surf, shrink=0.5, aspect=5) ax.set_zlim(29000, 32000) ax.view_init(15, -20) def animate(t): # Delete the existing contour ax.collections = [] # Plot the ith contour ax.plot_surface(lon_grid, lat_grid, data['z'][t, height].values, cmap=cm.coolwarm, linewidth=0, antialiased=False) anim = FuncAnimation(fig, animate, frames=np.arange(start_hour, start_hour + length), interval=50, repeat=False) anim.save(save_dir, dpi=100, writer=PillowWriter(fps=10)) fig.show()
def wind_vis(start_hour=0, length=100): current_dir = os.path.dirname(os.path.realpath(__file__)) save_dir = os.path.join(current_dir, '../experiment/plot/wind', 'wind.gif') data = xr.open_dataset(args['1grid_data']) lon = np.array(data['longitude'].values) lat = np.array(data['latitude'].values) lon_grid, lat_grid = np.meshgrid(lon, lat, ) u = data['v'][start_hour, 0].values v = data['v'][start_hour, 0].values # # ax = fig.gca(projection='3d') fig, ax = plt.subplots(figsize=(12, 12)) fig.set_tight_layout(True) # arrow = ax.quiver(lon_grid, lat_grid, u, v, units='width') def update(t): label = 'timestep {0}'.format(t) now_date = startdate + datetime.timedelta(days=int(t / 4), hours=6 * int(t % 4)) print(now_date.strftime("%Y-%m-%d, %H:%M:%S")) u = data['v'][t, 0].values v = data['v'][t, 0].values arrow.set_UVC(u, v) return arrow, anim = FuncAnimation(fig, update, frames=np.arange(start_hour, start_hour + length), interval=50, repeat=False) anim.save(save_dir, dpi=100, writer=PillowWriter(fps=10)) fig.show()
def plot_p_gif(): """ x,yのgrid格子をベースに,時間tが変化していったときの圧力分布を gifとして出力する. :return: """ fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title("Time") ims = [] for i in range(0, 250): print(i) p_np_part = read_p_csv("./rectangular/data/p" + str(1 + i * 40) + ".csv") p_np.append(p_np_part) im = plt.imshow(p_np[-1], extent=[np.min(x), np.max(x), np.min(y), np.max(y)], vmin=-0.1, vmax=0.1) # vmin,vmaxで等高線のカラーリングを調整 ims.append([im]) anim = animation.ArtistAnimation(fig, ims, interval=20, blit=False) anim.save('./rectangular/karman_rect.gif', writer=PillowWriter()) plt.show()
def make_animated_gif(sim, idx): from matplotlib.animation import FuncAnimation, PillowWriter fs = USGSFigure(figure_type="map", verbose=False) sim_name = example_name sim_ws = os.path.join(ws, sim_name) gwf = sim.get_model("flow") gwt = sim.get_model("trans") cobj = gwt.output.concentration() times = cobj.get_times() times = np.array(times) conc = cobj.get_alldata() fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(1, 1, 1, aspect="equal") pxs = flopy.plot.PlotCrossSection(model=gwf, ax=ax, line={"row": 0}) pc = pxs.plot_array(conc[0], cmap="jet", vmin=conc_inflow, vmax=conc_sat) def init(): ax.set_xlim(0, 75.0) ax.set_ylim(0, 75.0) ax.set_title("Time = {} seconds".format(times[0])) def update(i): pc.set_array(conc[i].flatten()) ax.set_title("Time = {} seconds".format(times[i])) ani = FuncAnimation(fig, update, range(1, times.shape[0]), init_func=init) writer = PillowWriter(fps=50) fpth = os.path.join("..", "figures", "{}{}".format(sim_name, ".gif")) ani.save(fpth, writer=writer) return
def animate(u, total_time, filename=""): # pragma: no cover """ Creates an animation of u :param u: frames to show :type u: list of 2d numpy arrays :param total_time: total time over which the animation should run :type total_time: float :param filename: file to which to save the animation, if no filename is provided, the animation will not be saved :type filename: string :return: """ fig = plt.figure() ims = [] # create image for each frame for frame in u: im = plt.imshow(frame, animated=True) ims.append([im]) # calculate number of miliseconds required between each frame to make the total length of the animation total_time interval = (1000 * total_time) / len(u) ani = animation.ArtistAnimation(fig, ims, interval=interval, blit=True, repeat_delay=1000) # save animation if filename != "": writer = PillowWriter(fps=15, bitrate=1800) ani.save(filename + ".gif", writer=writer) plt.show()
def make_animated_gif(sims, idx): import matplotlib as mpl from matplotlib.animation import FuncAnimation, PillowWriter import copy print("Animating conc model results...") sim_name = example_name sim_mf6gwf, sim_mf6gwt, sim_mf2005, sim_mt3dms = sims gwf = sim_mf6gwf.flow gwt = sim_mf6gwt.trans botm = gwf.dis.botm.array # load head fs = USGSFigure(figure_type="map", verbose=False) head = gwf.output.head().get_data() head = np.where(head > botm, head, np.nan) # load concentration cobj = gwt.output.concentration() conc_times = cobj.get_times() conc_times = np.array(conc_times) conc = cobj.get_alldata() # set up the figure fig = plt.figure(figsize=(7.5, 3)) ax = fig.add_subplot(1, 1, 1) pxs = flopy.plot.PlotCrossSection( model=gwf, ax=ax, line={"row": 0}, extent=(0, 10000, 0, 2000), ) cmap = copy.copy(mpl.cm.get_cmap("jet")) cmap.set_bad("white") nodata = -999.0 a = np.where(head > botm, conc[0], nodata) a = np.ma.masked_where(a < 0, a) pc = pxs.plot_array(a, head=head, cmap=cmap, vmin=0, vmax=1) pxs.plot_bc(ftype="RCH", color="red") pxs.plot_bc(ftype="CHD") def init(): ax.set_title("Time = {} days".format(conc_times[0])) def update(i): a = np.where(head > botm, conc[i], nodata) a = np.ma.masked_where(a < 0, a) a = a[~a.mask] pc.set_array(a.flatten()) ax.set_title("Time = {} days".format(conc_times[i])) # Stop the animation at 18,000 days idx_end = (np.abs(conc_times - 18000.0)).argmin() ani = FuncAnimation(fig, update, range(1, idx_end), init_func=init) writer = PillowWriter(fps=25) fpth = os.path.join("..", "figures", "{}{}".format(sim_name, ".gif")) ani.save(fpth, writer=writer) return
def draw(self, fname="ejemplo.gif"): ani = FuncAnimation(self.fig, self.update, [i for i in range(self.t)], init_func=self.init) writer = PillowWriter(fps=self.fps) ani.save(fname, writer=writer) #os.system(f"start {fname}s") os.system(f"eog {fname}&")
def save_graph(animation, name): if name.endswith(".mp4"): writer_ = writers["ffmpeg"] writer = writer_(fps=15, metadata={'artist': 'Me'}, bitrate=1800) animation.save(name, writer) elif name.endswith(".gif"): writergif = PillowWriter(fps=10) animation.save(name, writer=writergif)
def savegif(self, filename, fps): # save animation as a gif: requires pillow self.ani = FuncAnimation(self.fig,self.update,range(1,len(self.time)), interval=1000/fps, blit=False) # create animation #base_path = Path(__file__).parent # get main path of workspace filename += '.gif' #file_path = (base_path / "../gifs/"/filename).resolve() # put filename in correct subdirectory writer = PillowWriter(fps=fps, bitrate=-1) #self.ani.save(file_path, writer = writer) # save gif with pillow self.ani.save(filename, writer = writer)
def save_gif(self, filename, fps=30): ''' This function recreates and saves the animation to a file. Input: -> The name of the file followed by the suffix .gif Returns: (None) ''' ani = self.create_gif(fps) writer = PillowWriter(fps=fps) ani.save(filename, writer=writer)
def Simulation(self): writer = PillowWriter(fps=25) print("Cargando...") anim = animation.FuncAnimation(self.fig, self.anima, len(self.time_span), interval=10000 / len(self.time_span), blit=False) anim.save("threeBody.gif", writer=writer)
def gif_from_path( path=None, figsize=(10, 10), fps=0.5, interval=500, repeat_delay=1000, filename=None, dpi=400, ): """ Create an animated gif from a director of image files. Parameters ---------- path :str, required path to directory of images figsize : tuple, optional output figure size passed to matplotlib.pyplot fps : float, optional frames per second interval : int, optional interval between frames in miliseconds, default 500 repeat_delay : int, optional time before animation repeats in miliseconds, default 1000 filename : str, required output file name dpi : int, optional image dpi passed to matplotlib writer """ assert filename, "You must provide an output filename ending in .gif" imgs = os.listdir(path) imgs.sort(key=lambda var: [ int(x) if x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var) ]) fig, ax = plt.subplots(figsize=figsize) ax.axis("off") ims = [] for i in imgs: c = plt.imread(str(PurePath(path, i))) im = plt.imshow(c, animated=True) ims.append([im]) writer = PillowWriter(fps=fps) ani = ArtistAnimation(fig, ims, interval=interval, blit=True, repeat_delay=repeat_delay) plt.tight_layout() ani.save(filename, writer=writer, dpi=dpi)
def display_trajectories(results, animated=True, save_animation=True): """Displays an animation or graph of results""" # Unpack results p1_x = results[:, 0] p1_y = results[:, 1] p2_x = results[:, 2] p2_y = results[:, 3] p3_x = results[:, 4] p3_y = results[:, 5] p4_x = results[:, 6] p4_y = results[:, 7] # Determine scale of window xmax = max([max(p1_x), max(p2_x), max(p3_x), max(p4_x)]) xmin = min([min(p1_x), min(p2_x), min(p3_x), min(p4_x)]) ymax = max([max(p1_y), max(p2_y), max(p3_y), max(p4_y)]) ymin = min([min(p1_y), min(p2_y), min(p3_y), min(p4_y)]) # Create visualization if animated: # Initial state of plot fig, ax = plt.subplots() ax.axis([-3.75, 0.6, -0.52, 3.5]) #line1, = ax.plot(p1[0], p1[1]) #line2, = ax.plot(p2[0], p2[1]) #line3, = ax.plot(p3[0], p3[1]) #line4, = ax.plot(p4[0], p4[1]) # Animate the plot three_body_animation = FuncAnimation(fig, func=animation_frame, frames=range(len(p1_x)), interval=1, save_count=len(p1_x)) plt.show() else: #Plot without animation fig, ax = plt.subplots() ax.axis([-3.75, 0.6, -0.52, 3.5]) ax.plot(p1_x, p1_y) ax.plot(p2_x, p2_y) ax.plot(p3_x, p3_y) ax.plot(p4_x, p4_y) plt.show() if (animated and save_animation): # Save the animation print("Generating GIF...") s = time.perf_counter() three_body_animation.save('test_export.gif', writer=PillowWriter(fps=24)) e = time.perf_counter() print(f"Done ({e - s} s)")
def main(filename): fig, ax = plt.subplots() line, = ax.plot([], []) ax.grid() ax.set_xlabel('Field (mT)') ax.set_ylabel('Absorption (arb. u)') ax.set_yticks([]) r_text = ax.text(0.02, 0.95, '', transform=ax.transAxes) xdata, ydata = [], [] data = np.loadtxt(filename, delimiter=',') if np.shape(data)[0] > np.shape(data)[1]: data = np.transpose(data) init_max_y = np.max(data[0, :]) init_min_y = np.min(data[0, :]) def data_gen(data): for ii in range(len(data)): yield np.linspace(-3, 3, np.shape(data)[1]), data[ii, :], ii def init(): ax.set_xlim(-3, 3, np.shape(data)[1]) ax.set_ylim(init_min_y, init_max_y) r_text.set_text('') del xdata[:], ydata[:] line.set_data(xdata, ydata) return line, def run(data): xdata, ydata, ii = data r_text.set_text(f"r={1+np.linspace(0,5,len(xdata))[ii]:.2f} nm") max_y = np.max(ydata) min_y = np.min(ydata) ax.set_ylim([1.1 * min_y, 1.1 * max_y]) ax.figure.canvas.draw() line.set_data(xdata, ydata) return line, ani = FuncAnimation(fig, run, frames=data_gen(data), blit=False, repeat=False, init_func=init, save_count=np.shape(data)[0]) startsave = '/'.join(filename.split('/')[:-1]) + '/gifs/' + filename.split( '/')[-1][:-4] + '.gif' savefile = iterate(startsave) ani.save(savefile, writer=PillowWriter(fps=10))
def gif_maker(optic, show_process=None, frame_per_second=10): from matplotlib.animation import FuncAnimation, PillowWriter if show_process: plt.ion() fig, (ax0, ax1) = plt.subplots(1, 2, figuresize=(11, 5)) for i, ic in enumerate(optic.cmode): ax0.imshow(np.abs(ic)**2) ax1.imshow(np.angle(ic)) fig.canvas.draw() fig.canvas.flush_events() plt.close("all") fig, ax = plt.subplots() def init(): ax.imshow(np.angle(optic.cmode[0])) def update(ic): ax.imshow(np.angle(optic.cmode[ic])) ani = FuncAnimation(fig, update, range(len(optic.cmode)), init_func=init) write = PillowWriter(fps=frame_per_second) ani.save(optic.name + "_phase.gif", writer=write) fig, ax = plt.subplots() def init(): ax.imshow(np.abs(optic.cmode[0])**2) def update(ic): ax.imshow(np.abs(optic.cmode[ic])**2) ani = FuncAnimation(fig, update, range(len(optic.cmode)), init_func=init) write = PillowWriter(fps=frame_per_second) ani.save(optic.name + "_intensity.gif", writer=write)
def gif_generator(self, dt, t_max, C0, save_every_n=500): r""" Generates an animated image (.gif) with the time evolution of the one-body density and the time evolution of the one body potential. **Args**: dt (float) : time step t_max (float) : total duration of the time evolution C0 (np.ndarray) : coefficient matrix at time t=0 save_every_n (int) : number of time steps between two successive frames in the final .gif file """ fig, ax = plt.subplots(figsize=(10, 7)) #plt.title(r'$\Omega=0.25,\;\omega=8.0,\; \delta t = 10^{-4},\; T_{max}= 1.2 \times 2 \pi / \Omega$', fontsize=18) ax.set_xlim([-10, 10]) ax.set_ylim([-0.1, 1.5]) ax.set_xlabel(r'$x$ [a.u.]', fontsize=22) ax.tick_params(axis='both', which='major', pad=5, labelsize=18) ax.grid() epsilon, C0, energy_per_step, delta_per_step = self.solve_TIHF( tolerance=1e-6, max_iter=100) line1, = ax.plot(self.system.grid, self.eval_one_body_density(C0).real, label=r'$\rho(x)$') line2, = ax.plot(self.system.grid, self.potential(self.system.grid), label='One-body potential') ax.legend(loc='upper right') props = dict(boxstyle='round', facecolor='white') text = ax.text(-9, 1.4, r'$t/T_{max}=0$', fontsize=16, bbox=props, animated=True) integrator = scipy.integrate.ode(self.rhsf).set_integrator('zvode') integrator.set_initial_value(np.reshape(C0, len(C0)**2), 0) i_max = i_max = int(np.floor(t_max / dt / save_every_n)) anim = FuncAnimation(fig, self.anima, fargs=(text, line1, line2, integrator, dt, t_max, save_every_n), frames=i_max) writer = PillowWriter(fps=15) anim.save("animation.gif", writer=writer)
def compare_predict(self, mode: str) -> None: # Generates frames. batch, predicted_batch = self.predict(mode) nrows = 2 ncols = 4 fig = plt.gcf() fig.set_size_inches(ncols * 4, nrows * 4) fig.patch.set_facecolor('white') predicted_stacks = predicted_batch[0:4] stacks = batch[0:4] if self.config['DATA'].getboolean('Movement'): def _update(predicted_stacks, stacks, index): for i in range(len(predicted_stacks)): msg = 'Movement = True, but data does not have rank 5.' assert len(predicted_stacks.shape) == 5, msg name = f'Stack {i}.' sp = plt.subplot(nrows, ncols, i + 1) sp.set_title(f'{name}') plt.imshow(stacks[i, :, :, index]) p_name = f'Predicted stack {i}.' sp = plt.subplot(nrows, ncols, i + 5) sp.set_title(f'{p_name}') plt.imshow(predicted_stacks[i, :, :, index]) duration = self.config['DATA'].getint('MovementDuration') ani = FuncAnimation(fig, lambda i: _update(predicted_stacks, stacks, i), list(range(duration)), init_func=_update(predicted_stacks, stacks, 0)) writer = PillowWriter(fps=duration) ani.save(f"output/compare_{mode}_{dt_string}.gif", writer=writer) else: for i in range(len(predicted_stacks)): msg = 'Movement = False, but data does not have rank 4.' assert len(predicted_stacks.shape) == 4, msg name = f'Stack {i}.' sp = plt.subplot(nrows, ncols, i + 1) sp.set_title(f'{name}') plt.imshow(stacks[i]) p_name = f'Predicted stack {i}.' sp = plt.subplot(nrows, ncols, i + 5) sp.set_title(f'{p_name}') plt.imshow(predicted_stacks[i]) plt.savefig(f'output/compare_{mode}_{dt_string}.png')
def display_trajectories(self, animated=True, save_animation=True): """Displays an animation or graph of results""" # Unpack results self.p1_x = self.results[:, 0] self.p1_y = self.results[:, 1] self.p2_x = self.results[:, 2] self.p2_y = self.results[:, 3] self.p3_x = self.results[:, 4] self.p3_y = self.results[:, 5] # Determine scale of window xmax = max([max(self.p1_x), max(self.p2_x), max(self.p3_x)]) xmin = min([min(self.p1_x), min(self.p2_x), min(self.p3_x)]) ymax = max([max(self.p1_y), max(self.p2_y), max(self.p3_y)]) ymin = min([min(self.p1_y), min(self.p2_y), min(self.p3_y)]) # Create visualization if animated: # Initial state of plot fig, ax = plt.subplots() ax.axis([xmin, xmax, ymin, ymax]) self.line1, = ax.plot(self.p1[0], self.p1[1]) self.line2, = ax.plot(self.p2[0], self.p2[1]) self.line3, = ax.plot(self.p3[0], self.p3[1]) # Animate the plot self.three_body_animation = FuncAnimation( fig, func=self.animation_frame, frames=range(len(self.p1_x)), interval=1, save_count=len(self.p1_x)) plt.show() else: #Plot without animation fig, ax = plt.subplots() ax.plot(self.p1_x, self.p1_y) ax.plot(self.p2_x, self.p2_y) ax.plot(self.p3_x, self.p3_y) plt.show() if (animated and save_animation): # Save the animation print("Generating GIF...") s = time.perf_counter() self.three_body_animation.save('test_export.gif', writer=PillowWriter(fps=24)) e = time.perf_counter() print(f"Done ({e - s} s)")
def save_gif(self, filename): """Saves the animation to a gif A convience function. Provided to let the user avoid dealing with writers. Parameters ---------- filename : str the name of the file to be created without the file extension """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(filename + '.gif', writer=PillowWriter(fps=self.timeline.fps))
def save_gif_example(args, file): features = np.load(args.features_path) img = features[str(file)] fig = plt.figure() ims = [] for frame in img: ims.append([plt.imshow(frame)]) ani = animation.ArtistAnimation(fig, ims, interval=100,blit=True, repeat_delay=1000) ani.save('../data/processed/run_example.gif',writer=PillowWriter(fps=10))
def save(self, filename="result.gif"): ''' Save the animation as a file. Parameters ---------- filename : string, optional The name of the file - must terminate in ".gif". The default is "result.gif". Returns ------- None. ''' self.ani.save(filename=filename, writer=PillowWriter(fps=20))