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()
class AnimationWidget(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) vbox = QtGui.QVBoxLayout() self.canvas = MyMplCanvas(self, width=5, height=4, dpi=100) vbox.addWidget(self.canvas) hbox = QtGui.QHBoxLayout() self.start_button = QtGui.QPushButton("start", self) self.stop_button = QtGui.QPushButton("stop", self) self.start_button.clicked.connect(self.on_start) self.stop_button.clicked.connect(self.on_stop) hbox.addWidget(self.start_button) hbox.addWidget(self.stop_button) vbox.addLayout(hbox) self.setLayout(vbox) self.x = np.linspace(0, 5*np.pi, 400) self.p = 0.0 self.y = np.sin(self.x + self.p) self.line, = self.canvas.axes.plot(self.x, self.y, animated=True, lw=2) def update_line(self, i): self.p += 0.1 y = np.sin(self.x + self.p) self.line.set_ydata(y) return [self.line] def on_start(self): self.ani = FuncAnimation(self.canvas.figure, self.update_line, blit=True, interval=25) def on_stop(self): self.ani._stop()
def __init__(self, fig, startFrame, endFrame, tail, fade=False, **kwargs) : """ Create an animation of track segments. *fig* matplotlib Figure object *startFrame* The frame number to start animation loop at *endFrame* The frame number to end the loop at *tail* How many frames to keep older segments in view *fade* Whether or not to fade track tails for non-active tracks (default: False). All other :class:`FuncAnimation` constructor kwargs are available except *frames* and *fargs*. TODO: Add usage info. """ self._lineData = [] self._lines = [] if 'frames' in kwargs : raise KeyError("Do not specify 'frames' for the constructor" " of SegAnimator") self.fade = fade FuncAnimation.__init__(self, fig, self.update_lines, endFrame - startFrame + 1, fargs=(self._lineData, self._lines, startFrame, endFrame, tail), **kwargs)
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
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 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 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')
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 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 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 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 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 __init__(self, fig, files, load_func=None, robust=False, **kwargs): """ Create an animation object for viewing radar reflectivities. *fig* matplotlib Figure object *files* list of filenames containing the radar data *load_func* The function to use to load the data from a file. Must return a dictionary of 'vals' which contains the 3D numpy array (T by Y by X), 'lats' and 'lons'. It is also optional that the loading function also provides a 'scan_time', either as a :class:`datetime.datetime` object or as an integer or a float representing the number of seconds since UNIX Epoch. *frames* The number of frames to display. If not given, then assume it is the same number as 'len(files)'. *robust* Boolean (default: False) indicating whether or not we can assume all the data will be for the same domain. If you can't assume a consistant domain, then set *robust* to True. This often happens for PAR data. Note that a robust rendering is slower. All other kwargs for :class:`FuncAnimation` are also allowed. To use, specify the axes to display the image on using :meth:`add_axes`. """ self._rd = files self._loadfunc = load_func if load_func is not None else LoadRastRadar self._ims = [] self._im_kwargs = [] self._new_axes = [] self._curr_time = None self._robust = robust frames = kwargs.pop("frames", None) # if len(files) < frames : # raise ValueError("Not enough data files for the number of frames") FuncAnimation.__init__( self, fig, self.nextframe, frames=len(self._rd), # init_func=self.firstframe, **kwargs )
def __init__(self, fig, grid, filelists, load_funcs=None, robusts=False, **kwargs) : self._filelists = [cycle(files) for files in filelists] self._loadfunc = load_func if load_func is not None else LoadRastRadar self._curr_times = [None] * len(filelists) self._ims = [None] * len(filelists) self._datas = [None] * len(filelists) #self.im_kwargs = [None] * len(filelists) self._has_looped = [False] * len(filelists) self._grid = grid self.robust = robust FuncAnimation.__init__(self, fig, self.nexttick, blit=False, init_func=self.firsttick, **kwargs)
def __init__(self, fig, func, frames=None, init_func=None, fargs=None, save_count=None, mini=0, maxi=100, pos=(0.2, 0.98), **kwargs): self.i = 0 self.min = mini self.max = maxi self.runs = True self.forwards = True self.fig = fig self.func = func self.setup(pos) FuncAnimation.__init__( self, self.fig, self.update, frames=self.play(), init_func=init_func, fargs=fargs, save_count=save_count, **kwargs )
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 start_timer(self): self.system.ode_init() self.line, = self.axe.plot(self.system.x, -self.system.y, "-o", animated=True) self.axe.set_xlim(-0.1, 1.1) self.axe.set_ylim(-1, 0.1) self.ani = FuncAnimation(self.figure, self.update_figure, blit=True, interval=20)
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 __init__(self, figure, frameCnt, tail=0, fade=False, **kwargs): """ Create an animation of the 'corners' (the centroids of detections). *figure* The matplotlib Figure object *frameCnt* The number of frames for the animation loop *tail* The number of frames to hold older corners *fade* Whether to fade older features (default: False). All other :class:`FuncAnimation` kwargs are available. TODO: Add usage information. """ self._allcorners = [] self._flatcorners = [] self._myframeCnt = frameCnt self.fade = fade FuncAnimation.__init__(self, figure, self.update_corners, frameCnt, fargs=(self._allcorners, tail), **kwargs)
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')
class AnimationGui(HasTraits): figure = Instance(Figure, ()) system = Instance(Catenary, ()) view = View( Group( Group( Item("object.system.g"), Item("object.system.length"), Item("object.system.k"), Item("object.system.dump"), ), Item("figure", editor=MPLFigureEditor(toolbar=True)), show_labels = False, orientation = 'horizontal' ), width = 800, height = 600, resizable = True) def __init__(self, **kw): super(AnimationGui, self).__init__(**kw) self.axe = self.figure.add_subplot(111) def start_timer(self): self.system.ode_init() self.line, = self.axe.plot(self.system.x, -self.system.y, "-o", animated=True) self.axe.set_xlim(-0.1, 1.1) self.axe.set_ylim(-1, 0.1) self.ani = FuncAnimation(self.figure, self.update_figure, blit=True, interval=20) def stop_timer(self): self.ani._stop() def update_figure(self, frame): self.system.ode_step(0.2) self.line.set_data(self.system.x, -self.system.y) return self.line,
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 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 startAnimation(self, iterations=0): ''' This method must be called to begin the simulation and will block until the simulation is finished. Arguments: iterations []: Number of times the update method will be called. ''' if iterations == 0 : frames=None else : frames=range(iterations) self.reset(self.controller.reset_ar()) self.ani = FuncAnimation(self.figure, self.update, frames=frames, interval=self.period_ms, repeat=False, event_source=self.event_source) self.figure.show() return self.state_posterior
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
# buffer = [] # for line in lines: # current_time = time.time() * 1000 # if current_time > line[0]: # buffer.append(line) # # get closes and timestamps from buffer # for line in buffer: # timestamps = [] # closes = [] # timestamps.append(line[0]) # closes.append(line[1]) # first, plot old values in buffer # color = 'tab:green' # ax1.set_xlabel('Date') # ax1.set_ylabel('Price', color=color) # ax1.set_ylim(min(closes)-100, max(closes) + 50) # ax1.plot(timestamps, closes, color=color, linewidth=0.5) # ax1.tick_params(axis='y', labelcolor=color) # start a process that get constantly new closed candles to a queue print('Started collecting from binance...') p1 = Process(target=bufferFeed, args=( market, interval, )) p1.start() ani = FuncAnimation(fig, animate, blit=True, interval=1000) plt.show()
def plot_MAB_experiment(self, bandit_colors, plot_title): """ plots and animates estimated probability distributions over expected reward (p(\theta|y)) during a single simulation """ # clearing past figures plt.close('all') # lists for accumulating draws, bandit choices and rewards k_list = [] reward_list = [] # animation dict for the posteriors posterior_anim_dict = {i: [] for i in range(self.n_bandits)} # opening figure fig = plt.figure(figsize=(9, 5), dpi=150) # position our plots in a grid, the largest being our plays colspan1 = self.n_bandits rowspan1 = self.n_bandits - 1 ax = [] ax.append( plt.subplot2grid((self.n_bandits + 1, self.n_bandits), (0, 0), colspan=colspan1, rowspan=rowspan1)) for i in range(self.n_bandits): ax.append( plt.subplot2grid((self.n_bandits + 1, self.n_bandits), (rowspan1, i), rowspan=2)) self.reset() # loop generating draws for round_id in range(self.n_rounds): # record information about this draw k = self.select_bandit() reward, regret = self.draw(k) # record information about this draw self.record_result(k, reward, round_id) k_list.append(k) reward_list.append(reward) # sucesses and failures for our beta distribution success_count = self.n_arm_rewards * self.n_arm_samples failure_count = self.n_arm_samples - success_count # calculating pdfs for each bandit for bandit_id in range(self.n_bandits): X = np.linspace(0, 1, 1000) curve = beta.pdf(X, 1 + success_count[bandit_id], 1 + failure_count[bandit_id]) # appending to posterior animation dict posterior_anim_dict[bandit_id].append({'X': X, 'curve': curve}) # getting list of colors that tells us the bandit color_list = [bandit_colors[k] for k in k_list] # getting list of facecolors that tells us the reward facecolor_list = [['none', bandit_colors[k_list[i]]][r] for i, r in enumerate(reward_list)] # fixing properties of the plots ax[0].set(xlim=(-1, self.n_rounds), ylim=(-0.5, self.n_bandits - 0.5)) ax[0].set_title(plot_title, fontsize=10) ax[0].set_xlabel('Round', fontsize=10) ax[0].set_ylabel('Bandit', fontsize=10) ax[0].set_yticks(np.arange(self.n_bandits).tolist()) ax[0].set_yticklabels([ '{}\n($\\theta = {}$)'.format(i, self.bandit_probs[i]) for i in range(self.n_bandits) ]) ax[0].tick_params(labelsize=10) # titles of distribution plots for i in range(self.n_bandits): ax[i + 1].set_title('Estimated $\\theta_{}$'.format(i), fontsize=10) # initializing with first data scatter = ax[0].scatter(y=[k_list[0]], x=[list(range(self.n_rounds))[0]], color=[color_list[0]], \ linestyle='-', marker='o', s=30, facecolor=[facecolor_list[0]]) dens = [] for i in range(self.n_bandits): densi = ax[i+1].fill_between(posterior_anim_dict[i][0]['X'], 0, posterior_anim_dict[i][0]['curve'], \ color=bandit_colors[i], alpha=0.7) dens.append(densi) # function for updating def animate(i): # clearing axes ax[0].clear() for k in range(self.n_bandits): ax[k + 1].clear() # updating game rounds scatter = ax[0].scatter(y=k_list[:i], x=list(range(self.n_rounds))[:i], color=color_list[:i], linestyle='-', marker='o', s=30, facecolor=facecolor_list[:i]) # fixing properties of the plot ax[0].set(xlim=(-1, self.n_rounds), ylim=(-0.5, self.n_bandits - 0.5)) ax[0].set_title(plot_title, fontsize=10) ax[0].set_xlabel('Round', fontsize=10) ax[0].set_ylabel('Bandit', fontsize=10) ax[0].set_yticks(np.arange(self.n_bandits).tolist()) ax[0].set_yticklabels([ '{}\n($\\theta = {}$)'.format(i, self.bandit_probs[i]) for i in range(self.n_bandits) ]) ax[0].tick_params(labelsize=10) # updating distributions for j in range(self.n_bandits): dens[j] = ax[j + 1].fill_between( posterior_anim_dict[j][i]['X'], 0, posterior_anim_dict[j][i]['curve'], color=bandit_colors[j], alpha=0.7) # titles of distribution plots for l in range(self.n_bandits): ax[l + 1].set_title('Estimated $\\theta_{}$'.format(l), fontsize=10) # do not need to return return () # function for creating animation anim = FuncAnimation(fig, animate, frames=self.n_rounds, interval=100, blit=True) # fixing the layout fig.tight_layout() # showing return HTML(anim.to_html5_video())
def create_video(embs, frames, video_path, use_dtw, query, candidate, interval): """Create aligned videos.""" # If candiidate is not None implies alignment is being calculated between # 2 videos only. if (candidate is not None) or (len(embs) < 4): fig, ax = plt.subplots(ncols=2, figsize=(10, 10), tight_layout=True) nns = align(embs[query], embs[candidate], use_dtw) def update(i): """Update plot with next frame.""" logging.info('%s/%s', i, len(embs[query])) ax[0].imshow(unnorm(frames[query][i])) ax[1].imshow(unnorm(frames[candidate][nns[i]])) # Hide grid lines ax[0].grid(False) ax[1].grid(False) # Hide axes ticks ax[0].set_xticks([]) ax[1].set_xticks([]) ax[0].set_yticks([]) ax[1].set_yticks([]) plt.tight_layout() else: ncols = int(math.sqrt(len(embs))) fig, ax = plt.subplots(ncols=ncols, nrows=ncols, figsize=(5 * ncols, 5 * ncols), tight_layout=True) nns = [] for candidate in range(len(embs)): nns.append(align(embs[query], embs[candidate], use_dtw)) ims = [] def init(): k = 0 for k in range(ncols): for j in range(ncols): ims.append(ax[j][k].imshow( unnorm(frames[k * ncols + j][nns[k * ncols + j][0]]))) ax[j][k].grid(False) ax[j][k].set_xticks([]) ax[j][k].set_yticks([]) return ims ims = init() def update(i): logging.info('%s/%s', i, len(embs[query])) for k in range(ncols): for j in range(ncols): ims[k * ncols + j].set_data( unnorm(frames[k * ncols + j][nns[k * ncols + j][i]])) plt.tight_layout() return ims anim = FuncAnimation(fig, update, frames=np.arange(len(embs[query])), interval=interval, blit=False) anim.save(video_path, dpi=80)
ax.set_xlim(0, 4) ## Funzione che viene chiamata prima di FuncAnimation def init(): global line ## Creo la linea che animeremo line, = ax.plot([], [], lw=3) return line, ## Funzione che serve per l'animazione def animate(i): ## Prendo i valori dallo 0 fino al 4 x = np.linspace(0, 4, 1000) ## Prendo il seno di x y = np.sin((x - (0.01 * i))) ## Li metto nel grafico line.set_data(x, y) return line, ''' fig è la figura a cui si fà riferimento animate è la funzione che svolge la funzione di Animazione init è la prima funzione che esegue FuncAnimation prima di iniziare con animate ''' anim = FuncAnimation(fig, animate, init_func=init, interval=10, blit=True) ## Mostro plt.show()
def start_ani(self): self.ani = FuncAnimation(self.fig, self.update, frames=np.arange(1000), blit=True, interval=1) plt.show()
from matplotlib.animation import FuncAnimation plt.style.use('fivethirtyeight') # animate function def animate(i): # using pandas to read csv. data = pd.read_csv('data.csv') x = data['x_value'] y1 = data['total_1'] y2 = data['total_2'] # clearing our labels each time we plot plt.cla() plt.plot(x, y1, label='Channel 1') plt.plot(x, y2, label='Channel 2') # specifing legend position every time we plot, otherwise it might change with new data. plt.legend(loc='upper left') # same thing here, auto adjusting padding after each plot, since data might change. plt.tight_layout() # creating our animation with FuncAnimation object. ani = FuncAnimation(plt.gcf(), animate, interval=1000) plt.show()
line = axis.plot(x, y, animated=True)[0] fft_x = [] fft_y = [] old_fft_y = [] def animate(i): global old_fft_y new_data_str = open("last_data_point.dat", "r").read() new_data_token = new_data_str.split() if len(new_data_token) == 2: x.append(float(new_data_token[0])) y.append(float(new_data_token[1])) fft_x = np.fft.rfftfreq(len(x[-N:-1]), d=1 / 60) fft_y = abs(np.fft.rfft(y[-N:-1]).real) axis = plt.axis([0, 20, 0, 100]) avg_fft_y = [0.5 * (x + y) for x, y in zip(fft_y, old_fft_y)] line.set_data(fft_x, avg_fft_y) old_fft_y = fft_y return line, anim = FuncAnimation(fig, animate, interval=0, blit=True) plt.show()
else: m.append(HSL[i,gauss_point]) m2.append(stress_array[i,gauss_point]) #print np.shape(cb_domain) t.append(tarray[i]) print "time = " + str(t[i]) #print np.shape(y) line[0].set_data(cb_domain,y) line[1].set_data(t,m) line[2].set_data(t,m2) #time.sleep(0.25) return line anim = FuncAnimation(fig, animate, init_func=init, frames = num_timesteps-1, interval = 50, blit=True,save_count=200) #mng = plt.get_current_fig_manager() #mng.frame.Maximize(True) #plt.figure() plt.subplots_adjust(left=.175,right=.95,wspace=0.5) plt.plot(HSL) #plt.switch_backend('Qt4Agg') #mng=plt.get_current_fig_manager() #mng.window.showMaximized() #mng.show() #print(anim.to_html5_video()) anim.save('test.mp4','ffmpeg',15) #anim.to_html5_video('test_animation')
import h5py import dask.array as da import numpy as np import matplotlib.pyplot as plt import sys fname = sys.argv[1] hf = h5py.File(fname, 'r') dsets = [hf[str(i)]['rho_y'][0] for i in sorted(hf.keys(), key=int)] arrays = [da.from_array(dset, chunks=(100, 100)) for dset in dsets] x = da.stack(arrays, axis=0) min_val = x.min().compute() max_val = x.max().compute() fig, ax = plt.subplots() h = ax.imshow(x[0], cmap='hot') fig.colorbar(h) def plot_frame(i): h.set_data(x[i]) from matplotlib.animation import FuncAnimation anim = FuncAnimation(fig, plot_frame, frames=range(len(x)), interval=50) plt.show()
scale = 50 fig, ax = plt.subplots(subplot_kw=dict( projection=lev3.observation.wcs.dropaxis(-1).dropaxis(-1), title='Level 3 Difference (Camera 2 Minus Camera 3)')) ax.set_xlabel('Solar X (arcsec)') ax.set_ylabel('Solar Y (arcsec)') img = ax.imshow(lev3_dif[0, ...], vmin=-scale, vmax=scale) t = ax.annotate(str(times[0]), (5, 5)) fig.colorbar(img, ax=ax, label="Intensity Difference (photons)") def update(frame, lev3_dif, times): img.set_data(lev3_dif[frame, ...]) t.set_text(str(times[frame])) ani = FuncAnimation(fig, update, np.arange(lev3.observation.data.shape[0]), fargs=(lev3_dif, times)) # save_path = pathlib.Path(__file__).parent / 'figures/' / 'dif_movie.html' # save_path.parent.mkdir(parents=True, exist_ok=True) # with open(save_path, 'w') as f: # print(ani.to_html5_video(), file=f) plt.show() save_path = pathlib.Path(__file__).parent / 'figures/' / 'dif_movie.avi' save_path.parent.mkdir(parents=True, exist_ok=True) ani.save(save_path, 'ffmpeg', dpi=200)
4], lineArray[i + changeIdx:i + batchSize, 5], ".C{:d}".format(pointColor)) else: pointColor = 2 - pointColor plt.plot(lineArray[i:i + batchSize, 4], lineArray[i:i + batchSize, 5], ".C{:d}".format(pointColor)) # plt.plot(lineArray[i: i+batchSize, 4], lineArray[i: i+batchSize, 5], ".C1") # plt.draw() # plt.pause(0.00001) fig = plt.figure(figsize=(12, 8)) plt.ylim([870000, 910000]) plt.xlim([967500, 1002500]) # anim = FuncAnimation(fig, animate, frames=1000, fargs=(color, batchSize), interval=1, blit=False) anim = FuncAnimation(fig, animate, frames=1000, interval=1, blit=False, repeat=False) # plt.show() writervideo = FFMpegWriter(fps=30) anim.save(os.path.join(saveFolder, "animation.mp4"), writer=writervideo) print("Save animation to: " + os.path.join(saveFolder, "animation.mp4")) # Change global variable inside the local function: https://www.geeksforgeeks.org/global-keyword-in-python/
# FuncAnimation is more generic, using an arbitrary callback to set the frame for each animation, similar to what was done using just a timer. It is a bit more verbose, but gives greater flexibility in what can be done. Also, it can be more efficient by not creating so many artists but just re-using them with changing data. # <codecell> t = np.linspace(0, 10, 500) x = np.exp(-0.5 * t) * np.sin(2 * np.pi * t) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) line, = plt.plot(t, x) def update_line(frame, line, t, x): line.set_data(t[:frame], x[:frame]) anim = FuncAnimation(fig, update_line, fargs=(line, t, x), interval=50) # <headingcell level=2> # Exercise: # <markdowncell> # Let's redo the timer example with the FuncAnimation class and see how things are simplified. You'll need to: # # * Create a callback function for updating the data on the lines # * Createa FuncAnimation using this callback and the appropriate list of parameters # # Here is the same starting boilerplate: # <codecell>
elif centroid[1] > a_birds['position'][ 0, 1] and centroid[0] < a_birds['position'][0, 0]: a_birds['position'][0, 1] -= 0.001 a_birds['position'][0, 0] += 0.001 elif centroid[1] < a_birds['position'][ 0, 1] and centroid[0] > a_birds['position'][0, 0]: a_birds['position'][0, 1] += 0.001 a_birds['position'][0, 0] -= 0.001 elif centroid[1] < a_birds['position'][ 0, 1] and centroid[0] < a_birds['position'][0, 0]: a_birds['position'][0, 1] += 0.001 a_birds['position'][0, 0] += 0.001 def update(frame_number): # Pick position for regular birds for i in range(n_birds): decide_move(i) # Generate psuedo random movements a_decide_move() # Update the scatter collection, with the new position scat.set_offsets(birds['position']) a_scat.set_offsets(a_birds['position']) # Construct the animation, using the update function as the animation # director. animation = FuncAnimation(fig, update, interval=10) plt.show()
print( "=============================================================================" ) print("****** SPATIAL DANCE ******+") print( "=============================================================================" ) # listen to Arduino trajectory in real time, save coordinates and draw graph #NOTE: currently stop listening after a certain number of frames. Could also be related to an ending signal (if arduino sends it...) plt.figure(figsize=(10, 5)) #compute for how many frames fo the ritual num_frames = random.randint(MIN_FRAMES, MAX_FRAMES) print("Performing spatial ritual for {} frames".format(num_frames)) ani = FuncAnimation(plt.gcf(), spatial_ritual, frames=num_frames, interval=INTERVAL_LISTEN, repeat=False) plt.show(block=True) trajectory = trajectory[: -1] #because the trajectory had one more point than when wee looked for concepts... print("Trajectory of length {}".format(len(trajectory))) print( "=============================================================================" ) print("****** SPIRITUAL READING ****** ") print( "=============================================================================" ) trinity, trinity_trajectory, custom_embeddings, haiku = reading_event(
def travelPerson(self): ''' "Main" function for combining: reads data, creates permutations, visits each location, and find the best path/distance. Also can plot the traversal. ''' self.readData() initialize = True self.startRandom() self.getFirstAndLast() ## for plotting # self.perms.append(self.locs) bestFitnesses = [] ## combines all genetic methods for the desired number of iterations for i in range(self.iterations): self.evolve() print("Current Best Fitness: ", self.currentGlobalFitness) # print("Current Fitness: ", self.globalFitnesses[len(self.globalFitnesses)-1]) bestFitnesses.append(self.currentGlobalFitness) bestFitnesses.append(self.currentGlobalFitness) bestFitnesses.append(self.currentGlobalFitness) bestFitnesses.append(self.currentGlobalFitness) bestFitnesses.append(self.currentGlobalFitness) bestFitnesses.append(self.currentGlobalFitness) bestFitnesses.append(self.currentGlobalFitness) bestFitnesses.append(self.currentGlobalFitness) bestFitnesses.append(self.currentGlobalFitness) if self.verbose: self.plot, = self.ax.plot(range(self.dataCount), np.zeros(self.dataCount) * np.NaN, 'mediumspringgreen') anim = FuncAnimation(self.fig, self.plotter, frames=len(self.perms), repeat=False, interval=100) #, blit=True) plt.show() else: plt.close() ## plots the iterations of search plt.plot(np.array([i for i in range(len(bestFitnesses))]), np.array(bestFitnesses)) plt.plot(np.array([i for i in range(len(bestFitnesses))]), np.array(self.globalFitnesses)) plt.show() ## plots the trails path of travel x, y = np.array(self.bestPermutation)[:, 0], np.array( self.bestPermutation)[:, 1] plt.plot(x, y) plt.show() print("⚶" * 90) print("Shortest Distance: {:.2f}\nPath of Travel: {}".format( self.currentGlobalFitness, str(self.bestPermutation))) print("⚶" * 90)
for year in reversed(range(0, timepoints, 1)): kid_num = kid_by_year(year, dictOfkids) kidos.append(kid_num) # print("kidos ", kidos) def update(frame_number): # for year in range(9, 100, 10): year = frame_number % timepoints Pointsize = np.ma.masked_equal(kidos[year], 0) scat.set_sizes(Pointsize) # scat.set_offsets(locs[alive_sam, 0], locs[alive_sam, 1]) Points['xy'][:, 0] = locs[alive_sam, 0] Points['xy'][:, 1] = locs[alive_sam, 1] scat.set_sizes(Pointsize) scat.set_offsets(Points['xy']) scat.set_array(np.array(kidos[year])) ax.set_title("Generation %d" % year) t = list(range(0, timepoints, 1)) Pointsize = [10] * 3 Points = np.zeros(samplesize, dtype=[('xy', float, 2)]) ax.scatter(locs[alive_sam, 0], locs[alive_sam, 1]) # blue points ax.set_ylabel(filename) animation = FuncAnimation(fig, update, interval=600, frames=timepoints) scat = ax.scatter(0, 0, s=1, edgecolors='none', color="red") animation.save('/Users/victoria/Desktop/test_' + filename + "_samplesize_" + str(samplesize) + "_timepoints_" + str(timepoints) + '.gif', writer='imagemagick', fps=10) # plt.show()
from datetime import datetime from matplotlib import pyplot from matplotlib.animation import FuncAnimation from random import randrange x_data, y_data = [], [] figure = pyplot.figure() line, = pyplot.plot_date(x_data, y_data, '-') def update(frame): x_data.append(datetime.now()) y_data.append(randrange(0, 100)) line.set_data(x_data, y_data) figure.gca().relim() figure.gca().autoscale_view() return line, animation = FuncAnimation(figure, update, interval=200) pyplot.show()
node_color='y') ax = nx.draw_networkx_edges(graph, npos, edgelist=negedges, width=3, alpha=0.4, edge_color='r') plt.title("frame " + str(frames)) return ax #print(control_nodes) ani = FuncAnimation(fig, evo, frames=np.arange(0, 500), interval=200, init_func=init, blit=False) #ani.save('network.gif',dpi = 100,writer = "imagemagick") plt.savefig("network.png") # #%% # import numpy as np # import matplotlib.pyplot as plt # from matplotlib.animation import FuncAnimation # from random import choice # from functools import reduce # import matplotlib.animation as animation # animation plot # import pandas as pd # import networkx as nx # import random_network as rn
if __name__ == "__main__": from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation data_GR = _load_GR( filename="STT_phiScal_J_APR4_beta0.000e+00_m0.000e+00_lambda0.000e+00") data_Kalin = _load_kalin_file() #~ do not want kalin data now data_Kalin.clear() data_previus = _load_previus_data() #~ data_previus.clear() fig, ax = _get_figure(nrows=2, ncols=2, grid_placement=_set_PhiScalMARJ_grid_placement) animation_live = FuncAnimation(fig=fig, func=update, fargs=(ax, _set_parms_PhiScalMARJ, _plot_PhiScalMARJ, data_GR, data_Kalin, data_previus), frames=update_data, interval=500, save_count=0, repeat=False) plt.show()
def simple_xep_plot(device_name, record=False, baseband=False): """ Plots the recorded data. Parameters: device_name: str port that device is connected to. record: boolean check if device is recording. baseband: boolean check if recording with baseband iq data. Return: Simple plot of range bin by amplitude. """ FPS = 10 directory = '.' reset(device_name) mc = pymoduleconnector.ModuleConnector(device_name) # Assume an X4M300/X4M200 module and try to enter XEP mode app = mc.get_x4m300() # Stop running application and set module in manual mode. try: app.set_sensor_mode(0x13, 0) # Make sure no profile is running. except RuntimeError: # Profile not running, OK pass try: app.set_sensor_mode(0x12, 0) # Manual mode. except RuntimeError: # Maybe running XEP firmware only? pass if record: recorder = mc.get_data_recorder() recorder.subscribe_to_file_available(pymoduleconnector.AllDataTypes, on_file_available) recorder.subscribe_to_meta_file_available(on_meta_file_available) xep = mc.get_xep() # Set DAC range xep.x4driver_set_dac_min(900) xep.x4driver_set_dac_max(1150) # Set integration xep.x4driver_set_iterations(16) xep.x4driver_set_pulses_per_step(26) xep.x4driver_set_downconversion(int(baseband)) # Start streaming of data xep.x4driver_set_fps(FPS) def read_frame(): """Gets frame data from module""" d = xep.read_message_data_float() frame = np.array(d.data) # Convert the resulting frame to a complex array if downconversion is enabled if baseband: n = len(frame) frame = frame[:n // 2] + 1j * frame[n // 2:] return frame def animate(i): if baseband: line.set_ydata(abs(read_frame())) # update the data else: line.set_ydata(read_frame()) return line, fig = plt.figure() fig.suptitle("example version %d " % (__version__)) ax = fig.add_subplot(1, 1, 1) ax.set_ylim(0 if baseband else -0.03, 0.03) # keep graph in frame (FIT TO YOUR DATA) frame = read_frame() if baseband: frame = abs(frame) line, = ax.plot(frame) clear_buffer(mc) if record: recorder.start_recording(DataType.BasebandApDataType | DataType.FloatDataType, directory) ani = FuncAnimation(fig, animate, interval=FPS) try: plt.show() finally: # Stop streaming of data xep.x4driver_set_fps(0)
# Create and train the model. lin_model = LinearRegression(0.000001, 10000) train_linear_all = lin_model.fit(X_poly, y, True) def init(): line.set_data([], []) return line, def animate(i): line.set_data(X, train_linear_all[i]) line.set_label('Prediction') plt.legend() return line, fig = plt.figure() ax = plt.axes(xlim=[X.min(),X.max()], ylim=[y.min(),y.max()]) ax.scatter(X, y, c='black', label='Target') line, = ax.plot([], [], lw=3) plt.xlabel('X') plt.ylabel('y') plt.title('Polynomial Regression') plt.rc('figure', titlesize=20) plt.legend() anim = FuncAnimation(fig, animate, init_func=init, frames=np.arange(0, len(train_linear_all)), interval=500, blit=True) anim.save('Polynomial_Regression.gif', writer='imagemagick')
# This vertical line represents the theoretical value, to # which the plotted distribution should converge. self.ax.axvline(prob, linestyle='--', color='black') def init(self): self.success = 0 self.line.set_data([], []) return self.line, def __call__(self, i): # This way the plot can continuously run and we just keep # watching new realizations of the process if i == 0: return self.init() # Choose success based on exceed a threshold with a uniform pick if np.random.rand(1,) < self.prob: self.success += 1 y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1) self.line.set_data(self.x, y) return self.line, # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() ud = UpdateDist(ax, prob=0.7) anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init, interval=100, blit=True) plt.show()
def examine(args): with h5py.File(args.data_file, "r") as h5: images = h5["images"] # images.shape = (None, 560, 84, 160, 3) actions = h5["action"] # actions.shape = (None, 560, 7) # action (7) = (velocity, steering, accel, should_turn_left, should_turn_right, stripped_line, contains_data) assert images.shape[0] == actions.shape[0], f"Images and Action must match in length! \n" \ f" images length: {images.shape[0]}, " \ f" actions length: {actions.shape[0]}" datasets_count = images.shape[0] print(f"--- There are {datasets_count} datasets in the file ---") #### Look at some data from dataset ##### # region ### Plot steering for 1st ride ### print("--- Steering for 1st fide ---") ride = actions[0, :, 1] # * 20 fig, axs = plt.subplots(2, 2, figsize=(12, 6)) h = {1: "a", 2: "b", 4: "c", 5: "d"} for i in range(2): for j in range(2): smoothness = 1 + (i * 3) + j x = moving_average(ride, smoothness) ax = axs[i][j] ax.plot(ride, color="lightblue") ax.plot(x, color="red") # ax.plot(smooth(ride, smoothness)) # ax.set_title(f"Steering - smoothness: {smoothness}") ax.set_title(f"{h[smoothness]})") fig.suptitle("Steering") plt.show() # endregion # region ### (should_turn_left, should_turn_right, stripped_line) ### print("--- More interesting data: ---") total_steps = 0 should_turn_lefts = 0 should_turn_rights = 0 stripped_lines = 0 for series in actions: for action in series: if action[6]: total_steps += 1 if action[3]: should_turn_lefts += 1 if action[4]: should_turn_rights += 1 if action[5]: stripped_lines += 1 else: break print(" total_steps: ", total_steps) print(" should_turn_lefts: ", should_turn_lefts) print("should_turn_rights: ", should_turn_rights) # endregion # region ### Show some images from ride ### print("--- Some images from ride ---") fig, axs = plt.subplots(3, 3) for i in range(3): for j in range(3): m = images[0][i * 50 + j * 100] ax = axs[i][j] ax.imshow(m, cmap="bone") ax.set_xticks([]) ax.set_yticks([]) fig.suptitle("Some images from ride") plt.show() # endregion # region ### Plot steering distribution ### print("--- Steering distribution ---") out_steers = [] for series in actions: for action in series: if action[6]: out_steers.append(action[1]) else: break out_steers = np.array( out_steers ) # * 20 # Steering is really small, so scale it for easier learning out_steers = np.clip(out_steers, -1, 1) # Clip to be sure it is really in -1 to 1 plt.hist(out_steers, label="Steer") plt.show() # endregion # region ### Play video of 1th ride ### print("--- Video of 1st ride ---") fig = plt.figure() im = plt.imshow(images[0][0]) def init(): im.set_data(images[0][0]) def animate(frame): img = images[0][frame] im.set_data(img) return im ani = FuncAnimation(fig, animate, init_func=init, frames=len([1 for point in actions[0] if point[6]]), interval=50) plt.show()
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!!!")
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') # prevent wired error _ = Axes3D.__class__.__name__ 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(["x"]) ax.set_yticklabels(["y"]) ax.set_zticklabels(["z"]) 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, fps=None, 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() pbar = tqdm(total=limit) 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 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 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]) pbar.update() fig.tight_layout() anim = FuncAnimation(fig, update_video, frames=limit, interval=1000.0 / 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=60, writer='imagemagick') else: raise ValueError( 'Unsupported output format (only .mp4 and .gif are supported)') pbar.close() plt.close()
d = MetaWear(sys.argv[i + 1]) d.connect() print("Connected to " + d.address) states.append(State(d)) ### Animated plot ### th = threading.Thread(target=connection) th.start() fig = plt.figure() xlim = 100 ylim = 1000 ax = plt.axes(xlim=(0, xlim), ylim=(-ylim, ylim)) lines = [plt.plot([], [])[0] for _ in range(3)] anim = FuncAnimation(fig, animate, frames=200, interval=30, blit=False) plt.show() th.join() print("Total Samples Received") for s in states: print("%s -> %d" % (s.device.address, s.samples)) ### Dynamic plot ### fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.25) plt.axis([0, xlim, -ylim, ylim]) plt.plot(x, label='x-line', linewidth=1)
print(np.mean((y_t - pred)**2)) step[0] += 1 ln.set_data(x_t, pred) return ln, if __name__ == "__main__": x = np.reshape(np.linspace(-50, 50, 26), (26, 1)) y = x**2 x_s = np.ones((26, 1)) x = np.concatenate((x, x_s), axis=1) # BIAS func = (sigmoid, ReLU, ReLU) d_func = (sigmoid_derivative, ReLU_derivative, ReLU_derivative) nn = NeuralNetwork(x, y, func, d_func) x_t = np.reshape(np.linspace(-50, 50, 101), (101, 1)) y_t = x_t**2 x_s = np.ones((101, 1)) x_test = np.concatenate((x_t, x_s), axis=1) # BIAS plt.plot(x_t, y_t, 'bo', markersize=5) ani = FuncAnimation(fig, update, frames=20, init_func=init) plt.show() # Dla sieci 1-5-3-1 wyniki sa lepsze, ale nauka trwa dluzej, # odpowiednio trzeba dobrac wspolczynnik eta, aby nie # "przestrzelic" rozwiazan # Po dluzszej nauce aproksymacja jest lepsza od sieci # 1-100-1, dostajemy mniejszy blad srednio-kwadratowy
if __name__ == '__main__': stormcells = storm_loader('polygons.shp') ncf = netcdf_file('KTLX_20100510_22Z.nc') data = ncf.variables['Reflectivity'] lats = ncf.variables['lat'] lons = ncf.variables['lon'] framecnt = data.shape[0] fig, ax = plt.subplots(1, 1) rad_disp = RadarDisplay(ax, lats, lons) fig.colorbar(rad_disp.im) trks = Tracks(ax) cells = Stormcells(ax, stormcells) cells.toggle_polygons(0, True) radanim = FuncAnimation(fig, lambda i, dat: rad_disp.update_display(dat[i]), framecnt, fargs=(data, )) event_source = radanim.event_source trkanim = FuncAnimation(fig, trks.update_lines, framecnt, fargs=(stormcells, ), event_source=event_source) strmanim = ArtistAnimation(fig, [[p] for p in cells.polygons], event_source=event_source) radanim.save('multi_animation.mp4', extra_anim=[trkanim, strmanim]) 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()
fig, ax = plt.subplots() fig.set_tight_layout(True) line, = ax.plot([0, 0, 0, 0, 0], [0, 0, 0, 0, 0], '.') ax.axis([-2, 2, -2, 2]) # Add zeros at the beginning so that when gif loops it has a transition period temp_out = np.concatenate((np.zeros(50), out)) def update(i): print(i) line.set_xdata([np.real(temp_out[i:i + 5])]) line.set_ydata([np.imag(temp_out[i:i + 5])]) return line, ax anim = FuncAnimation(fig, update, frames=np.arange(0, len(out - 5)), interval=20) anim.save('/tmp/time-sync-constellation-animated.gif', dpi=80, writer='imagemagick') exit() # COSTAS LOOP. THIS ONE IS FROM GNURADIO's COSTAS LOOP IMPL, AND REMEMBER IT INHERITS CONTROL LOOP WHICH IS IN GR-BLOCKS samples = out # copy samples from output of timing sync # For QPSK def phase_detector_4(sample): if sample.real > 0: a = 1.0 else:
newdata = np.asarray(sample[0][:n]) # print(newdata) zscoreArray, data = getCmapForZscores(data, newdata, -1) # define vectors for plot colors and opacity # altColors = freqs / 33 colors = cmap(zscoreArray) # colors.astype(float) # colors[:, -1] = maxes / maxes.max() # print(altColors) # print(colors) ax1.set_xlim(-6, 6) ax1.set_ylim(-6, 6) # ax1.scatter(x, y, s = 100, c = altColors, cmap = plt.cm.jet_r) ax1.scatter(x, y, s=100, c=colors) elapsed_time = time.time() - start_time # print(elapsed_time) # plot animation ani = FuncAnimation(fig, plotNodes, interval=100) # ani.save('visual.mp4', fps=7)3 # # save animation (uncomment to record) # ani.save('EEG_visiualization_LSL.mp4', writer=writer) plt.show()
#!/Users/dora/anaconda3/bin/python #Time Series Movie import yt from matplotlib.animation import FuncAnimation from matplotlib import rc_context ts = yt.load('./GasSloshingLowRes/sloshing_low_res_hdf5_plt_cnt_*') plot = yt.SlicePlot(ts[0], 'z', 'density') plot.set_zlim('density', 8e-29, 3e-26) fig = plot.plots['density'].figure # animate must accept an integer frame number. We use the frame number # to identify which dataset in the time series we want to load def animate(i): ds = ts[i] plot._switch_ds(ds) animation = FuncAnimation(fig, animate, frames=len(ts)) # Override matplotlib's defaults to get a nicer looking font with rc_context({'mathtext.fontset': 'stix'}): animation.save('animation.mp4')