def confusion_worker(queue, animation=False): """Matplotlib worker.""" config = get_config() titles = json.loads(config.get('sentiment', 'titles')) def init(): clear_annotations(annotations) for ax, image, title in zip(axes, images, titles): empty_confusion = [[0] * 3] * 3 image.set_data(empty_confusion) # annotate_confusion_matrix(ax, empty_confusion, annotations) return images fig, axes, images, annotations = make_confusion() # Important to assign it to a variable, even if we don't use it. anim = FuncAnimation(fig=fig, func=update_confusion, frames=lambda: get_data(queue), fargs=(images, axes, annotations), interval=200, repeat=False, init_func=init, blit=False) if animation: anim.save('confusion.mp4', fps=10, extra_args=['-vcodec', 'libx264']) else: plt.show()
def main(self, outfile, fps=30): frame = defaultdict(list) for _, [t, item], val in self.interp.chart['frame/2'][:,:,:]: if val: frame[t].append(item) nframes = max(frame) def draw_frame(t): ax.cla() ax.set_title(t) ax.set_xlim(-2,2) # TODO: this isn't right... ax.set_ylim(-2,2) if t not in frame: print 'frame', t, 'missing.' for item in frame[t]: if item.fn == 'line/2': [(a,b), (c,d)] = map(topython, item.args) ax.plot([a,c], [b,d], color='b', alpha=0.5) elif item.fn == 'text/2': (s,(x,y)) = map(topython, item.args) ax.text(x,y,s) else: print 'dont know how to render', item fig = pl.figure() ax = pl.axes() anim = FuncAnimation(fig, draw_frame, frames=nframes) anim.save(outfile, fps=fps, extra_args=['-vcodec', 'libx264'])
def plot_data_scatterplot(x, y, mb_history=None): """Plot the data: y as a function of x, in a scatterplot. x, y: arrays of data. mb_history: if provided, it's a sequence of (m, b) pairs that are used to draw animated lines on top of the scatterplot. """ fig, ax = plt.subplots() fig.set_tight_layout(True) fig.set_size_inches((8, 6)) save_dpi = 80 ax.scatter(x, y, marker='x') ax.set_xlabel('x') ax.set_ylabel('y') if mb_history: m0, b0 = mb_history[0] line, = ax.plot(x, x * m0 + b0, 'r-', linewidth=2.0) # Downsample mb_history by 2 to reduce the number of frames shown. def update(frame_i): mi, bi = mb_history[frame_i * 2] line.set_ydata(x * mi + bi) ax.set_title('Fit at iteration {0}'.format(frame_i * 2)) return [line] anim = FuncAnimation(fig, update, frames=range(len(mb_history) // 2), interval=200) anim.save('regressionfit.gif', dpi=save_dpi, writer='imagemagick') else: fig.savefig('linreg-data.png', dpi=save_dpi) plt.show()
def record_gif(self, gen_func, savefn): gen = gen_func() frame_func = lambda t: next(gen) ax = plt.subplot(1,1,1) f = ax.get_figure() animation = FuncAnimation(f, frame_func, frames = np.arange(0,10,0.1), interval = 200) animation.save(savefn + '.gif', dpi = 80, writer = 'imagemagick')
def main(): fig = plt.figure(figsize=(3.2, 1.8)) ax = fig.add_axes([0, 0, 1, 1]) signal = create_gammapy_skymap().data background = np.ones(signal.shape) background /= background.sum() data = (1 * signal + background) / 2. # setup counts generator pdf = data.copy().flatten() x = np.arange(pdf.size) counts_generator = rv_discrete(name='counts', values=(x, pdf)) counts = np.zeros_like(data) image = ax.imshow(counts, cmap='afmhot', origin='lower', vmin=0, vmax=9, interpolation='None') bins = np.arange(counts.size + 1) - 0.5 anim = FuncAnimation(fig, animate, fargs=[image, counts, bins, counts_generator], frames=200, interval=50) filename = 'gammapy_logo.gif' anim.save(filename, writer='imagemagick')
class Blocks(): def __init__(self, numBlocks,L,data, point_count,colormap): self.point_count = point_count self.data = data self.c = data-data[0] self.positions = np.linspace(0,L,numBlocks) self.get_color_range(colormap, self.c) self.fig,self.ax = plt.subplots() self.scatter = plt.scatter(self.data[0],np.zeros_like(self.data[0]), c=self.crange[0],s=50, cmap = colormap) self.animation = FuncAnimation(self.fig, self.update,data.shape[0], fargs=(self.data, self.scatter), interval =25) def get_color_range(self,colormap, c): mapper = cm.ScalarMappable(cmap = colormap) self.crange = mapper.to_rgba(c) def update(self,num,data, scat): array = np.array((data[num],np.zeros_like(data[num]))).T self.scatter.set_offsets(array) self.scatter.set_facecolor(self.crange[num]), print ("%d/%d" %(num,self.point_count)) return self.scatter, def animate(self, numBlocks, save = False, filename="output/animation.gif"): plt.show() if save: print("Writing to %s, this make take a while" %filename) self.animation.save(filename, writer='imagemagick', fps=30)
def run(self, animating = False, iteration_count = 10000): population_counts = np.zeros((2, iteration_count), dtype=int) def loop(t): if animating: self.draw() self.step() for agent in self.agents: if agent.type == PREDATOR: population_counts[0,t] += 1 else: population_counts[1,t] += 1 if animating: figure = plt.figure() figure.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) animation = FuncAnimation(figure, loop, init_func=self.init_drawing, frames=iteration_count) # save video directory = "videos" if not os.path.exists(directory): os.makedirs(directory) filename = "{}/{}.mp4".format(directory, datetime.now()) animation.save(filename, fps=20, codec="libx264", extra_args=['-pix_fmt','yuv420p']) else: animation = None for t in range(iteration_count): loop(t) if np.any(population_counts[:,t] == 0): return population_counts[:, :t + 1] return population_counts
def plot_worker(queue, animation=False): """Matplotlib worker.""" def init(): updated_lines = [] for ax_lines in lines: for line, x, y in ax_lines: line.set_data([], []) updated_lines.append(line) return updated_lines fig, axes, lines = make_subplots() # Important to assign it to a variable, even if we don't use it. anim = FuncAnimation(fig=fig, func=update_figure, frames=lambda: get_data(queue), fargs=(lines, axes), interval=200, repeat=False, init_func=init, blit=False) if animation: anim.save('plot.mp4', fps=10, extra_args=['-vcodec', 'libx264']) else: plt.show()
def showAnimation(self, Nframe=500): ax = self.fig.add_axes([0,0,1,1]) plt.cla() color_map = {1:'b', 2:'r', 3:'g'} animation = FuncAnimation(self.fig, self.updateFig, interval=50, blit=False, frames=Nframe) animation.save("LanguageAdoptionModel.mp4")
def animate(basetimer,fig,timer=None,save=None,**ka): ka['repeat'] = ka['repeat_delay']>0 from matplotlib.animation import FuncAnimation anim = FuncAnimation(fig,save_count=1,**ka) if timer is not None: config(basetimer,**timer) basetimer.launch(anim) if save is not None: anim.save(**save)
def generate(self, run_data): self._print_generating_line() self.fig = plt.figure() self.initial(run_data) anim = FuncAnimation(self._fig, self.animate, frames=len(self._times), interval=run_data.log_interval_ticks) anim.save(self.get_figfilename(), dpi=self.dpi) plt.close(self.fig)
def main(data,outmov): #entropy calculation with plots fun = lik.VESPA_fit(data,spec_lib='bc03') SSP = fun.SSP ages = fun._age_unq metal = nu.linspace(fun._metal_unq.min(),fun._metal_unq.max(),10) t,z = nu.meshgrid(ages,metal) spec = [] d = nu.vstack((t.ravel(),z.ravel())).T for i in d: try: spec.append(SSP.get_sed(10**(i[0]-9),10**i[1])) except: spec.append(SSP.get_sed(round(10**(i[0]-9)),10**i[1])) #make array spec = nu.asarray(spec) #match wavelenth with data if not nu.all(nu.sort(SSP.sed_ls) == SSP.sed_ls): #check if sorted wave = SSP.sed_ls[::-1] spec = spec[:,::-1] else: wave = SSP.sed_ls new_spec = nu.zeros((len(d),len(data))) for i in xrange(len(d)): new_spec[i,:] = nu.interp(data[:,0],wave,spec[i,:]) spec = new_spec H = get_information(data,spec) #make animation of how information changes likelihood #get spectra chi = [] flux = data[:,1] #how i think the enropy should look -sum((1-p)*log(p)) #tot_infor = nu.sum(mod_shannon(H)) #H = mod_shannon(H) H = shannon(H) wave =data[:,0] del_index = flux == flux print 'Making images' for i in xrange(len(wave)): index = nu.nanargmin(H) H[index] = nu.nan del_index[index] = False chi.append([make_chi(flux[del_index],spec,t,z,del_index),nu.nansum(H),nu.copy(del_index)]) pik.dump((chi,z,t,wave,flux),open('temp.pik','w'),2) print 'Saving animations as movie' #make animation an = anim(t, z, chi, wave, flux) ani = FuncAnimation(an.fig,an.make_im,frames = len(chi)) ani.save(outmov+'.mp4')
def anim(): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlim3d([-20.0, 20.0]) ax.set_xlabel('X') ax.set_ylim3d([-20.0, 20.0]) ax.set_ylabel('Y') ax.set_zlim3d([-20.0, 20.0]) ax.set_zlabel('Z') ax.set_title('3D Test') sc = [ax.scatter(points[0][i][0], points[0][i][1], points[0][i][2], c='b', s=0.1,facecolor='0.5', lw = 0) for i in range(len(points[0]))] ani = FuncAnimation(fig, update, frames=3000, fargs=(points, sc, ax), interval=10) ani.save("basic_animation.mp4", fps=30, extra_args=['-vcodec', 'libx264'])
def animate(data, arrowscale=1, savepath=None): """ animates the quiver plot for the dataset (multiple frames) Input: data : xarray PIV type of DataSet arrowscale : [optional] integer, default is 1 savepath : [optional] path to save the MP4 animation, default is None Output: if savepath is None, then only an image display of the animation if savepath is an existing path, a file named im.mp4 is saved """ X, Y = data.x, data.y U, V = data.u[:,:,0], data.v[:,:,0] # first frame fig, ax = plt.subplots(1,1) M = np.sqrt(U**2 + V**2) Q = ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3], units='inches', scale=arrowscale) cb = plt.colorbar(Q) units = data.attrs['units'] cb.ax.set_ylabel('velocity (' + units[2] + ')') text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes) def update_quiver(num,Q,data,text): U,V = data.u[:,:,num],data.v[:,:,num] M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return Q anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames = len(data.t), blit=False) mywriter = FFMpegWriter() if savepath: p = os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p) else: anim.save('im.mp4', writer=mywriter)
def __init__(self): N = 200 self.dx = 1. / N cfl = .1 self.c = 100. self.dt = cfl * self.dx / self.c self.t = 0 self.x = np.linspace(0, 1, N) self.u = np.sin(2 * np.pi * self.x) * 0 self.u[0] = 1 self.fig = plt.figure() self.line, = plt.plot(self.x, self.u) ani = FuncAnimation(self.fig, self.update, range(10000), interval=10, blit=True) Writer = writers['ffmpeg'] writer = Writer(fps=100, metadata=dict(artist='Laurent Garcin'), bitrate=18000) ani.save('transport.mp4', writer=writer) plt.show()
def networkxApproach(): import numpy as np import networkx as nx import matplotlib import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation G = nx.Graph() G.add_edges_from([(0,1),(1,2),(2,0)]) fig = plt.figure(figsize=(8,8)) pos = nx.graphviz_layout(G) nc = np.random.random(3) nodes = nx.draw_networkx_nodes(G,pos,node_color=nc) edges = nx.draw_networkx_edges(G,pos) def update(n): nc = np.random.random(3) nodes.set_array(nc) return nodes, anim = FuncAnimation(fig, update, interval=50, blit=False) anim.save('outNetworkx.mp4')
def visual2D(): ''' for i in range(10 ): plt.plot(pca.components_[i,:]) plt.show() ''' fig = plt.figure() color=['g','b','k','r','y','c'] i=0;start=0 def update(frame): s=50*np.random.random(2072) for scat in root: scat.set_sizes(s) return root root=[] for cl in data.keys(): leng = len(data[cl]) scat=plt.scatter (data_trans[start:start+leng,0],data_trans[start:start+leng,1],c=color[i],s=50*np.random.random(leng),alpha=0.5) root.append(scat) i+=1;start=start+leng animation = FuncAnimation(fig, update, interval=10) plt.show() animation.save('../rain.gif', writer='imagemagick', fps=30, dpi=72)
def showAnimation(self, Nframe=500): # ax = self.fig.add_axes([0.1,0.1, 0.9, 0.9]) plt.cla() animation = FuncAnimation(self.fig, self.updateFig, interval=50, blit=False, frames=Nframe) animation.save("LanguageAdoptionLattice.mp4")
def animate_with_live_integration( containers, integrator, dt, xlim, ylim, figsize, particle_radius, frame_show_modulus=1, num_frames_to_bootstrap=0, info_for_naming='', save_animation=False, show_animation=True, run_until_func=None, anim_save_kwargs=None, anchor_ixs=None, sim_wide_params=None): """ """ global num_forward_frames anim_save_kwargs = anim_save_kwargs or {'fps': 30} init_container = containers[0] plot_title = info_for_naming also_run_backwards = False num_forward_frames = len(containers) for i in [0, 1]: assert type(figsize[i]) is int, "Can't save an animation with float figsize" fig = pl.figure(figsize=figsize) ax = pl.axes(xlim=xlim, ylim=ylim) ax.set_aspect('equal') # NOTE: This can make the plot look squished if figsize isn't wide enough title_width = int(figsize[0] * 10) # dynamic way to figure out how much text will fit in the title title_wrapped = '\n'.join(textwrap.wrap(plot_title, width=title_width)) pl.title(title_wrapped, fontsize=12) ## pl.xlabel('X Position') ## pl.ylabel('Y Position') # Bootstrap some frames using user-suppliend func and/or count if run_until_func is not None: while run_until_func(containers[-1]): containers.append(integrator.step(containers[-1], dt)) num_forward_frames = len(containers) // frame_show_modulus # NOTE: int division while num_forward_frames < num_frames_to_bootstrap: num_forward_frames += 1 for i in xrange(frame_show_modulus): next_container = integrator.step(containers[-1], dt) containers.append(next_container) ## Set up plotting circles = [] for i in xrange(init_container.num_particles): e = get_nice_circle(0, 0, particle_radius) circles.append(ax.add_patch(e)) # NOTE: We can animate an annotations, but not using textcoords='figure points' multi_text = ax.annotate('stats', (0, 0), xytext=(5, 5), textcoords='axes points', ha='left', va='bottom') time_text = ax.text(0, -2, 'time', transform=ax.transAxes) flux_text = ax.text(0.5, -2, 'flux', transform=ax.transAxes) pulling_force_text = ax.text(0.5, 0.90, '', transform=ax.transAxes) damp_force_text = ax.text(0.5, 0.80, '', transform=ax.transAxes) ## aperture_line = ax.plot(xlim, [sim_wide_params.y_funnel_bottom]*2, ## linestyle='-', color='black', alpha=0.5, ## linewidth=0.5) # init fn seems to prevent 'ghosting' of first-plotted data texts = [multi_text, time_text, flux_text, pulling_force_text, damp_force_text] def init(): """initialize animation""" for t in texts: t.set_text('') for c in circles: c.center = (-100, -100) # hide off-screen return circles + texts def next_frame(ix_frame): global num_forward_frames ## if ix_frame % 100 == 1: ## print 'frame', ix_frame # Do only the integration necessary to get to the requested frame container_ix = ix_frame*frame_show_modulus while num_forward_frames <= ix_frame: num_forward_frames += 1 for _ in xrange(1 + frame_show_modulus): # always run at least once next_container = integrator.step(containers[-1], dt) containers.append(next_container) c = containers[container_ix] posns = c.positions try: stats = 'time={t:.1f}\ncount={n}'.format( t = c.time, n = c.cumulative_grains_below_aperture) multi_text.set_text(stats) ## time_text.set_text('time = %.1f' % c.time) ## flux_text.set_text('count = {}'.format(c.cumulative_grains_below_aperture)) pulling_force_text.set_text('Fp = ' + str(c.pull_accelerations)) damp_force_text.set_text('Fd = ' + str(c.damp_accelerations)) except AttributeError: pass for i, circle in zip(xrange(init_container.num_particles), circles): circle.center = (posns[i][0], posns[i][1]) # x and y try: for ix, force_mag in zip(sim_wide_params.anchor_ixs, c.anchor_accels): anchor_circle = circles[ix] anchor_circle.set_facecolor('black') # Consider using logarithm max_expected_force = 1000 alpha = min(math.log(force_mag + 2, max_expected_force), 1) # always > 0.1 so visible; cap at 100% ## alpha = min(force_mag/100.0 + 0.01, 1) anchor_circle.set_alpha(alpha) except AttributeError: pass return circles + texts # Amount of framedata to keep around for saving movies. save_count = 5000 # should be enough for animation to be able to save entire movie, if desired, without having to re-run anim = FuncAnimation(fig, next_frame, interval=dt, blit=True, init_func=init, save_count=save_count) if show_animation: try: pl.show() except AttributeError as e: # 'NoneType' object has no attribute 'tk' print e else: pl.close() ## end_container = containers[-1] ## # Now run... backwards! ## if also_run_backwards: ## for i in xrange(num_forward_frames): ## next_container = integrator.step(containers[-1], -dt) ## containers.append(next_container) num_total_frames = num_forward_frames if also_run_backwards: num_total_frames += num_forward_frames if save_animation: if not show_animation: # If we haven't run/showed yet, we need to have the animation know how many frames to run for anim = FuncAnimation(fig, next_frame, interval=dt, blit=True, frames=num_total_frames) print 'beginning save of animation with frame count:', num_total_frames, 'at', time.strftime("%a %b %d %H:%M:%S") prefix = '{wd}/dumps/{name}'.format(wd = working_directory, name = info_for_naming) make_dirs_if_necessary(prefix) try: anim.save('{pre}/anim len={len}.avi'.format( pre=prefix, len=num_total_frames), **anim_save_kwargs) print 'done saving at', time.strftime("%a %b %d %H:%M:%S") except RuntimeError as e: #Error writing to file print e try: pl.close() except: pass
d = 10 gapArray = [] for key, value in data.items(): if value["HamiVal"][4] - value["HamiVal"][3] < d: if value["gap"] in dic.keys(): dic[value["gap"]].append(value["Pos"]) else: dic[value["gap"]] = [value["Pos"]] gapArray = list(dic.keys()) def update_graph(gap): x, y, z = np.transpose(np.array(dic[gap])) graph.set_data(x, y) graph.set_3d_properties(z) title.set_text('3D Test, time={}'.format(gap)) return title, graph, fig = plt.figure() ax = p3.Axes3D(fig) title = ax.set_title('3D Test') # initialize scatters x, y, z = np.transpose(np.array(dic[gapArray[0]])) graph, = ax.plot(x, y, z, linestyle="", marker="o") anim = FuncAnimation(fig, update_graph, gapArray, interval=1, blit=False) anim.save("dHzWeyl3Danim_d=" + str(d) + ".mp4")
return plt_force_traj, plt_xi_traj, plt_pos_traj else: plt_pos_traj = mins[ min_counter[0]].plot_pos_from_pos_traj_index(i - offset[0]) return plt_pos_traj anim = FuncAnimation(fig, animate, init_func=init, interval=2, blit=False) if save_animation: animation_name = "animation.gif" print("Saving animation") anim.save(animation_name) print(f"Animation saved to {animation_name}") else: if plot_propterties: env.plot(ax1_1) scs.plot(ax1_1) for mn in beacons[ 1:]: #SCS is already plotted, using beacons instead of mins so that only landed mins are taken into account mn.plot(ax1_1) mn.plot_traj_line(ax1_1) mn.plot_vectors(env, ax1_1) mn.plot_force_traj_line(ax2_1) mn.plot_xi_traj_line(ax2_2) ax2_1.legend(ncol=2, prop={'size': 9}) else:
def Save_statesAnimation(map, LMPCOpenLoopData, LMPController, it): SS_glob = LMPController.SS_glob TimeSS = LMPController.TimeSS SS = LMPController.SS uSS = LMPController.uSS xdata = [] ydata = [] fig = plt.figure() fig.set_tight_layout(True) axvx = fig.add_subplot(3, 2, 1) plt.plot(SS[0:TimeSS[it], 4, it], SS[0:TimeSS[it], 0, it], '-ok', label="Closed-loop trajectory") lineSSvx, = axvx.plot(xdata, ydata, 'sb-', label="SS") linevx, = axvx.plot(xdata, ydata, 'or-', label="Predicted Trajectory") plt.ylabel("vx") plt.xlabel("s") plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.2), loc="lower left", mode="expand", borderaxespad=0, ncol=3) axvy = fig.add_subplot(3, 2, 2) axvy.plot(SS[0:TimeSS[it], 4, it], SS[0:TimeSS[it], 1, it], '-ok') lineSSvy, = axvy.plot(xdata, ydata, 'sb-') linevy, = axvy.plot(xdata, ydata, 'or-') plt.ylabel("vy") plt.xlabel("s") axwz = fig.add_subplot(3, 2, 3) axwz.plot(SS[0:TimeSS[it], 4, it], SS[0:TimeSS[it], 2, it], '-ok') lineSSwz, = axwz.plot(xdata, ydata, 'sb-') linewz, = axwz.plot(xdata, ydata, 'or-') plt.ylabel("wz") plt.xlabel("s") axepsi = fig.add_subplot(3, 2, 4) axepsi.plot(SS[0:TimeSS[it], 4, it], SS[0:TimeSS[it], 3, it], '-ok') lineSSepsi, = axepsi.plot(xdata, ydata, 'sb-') lineepsi, = axepsi.plot(xdata, ydata, 'or-') plt.ylabel("epsi") plt.xlabel("s") axey = fig.add_subplot(3, 2, 5) axey.plot(SS[0:TimeSS[it], 4, it], SS[0:TimeSS[it], 5, it], '-ok') lineSSey, = axey.plot(xdata, ydata, 'sb-') lineey, = axey.plot(xdata, ydata, 'or-') plt.ylabel("ey") plt.xlabel("s") Points = np.floor( 10 * (map.PointAndTangent[-1, 3] + map.PointAndTangent[-1, 4])) Points1 = np.zeros((Points, 2)) Points2 = np.zeros((Points, 2)) Points0 = np.zeros((Points, 2)) for i in range(0, int(Points)): Points1[i, :] = map.getGlobalPosition(i * 0.1, map.width) Points2[i, :] = map.getGlobalPosition(i * 0.1, -map.width) Points0[i, :] = map.getGlobalPosition(i * 0.1, 0) axtr = fig.add_subplot(3, 2, 6) plt.plot(map.PointAndTangent[:, 0], map.PointAndTangent[:, 1], 'o') plt.plot(Points0[:, 0], Points0[:, 1], '--') plt.plot(Points1[:, 0], Points1[:, 1], '-b') plt.plot(Points2[:, 0], Points2[:, 1], '-b') plt.plot(SS_glob[0:TimeSS[it], 4, it], SS_glob[0:TimeSS[it], 5, it], '-ok') SSpoints_x = [] SSpoints_y = [] xPred = [] yPred = [] SSpoints_tr, = axtr.plot(SSpoints_x, SSpoints_y, 'sb') line_tr, = axtr.plot(xPred, yPred, '-or') N = LMPController.N numSS_Points = LMPController.numSS_Points def update(i): xPred = LMPCOpenLoopData.PredictedStates[:, :, i, it] SSpoints = LMPCOpenLoopData.SSused[:, :, i, it] linevx.set_data(xPred[:, 4], xPred[:, 0]) linevy.set_data(xPred[:, 4], xPred[:, 1]) linewz.set_data(xPred[:, 4], xPred[:, 2]) lineepsi.set_data(xPred[:, 4], xPred[:, 3]) lineey.set_data(xPred[:, 4], xPred[:, 5]) lineSSvx.set_data(SSpoints[4, :], SSpoints[0, :]) lineSSvy.set_data(SSpoints[4, :], SSpoints[1, :]) lineSSwz.set_data(SSpoints[4, :], SSpoints[2, :]) lineSSepsi.set_data(SSpoints[4, :], SSpoints[3, :]) lineSSey.set_data(SSpoints[4, :], SSpoints[5, :]) xPred = np.zeros((N + 1, 1)) yPred = np.zeros((N + 1, 1)) SSpoints_x = np.zeros((numSS_Points, 1)) SSpoints_y = np.zeros((numSS_Points, 1)) for j in range(0, N + 1): xPred[j, 0], yPred[j, 0] = map.getGlobalPosition( LMPCOpenLoopData.PredictedStates[j, 4, i, it], LMPCOpenLoopData.PredictedStates[j, 5, i, it]) for j in range(0, numSS_Points): SSpoints_x[j, 0], SSpoints_y[j, 0] = map.getGlobalPosition( LMPCOpenLoopData.SSused[4, j, i, it], LMPCOpenLoopData.SSused[5, j, i, it]) line_tr.set_data(xPred, yPred) SSpoints_tr.set_data(SSpoints_x, SSpoints_y) anim = FuncAnimation(fig, update, frames=np.arange(0, int(LMPController.TimeSS[it])), interval=100) anim.save('ClosedLoopStates.gif', dpi=80, writer='imagemagick')
def f3(): """ 图(Figures), 子坐标(Subplots), 轴(Axes) 和 Ticks f2()中使用隐式图和轴的创建(implicit figure and axes creation)来快速的绘图,但我们能通过 figure, subplot, 和 axes explicitly 进一步控制绘图 我们已经在没有正式称呼使用 figures 和 subplots 的情况下使用了他们。当我们调用 plot,matplotlib 会调用 gca() 来获取当前轴(axes), 同时 gca 调用 gcf() 来获取当前 figure,如果没有 figure,它便会调用 figure() 来创建一个,严格地说是创建一个 subplot 调用顺序: 默认情况下, matplotlib 会调用 gca() 来获取当前轴(axes) gca 调用 gcf() 来获取当前 figure,如果没有 figure,它便会调用 figure() 来创建一个,严格地说是创建一个 subplot 图(Figures),参数如下: num 1 figure的编号 figsize figure.figsize figure的大小(宽,高,单位英尺) dpi figure.dpi 每英尺内的像素点 facecolor figure.facecolor 背景色 edgecolor figure.edgecolor 边缘的颜色 background frameon True 是否有边界 Subplots: 通过 subplots ,你可以把其他坐标限定在常规坐标里。你需要指定行数和列数 Axes: axes 非常类似于 subplots,但 axes 允许把 plots 放置在 figure 的任何位置。所以如果我们想把一个小的坐标放在大坐标里,我们应该用 axes Tick 定位器(Tick Locators): 被良好格式化的坐标轴是准备发布(publishing-ready)的 figures 的重要的一部分。Matplotlib 为坐标轴提供了一个完全可配置的系统。 tick 定位器(tick locators)是用来指定ticks 应该在哪里出现,tick 格式化器(tick formatters)则是让 ticks 拥有你希望的外观。 主要和次要的 ticks 可以单独指定位置和格式化。每个默认的次要 ticks 不会被显示,也就是说那里只会显示一个空的列表,因为它是 NullLocator(见下文)。 主要定位器如下: Class Description NullLocator 没有 ticks. IndexLocator 在每一个点的基础上绘制一个刻度。 FixedLocator Tick 的位置是固定的。 LinearLocator 每隔一个间隔放置一个 Tick MultipleLocator 每隔单位间隔放置一个 Tick AutoLocator Select no more than n intervals at nice locations. LogLocator Determine the tick locations for log axes. 所有的定位器都是从基类 matplotlib.ticker.Locator 派生 Animation 制作动画 在 matolotlib 中制作动画的最简单的方法是声明一个 FuncAnimation 对象,FuncAnimation 对象可以告知 matplotlib 哪个数字或哪个函数需要更新、 使用什么函数来更新和每个帧之间的间隔 """ # New figure with white background fig = plt.figure(figsize=(6, 6), facecolor='white') # New axis over the whole figure, no frame and a 1:1 aspect ratio ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1) n = 50 size_min = 50 size_max = 50 * 50 # Ring position P = np.random.uniform(0, 1, (n, 2)) # Ring colors C = np.ones((n, 4)) * (0, 0, 0, 1) # Alpha color channel goes from 0 (transparent) to 1 (opaque) C[:, 3] = np.linspace(0, 1, n) # Ring sizes S = np.linspace(size_min, size_max, n) # Scatter plot scat = ax.scatter(P[:, 0], P[:, 1], s=S, lw=0.5, edgecolors=C, facecolors='None') # Ensure limits are [0,1] and remove ticks ax.set_xlim(0, 1), ax.set_xticks([]) ax.set_ylim(0, 1), ax.set_yticks([]) def update(frame): global P, C, S # Every ring is made more transparent C[:, 3] = np.maximum(0, C[:, 3] - 1.0 / n) # Each ring is made larger S += (size_max - size_min) / n # Reset ring specific ring (relative to frame number) i = frame % 50 P[i] = np.random.uniform(0, 1, 2) S[i] = size_min C[i, 3] = 1 # Update scatter object scat.set_edgecolors(C) scat.set_sizes(S) scat.set_offsets(P) # Return the modified object return scat, animation = FuncAnimation(fig, update, interval=10, blit=True, frames=200) # ValueError: Cannot save animation: no writers are available. Please install ffmpeg to save animations. !!! animation.save('rain.gif', writer='imagemagick', fps=30, dpi=40) plt.show()
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation datos = np.loadtxt("datos.txt") x = np.linspace(0, 100, 125) fig, ax = plt.subplots() cuerda, = ax.plot(x, datos[0:125]) c = plt.gca() c.set_ylim([-1.0, 1.0]) def update(i): cuerda.set_ydata(datos[i * 125:(i + 1) * 125]) return cuerda marcos = np.arange(0, 250) anim = FuncAnimation(fig, update, frames=marcos, interval=20) anim.save("cuerda.gif", dpi=60, writer='imagemagick')
y = y_solution solution_trajectory.set_data(x, y) solution_trajectory.set_markersize(1.5) return solution_trajectory, node_explore_frames = 150 solution_traj_frames = 50 total_frames = node_explore_frames + solution_traj_frames step1 = int(len(x_explore)/node_explore_frames) step2 = int(len(x_solution)/solution_traj_frames) animation = FuncAnimation(fig, animate, frames=total_frames, interval=30, blit=True, repeat=False) animation.save('Mobile Robot Visualization (Dijkstra).mp4', dpi=300) plt.close() print('\n\n### Writing Visited Nodes to an Output File ###') fname1 = './Visited_Nodes_Mobile_Robot_Dijkstra.txt' myfile1 = open(fname1, "w") myfile1.write('Node # \t X \t Y \t Cumulative Cost\n') for node, x_pt, y_pt, final_cost in zip(visited_nodes, x_explore, y_explore, visited_nodes_cost): myfile1.write('{0} \t {1:1.3f} \t {2:1.3f} \t {3:1.3f}\n'.format(node, x_pt, y_pt, final_cost)) print('\nCompleted !!!') print('\n\n### Writing the solution trajectory to an Output File ###')
########################################################### #fit x = np.linspace(0, 10, num=1000) maxwellpdf = 2 * np.sqrt(m / (2 * np.pi * KT)) * np.exp(-x**2 * m / (2 * KT)) / 50 maxwelldist.set_data(hist[1][1:], hist[0] / 50) maxwellfit.set_data(x, maxwellpdf) entr.set_data(np.arange(0, len(entropy)), entropy) x = np.linspace(0, 1000, num=1000) y = np.ones(1000) * (np.log(KT) + 0.5 * np.log(var)) shan.set_data(x, y) return particle, trajectory, phasespace, maxwelldist, maxwellfit, entr, shan ani = FuncAnimation(fig, evo, frames=np.arange(0, 100), interval=50, init_func=init, blit=True) plt.tight_layout(rect=[0, 0.02, 1, 0.95]) #plt.show() # if you want to save a gif ani.save('Doublewell.gif', dpi=200, writer='pillow')
# Creation of first frame fig, ax = plt.subplots(1, 1, figsize=(1, 1), frameon=False) ax.axis("off") # Remove annoying black frame. data_x, data_y, density = load_and_extract("kelvinhelmholtz_0000.hdf5") x = np.linspace(0, 1, dpi) y = np.linspace(0, 1, dpi) xv, yv = np.meshgrid(x, y) mesh = si.griddata((data_x, data_y), density, (xv, yv), method="nearest") # Global variable for set_array plot = ax.imshow(mesh, extent=[0, 1, 0, 1], animated=True, interpolation="none") anim = FuncAnimation(fig, frame, frames, interval=40, blit=False) # Remove all whitespace fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) # Actually make the movie anim.save("khmovie.mp4", dpi=dpi, bitrate=4096)
def plot_1d_series(self, args, series_pairs, data_names): ''' Initial lines arguments: args parsed dictionary plotting arguments series_pair a list of 1D series pairs(index, grid) data_names names associated with the dictionaries to be plotted ''' fig = PyPloter.figure() def init_lines(): ''' Initial lines arguments: args parsed dictionary plotting arguments dictionaries a list of 1D series dictionary data to be plotted data_names names associated with the dictionaries to be plotted ''' if (args.hide_plot): PyPloter.switch_backend('agg') if len(series_pairs) is not len(data_names): print( "Error: len of dictionaries do not match length of associated data names" ) sys.exit(0) xname = args.x_value_name yname = args.y_value_name if len(args.scale_x) != len(series_pairs): if len(args.scale_x) == 0: args.scale_x = [1.0] * len(series_pairs) else: args.scale_x = [args.scale_x[-1]] * len(series_pairs) if len(args.scale_y) != len(series_pairs): if len(args.scale_y) == 0: args.scale_y = [1.0] * len(series_pairs) else: args.scale_y = [args.scale_y[-1]] * len(series_pairs) for series_pair, filename, scale_x, scale_y in zip( series_pairs, data_names, args.scale_x, args.scale_y): series_data = series_pair.grid index_key = next(iter(series_pair.index)) # find min and max of the data and write it to a file if necessary # clean file names if (args.data_file_name is not None): outputfile = open( args.data_file_name + '_' + filename.split('/')[-1] + '.' + re.sub(r'[^\w]', '', yname) + '.dat', 'w') xmin = (np.array(series_data[0][xname]) * scale_x).min() xmax = (np.array(series_data[0][xname]) * scale_x).max() ymin = (np.array(series_data[0][yname]) * scale_y).min() ymax = (np.array(series_data[0][yname]) * scale_y).max() for data, index_value in zip(series_data, series_pair.index[index_key]): x = np.array(data[xname]) * scale_x y = np.array(data[yname]) * scale_y xmin = min(x.min(), xmin) xmax = max(x.max(), xmax) ymin = min(y.min(), ymin) ymax = max(y.max(), ymax) if (args.data_file_name is not None): if (args.x_label is not None): header_xlabel = args.x_label else: header_xlabel = xname if (args.y_label is not None): header_ylabel = args.y_label else: header_ylabel = yname print('# ', index_key, header_xlabel, header_ylabel, file=outputfile) for x_value, y_value in zip(x, y): outstring = "%.9e" % (index_value) + " %.9e" % ( x_value * scale_x) + " %.9e" % (y_value * scale_y) + "\n" outputfile.write(outstring) if (args.data_file_name is not None): print("data saved as -- " + args.data_file_name + '_' + filename.split('/')[-1] + '.' + re.sub(r'[^\w]', '', yname) + '.dat') outputfile.close() if (args.find_max_y): print(yname, "max y value ", ymax) if (args.find_min_y): print(yname, "min y value ", ymin) # initialize the figure and axes axes = PyPloter.axes(xlim=(xmin, xmax), ylim=(ymin, ymax)) lines = [] # initialize lines data for filename in data_names: data_name = '' line, = axes.plot([], []) if (args.line_names is not None): if (len(args.line_names) != len(args.data_names)): print( "number of line names doesn't match the number of plotted lines" ) print( "line names have to be specified either for ALL or NONE of the plotted lines" ) print("number of line names = ", len(args.tracer_names)) print("number of y_value_names = ", len(args.tracer_numbers)) sys.exit() for temp_name, line_name in zip(args.data_names, args.line_names): if (temp_name == filename): data_name = filename.split( '/')[-1] + " - " + line_name else: data_name = filename.split('/')[-1] + " " + str(yname) data_line_type = '' if (args.line_types is not None): if (len(args.line_types) != len(args.y_value_names)): print( "number of line types doesn't match the number of plotted lines" ) print( "line types have to be specified either for ALL or NONE of the lines" ) print("number of line types = ", len(args.line_types)) print("number of y_value_names = ", len(args.tracer_numbers)) sys.exit() for temp_y_name, line_type in zip(args.y_value_names, args.line_types): if (temp_y_name == yname): data_line_type = line_type.strip(' ') data_line_color = '' if (args.line_colors is not None): if (len(args.line_colors) != len(args.filenames)): print( "number of line colors doesn't match the number of inputs plotted" ) print( "line colors have to be specified either for ALL or NONE of the lines" ) print("number of line colors = ", len(args.line_colors)) print("number of files plotted = ", len(data_names)) sys.exit() for temp_filename, line_color in zip( data_names, args.line_colors): if (temp_filename == filename): data_line_color = line_color if (data_line_color != '' and data_line_type != ''): line, = axes.plot([], [], label=data_name, linestyle=data_line_type, color=data_line_color) elif (data_line_color != ''): line, = axes.plot([], [], label=data_name, color=data_line_color) elif (data_line_type != ''): line, = axes.plot([], [], label=data_name, linestyle=data_line_type) else: line, = axes.plot([], [], label=data_name) lines.append(line) if (args.x_label is not None): PyPloter.xlabel(args.x_label) else: PyPloter.xlabel(xname) if (args.x_limits is not None): PyPloter.xlim(args.x_limits) if (args.y_label is not None): PyPloter.ylabel(args.y_label) else: PyPloter.ylabel(yname) if (args.y_limits is not None): PyPloter.ylim(args.y_limits) if (args.plot_grid): PyPloter.grid() PyPloter.legend(loc='best') if (args.log_x): PyPloter.xscale("log") if (args.log_y): PyPloter.yscale("log") return lines lines = init_lines() def animate(i): xname = args.x_value_name yname = args.y_value_name for j in range(0, len(series_pairs)): data = series_pairs[j].grid[i] lines[j].set_data( np.array(data[xname]) * args.scale_x[j], np.array(data[yname]) * args.scale_y[j]) return lines ani = FuncAnimation(fig, animate, frames=len(series_pairs[0].grid), blit=True) if (args.figure_name is not None): ani.save(args.figure_name, fps=30, extra_args=['-vcodec', 'libx264']) print("Plot save as -- " + args.figure_name) elif (not args.hide_plot): PyPloter.show()
def main(): parser = argparse.ArgumentParser() parser.add_argument('database', type=str) parser.add_argument('start_year', type=int, help='event start year') parser.add_argument('stop_year', type=int, help='event stop year') parser.add_argument('countries', type=str, nargs='+', help='selected countries') parser.add_argument('-t', '--title', type=str, help='title') parser.add_argument('-m', '--mode', type=str, help='mode: barh, scatter, line, pie, gantt', default='barh') parser.add_argument('-c', '--color', type=str, help='color: color, bw', default='color') parser.add_argument('-s', '--save', action='store_true', help='save plot', default=False) parser.add_argument('-d', '--density', type=str, help='density data filename') parser.add_argument('-o', '--output', type=str, help='output', default='') args = parser.parse_args() data, shorts = parse_file(args.database) if args.density: density_data, density_shorts = parse_file(args.density, 'float') not_countries = [ 'World', 'IDA & IBRD total', 'Low & middle income', 'Middle income', 'IBRD only', 'Upper middle income', 'Late-demographic dividend', 'East Asia & Pacific', 'Early-demographic dividend', 'Lower middle income', 'East Asia & Pacific (excluding high income)', 'East Asia & Pacific (IDA & IBRD countries)', 'OECD members', 'High income', 'Post-demographic dividend', 'Europe & Central Asia', 'South Asia', 'South Asia (IDA & IBRD)', 'European Union', 'IDA total', 'Europe & Central Asia (IDA & IBRD countries)', 'Europe & Central Asia (excluding high income)', 'Euro area', 'IDA only', 'Least developed countries: UN classification', 'Sub-Saharan Africa', 'Sub-Saharan Africa (IDA & IBRD countries)', 'Sub-Saharan Africa (excluding high income)', 'Latin America & Caribbean', 'Latin America & the Caribbean (IDA & IBRD countries)', 'Latin America & Caribbean (excluding high income)', 'North America', 'Pre-demographic dividend', 'Heavily indebted poor countries (HIPC)', 'Low income', 'IDA blend', 'Fragile and conflict affected situations', 'Middle East & North Africa', 'Middle East & North Africa (excluding high income)', 'Middle East & North Africa (IDA & IBRD countries)', 'Arab World', 'Central Europe and the Baltics', ] for ncount in not_countries: if ncount in data: del data[ncount] countries = {country: data[country] for country in args.countries} countries = {k: v for k, v in sorted(countries.items(), key=lambda item: item[1][args.start_year], reverse=True)} countries = list(countries.keys()) font = {'size': 22} convert_dict = {'United States': 'USA', 'Egypt, Arab Rep.': 'Egypt', 'Venezuela, RB': 'Venezuela', 'Russian Federation': 'Russia', 'Iran, Islamic Rep.': 'Iran', 'Saudi Arabia': 'S. Arabia'} plt.rc('font', **font) fig, ax = plt.subplots(figsize=(15, 8)) countries_names = [convert_dict.get(country_name, country_name) for country_name in countries] countries_shorts = [shorts[country_name] for country_name in countries] def billions(x, pos): return '%1.1fB' % (x * 1e-9) def millions(x, pos): return '%1.1fM' % (x * 1e-6) max_x = 1.1 * data[countries[0]][stop_year] formatter = ticker.FuncFormatter(millions if max_x < 300000000 else billions) def init(): return ax def animate(i): global ry, pause_dur, pause_dur2 current_year = (start_year + ry) % (stop_year + 1) ry += 1 if current_year == args.start_year: if pause_dur: pause_dur -= 1 ry -= 1 if current_year == args.stop_year: if pause_dur2: pause_dur2 -= 1 ry -= 1 i = ry ax.clear() plt.title(args.title, pad=20) pop = [data[cntry][current_year] for cntry in countries] if args.mode == 'barh': plt.xlabel('Population') ax.set_xlim(0, 1.1 * data[countries[0]][stop_year]) ax.xaxis.set_major_formatter(formatter) ax.tick_params(axis='x', which='minor', direction='out', bottom=True, length=len(countries)) ax.text(0.75, 0.82, f'{(start_year + i) % (stop_year + 1)}', transform=ax.transAxes, size=44) if args.color == 'color': ax.barh(countries_names, pop, color='royalblue') elif args.color == 'bw': ax.barh(countries_names, pop, color='white', edgecolor='black', hatch='*') else: raise Exception('Wrong color') for j, country_name in enumerate(countries): value = pop[j] + 0.01 * 1.1 * data[countries[0]][stop_year] short = countries_shorts[j] ax.text(value, j, short) elif args.mode == 'pie': ax.text(-0.2, 0.82, f'{(start_year + i) % (stop_year + 1)}', transform=ax.transAxes, size=44) ax.pie(pop, labels=countries_names, autopct='%1.1f%%') elif args.mode == 'scatter': plt.ylabel('Population') dens = [density_data[cntry][start_year + i] * 20 for cntry in countries] ax.set_ylim(0, 1.1 * data[countries[0]][stop_year]) ax.set_xlim(start_year, stop_year + 2) ax.yaxis.set_major_formatter(formatter) ax.set_xticks([year for year in range(start_year, stop_year + 2)], minor=True) ax.text(0.1, 0.82, f'{(start_year + i) % (stop_year + 1)}', transform=ax.transAxes, size=44) ax.scatter([start_year + i for _ in range(len(countries))], pop, s=dens, alpha=0.3, c=['red', 'orange', 'purple', 'blue', 'green']) for j, country_name in enumerate(countries): value = pop[j] short = countries_shorts[j] dx, dy = np.sqrt(dens[j] * 10) / fig.dpi / 2 + 10 / fig.dpi, 0. offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) ax.text(start_year + i, value, short, va='center', ha='left', transform=ax.transData + offset) elif args.mode == 'line': plt.ylabel('Population') ax.set_ylim(0, 1.1 * data[countries[0]][stop_year]) ax.set_xlim(start_year, stop_year + 2) ax.yaxis.set_major_formatter(formatter) ax.set_xticks([year for year in range(start_year, stop_year + 2)], minor=True) ax.text(0.1, 0.82, f'{(start_year + i) % (stop_year + 1)}', transform=ax.transAxes, size=44) # first must be present to connect lines prev = cpop = [data[cntry][start_year] for cntry in countries] if i == 0: # only when first frame ax.scatter([start_year for _ in range(len(countries))], cpop, c=['red', 'orange', 'purple', 'blue', 'green']) for j in range(start_year + 1, start_year + i): colors = ['red', 'orange', 'purple', 'blue', 'green'] cpop = [data[cntry][j] for cntry in countries] if j == start_year + i - 1: ax.scatter([j for _ in range(len(countries))], cpop, c=colors) for k in range(len(countries)): ax.plot([j - 1, j], [prev[k], cpop[k]], colors[k]) prev = cpop for j, country_name in enumerate(countries): value = pop[j] short = countries_shorts[j] dx, dy = 1 / fig.dpi / 2 + 10 / fig.dpi, 0. offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) ax.text(start_year + i, value, short, va='center', ha='left', transform=ax.transData + offset) else: raise Exception('Wrong mode') if args.stop_year >= current_year >= args.start_year: ax.text(0.32, 0.82, f'No data for Kuwait', transform=ax.transAxes, size=30) ax.text(0.72, 0.62, f'Gulf War', transform=ax.transAxes, size=30) ax.text(0.70, 0.52, f'(1990 - 1991)', transform=ax.transAxes, size=30) return ax global pause_dur2, pause_dur anim = FuncAnimation(fig, animate, init_func=init, frames=stop_year - start_year + 1 + pause_dur + pause_dur2, interval=200, blit=False) if args.save: anim.save(f'{args.output}event_{args.mode}_{args.color}.gif', writer='imagemagick') else: plt.show()
out = l.forward(data) se, mse0 = l.MSELoss(out, target) mean0 = mse0 ax1.scatter(l.w, l.b, mean0, c='red', alpha=0.5, s=2) ax1.scatter(minw, minb, minloss, marker='+', s=60) ax1.plot([prevw, l.w], [prevb, l.b], [prevz, mean0], alpha=0.3, c='red') prevw = l.w prevb = l.b prevz = mean0 l.backward() l.momentumGD(lr=lr) ax0.clear() ax0.title.set_text(f'prediction, epoch: {i+1}') ax0.scatter(data, target, label='data') ax0.plot([minx, maxx], [l.forward(minx), l.forward(maxx)], color='red', label='model') ax0.legend() ax0.set_ylim(miny, maxy) plt.draw() plt.pause(2e-12) print(f'epoch: {i}') return fig anim = FuncAnimation(fig, update, frames=np.arange(0, 100), interval=200) anim.save('momentum.gif', dpi=1, writer='imagemagick')
# Query the figure's on-screen size and DPI. Note that when saving the figure to # a file, we need to provide a DPI for that separately. print('fig size: {0} DPI, size in inches {1}'.format(fig.get_dpi(), fig.get_size_inches())) # Plot a scatter that persists (isn't redrawn) and the initial line. x = np.arange(0, 20, 0.1) ax.scatter(x, x + np.random.normal(0, 3.0, len(x))) line, = ax.plot(x, x - 5, 'r-', linewidth=2) def update(i): label = 'timestep {0}'.format(i) print(label) # Update the line and the axes (with a new xlabel). Return a tuple of # "artists" that have to be redrawn for this frame. line.set_ydata(x - 5 + i) ax.set_xlabel(label) return line, ax if __name__ == '__main__': # FuncAnimation will call the 'update' function for each frame; here # animating over 10 frames, with an interval of 200ms between frames. anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200) if len(sys.argv) > 1 and sys.argv[1] == 'save': anim.save('line.gif', dpi=80, writer='imagemagick') else: # plt.show() will just loop the animation forever. plt.show()
def generateVoltChart(tree, rawOut, modelDir, neatoLayout=True): ''' Map the voltages on a feeder over time using a movie.''' # We need to timestamp frames with the system clock to make sure the browser caches them appropriately. genTime = str(datetime.datetime.now()).replace(':','.') # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob)==dict and ob.get('bustype','')=='SWING': feedVoltage = float(ob.get('nominal_voltage',1)) # Make a graph object. fGraph = feeder.treeToNxGraph(tree) if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) # was formerly : positions = nx.graphviz_layout(cleanG, prog='neato') but this threw an error positions = nx.nx_agraph.graphviz_layout(cleanG, prog='neato') else: rawPositions = {n:fGraph.node[n].get('pos',(0,0)) for n in fGraph} #HACK: the import code reverses the y coords. def yFlip(pair): try: return (pair[0], -1.0*pair[1]) except: return (0,0) positions = {k:yFlip(rawPositions[k]) for k in rawPositions} # Plot all time steps. nodeVolts = {} for step, stamp in enumerate(rawOut['aVoltDump.csv']['# timestamp']): # Build voltage map. nodeVolts[step] = {} for nodeName in [x for x in rawOut.get('aVoltDump.csv',{}).keys() + rawOut.get('1nVoltDump.csv',{}).keys() + rawOut.get('1mVoltDump.csv',{}).keys() if x != '# timestamp']: allVolts = [] for phase in ['a','b','c','1n','2n','1m','2m']: try: voltStep = rawOut[phase + 'VoltDump.csv'][nodeName][step] except: continue # the nodeName doesn't have the phase we're looking for. # HACK: Gridlab complex number format sometimes uses i, sometimes j, sometimes d. WTF? if type(voltStep) is str: voltStep = voltStep.replace('i','j') v = complex(voltStep) phaseVolt = abs(v) if phaseVolt != 0.0: if _digits(phaseVolt)>3: # Normalize to 120 V standard phaseVolt = phaseVolt*(120/feedVoltage) allVolts.append(phaseVolt) # HACK: Take average of all phases to collapse dimensionality. nodeVolts[step][nodeName] = avg(allVolts) # Line current calculations lineCurrents = {} if os.path.exists(pJoin(modelDir,'OH_line_current_phaseA.csv')): for step, stamp in enumerate(rawOut['OH_line_current_phaseA.csv']['# timestamp']): lineCurrents[step] = {} currentArray = [] # Finding currents of all phases on the line for key in [x for x in rawOut.get('OH_line_current_phaseA.csv',{}).keys() if x != '# timestamp']: currA = rawOut['OH_line_current_phaseA.csv'][key][step] currB = rawOut['OH_line_current_phaseB.csv'][key][step] currC = rawOut['OH_line_current_phaseC.csv'][key][step] flowDir = rawOut['OH_line_flow_direc.csv'][key][step] lineRating = rawOut['OH_line_cont_rating.csv'][key][step] if 'R' in flowDir: direction = -1 else : direction = 1 if type(currA) is str: currA = stringToMag(currA) currB = stringToMag(currB) currC = stringToMag(currC) maxCurrent = max(abs(currA),abs(currB),abs(currC)) directedCurrent = float(maxCurrent/lineRating * direction) for objt in tree: if 'name' in tree[objt].keys(): if tree[objt]['name'] == str(int(key)): keyTup = (tree[objt]['to'],tree[objt]['from']) lineCurrents[step][keyTup] = directedCurrent # Underground Lines if os.path.exists(pJoin(modelDir,'UG_line_current_phaseA.csv')): for step, stamp in enumerate(rawOut['UG_line_current_phaseA.csv']['# timestamp']): currentArray = [] # Finding currents of all phases on the line for key in [x for x in rawOut.get('UG_line_current_phaseA.csv',{}).keys() if x != '# timestamp']: currA = rawOut['UG_line_current_phaseA.csv'][key][step] currB = rawOut['UG_line_current_phaseB.csv'][key][step] currC = rawOut['UG_line_current_phaseC.csv'][key][step] flowDir = rawOut['UG_line_flow_direc.csv'][key][step] lineRating = rawOut['UG_line_cont_rating.csv'][key][step] if 'R' in flowDir: direction = -1 else : direction = 1 if type(currA) is str: currA = stringToMag(currA) currB = stringToMag(currB) currC = stringToMag(currC) maxCurrent = max(abs(currA),abs(currB),abs(currC)) directedCurrent = float(maxCurrent/lineRating * direction) for objt in tree: if 'name' in tree[objt].keys(): if tree[objt]['name'] == str(int(key)): keyTup = (tree[objt]['to'],tree[objt]['from']) lineCurrents[step][keyTup] = directedCurrent for step in lineCurrents: for edge in fGraph.edges(): if edge not in lineCurrents[step].keys(): lineCurrents[step][edge] = 0 # Draw animation. voltChart = plt.figure(figsize=(15,15)) plt.axes(frameon = 0) plt.axis('off') #set axes step equal voltChart.gca().set_aspect('equal') custom_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(0.0,'blue'),(0.25,'darkgray'),(0.75,'darkgray'),(1.0,'yellow')]) custom_cm.set_under(color='black') current_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(0.0,'green'),(0.999999,'green'),(1.0,'red')]) # current_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(-1.0,'green'),(0.0, 'gray'),(1.0,'red'),(1.0,'red')]) # use edge color to set color and dashness of overloaded/negative currents if len(lineCurrents)>0: edgeIm = nx.draw_networkx_edges(fGraph, pos = positions, edge_color = [lineCurrents[0].get(n,0) for n in fGraph.edges()], edge_cmap = current_cm) else: edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes(fGraph, pos = positions, node_color = [nodeVolts[0].get(n,0) for n in fGraph.nodes()], linewidths = 0, node_size = 30, cmap = custom_cm) plt.sci(nodeIm) plt.clim(110,130) plt.colorbar() plt.title(rawOut['aVoltDump.csv']['# timestamp'][0]) def update(step): nodeColors = np.array([nodeVolts[step].get(n,0) for n in fGraph.nodes()]) if len(lineCurrents)>0: edgeColors = np.array([lineCurrents[step].get(n,0) for n in fGraph.edges()]) edgeIm.set_array(edgeColors) plt.title(rawOut['aVoltDump.csv']['# timestamp'][step]) nodeIm.set_array(nodeColors) return nodeColors, mapTimestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") anim = FuncAnimation(voltChart, update, frames=len(rawOut['aVoltDump.csv']['# timestamp']), interval=200, blit=False) anim.save(pJoin(modelDir,'voltageChart_'+ mapTimestamp +'.mp4'), codec='h264', extra_args=['-pix_fmt', 'yuv420p']) # Reclaim memory by closing, deleting and garbage collecting the last chart. voltChart.clf() plt.close() del voltChart gc.collect() return genTime, mapTimestamp
# plot the initial line. pred[0] = net(x) line, = ax.plot(x.data.numpy(), pred[0].data.numpy(), 'r-', lw=5) def update(i): label = 'timestep {0}'.format(i) print(label) # Update the line and the axes (with a new xlabel). Return a tuple of # "artists" that have to be redrawn for this frame. line.set_ydata(pred[i].data.numpy()) ax.set_xlabel(label) return line, ax if __name__ == '__main__': for t in range(iteration): prediction = net(x) # input x and predict based on x loss = loss_func(prediction, y) # must be (1. nn output, 2. target) optimizer.zero_grad() # clear gradients for next train loss.backward() # backpropagation, compute gradients optimizer.step() # apply gradients if t % steplength == 0: pred[t/steplength] = prediction # FuncAnimation will call the 'update' function for each frame; here # animating over 20 frames, with an interval of 200ms between frames. anim = FuncAnimation(fig, update, frames=np.arange(0, iteration/steplength), interval=200) anim.save('regression.gif', dpi=80, writer='imagemagick')
class ThreeBodyProblem: """An engine for solving 3 body problems""" # Constants # Universal Gravitational Constant G = 6.67408e-11 #N-m2/kg2 # Mass of sun m_nd = 1.989e+30 # kg # Distance between stars in Alpha Centauri r_nd = 5.326e+12 # m # Relative velocity of earth around the sun v_nd = 30_000 # m/s # Orbital period of Alpha Centauri t_nd = 79.91 * 365 * 24 * 3_600 * 0.51 # s # Simplify constants into one variable for easy use in equations K1 = (G * t_nd * m_nd) / (r_nd**2 * v_nd) K2 = (v_nd * t_nd) / r_nd def __init__(self, orbital_periods, m1, m2, m3, p1, p2, p3, v1, v2, v3): """Inititalize ThreeBodyProblem object""" self.orbital_periods = orbital_periods self.m1 = m1 self.m2 = m2 self.m3 = m3 self.p1 = p1 self.p2 = p2 self.p3 = p3 self.v1 = v1 self.v2 = v2 self.v3 = v3 # Convert position vectors to arrays p1 = np.array(p1, dtype="float64") p2 = np.array(p2, dtype="float64") p3 = np.array(p3, dtype="float64") # Find Center of Mass self.p_com = ((m1 * p1) + (m2 * p2) + (m3 * p3)) / (m1 + m2 + m3) # Convert velocity vectors to arrays v1 = np.array(v1, dtype="float64") v2 = np.array(v2, dtype="float64") v3 = np.array(v3, dtype="float64") # Find Velocity of Center of Mass self.v_com = ((m1 * v1) + (m2 * v2) + (m3 * v3)) / (m1 + m2 + m3) def equations(self, w, t, G, m1, m2, m3): """Equation model to be passed to odeint solver""" # Unpack data p1 = w[:2] p2 = w[2:4] p3 = w[4:6] v1 = w[6:8] v2 = w[8:10] v3 = w[10:12] # Find distance between bodies p12 = sci.linalg.norm(p2 - p1) p13 = sci.linalg.norm(p3 - p1) p23 = sci.linalg.norm(p3 - p2) # Run equations dv1dt = ((self.K1 * m2 * (p2 - p1)) / p12**3) + ((self.K1 * m3 * (p3 - p1)) / p13**3) dv2dt = ((self.K1 * m1 * (p1 - p2)) / p12**3) + ((self.K1 * m3 * (p3 - p2)) / p23**3) dv3dt = ((self.K1 * m1 * (p1 - p3)) / p13**3) + ((self.K1 * m2 * (p2 - p3)) / p23**3) dp1dt = self.K2 * v1 dp2dt = self.K2 * v2 dp3dt = self.K2 * v3 # Package results to be returned to solver p12_derivs = np.concatenate((dp1dt, dp2dt)) r_derivs = np.concatenate((p12_derivs, dp3dt)) v12_derivs = np.concatenate((dv1dt, dv2dt)) v_derivs = np.concatenate((v12_derivs, dv3dt)) derivs = np.concatenate((r_derivs, v_derivs)) return derivs def calculate_trajectories(self): """Calculates the trajectories of the 3 bodies in instance of problem""" print("Calculating trajectories...") s = time.perf_counter() # Prepare initial parameters init_params = np.array( [self.p1, self.p2, self.p3, self.v1, self.v2, self.v3]) init_params = init_params.flatten() time_span = np.linspace(0, self.orbital_periods, 750) # Run the odeint solver self.results = odeint(self.equations, init_params, time_span, args=(self.G, self.m1, self.m2, self.m3)) e = time.perf_counter() print(f"Done ({ (e - s) * 1000} ms)") return self.results def animation_frame(self, i): """Function for animating display of data""" self.line1.set_data(self.p1_x[:i], self.p1_y[:i]) self.line2.set_data(self.p2_x[:i], self.p2_y[:i]) self.line3.set_data(self.p3_x[:i], self.p3_y[:i]) return self.line1, self.line2, self.line3 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 to_csv(self, filename): """Writes results to a csv file""" fields = [ "p1_x", "p1_y", "p2_x", "p2_y", "p3_x", "p3_y", "v1_x", "v1_y", "v2_x", "v2_y", "v3_x", "v3_y" ] print(f"Writing to {filename}...") with open(filename, 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(fields) csvwriter.writerows(self.results) print("Done")
def create_visualization(observations_file, output_file, viz_type="animation"): """Generates a plot overlaying user trace data on the SAR V1 map.""" # Load time and position data from the observation file position_times, position_coords = get_time_and_position_data( observations_file) # Create the plot object with a helpful title fig = plt.figure(figsize=(9, 8)) ax = plt.gca() ax.set_title("SAR Gameplay Time-based Position Trace") # Add arena walls and house objects arena_walls = PathCollection( [ Path([(44, 43), (98, 43), (98, 100), (44, 100), (44, 43)]), Path([(58, 77), (60, 77), (60, 74), (73, 74), (83, 74), (83, 43)]), ], edgecolor="black", facecolor="None", lw=3, ) small_and_large_houses = PathCollection( [ Path([(50, 96), (56, 96), (56, 90), (50, 90), (50, 96)]), Path([(45, 49), (49, 49), (49, 44), (45, 44), (45, 49)]), Path([(87, 55), (92, 55), (92, 49), (87, 49), (87, 55)]), Path([ (85, 97), (94, 97), (94, 91), (90, 91), (90, 85), (84, 85), (84, 90), (85, 90), (85, 97), ]), Path([ (73, 74), (83, 74), (83, 63), (78, 63), (78, 69), (73, 69), (73, 74), ]), Path([ (59, 66), (68, 66), (68, 60), (64, 60), (64, 54), (58, 54), (58, 59), (59, 59), (59, 66), ]), ], color=(166 / 255, 89 / 255, 50 / 255, 1.0), lw=1, ) ax.add_collection(small_and_large_houses) ax.add_collection(arena_walls) # Plot the user observation trace with a time legend (X, Y) = map(list, zip(*position_coords)) if viz_type == "plot": cax = ax.scatter(X, Y, s=1, c=position_times, cmap=plt.get_cmap("viridis")) cbar = fig.colorbar(cax) cbar.ax.set_ylabel("Time in minutes") plt.tight_layout() plt.savefig(output_file) elif viz_type == "animation": timestamp = plt.text(80, 101, "time = 0.0") (ln, ) = plt.plot([], []) def init(): return ln, timestamp xdata = [] ydata = [] def update(frame): xdata.append(X[frame]) ydata.append(Y[frame]) ln.set_data(xdata, ydata) timestamp.set_text(f"Time = {position_times[frame]}") return ln, timestamp animation = FuncAnimation( fig, update, frames=trange(len(position_times)), interval=1, init_func=init, ) animation.save(output_file) else: raise Exception("viz_type must be one of [plot|animation]")
calc_amp = np.nan center_x = np.nan center_y = np.nan calc_sig_x = np.nan calc_sig_y = np.nan calc_offset = off_guess cntr = ax.contour(x, y, blank_contour, 8, colors='w') animation = FuncAnimation(fig, update, frames=frames, interval=80, repeat=False) animation.save(ml + '.mp4', writer='ffmpeg', dpi=300, bitrate=24000, fps=14) plt.close('all') locus_loc_y = 0 locus_loc_x = 0 local_data = np.zeros((frames, local_size, local_size), np.uint16) for f in range(0, frames): data = im[f, :, :] if (not df.loc[(df['C1_Image'] == ml) & (df['C1_T Value (frame)'] == (f + 1)), 'C1_Y Value (pixel)'].empty) and (not df.loc[ (df['C1_Image'] == ml) & (df['C1_T Value (frame)'] == (f + 1)),
C[0] = C[0] - learning_rate * (1/math.sqrt(diag_G_C[0] + 10**(-8))) * derivative_x(C[0], C[1]) C[1] = C[1] - learning_rate * (1/math.sqrt(diag_G_C[1] + 10**(-8))) * derivative_y(C[0], C[1]) diag_G_D[0] = diag_G_D[0] + (derivative_x(D[0], D[1]))**2 diag_G_D[1] = diag_G_D[1] + (derivative_y(D[0], D[1]))**2 D[0] = D[0] - learning_rate * (1/math.sqrt(diag_G_D[0] + 10**(-8))) * derivative_x(D[0], D[1]) D[1] = D[1] - learning_rate * (1/math.sqrt(diag_G_D[1] + 10**(-8))) * derivative_y(D[0], D[1]) diag_G_E[0] = diag_G_E[0] + (derivative_x(E[0], E[1]))**2 diag_G_E[1] = diag_G_E[1] + (derivative_y(E[0], E[1]))**2 E[0] = E[0] - learning_rate * (1/math.sqrt(diag_G_E[0] + 10**(-8))) * derivative_x(E[0], E[1]) E[1] = E[1] - learning_rate * (1/math.sqrt(diag_G_E[1] + 10**(-8))) * derivative_y(E[0], E[1]) div = 1 #for i in range(0, epochs//10): def animate(i): # https://stackoverflow.com/questions/509211/understanding-slice-notation ax.plot(a_history[0][i*div:(i+1)*div + 1], a_history[1][i*div:(i+1)*div + 1], color='blue', linewidth=4) ax.plot(b_history[0][i*div:(i+1)*div + 1], b_history[1][i*div:(i+1)*div + 1], color='red', linewidth=4) ax.plot(c_history[0][i*div:(i+1)*div + 1], c_history[1][i*div:(i+1)*div + 1], color='cyan', linewidth=4) ax.plot(d_history[0][i*div:(i+1)*div + 1], d_history[1][i*div:(i+1)*div + 1], color='magenta', linewidth=4) ax.plot(e_history[0][i*div:(i+1)*div + 1], e_history[1][i*div:(i+1)*div + 1], color='black', linewidth=4) # https://eli.thegreenplace.net/2016/drawing-animated-gifs-with-matplotlib/ anim = FuncAnimation(fig, animate, frames=np.arange(0, epochs//div), interval=200) anim.save('images/adagrad-himmelblau.gif', dpi=80)
title=r'mode $n$ = {}'.format(i), xlim=(-5, 5)) ax.label_outer() print("All plot settings done") def update(frame): # Real part nmodeReal1.set_ydata(nFrames[0][frame][2, :]) nmodeReal2.set_ydata(nFrames[1][frame][2, :]) nmodeReal3.set_ydata(nFrames[2][frame][2, :]) nmodeReal4.set_ydata(nFrames[3][frame][2, :]) # Imaginary part nmodeImag1.set_ydata(nFrames[0][frame][3, :]) nmodeImag2.set_ydata(nFrames[1][frame][3, :]) nmodeImag3.set_ydata(nFrames[2][frame][3, :]) nmodeImag4.set_ydata(nFrames[3][frame][3, :]) return nmodeReal1, nmodeReal2, nmodeReal3, nmodeReal4, nmodeImag1, nmodeImag2, nmodeImag3, nmodeImag4, output = os.path.join(dataPars[0].getDataDir(), "plots", "normmodes") outputName = os.path.join(output, outputName) animation = FuncAnimation(fig, update, frames=range(1, len(nFrames[0]) // 10, 1), blit=True) animation.save(outputName, writer="imagemagick", fps=30, dpi=40)
def saveGif_xyResults(map, LMPCOpenLoopData, LMPController, it): SS_glob = LMPController.SS_glob TimeSS = LMPController.TimeSS SS = LMPController.SS uSS = LMPController.uSS Points = int( np.floor(10 * (map.PointAndTangent[-1, 3] + map.PointAndTangent[-1, 4]))) Points1 = np.zeros((Points, 2)) Points2 = np.zeros((Points, 2)) Points0 = np.zeros((Points, 2)) for i in range(0, int(Points)): Points1[i, :] = map.getGlobalPosition(i * 0.1, map.width) Points2[i, :] = map.getGlobalPosition(i * 0.1, -map.width) Points0[i, :] = map.getGlobalPosition(i * 0.1, 0) fig = plt.figure(101) plt.ylim((-5, 1.5)) fig.set_tight_layout(True) plt.plot(map.PointAndTangent[:, 0], map.PointAndTangent[:, 1], 'o') plt.plot(Points0[:, 0], Points0[:, 1], '--') plt.plot(Points1[:, 0], Points1[:, 1], '-b') plt.plot(Points2[:, 0], Points2[:, 1], '-b') plt.plot(SS_glob[0:TimeSS[it], 4, it], SS_glob[0:TimeSS[it], 5, it], '-ok', label="Closed-loop trajectory", markersize=1, zorder=-1) ax = plt.axes() SSpoints_x = [] SSpoints_y = [] xPred = [] yPred = [] SSpoints, = ax.plot(SSpoints_x, SSpoints_y, 'sb', label="SS", zorder=0) line, = ax.plot(xPred, yPred, '-or', label="Predicted Trajectory", zorder=1) v = np.array([[1., 1.], [1., -1.], [-1., -1.], [-1., 1.]]) rec = patches.Polygon(v, alpha=0.7, closed=True, fc='r', ec='k', zorder=10) ax.add_patch(rec) plt.legend(mode="expand", ncol=3) # plt.legend(bbox_to_anchor=(0,1.02,1,0.2), loc="lower left", # mode="expand", borderaxespad=0, ncol=3) N = LMPController.N numSS_Points = LMPController.numSS_Points def update(i): xPred = np.zeros((N + 1, 1)) yPred = np.zeros((N + 1, 1)) SSpoints_x = np.zeros((numSS_Points, 1)) SSpoints_y = np.zeros((numSS_Points, 1)) for j in range(0, N + 1): xPred[j, 0], yPred[j, 0] = map.getGlobalPosition( LMPCOpenLoopData.PredictedStates[j, 4, i, it], LMPCOpenLoopData.PredictedStates[j, 5, i, it]) if j == 0: x = SS_glob[i, 4, it] y = SS_glob[i, 5, it] psi = SS_glob[i, 3, it] l = 0.4 w = 0.2 car_x = [ x + l * np.cos(psi) - w * np.sin(psi), x + l * np.cos(psi) + w * np.sin(psi), x - l * np.cos(psi) + w * np.sin(psi), x - l * np.cos(psi) - w * np.sin(psi) ] car_y = [ y + l * np.sin(psi) + w * np.cos(psi), y + l * np.sin(psi) - w * np.cos(psi), y - l * np.sin(psi) - w * np.cos(psi), y - l * np.sin(psi) + w * np.cos(psi) ] for j in range(0, numSS_Points): SSpoints_x[j, 0], SSpoints_y[j, 0] = map.getGlobalPosition( LMPCOpenLoopData.SSused[4, j, i, it], LMPCOpenLoopData.SSused[5, j, i, it]) SSpoints.set_data(SSpoints_x, SSpoints_y) line.set_data(xPred, yPred) rec.set_xy(np.array([car_x, car_y]).T) anim = FuncAnimation(fig, update, frames=np.arange(0, int(LMPController.TimeSS[it])), interval=100) anim.save('ClosedLoop.gif', dpi=80, writer='imagemagick')
binlist, geocarray = bin_accretion.cc_accretion(signal, var, target) print(geocarray) scalearray = np.full(len(geocarray), 1) #wvt=functions.generate_wvt(binlist,signal) for i in range(epsilon): geocarray, scalearray = iteration_func(target, signal, var, geocarray, scalearray) np.random.shuffle(geocarray) for offset in off: sbl, svl, freakya = iteration_funca(target, signal, var, geocarray, scalearray) print("iteration over") anim = FuncAnimation(fig, update, frames=range(offset, len(sbl)), fargs=(sbl, svl), interval=50) print("setup animation") objname = "s_testdata" anim.save(sourcedir + "/" + objname + "_" + str(offset) + "_vid.gif", writer=PillowWriter(fps=24)) print("exit")
ax = fig.axes[0] position_list = [[250, 100], [100, 250], [250, 400], [400, 250], [250, 100], [-10, 80]] frames = apt._generate_frames_position_list(position_list, num=10) fig.dpi = 100 fargs = [fig, poly] apt._draw_cursor(ax, frames[0][0], frames[0][1]) anim = FuncAnimation(fig, apt._update_frame_poly, frames=frames, fargs=fargs, interval=400, repeat=False) anim.save(os.path.join(my_path, "atom_selector_gui.gif"), writer='pillow') plt.close(fig) ##### s = am.dummy_data.get_precipitate_signal() peaks = am.get_atom_positions(s, 8) atom_selector = agc.GetAtomSelection(s, peaks, invert_selection=True) poly = atom_selector.poly fig = atom_selector.fig ax = fig.axes[0] position_list = [[250, 100], [100, 250], [250, 400], [400, 250], [250, 100], [-10, 80]] frames = apt._generate_frames_position_list(position_list, num=10)
def animate_emission(hmm, obs_map, M=8, height=12, width=12, delay=1): # Parameters. lim = 1200 text_x_offset = 40 text_y_offset = 80 x_offset = 580 y_offset = 520 R = 420 r = 100 arrow_size = 20 arrow_p1 = 0.03 arrow_p2 = 0.02 arrow_p3 = 0.06 # Initialize. n_states = len(hmm.A) obs_map_r = obs_map_reverser(obs_map) wordclouds = states_to_wordclouds(hmm, obs_map, max_words=20, show=False) # Initialize plot. fig, ax = plt.subplots() fig.set_figheight(height) fig.set_figwidth(width) ax.grid('off') plt.axis('off') ax.set_xlim([0, lim]) ax.set_ylim([0, lim]) # Plot each wordcloud. for i, wordcloud in enumerate(wordclouds): x = x_offset + int(R * np.cos(np.pi * 2 * i / n_states)) y = y_offset + int(R * np.sin(np.pi * 2 * i / n_states)) ax.imshow(wordcloud.to_array(), extent=(x - r, x + r, y - r, y + r), aspect='auto', zorder=-1) # Initialize text. text = ax.text(text_x_offset, lim - text_y_offset, '', fontsize=24) # Make the arrows. zorder_mult = n_states ** 2 * 100 arrows = [] for i in range(n_states): row = [] for j in range(n_states): # Arrow coordinates. x_i = x_offset + R * np.cos(np.pi * 2 * i / n_states) y_i = y_offset + R * np.sin(np.pi * 2 * i / n_states) x_j = x_offset + R * np.cos(np.pi * 2 * j / n_states) y_j = y_offset + R * np.sin(np.pi * 2 * j / n_states) dx = x_j - x_i dy = y_j - y_i d = np.sqrt(dx**2 + dy**2) if i != j: arrow = ax.arrow(x_i + (r/d + arrow_p1) * dx + arrow_p2 * dy, y_i + (r/d + arrow_p1) * dy + arrow_p2 * dx, (1 - 2 * r/d - arrow_p3) * dx, (1 - 2 * r/d - arrow_p3) * dy, color=(1 - hmm.A[i][j], ) * 3, head_width=arrow_size, head_length=arrow_size, zorder=int(hmm.A[i][j] * zorder_mult)) else: arrow = ax.arrow(x_i, y_i, 0, 0, color=(1 - hmm.A[i][j], ) * 3, head_width=arrow_size, head_length=arrow_size, zorder=int(hmm.A[i][j] * zorder_mult)) row.append(arrow) arrows.append(row) emission, states = hmm.generate_emission_original(M) def animate(i): if i >= delay: i -= delay if i == 0: arrows[states[0]][states[0]].set_color('red') elif i == 1: arrows[states[0]][states[0]].set_color((1 - hmm.A[states[0]][states[0]], ) * 3) arrows[states[i - 1]][states[i]].set_color('red') else: arrows[states[i - 2]][states[i - 1]].set_color((1 - hmm.A[states[i - 2]][states[i - 1]], ) * 3) arrows[states[i - 1]][states[i]].set_color('red') # Set text. text.set_text(' '.join([obs_map_r[e] for e in emission][:i+1]).capitalize()) return arrows + [text] # Animate! print('\nAnimating...') anim = FuncAnimation(fig, animate, frames=M+delay, interval=1000) Writer = animation.writers['ffmpeg'] writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800) anim.save('anim.mp4', writer=writer) return anim
def animate_mnist_examples(train_history, x_test, examples_indices, model_name) : batch_history = train_history['monitor_batches'] scores_history = train_history['monitor_importance_scores'] nll_loss_history = train_history['monitor_nll_losses'] sel_scores_history = [ temp_scores[0][examples_indices, ...] for temp_scores in scores_history ] sel_nll_loss_history = [ temp_nll_loss[examples_indices, ...] for temp_nll_loss in nll_loss_history ] min_nll_loss = np.min(np.array([np.min(sel_nll_loss_history[i]) for i in range(len(sel_nll_loss_history))])) max_nll_loss = np.max(np.array([np.max(sel_nll_loss_history[i]) for i in range(len(sel_nll_loss_history))])) def _rolling_average(x, window=50) : x_avg = [] for j in range(x.shape[0]) : j_min = max(j - window + 1, 0) x_avg.append(np.mean(x[j_min:j+1])) return np.array(x_avg) sel_nll_loss_history = np.concatenate([sel_nll_loss_history[t].reshape(1, -1) for t in range(len(sel_nll_loss_history))], axis=0) for example_ix in range(sel_nll_loss_history.shape[1]) : sel_nll_loss_history[:, example_ix] = _rolling_average(sel_nll_loss_history[:, example_ix]) sel_nll_loss_history = [ sel_nll_loss_history[t, :] for t in range(sel_nll_loss_history.shape[0]) ] #Concatenate time slices of all chosen example images big_images = [] big_scores = [] for t in range(len(sel_scores_history)) : big_image = np.concatenate([ np.concatenate([x_test[0, :, :, 1], x_test[1, :, :, 1], x_test[2, :, :, 1]], axis=0), np.concatenate([x_test[3, :, :, 1], x_test[4, :, :, 1], x_test[5, :, :, 1]], axis=0), np.concatenate([x_test[6, :, :, 1], x_test[7, :, :, 1], x_test[8, :, :, 1]], axis=0), ], axis=1) big_score = np.concatenate([ np.concatenate([sel_scores_history[t][0, :, :, 0], sel_scores_history[t][1, :, :, 0], sel_scores_history[t][2, :, :, 0]], axis=0), np.concatenate([sel_scores_history[t][3, :, :, 0], sel_scores_history[t][4, :, :, 0], sel_scores_history[t][5, :, :, 0]], axis=0), np.concatenate([sel_scores_history[t][6, :, :, 0], sel_scores_history[t][7, :, :, 0], sel_scores_history[t][8, :, :, 0]], axis=0), ], axis=1) big_images.append(big_image) big_scores.append(big_score) #Animation 1: NLL Loss and Example Images n_examples = sel_nll_loss_history[0].shape[0] n_frames = len(big_images) - 1 f, (ax1, ax2) = plt.subplots(2, 1, figsize=(5, 9), gridspec_kw={'width_ratios': [1], 'height_ratios': [2, 3.5]}) #Plot Images #ax2.axis('off') #ax2.get_yaxis().set_visible(False) plt.sca(ax2) plt.xticks([], []) plt.yticks([], []) ax2.imshow(big_images[-1], cmap="Greys", vmin=0.0, vmax=1.0, aspect='equal') ax2.imshow(big_scores[-1], alpha=0.75, cmap="hot", vmin=0.0, vmax=np.max(big_scores[-1]), aspect='equal') loss_lines = [] for i in range(n_examples) : line, = ax1.plot([], [], linewidth=2) loss_lines.append(line) plt.sca(ax1) plt.ylabel("Reconstruction Loss", fontsize=14) plt.xticks([0, batch_history[n_frames-1]], [0, batch_history[n_frames-1]], fontsize=14) plt.yticks(fontsize=14) plt.xlim(0, batch_history[n_frames-1]) plt.ylim(0., max_nll_loss + 0.02 * max_nll_loss * np.sign(max_nll_loss)) plt.title("Weight Update 0\n1x Speedup >", fontsize=14) plt.tight_layout() plt.subplots_adjust(wspace=0.15) loss_data_x = [[0] for i in range(n_examples)] loss_data_y = [[sel_nll_loss_history[0][i]] for i in range(n_examples)] def init() : for i in range(n_examples) : loss_lines[i].set_data([], []) return [] def animate(t) : if t % 10 == 0 : print("Grabbing frame " + str(t) + "...") if t > 0 : for i in range(n_examples) : loss_data_x[i].append(batch_history[t]) loss_data_y[i].append(sel_nll_loss_history[t][i]) loss_lines[i].set_data(loss_data_x[i], loss_data_y[i]) curr_speed = 1 speed_sign = ">" if t > 0 : curr_speed = int(batch_history[t] - batch_history[t-1]) if curr_speed <= 1 : speed_sign = ">" elif curr_speed > 1 and curr_speed <= 5 : speed_sign = ">>" elif curr_speed > 5 : speed_sign = ">>>" ax1.set_title("Weight Update " + str(batch_history[t]) + "\n" + str(curr_speed) + "x Speedup " + speed_sign, fontsize=14) ax2.clear() plt.sca(ax2) plt.xticks([], []) plt.yticks([], []) ax2.imshow(big_images[t], cmap="Greys", vmin=0.0, vmax=1.0, aspect='equal') ax2.imshow(big_scores[t], alpha=0.75, cmap="hot", vmin=0.0, vmax=np.max(big_scores[t]), aspect='equal') return [] anim = FuncAnimation(f, animate, init_func=init, frames=n_frames+1, interval=50, blit=True) anim.save(model_name + '.gif', writer='imagemagick')
# Query the figure's on-screen size and DPI. # Note that when saving the figure to a file, # we need to provide a DPI for that separately. print('fig size: {0} DPI, size in inches {1}'.format( fig.get_dpi(), fig.get_size_inches())) # Plot a scatter that persists (isn't redrawn) and the initial line. x = np.arange(0, 20, 0.1) ax.scatter(x, x + np.random.normal(0, 3.0, len(x))) line, = ax.plot(x, x - 5, 'r-', linewidth=2) def update(i): label = 'timestep {0}'.format(i) print(label) # Update the line and the axes (with a new xlabel). # Return a tuple of "artists" that have to be redrawn for this frame. line.set_ydata(x - 5 + i) ax.set_xlabel(label) return line, ax if __name__ == '__main__': # FuncAnimation will call the 'update' function for each frame; here # animating over 10 frames, with an interval of 200ms between frames. anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200) if len(sys.argv) > 1 and sys.argv[1] == 'save': anim.save('line.gif', dpi=80, writer='imagemagick') else: # plt.show() will just loop the animation forever. plt.show()
self._emit('select', self.selected) else: self.selected = None self.fig.canvas.draw_idle() if __name__ == '__main__': from matplotlib.animation import FuncAnimation ncf = netcdf_file('KTLX_20100510_22Z.nc') data = ncf.variables['Reflectivity'] lats = ncf.variables['lat'] lons = ncf.variables['lon'] stormcells = storm_loader('polygons.shp') fig, ax = plt.subplots(1, 1) raddisp = RadarDisplay(ax, lats, lons) raddisp.update_display(data[0]) fig.colorbar(raddisp.im) polycolls = Stormcells(ax, stormcells) linecoll = Tracks(ax) # Turn on the first frame's polygons polycolls.toggle_polygons(0, True) ax.autoscale(True) ctrl_sys = ControlSys(fig, raddisp, data, polycolls, linecoll, stormcells) anim = FuncAnimation(fig, lambda _: ctrl_sys.change_frame(1), frames=data.shape[0], repeat=False) anim.save('storms_with_tracks.gif', writer='imagemagick')
def generateVoltChart(tree, rawOut, modelDir, neatoLayout=True): ''' Map the voltages on a feeder over time using a movie.''' # We need to timestamp frames with the system clock to make sure the browser caches them appropriately. genTime = str(datetime.datetime.now()).replace(':','.') # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob)==dict and ob.get('bustype','')=='SWING': feedVoltage = float(ob.get('nominal_voltage',1)) # Make a graph object. fGraph = feeder.treeToNxGraph(tree) if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) # was formerly : positions = nx.graphviz_layout(cleanG, prog='neato') but this threw an error positions = graphviz_layout(cleanG, prog='neato') else: rawPositions = {n:fGraph.node[n].get('pos',(0,0)) for n in fGraph} #HACK: the import code reverses the y coords. def yFlip(pair): try: return (pair[0], -1.0*pair[1]) except: return (0,0) positions = {k:yFlip(rawPositions[k]) for k in rawPositions} # Plot all time steps. nodeVolts = {} for step, stamp in enumerate(rawOut['aVoltDump.csv']['# timestamp']): # Build voltage map. nodeVolts[step] = {} for nodeName in [x for x in rawOut['aVoltDump.csv'].keys() if x != '# timestamp']: allVolts = [] for phase in ['a','b','c']: voltStep = rawOut[phase + 'VoltDump.csv'][nodeName][step] # HACK: Gridlab complex number format sometimes uses i, sometimes j, sometimes d. WTF? if type(voltStep) is str: voltStep = voltStep.replace('i','j') v = complex(voltStep) phaseVolt = abs(v) if phaseVolt != 0.0: if _digits(phaseVolt)>3: # Normalize to 120 V standard phaseVolt = phaseVolt*(120/feedVoltage) allVolts.append(phaseVolt) # HACK: Take average of all phases to collapse dimensionality. nodeVolts[step][nodeName] = avg(allVolts) # Draw animation. voltChart = plt.figure(figsize=(15,15)) plt.axes(frameon = 0) plt.axis('off') #set axes step equal voltChart.gca().set_aspect('equal') custom_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(0.0,'blue'),(0.25,'darkgray'),(0.75,'darkgray'),(1.0,'yellow')]) edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes(fGraph, pos = positions, node_color = [nodeVolts[0].get(n,0) for n in fGraph.nodes()], linewidths = 0, node_size = 30, cmap = custom_cm) plt.sci(nodeIm) plt.clim(110,130) plt.colorbar() plt.title(rawOut['aVoltDump.csv']['# timestamp'][0]) def update(step): nodeColors = np.array([nodeVolts[step].get(n,0) for n in fGraph.nodes()]) plt.title(rawOut['aVoltDump.csv']['# timestamp'][step]) nodeIm.set_array(nodeColors) return nodeColors, anim = FuncAnimation(voltChart, update, frames=len(rawOut['aVoltDump.csv']['# timestamp']), interval=200, blit=False) anim.save(pJoin(modelDir,'voltageChart.mp4'), codec='h264', extra_args=['-pix_fmt', 'yuv420p']) # Reclaim memory by closing, deleting and garbage collecting the last chart. voltChart.clf() plt.close() del voltChart gc.collect() return genTime
def write_animation(data, fileName, saturation=2, clims=(0,1), cmap=None, label=None, label_caption='meV', speed=8, zoom=1, **kwargs): ''' Create a movie from a 3D data set and save it to the path specified. Intended for visualising DOS maps and QPI data. Iterates through the first index in the data set to create an animation. Notes: Make sure you include file extension (eg '.mov') in the file path. Currently supported file types are mov and mp4. Make sure you have ffmpeg installed (e.g. through Homebrew) before running. The MP4 writer is really difficult to get high quality. I learned that it depends on figsize, bitrate and dpi. Basically, if the combination of these parameters falls outside of a narrow window the compression session will fail to start. The defaults used in this script seem to work. Inputs: data - Required : A 3D numpy array containing each frame in the movie. fileName - Required : Full path for output file including extension. saturation - Optional : Saturation applied to each frame separately. clims - Optional : If saturation=None, user defined clims are used. Specify as a tuple (cmin, cmax). cmap - Optional : Colormap instance will default to cm.bone_r if not specified. label - Optional : Data to use for labeling frames. Must have the same length as data.shape[0]. label_caption - Optional : String to be displayed after label. speed - Optional : Frames per second for output. zoom - Optional : Float for zoom factor (eg. 2 times zoom). **kwarg - Optional : Additional keyword arguments are sent to imshow(). Returns: Has no returns. Usage: write_animation(data, fileName, saturation=2, clims=(0,1), cmap=None, label=None, label_caption='meV', speed=8, zoom=1, **kwargs) History: 2017-06-08 - HP : Added **kwargs sent to imshow 2017-06-23 - HP : Added support for MP4 export and made codec choice automatic. ''' boxProperties = dict(boxstyle='square', facecolor='w', alpha=0.8, linewidth=0.0) textOptions = dict(fontsize=14, color='k', bbox=boxProperties, ha='right', va='center') if cmap is None: cmap = cm.bone_r fig = plt.figure(figsize=[4,4]) ax = plt.subplot(111) ax.set_xticks([]), ax.set_yticks([]) im = plt.imshow(data[0], cmap=cmap, extent=[-1,1,-1,1], origin='lower', **kwargs) ax.set_xlim(-1.0/zoom, 1.0/zoom) ax.set_ylim(-1.0/zoom, 1.0/zoom) if saturation is not None: saturate(saturation, im=im) else: plt.clim(clims) if label is not None: tx = ax.text(0.95,0.95,'{:2.1f} {:}'.format(label[0], label_caption), transform=ax.transAxes, **textOptions) def init(): im.set_array(data[0]) ax.text(20,200,'') return [im] def animate(i): im.set_array(data[i]) if saturation is not None: saturate(saturation, im=im) else: plt.clim(clims) if label is not None: tx.set_text('{:2.1f} {:}'.format(label[i], label_caption)) return [im] fig.tight_layout() ani = FuncAnimation(fig, animate, init_func=init, frames=data.shape[0]) if fileName.endswith('.mov'): ani.save(fileName, codec='prores', dpi=200, fps=speed) elif fileName.endswith('.mp4'): ani.save(fileName, dpi=200, bitrate=1e5, fps=speed) else: print('ERR: fileName must end with .mov or .mp4')
def render_animation_valid(input_pose_kinect, keypoints, poses, skeleton, fps, bitrate, azim, output, viewport, limit=-1, downsample=1, size=6, input_image_folder=None, input_video_skip=0): """ input_pose_kinect TODO Render an animation. The supported output modes are: -- 'interactive': display an interactive figure (also works on notebooks if associated with %matplotlib inline) -- 'html': render the animation as HTML5 video. Can be displayed in a notebook using HTML(...). -- 'filename.mp4': render and export the animation as an h264 video (requires ffmpeg). -- 'filename.gif': render and export the animation a gif file (requires imagemagick). """ plt.ioff() fig = plt.figure(figsize=(size * (2 + len(poses)), size)) ax_in = fig.add_subplot(1, 3, 1) ax_in.get_xaxis().set_visible(False) ax_in.get_yaxis().set_visible(False) ax_in.set_axis_off() ax_in.set_title('Input with 2D points') ax_3d = [] lines_3d = [] trajectories = [] radius = 1.7 for index, (title, data) in enumerate(poses.items()): ax = fig.add_subplot(1, 3, index + 2, projection='3d') ax.view_init(elev=15., azim=azim) ax.set_xlim3d([-radius / 2, radius / 2]) ax.set_zlim3d([0, radius]) ax.set_ylim3d([-radius / 2, radius / 2]) ax.set_aspect('equal') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_zticklabels([]) ax.dist = 12.5 ax.set_title(title) # , pad=35 ax_3d.append(ax) lines_3d.append([]) trajectories.append(data[:, 0, [0, 1]]) poses = list(poses.values()) lines_kinect=[] axk = fig.add_subplot(1,3,3, projection='3d') axk.view_init(elev=15., azim=azim) axk.set_xticklabels([]) axk.set_yticklabels([]) axk.set_zticklabels([]) axk.set_xlim3d([-radius / 2, radius / 2]) axk.set_zlim3d([0, radius]) axk.set_ylim3d([-radius / 2, radius / 2]) axk.set_aspect('equal') axk.set_title('Kinect') axk.dist=12.5 kinect_parents = [1, 16, 3, -1 , 16, 4, 5, 16, 7, 8, 0, 10, 11, 0, 13, 14, 2 ] # Decode video if input_image_folder is None: # Black background all_frames = np.zeros((keypoints.shape[0], viewport[1], viewport[0]), dtype='uint8') else: # Load images all_frames = [] if os.path.isdir(input_image_folder): im_list = glob.iglob(input_image_folder + '/*' + '.bmp') else: im_list = [input_image_folder] im_list = sorted(im_list) for i, im_name in enumerate(im_list): print("Index: {} - Image: {}".format(i, im_name)) _image = cv2.imread(im_name) b, g, r = cv2.split(_image) # get b,g,r rgb_img = cv2.merge([r, g, b]) # switch it to rgb all_frames.append(rgb_img) #if(i == 10): # break if downsample > 1: keypoints = downsample_tensor(keypoints, downsample) all_frames = downsample_tensor(np.array(all_frames), downsample).astype('uint8') for idx in range(len(poses)): poses[idx] = downsample_tensor(poses[idx], downsample) trajectories[idx] = downsample_tensor(trajectories[idx], downsample) fps /= downsample initialized = False image = None lines = [] points = None points2 = None if limit < 1: limit = len(all_frames) else: limit = min(limit, len(all_frames)) parents = skeleton.parents() def update_video(i): nonlocal initialized, image, lines, points, points2 for n, ax in enumerate(ax_3d): ax.set_xlim3d([-radius / 2 + trajectories[n][i, 0], radius / 2 + trajectories[n][i, 0]]) ax.set_ylim3d([-radius / 2 + trajectories[n][i, 1], radius / 2 + trajectories[n][i, 1]]) # Update 2D poses if not initialized: index_k = 0 image = ax_in.imshow(all_frames[i], aspect='equal') for j, j_parent in enumerate(parents): if j_parent != -1: if len(parents) == keypoints.shape[1] and 1 == 2: # Draw skeleton only if keypoints match (otherwise we don't have the parents definition) lines.append(ax_in.plot([keypoints[i, j, 0], keypoints[i, j_parent, 0]], [keypoints[i, j, 1], keypoints[i, j_parent, 1]], color='pink')) col = 'red' if j in skeleton.joints_right() else 'black' for n, ax in enumerate(ax_3d): pos = poses[n][i] lines_3d[n].append(ax.plot([pos[j, 0], pos[j_parent, 0]], [pos[j, 1], pos[j_parent, 1]], [pos[j, 2], pos[j_parent, 2]], zdir='z', c=col)) col_kin = 'red' if index_k in [4,5,6,10,11,12] else 'black' kin_pos = input_pose_kinect[i] lines_kinect.append(axk.plot([kin_pos[j,0], kin_pos[j_parent,0]], [kin_pos[j, 1], kin_pos[j_parent, 1]], [kin_pos[j, 2], kin_pos[j_parent, 2]], zdir='z', c=col)) index_k+=1 points = ax_in.scatter(*keypoints[i].T, 5, color='red', edgecolors='white', zorder=10) #points2 = axk.scatter(input_pose_kinect[i,:,0], input_pose_kinect[i,:,2], zs=input_pose_kinect[i,:,1], zdir='y', s=20, c='blue', depthshade=True, marker='s') initialized = True else: image.set_data(all_frames[i]) index_k = 0 for j, j_parent in enumerate(parents): if j_parent != -1: if len(parents) == keypoints.shape[1] and 1 == 2: lines[j - 1][0].set_data([keypoints[i, j, 0], keypoints[i, j_parent, 0]], [keypoints[i, j, 1], keypoints[i, j_parent, 1]]) for n, ax in enumerate(ax_3d): pos = poses[n][i] lines_3d[n][j - 1][0].set_xdata([pos[j, 0], pos[j_parent, 0]]) lines_3d[n][j - 1][0].set_ydata([pos[j, 1], pos[j_parent, 1]]) lines_3d[n][j - 1][0].set_3d_properties([pos[j, 2], pos[j_parent, 2]], zdir='z') kin_pos = input_pose_kinect[i] lines_kinect[j-1][0].set_xdata([kin_pos[j, 0], kin_pos[j_parent, 0]]) lines_kinect[j-1][0].set_ydata([kin_pos[j, 1], kin_pos[j_parent, 1]]) lines_kinect[j-1][0].set_3d_properties([kin_pos[j, 2], kin_pos[j_parent, 2]], zdir='z') index_k += 1 #points2._offsets3d = (input_pose_kinect[i,:,0], input_pose_kinect[i,:,2], input_pose_kinect[i,:,1]) points.set_offsets(keypoints[i]) print('{}/{} '.format(i, limit), end='\r') fig.tight_layout() #limit anim = FuncAnimation(fig, update_video, frames=np.arange(0, limit), interval=1000 / fps, repeat=False) if output.endswith('.mp4'): Writer = writers['ffmpeg'] writer = Writer(fps=fps, metadata={}, bitrate=bitrate) anim.save(output, writer=writer) elif output.endswith('.gif'): anim.save(output, dpi=80, writer='imagemagick') elif output.endswith('.png'): anim.save(output, writer='imagemagick') else: raise ValueError('Unsupported output format (only .mp4 and .gif are supported)') plt.close() print("Done thanks for running!!!")
frame = np.array([ [0, 0, 1, 1, 2], [0, 0, 1, 2, 1], [0, 0, 1, 1, 2], [0, 0, 2, 1, 1], [0, 0, 1, 1, 2], [2, 0, 1, 1, 0], [1, 0, 1, 1, 0], ]) # number of nodes size = len(frame) # draw the topology of the graph, what changes during animation # is just the color nodes = nx.draw_networkx_nodes(G, pos, node_size=500,) edges = nx.draw_networkx_edges(G, pos) labels = nx.draw_networkx_labels(G, pos, font_color='w') plt.axis('off') # pass frames to funcanimation via update function def update(i): nc = frame[i] nodes.set_array(nc) return nodes, # save animation fig = plt.gcf() ani = FuncAnimation(fig, update, interval=50, frames=range(size), blit=True) ani.save('bee_coloring.gif', writer='imagemagick', savefig_kwargs={'facecolor':'white'}, fps=0.5)
def render_animation(keypoints, keypoints_metadata, poses, skeleton, fps, bitrate, azim, output, viewport, limit=-1, downsample=1, size=6, input_video_path=None, input_video_skip=0, show=False): """ TODO Render an animation. The supported output modes are: -- 'interactive': display an interactive figure (also works on notebooks if associated with %matplotlib inline) -- 'html': render the animation as HTML5 video. Can be displayed in a notebook using HTML(...). -- 'filename.mp4': render and export the animation as an h264 video (requires ffmpeg). -- 'filename.gif': render and export the animation a gif file (requires imagemagick). """ plt.ioff() fig = plt.figure(figsize=(size * (1 + len(poses)), size)) ax_in = fig.add_subplot(1, 1 + len(poses), 1) ax_in.get_xaxis().set_visible(False) ax_in.get_yaxis().set_visible(False) ax_in.set_axis_off() ax_in.set_title('Input') ax_3d = [] lines_3d = [] trajectories = [] radius = 1.7 for index, (title, data) in enumerate(poses.items()): ax = fig.add_subplot(1, 1 + len(poses), index + 2, projection='3d') ax.view_init(elev=15., azim=azim) ax.set_xlim3d([-radius / 2, radius / 2]) ax.set_zlim3d([0, radius]) ax.set_ylim3d([-radius / 2, radius / 2]) ax.set_aspect('equal') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_zticklabels([]) ax.dist = 7.5 ax.set_title(title) # , pad=35 ax_3d.append(ax) lines_3d.append([]) trajectories.append(data[:, 0, [0, 1]]) poses = list(poses.values()) # Decode video if input_video_path is None: # Black background all_frames = np.zeros((keypoints.shape[0], viewport[1], viewport[0]), dtype='uint8') else: # Load video using ffmpeg all_frames = [] for f in read_video(input_video_path, skip=input_video_skip, limit=limit): all_frames.append(f) effective_length = min(keypoints.shape[0], len(all_frames)) all_frames = all_frames[:effective_length] keypoints = keypoints[input_video_skip:] # todo remove for idx in range(len(poses)): poses[idx] = poses[idx][input_video_skip:] if fps is None: fps = get_fps(input_video_path) if downsample > 1: keypoints = downsample_tensor(keypoints, downsample) all_frames = downsample_tensor(np.array(all_frames), downsample).astype('uint8') for idx in range(len(poses)): poses[idx] = downsample_tensor(poses[idx], downsample) trajectories[idx] = downsample_tensor(trajectories[idx], downsample) fps /= downsample initialized = False image = None lines = [] points = None if limit < 1: limit = len(all_frames) else: limit = min(limit, len(all_frames)) parents = skeleton.parents() # print("trajectories:", trajectories[0][0, 0], trajectories[0][0, 1]) # noinspection PyUnresolvedReferences def update_video(i): nonlocal initialized, image, lines, points for n, ax in enumerate(ax_3d): ax.set_xlim3d([ -radius / 2 + trajectories[n][i, 0], radius / 2 + trajectories[n][i, 0] ]) ax.set_ylim3d([ -radius / 2 + trajectories[n][i, 1], radius / 2 + trajectories[n][i, 1] ]) # Update 2D poses joints_right_2d = keypoints_metadata['keypoints_symmetry'][1] # noinspection PyTypeChecker colors_2d = np.full(keypoints.shape[1], 'black') colors_2d[joints_right_2d] = 'red' if not initialized: image = ax_in.imshow(all_frames[i], aspect='equal') for j, j_parent in enumerate(parents): if j_parent == -1: continue if len(parents) == keypoints.shape[ 1] and keypoints_metadata['layout_name'] != 'coco': # Draw skeleton only if keypoints match (otherwise we don't have the parents definition) lines.append( ax_in.plot( [keypoints[i, j, 0], keypoints[i, j_parent, 0]], [keypoints[i, j, 1], keypoints[i, j_parent, 1]], color='pink')) col = 'red' if j in skeleton.joints_right() else 'black' for n, ax in enumerate(ax_3d): pos = poses[n][i] lines_3d[n].append( ax.plot([pos[j, 0], pos[j_parent, 0]], [pos[j, 1], pos[j_parent, 1]], [pos[j, 2], pos[j_parent, 2]], zdir='z', c=col)) points = ax_in.scatter(*keypoints[i].T, 10, color=colors_2d, edgecolors='white', zorder=10) initialized = True else: image.set_data(all_frames[i]) for j, j_parent in enumerate(parents): if j_parent == -1: continue if len(parents) == keypoints.shape[ 1] and keypoints_metadata['layout_name'] != 'coco': lines[j - 1][0].set_data( [keypoints[i, j, 0], keypoints[i, j_parent, 0]], [keypoints[i, j, 1], keypoints[i, j_parent, 1]]) for n, ax in enumerate(ax_3d): pos = poses[n][i] lines_3d[n][j - 1][0].set_xdata( [pos[j, 0], pos[j_parent, 0]]) lines_3d[n][j - 1][0].set_ydata( [pos[j, 1], pos[j_parent, 1]]) lines_3d[n][j - 1][0].set_3d_properties( [pos[j, 2], pos[j_parent, 2]], zdir='z') points.set_offsets(keypoints[i]) print('{}/{} '.format(i, limit), end='\r') fig.tight_layout() anim = FuncAnimation(fig, update_video, frames=limit, interval=1000 / fps, repeat=False) if show: plt.show() else: if output.endswith('.mp4'): writer = writers['ffmpeg'] writer = writer(fps=fps, metadata={}, bitrate=bitrate) anim.save(output, writer=writer) elif output.endswith('.gif'): anim.save(output, dpi=80, writer='imagemagick') else: raise ValueError( 'Unsupported output format (only .mp4 and .gif are supported)') plt.close()
self.fig = fig self.data = data self.i = 0 self.im = im def animator (self,index): for im_idx in range(len(im)): self.im[im_idx].set_data(sparse_to_rgba(self.data[im_idx][index])) ax_arr[im_idx].text(0.03,0.03,"Time: %d ms"%(ts[index]*1000),transform=ax_arr[im_idx].transAxes , fontsize=9, bbox={'boxstyle':'round','facecolor':'wheat','alpha':0.9} ) if len(ax_arr[im_idx].texts) > 2: ax_arr[im_idx].texts = [ax_arr[im_idx].texts[idx] for idx in [0,-1]] self._status_printer("Time: %d ms"%(ts[index]*1000)) def _status_printer(self,str): cleaner = ' ' * 100 print '\r' + cleaner + '\r' + str, # plt.rcParams['animation.ffmpeg_path'] = '/usr/bin/ffmpeg' anime = animator (fig,all_frames,im) anim = FuncAnimation(fig, anime.animator, frames=shape(all_frames)[1],interval=100,repeat_delay=3000) # plt.show() movieMaker_dir = os.path.join(folderpath,'MovieMaker_Output') if not os.path.isdir(movieMaker_dir): os.mkdir(movieMaker_dir) anim.save(os.path.abspath(os.path.join(movieMaker_dir,filename+'.mp4')),extra_args=['-vcodec', 'libx264'])
class Renderer: def __init__(self, file_name, hide, n, interval=100, hide_widgets=False): self.root = tkinter.Tk() if not file_name: file_name = askopenfilename(initialdir="output", title="Select param", filetypes=[ ("param files", "*.param")]) self.file_name = file_name X = pickle.load(open(file_name, 'rb')) self.plotter = Plotter(X, hide, n) self.interval = interval self.hide_widgets = hide_widgets def render(self): print(f'drawing with {self.plotter.n} circles') self.fig = Figure(figsize=(13, 13), dpi=100) self.ax = self.fig.subplots() self.root.wm_title(f"Render - {base_name(args.file_name, True)}") canvas = FigureCanvasTkAgg(self.fig, master=self.root) canvas.draw() canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) if not self.hide_widgets: rax = self.fig.add_axes([0.05, 0.0, 0.1, 0.1]) rax.axis('off') self.check = CheckButtons(rax, ('hide',), (self.plotter.hide,)) self.check.on_clicked(lambda _: self.plotter.toggle_hide()) nax = self.fig.add_axes([0.2, 0.07, 0.7, 0.02]) self.nslider = Slider(nax, 'n', 2, self.plotter.frames, valinit=self.plotter.n, valstep=1) self.nslider.on_changed(self._update_n) fpsax = self.fig.add_axes([0.2, 0.03, 0.7, 0.02]) self.fpsslider = Slider(fpsax, 'fps', 1, 50, valinit=10, valstep=1) self.fpsslider.on_changed(self._update_fps) self._init_animation() if args.save: self.save(args.out) else: tkinter.mainloop() def _init_animation(self): self.animation = FuncAnimation(self.fig, self.plotter.render_frame, frames=range(self.plotter.frames), interval=self.interval, repeat_delay=1000, init_func=partial( self.plotter.init_frame, self.ax), repeat=True) def _update_fps(self, fps): self.animation.event_source.stop() self.interval = int(1000 / fps) self._init_animation() def _update_n(self, n): self.animation.event_source.stop() self.plotter = Plotter(self.plotter.X, self.plotter.hide, int(n)) self._init_animation() def save(self, out_fname): if not out_fname: out_fname = f'output/{base_name(self.file_name)}.mp4' print(f'saving to {out_fname}') self.animation.save( out_fname, writer=FFMpegWriter(fps=10, bitrate=1000))
rain_drops = np.zeros(n_drops, dtype=[('position', float, 2), ('size', float, 1), ('color', float, 4)]) rain_drops['position'] = farms['position'] rain_drops['size'].fill(marker_size) rain_drops['color'][:]=np.array((0.0, 0.0, 0.0, 0.0)) # Construct the scatter which we will update during animation # as the raindrops develop. farms_scat = ax.scatter(farms['position'][:,0], farms['position'][:,1], s=farms['size'], lw=0.5, facecolors=farms['color'], edgecolors='none') rain_scat = ax.scatter(rain_drops['position'][:,0], rain_drops['position'][:,1], s=rain_drops['size'], lw=0.5, facecolors='none', edgecolors=rain_drops['color']) # Add infection for the initially infected sites for idx in initially_infected: farm_idx=idx-1 farms['color'][farm_idx] = color_code['infected'] rain_drops['size'][farm_idx]=marker_size rain_drops['color'][farm_idx, 3]=1.0 # Construct the animation, using the update function as the animation # director. animation = FuncAnimation(fig, update, frames=frame_cnt, interval=frame_interval, repeat=False) plt.show() animation.save(output_file)
start, stop, n_values = b[0], b[1], 100 x = np.linspace(start, stop, n_values) y = np.linspace(start, stop, n_values) X, Y = np.meshgrid(x, y) zs = np.array([f(np.array([x,y])) for x,y in zip(np.ravel(X), np.ravel(Y))]) Z = zs.reshape(X.shape) cm = plt.contourf(X, Y, Z, cmap='Blues') plt.colorbar(cm) ax.set_title('Alpine 1 function') ax.set_xlabel('x') ax.set_ylabel('y') scatter = ax.scatter(points["position"][:,0], points["position"][:,1], c='red', s=50) xs = results.traj_x def update(frame_number): points["position"] = xs[frame_number] ax.set_title('Alpine 1 function, Iteration: ' + str(frame_number)) scatter.set_offsets(points["position"]) return scatter, anim = FuncAnimation(fig, update, interval=0.1, frames=range(len(xs)), repeat_delay=2000) plt.show() # Save gif anim.save('TS.gif', writer='imagemagick', fps=400)
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() xdata, ydata = [], [] ln, = plt.plot([], [], 'ro') def init(): ax.set_xlim(0, 2*np.pi) ax.set_ylim(-1, 1) return ln, def update(frame): xdata.append(frame) ydata.append(np.sin(frame)) ln.set_data(xdata, ydata) return ln, ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128), init_func=init, blit=True) ani.save("test.mp4", bitrate=512) plt.show()
parser = ArgumentParser(description='heat equation in a rectangle') parser.add_argument( '-g', '--gif', action='store_true', help='write animated GIF', ) args = parser.parse_args() ax = plot(mesh, u_init[basis.nodal_dofs.flatten()], shading='gouraud') title = ax.set_title('t = 0.00') field = ax.get_children()[0] # vertex-based temperature-colour fig = ax.get_figure() fig.colorbar(field) def update(event): t, u = event u0 = {'skfem': (probe @ u)[0], 'exact': (probe @ exact(t))[0]} print('{:4.2f}, {:5.3f}, {:+7.4f}'.format(t, u0['skfem'], u0['skfem'] - u0['exact'])) title.set_text(f'$t$ = {t:.2f}') field.set_array(u[basis.nodal_dofs.flatten()]) animation = FuncAnimation(fig, update, evolve(0., u_init), repeat=False) if args.gif: animation.save(Path(__file__).with_suffix('.gif'), 'imagemagick') else: plt.show()
def render_animation(keypoints, poses, skeleton, fps, bitrate, azim, output, viewport, limit=-1, downsample=1, size=6, input_video_path=None, input_video_skip=0): """ TODO Render an animation. The supported output modes are: -- 'interactive': display an interactive figure (also works on notebooks if associated with %matplotlib inline) -- 'html': render the animation as HTML5 video. Can be displayed in a notebook using HTML(...). -- 'filename.mp4': render and export the animation as an h264 video (requires ffmpeg). -- 'filename.gif': render and export the animation a gif file (requires imagemagick). """ plt.ioff() fig = plt.figure(figsize=(size*(1 + len(poses)), size)) ax_in = fig.add_subplot(1, 1 + len(poses), 1) ax_in.get_xaxis().set_visible(False) ax_in.get_yaxis().set_visible(False) ax_in.set_axis_off() ax_in.set_title('Input') ax_3d = [] lines_3d = [] trajectories = [] radius = 1.7 for index, (title, data) in enumerate(poses.items()): ax = fig.add_subplot(1, 1 + len(poses), index+2, projection='3d') ax.view_init(elev=15., azim=azim) ax.set_xlim3d([-radius/2, radius/2]) ax.set_zlim3d([0, radius]) ax.set_ylim3d([-radius/2, radius/2]) ax.set_aspect('equal') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_zticklabels([]) ax.dist = 12.5 ax.set_title(title) #, pad=35 ax_3d.append(ax) lines_3d.append([]) trajectories.append(data[:, 0, [0, 1]]) poses = list(poses.values()) # Decode video if input_video_path is None: # Black background all_frames = np.zeros((keypoints.shape[0], viewport[1], viewport[0]), dtype='uint8') else: # Load video using ffmpeg all_frames = [] for f in read_video(input_video_path, skip=input_video_skip): all_frames.append(f) effective_length = min(keypoints.shape[0], len(all_frames)) all_frames = all_frames[:effective_length] if downsample > 1: keypoints = downsample_tensor(keypoints, downsample) all_frames = downsample_tensor(np.array(all_frames), downsample).astype('uint8') for idx in range(len(poses)): poses[idx] = downsample_tensor(poses[idx], downsample) trajectories[idx] = downsample_tensor(trajectories[idx], downsample) fps /= downsample initialized = False image = None lines = [] points = None if limit < 1: limit = len(all_frames) else: limit = min(limit, len(all_frames)) parents = skeleton.parents() def update_video(i): nonlocal initialized, image, lines, points for n, ax in enumerate(ax_3d): ax.set_xlim3d([-radius/2 + trajectories[n][i, 0], radius/2 + trajectories[n][i, 0]]) ax.set_ylim3d([-radius/2 + trajectories[n][i, 1], radius/2 + trajectories[n][i, 1]]) # Update 2D poses if not initialized: image = ax_in.imshow(all_frames[i], aspect='equal') for j, j_parent in enumerate(parents): if j_parent == -1: continue if len(parents) == keypoints.shape[1] and 1 == 2: # Draw skeleton only if keypoints match (otherwise we don't have the parents definition) lines.append(ax_in.plot([keypoints[i, j, 0], keypoints[i, j_parent, 0]], [keypoints[i, j, 1], keypoints[i, j_parent, 1]], color='pink')) col = 'red' if j in skeleton.joints_right() else 'black' for n, ax in enumerate(ax_3d): pos = poses[n][i] lines_3d[n].append(ax.plot([pos[j, 0], pos[j_parent, 0]], [pos[j, 1], pos[j_parent, 1]], [pos[j, 2], pos[j_parent, 2]], zdir='z', c=col)) points = ax_in.scatter(*keypoints[i].T, 5, color='red', edgecolors='white', zorder=10) initialized = True else: image.set_data(all_frames[i]) for j, j_parent in enumerate(parents): if j_parent == -1: continue if len(parents) == keypoints.shape[1] and 1 == 2: lines[j-1][0].set_data([keypoints[i, j, 0], keypoints[i, j_parent, 0]], [keypoints[i, j, 1], keypoints[i, j_parent, 1]]) for n, ax in enumerate(ax_3d): pos = poses[n][i] lines_3d[n][j-1][0].set_xdata([pos[j, 0], pos[j_parent, 0]]) lines_3d[n][j-1][0].set_ydata([pos[j, 1], pos[j_parent, 1]]) lines_3d[n][j-1][0].set_3d_properties([pos[j, 2], pos[j_parent, 2]], zdir='z') points.set_offsets(keypoints[i]) print('{}/{} '.format(i, limit), end='\r') fig.tight_layout() anim = FuncAnimation(fig, update_video, frames=np.arange(0, limit), interval=1000/fps, repeat=False) if output.endswith('.mp4'): Writer = writers['ffmpeg'] writer = Writer(fps=fps, metadata={}, bitrate=bitrate) anim.save(output, writer=writer) elif output.endswith('.gif'): anim.save(output, dpi=80, writer='imagemagick') else: raise ValueError('Unsupported output format (only .mp4 and .gif are supported)') plt.close()
raise FileNotFoundError("Could not find the snapshots in the directory") frames = tqdm(np.arange(0, i)) # Creation of first frame fig, ax = plt.subplots(1, 1, figsize=(1, 1), frameon=False) ax.axis("off") # Remove annoying black frame. data = load_and_extract("kelvinHelmholtz_0000.hdf5") mesh = project_gas_pixel_grid(data, dpi) # Global variable for set_array plot = ax.imshow( mesh, extent=[0, 1, 0, 1], animated=True, interpolation="none", vmin=1, vmax=2, cmap="RdBu_r", ) anim = FuncAnimation(fig, frame, frames, interval=40, blit=False) # Remove all whitespace fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) # Actually make the movie anim.save("khmovie.mp4", dpi=dpi)
def make_anim(imname, nselfcaliter=7): # base imname: W51-E_B6_uid___A001_X1296_X213_continuum_merged_12M_robust0 fig, (ax1, ax2, ax3) = pl.subplots(ncols=3, figsize=(18, 6)) fig.set_tight_layout(True) dpi = fig.get_dpi() size_inches = fig.get_size_inches() print(f"Figure size={size_inches} dpi={dpi}") for ax in (ax1, ax2, ax3): ax.set_xticklabels([]) ax.set_yticklabels([]) fig.subplots_adjust(hspace=0) cube = SpectralCube.read(f'{imname}_preselfcal.image.tt0', format='casa_image') norm = visualization.simple_norm(data=cube[0].value, stretch='asinh', min_percent=1, max_percent=99.00) im1 = ax1.imshow(cube[0].value, norm=norm) cube = SpectralCube.read(f'{imname}_preselfcal.residual.tt0', format='casa_image') norm = visualization.simple_norm(data=cube[0].value, stretch='asinh', min_percent=1, max_percent=99.95) im2 = ax2.imshow(cube[0].value, norm=norm) cube = SpectralCube.read(f'{imname}_preselfcal.model.tt0', format='casa_image') norm = visualization.simple_norm(data=cube[0].value, stretch='asinh', min_percent=1, max_percent=99.00) im3 = ax3.imshow(cube[0].value, norm=norm) title = pl.suptitle("Before selfcal") def update(ii): try: if ii == 0: return (im1, im2, im3), (ax1, ax2, ax3) else: cube = SpectralCube.read(f'{imname}_selfcal{ii}.image.tt0', format='casa_image') im1.set_data(cube[0].value) cube = SpectralCube.read(f'{imname}_selfcal{ii}.residual.tt0', format='casa_image') im2.set_data(cube[0].value) cube = SpectralCube.read(f'{imname}_selfcal{ii}.model.tt0', format='casa_image') im3.set_data(cube[0].value) title.set_text(f"Selfcal iteration {ii}") return (im1, im2, im3), (ax1, ax2, ax3) except Exception as ex: print(ex) anim = FuncAnimation(fig, update, frames=range(0, nselfcaliter), interval=400) anim.save(f'{imname}_selfcal_anim.gif', dpi=dpi, writer='imagemagick') return anim
def make_anim_single(imname, suffix, nselfcaliter=7, stretch='asinh', min_percent=1, max_percent=99.00): # base imname: W51-E_B6_uid___A001_X1296_X213_continuum_merged_12M_robust0 fig, ax = pl.subplots(ncols=1, figsize=(8, 8)) fig.set_tight_layout(True) dpi = fig.get_dpi() size_inches = fig.get_size_inches() print(f"Figure size={size_inches} dpi={dpi}") ax.set_xticklabels([]) ax.set_yticklabels([]) cube_before = SpectralCube.read(f'{imname}_preselfcal.{suffix}.tt0', format='casa_image') data = cube_before[0].value norm = visualization.simple_norm(data=data, stretch=stretch, min_percent=min_percent, max_percent=max_percent) im1 = ax.imshow(data, norm=norm) title = pl.title("Before selfcal") def update(ii): try: if os.path.exists(f'{imname}_selfcal{ii}_finaliter.{suffix}.tt0'): cube = SpectralCube.read( f'{imname}_selfcal{ii}_finaliter.{suffix}.tt0', format='casa_image') im1.set_data(cube[0].value) title.set_text(f"Selfcal iteration {ii} (final clean)") return im1, ax if ii == 0: im1.set_data(data) title.set_text(f"Before selfcal") return im1, ax else: cube = SpectralCube.read(f'{imname}_selfcal{ii}.{suffix}.tt0', format='casa_image') im1.set_data(cube[0].value) title.set_text(f"Selfcal iteration {ii}") return im1, ax except Exception as ex: print(ex) anim = FuncAnimation(fig, update, frames=range(0, nselfcaliter), interval=400) anim.save(f'{imname}_{suffix}_selfcal_anim.gif', dpi=dpi, writer='imagemagick') return anim