def plot(plt, prev, charges, posOffset): for elem in prev: elem.remove() # [x], [y], [q] pos = ([], [], []) neg = ([], [], []) neut = ([], [], []) for c in charges: if c.q > 0: pos[0].append(c.pos[0]) pos[1].append(c.pos[1]) pos[2].append(c.size) elif c.q < 0: neg[0].append(c.pos[0]) neg[1].append(c.pos[1]) neg[2].append(c.size) else: neut[0].append(c.pos[0]) neut[1].append(c.pos[1]) neut[2].append(c.size) curr = [] curr.append( plt.scatter(pos[0], pos[1], marker='o', color='red', s=pos[2]) ) curr.append( plt.scatter(neg[0], neg[1], marker='o', color='blue', s=neg[2]) ) curr.append( plt.scatter(neut[0], neut[1], marker='o', color='gray', s=neut[2]) ) for c in charges: curr.append( plt.text(c.pos[0], c.pos[1]+ sqrt(c.size/3.14) / 2 + posOffset, "%s, %s C" % (c.name, c.q), \ horizontalalignment='center') ) plt.draw() plt.pause(TIME_INTERVAL) return curr
def ManetPlot(): index_mob=0 index_route=00 plotting_time=0 pl.ion() fig,ax=pl.subplots() for index_mob in range(len(time_plot)): # plot the nodes with the positions given by index_mob of x_plot and yplot pl.scatter(x_plot[index_mob],y_plot[index_mob],s=100,c='g') # print x_plot[index_mob],y_plot[index_mob] for i, txt in enumerate(n): pl.annotate(txt,(x_plot[index_mob, i]+10,y_plot[index_mob, i]+10)) pl.xlabel('x axis') pl.ylabel('y axis') # set axis limits pl.xlim(0.0, xRange) pl.ylim(0.0, yRange) pl.title("Position updation at "+str(time_plot[index_mob])) # print time_plot[index_mob],route_table_time[index_route],ntemp,route_table[index_route,1:3] # print_neighbors(neighbor_nodes_time,time_neighb,x_plot[index_mob,:],y_plot[index_mob,:]) pl.show() pl.pause(.0005) # show the plot on the screen pl.clf()
def FindTransitManual(kic, lc, cut=10): """ This uses the KIC/EPIC to 1) Get matching data 2) Display in pyplot window 3) Allow the user to find and type the single transit parameters returns # lightcurve (cut to 20Tdur long) # 'guess' parameters'' """ if lc == []: lc = getKeplerLC(kic) p.ion() # PlotLC(lc, 0, 0, 0.1) p.figure(1) p.plot(lc[:, 0], lc[:, 1], ".") print lc print "You have 10 seconds to manouever the window to the transit (before it freezes)." print "(Sorry; matplotlib and raw_input dont work too well)" p.pause(25) Tcen = float(raw_input("Type centre of transit:")) Tdur = float(raw_input("Type duration of transit:")) depth = float(raw_input("Type depth of transit:")) # Tcen,Tdur,depth=2389.7, 0.35, 0.0008 return np.array((Tcen, Tdur, depth))
def main(plot=True): # Setup grid g = 4 nx, ny = 200, 50 Lx, Ly = 26, 26/4 (x, y), (dx, dy) = ghosted_grid([nx, ny], [Lx, Ly], 0) # monkey patch the velocity uc = MultiFab(sizes=[nx, ny], n_ghost=4, dof=2) uc.validview[0] = (y > Ly / 3) * (2 * Ly / 3 > y) uc.validview[1] = np.sin(2 * pi * x / Lx) * .3 / (2 * pi / Lx) # state.u = np.random.rand(*x.shape) tad = BarotropicSolver() tad.geom.dx = dx tad.geom.dy = dx dt = min(dx, dy) / 4 if plot: import pylab as pl pl.ion() for i, (t, uc) in enumerate(steps(tad.onestep, uc, dt, [0.0, 10000 * dt])): if i % 100 == 0: if plot: pl.clf() pl.pcolormesh(uc.validview[0]) pl.colorbar() pl.pause(.01)
def fftComputeAndGraph(self, data): fft = np.fft.fft(data) fftr = 10*np.log10(abs(fft.real))[:len(data)/2] ffti = 10*np.log10(abs(fft.imag))[:len(data)/2] fftb = 10*np.log10(np.sqrt(fft.imag**2+fft.real**2))[:len(data)/2] freq = np.fft.fftfreq(np.arange(len(data)).shape[-1])[:len(data)/2] freq = freq*self.RATE/1000 #make the frequency scale pylab.subplot(411) pylab.title("Original Data") pylab.grid() pylab.plot(np.arange(len(data))/float(self.RATE)*1000,data,'r-',alpha=1) pylab.xlabel("Time (milliseconds)") pylab.ylabel("Amplitude") pylab.subplot(412) pylab.title("Real FFT") pylab.xlabel("Frequency (kHz)") pylab.ylabel("Power") pylab.grid() pylab.plot(freq,fftr,'b-',alpha=1) pylab.subplot(413) pylab.title("Imaginary FFT") pylab.xlabel("Frequency (kHz)") pylab.ylabel("Power") pylab.grid() pylab.plot(freq,ffti,'g-',alpha=1) pylab.subplot(414) pylab.title("Real+Imaginary FFT") pylab.xlabel("Frequency (kHz)") pylab.ylabel("Power") pylab.grid() pylab.plot(freq,fftb,'k-',alpha=1) pylab.draw() pylab.pause(0.0001) pylab.clf()
def TablePlot(): index_time=0 # print [x[2] for x in RouteTablewithSeq] pl.ion() fig,ay=pl.subplots() fig,ax=pl.subplots() fig.set_tight_layout(True) idx_row = Index(np.arange(0,nNodes)) idx_col = Index(np.arange(0,nPackets)) df = DataFrame(cache_matrix[0,:,:], index=idx_row, columns=idx_col) # print df normal = pl.Normalize(0, 1) for index_time in range(len(RouteTablewithSeq_time)): vals=cache_matrix[index_time,:,:30] # fig = pl.figure(figsize=(15,8)) # ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[]) # print vals.shape the_table=pl.table(cellText=vals, rowLabels=df.index, colLabels=df.columns, colWidths = [0.03]*vals.shape[1], loc='center', cellColours=pl.cm.hot(normal(vals)), fontsize=3) the_table.alpha=0 for i in range(index_time+1): for j in range(vals.shape[0]): if (vals[j,i]==1): the_table._cells[(j+1, i)]._text.set_color('white') pl.title("Table at time: "+str(cache_time[index_time])+" Packet: "+str(index_time)+" Probability: "+str(p) ) pl.show() pl.pause(.0005) pl.clf()
def plot3DCamera(self, T): #transform affine ori = T * np.matrix([[0],[0],[0],[1]]) v1 = T * np.matrix([[self.camSize],[0],[0],[1]]) v2 = T * np.matrix([[0],[self.camSize],[0],[1]]) v3 = T * np.matrix([[0],[0],[self.camSize],[1]]) #initialize objects if not self.initialized: self.cam_x = self.ax.plot(np.squeeze([ori[0], v1[0]]), np.squeeze([ori[1], v1[1]]), np.squeeze([ori[2], v1[2]]), color="r") self.cam_y = self.ax.plot(np.squeeze([ori[0], v2[0]]), np.squeeze([ori[1], v2[1]]), np.squeeze([ori[2], v2[2]]), color="g") self.cam_z = self.ax.plot(np.squeeze([ori[0], v3[0]]), np.squeeze([ori[1], v3[1]]), np.squeeze([ori[2], v3[2]]), color="b") self.initialized = True else: xy=np.squeeze([ori[0:2], v1[0:2]]).transpose() z=np.squeeze([ori[2], v1[2]]).transpose() self.cam_x[0].set_data(xy) self.cam_x[0].set_3d_properties(z) xy=np.squeeze([ori[0:2], v2[0:2]]).transpose() z=np.squeeze([ori[2], v2[2]]).transpose() self.cam_y[0].set_data(xy) self.cam_y[0].set_3d_properties(z) xy=np.squeeze([ori[0:2], v3[0:2]]).transpose() z=np.squeeze([ori[2], v3[2]]).transpose() self.cam_z[0].set_data(xy) self.cam_z[0].set_3d_properties(z) pl.pause(0.00001)
def plot_graph(child_conn): umov = umov_mod.main() umov.umo.set_cube_from_conf_name('w') child_conn.send('loaded') key = '2' while key != 'q': if key == curses.KEY_UP: umov.umo.next_level() elif key == curses.KEY_DOWN: umov.umo.prev_level() elif key == curses.KEY_LEFT: umov.umo.prev_time() elif key == curses.KEY_RIGHT: umov.umo.next_time() elif key == ord('n'): umov.umo.next_cube() elif key == ord('p'): umov.umo.next_cube() child_conn.send(umov.umo.curr_cube.name()) plt.clf() umov.display_curr_frame() plt.pause(0.1) plt.show() key = child_conn.recv() child_conn.close()
def plot_coupe(sol): ax1.cla() ax2.cla() mx = int(sol.domain.N[0]/2-1) my = int(sol.domain.N[1]/2-1) x = sol.domain.x[0][1:-1] y = sol.domain.x[1][1:-1] u = sol.m[0][1][1:-1,1:-1] / rhoo for i in [0,mx,-1]: ax1.plot(y+x[i], u[i, :], 'b') for j in [0,my,-1]: ax1.plot(x+y[j], u[:,j], 'b') ax1.set_ylabel('velocity', color='b') for tl in ax1.get_yticklabels(): tl.set_color('b') ax1.set_ylim(-.5*rhoo*vmax, 1.5*rhoo*vmax) p = sol.m[0][0][1:-1,my] * la**2 / 3.0 p -= np.average(p) ax2.plot(x, p, 'r') ax2.set_ylabel('pressure', color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') ax2.set_ylim(pressure_gradient*L, -pressure_gradient*L) plt.title('Poiseuille flow at t = {0:f}'.format(sol.t)) plt.draw() plt.pause(1.e-3)
def test(c, s, N): dico = { 'box':{'x':[0., 1.], 'label':-1}, 'scheme_velocity':1., 'space_step':1./N, 'schemes':[ { 'velocities':[1,2], 'conserved_moments':u, 'polynomials':[1, X], 'equilibrium':[u, c*u], 'relaxation_parameters':[0., s], 'init':{u:(solution, (0.,))}, }, ], 'generator':pyLBM.CythonGenerator, } sol = pyLBM.Simulation(dico) while sol.t < Tf: sol.one_time_step() sol.f2m() x = sol.domain.x[0][1:-1] y = sol.m[0][0][1:-1] plt.clf() plt.plot(x, y, 'k', x, solution(x, sol.t), 'r') plt.pause(1.e-5) return sol.domain.dx * np.linalg.norm(y - solution(x, sol.t), 1)
def calc_idct(dct, cos, idct, choice): for i in range(352/8): for j in range(288/8): block_R=np.mat(dct[i*8:i*8+8,j*8:j*8+8,0]) block_G=np.mat(dct[i*8:i*8+8,j*8:j*8+8,1]) block_B=np.mat(dct[i*8:i*8+8,j*8:j*8+8,2]) block_R[:,0]=block_R[:,0]/1.414 block_G[:,0]=block_G[:,0]/1.414 block_B[:,0]=block_B[:,0]/1.414 block_R[0,:]=block_R[0,:]/1.414 block_G[0,:]=block_G[0,:]/1.414 block_B[0,:]=block_B[0,:]/1.414 r=(((block_R*cos).transpose())*cos)/4 g=(((block_G*cos).transpose())*cos)/4 b=(((block_B*cos).transpose())*cos)/4 idct[i*8:i*8+8,j*8:j*8+8,0]=r.round(2) idct[i*8:i*8+8,j*8:j*8+8,1]=g.round(2) idct[i*8:i*8+8,j*8:j*8+8,2]=b.round(2) if choice=='1': display(idct) pl.pause(arg[1]/1000+0.0000001) return idct
def get_fig(moves, key): global colors, arg # draw init speed # draw end point for i, move in enumerate(moves[key]): ax = make_axes() arrow(vel=key, color='r') endP = move[0] endV = move[2],move[1] arrow(start=endP, vel=endV, color='g') taken = move[3] bezier = move[4] s = "key: {0}\nendP: {1}\nendV: {2}\ntaken: {3}\n".format(key, endP, endV, taken) # s = str(endP) # print s pylab.text(-3.3 * arg, 3.3 * arg, s) pylab.scatter(zip(*bezier)[0], zip(*bezier)[1], c='g', alpha=.25, edgecolors='none') pylab.scatter(zip(*taken)[0], zip(*taken)[1], c='r', s=20, alpha=.75, edgecolors='none') pylab.draw() pylab.pause(0.0001) pylab.clf()
def update_plot(self): plt.clf() nsr = self.ca.grid.node_vector_to_raster(self.ca.node_state) plt.imshow(nsr, interpolation='None', origin='lower') plt.draw() plt.pause(0.01)
def run(self): plts = {} graphs = {} pos = 0 plt.ion() plt.style.use('ggplot') for name in sorted(self.names.values()): p = plt.subplot(math.ceil(len(self.names) / 2), 2, pos+1) p.set_ylim([0, 100]) p.set_title(self.machine_classes[name] + " " + name) p.get_xaxis().set_visible(False) X = range(0, NUM_ENTRIES, 1) Y = NUM_ENTRIES * [0] graphs[name] = p.plot(X, Y)[0] plts[name] = p pos += 1 plt.tight_layout() while True: for name, p in plts.items(): graphs[name].set_ydata(self.loads[name]) plt.draw() plt.pause(0.05)
def test_pf(): #seed(1234) N = 10000 R = .2 landmarks = [[-1, 2], [20,4], [10,30], [18,25]] #landmarks = [[-1, 2], [2,4]] pf = RobotLocalizationParticleFilter(N, 20, 20, landmarks, R) plot_pf(pf, 20, 20, weights=False) dt = .01 plt.pause(dt) for x in range(18): zs = [] pos=(x+3, x+3) for landmark in landmarks: d = np.sqrt((landmark[0]-pos[0])**2 + (landmark[1]-pos[1])**2) zs.append(d + randn()*R) pf.predict((0.01, 1.414), (.2, .05)) pf.update(z=zs) pf.resample() #print(x, np.array(list(zip(pf.particles, pf.weights)))) mu, var = pf.estimate() plot_pf(pf, 20, 20, weights=False) plt.plot(pos[0], pos[1], marker='*', color='r', ms=10) plt.scatter(mu[0], mu[1], color='g', s=100) plt.tight_layout() plt.pause(dt)
def draw(state_view, assets_view, progress_view, state, data_manager): state_view.cla() values = np.zeros((3, 4)) for y in range(3): for x in range(3): for entity in state[y][x][TEAM.RED]: values[y][x] += entity.hp for entity in state[y][x][TEAM.BLUE]: values[y][x] -= entity.hp values[y][x] = min(values[y][x], 100) values[y][x] = max(values[y][x], -100) values[0][3] = 100 values[1][3] = 0 values[2][3] = -100 # print values state_view.imshow(values, interpolation="nearest", cmap="bwr") assets_view.cla() assets_view.axis([0, max(50, len(data_manager.red_assets)), 0, 200]) assets_view.plot(data_manager.red_assets, "r") assets_view.plot(data_manager.blue_assets, "b") progress_view.cla() wins = data_manager.get_wins() progress_view.axis([0, len(wins), 0, 1]) progress_view.plot(wins) pl.pause(1.0 / FPS)
def draw(state_view, progress_view, state, tick): print state_view.cla() values = np.zeros((3, 4)) for y in range(3): for x in range(3): for entity in state[y][x][TEAM.RED]: values[y][x] += entity.hp for entity in state[y][x][TEAM.BLUE]: values[y][x] -= entity.hp values[y][x] = min(values[y][x], 100) values[y][x] = max(values[y][x], -100) values[0][3] = 100 values[1][3] = 0 values[2][3] = -100 print values state_view.imshow(values, interpolation="nearest", cmap="bwr") progress_view.cla() xs = np.arange(0, 2 * np.pi, 0.01) ys = np.sin(xs + tick * 0.1) progress_view.plot(ys) pl.pause(1.0 / FPS)
def transmission(path,g,src,dest): global disp_count global bar_colors global edge_colors global node_colors k=0 j=0 list_of_edges = g.edges() for node in path : k=path.index(node) disp_count = disp_count + 1 if k != (len(path)-1): k=path[k+1] j=list_of_edges.index((node,k)) initialize_edge_colors(j) #ec[disp_count].remove(-3000) pylab.subplot(121) nx.draw_networkx(g,pos = nx.circular_layout(g),node_color= node_colors,edge_color = edge_colors) pylab.annotate("Source",node_positions[src]) pylab.annotate("Destination",node_positions[dest]) pylab.title("Transmission") he=initializeEnergies(disp_count) print he pylab.subplot(122) pylab.bar(left=[1,2,3,4,5],height=[300,300,300,300,300],width=0.5,color = ['w','w','w','w','w'],linewidth=0) pylab.bar(left=[1,2,3,4,5],height=initializeEnergies(disp_count),width=0.5,color = 'b') pylab.title("Node energies") #pylab.legend(["already passed throgh","passing" , "yet to pass"]) pylab.xlabel('Node number') pylab.ylabel('Energy') pylab.suptitle('Leach Protocol', fontsize=12) pylab.pause(2) else : return
def image_loop(self, decay): import pylab fig = pylab.figure() pylab.ion() img = pylab.imshow(self.image, vmax=1, vmin=-1, interpolation='none', cmap='binary') if self.track_periods is not None: colors = ([(0,0,1), (0,1,0), (1,0,0), (1,1,0), (1,0,1)] * 10)[:len(self.p_y)] scatter = pylab.scatter(self.p_y, self.p_x, s=50, c=colors) else: scatter = None while True: #fig.clear() #print self.track_periods #pylab.plot(self.delta) #pylab.hist(self.delta, 50, range=(0000, 15000)) img.set_data(self.image) if scatter is not None: scatter.set_offsets(np.array([self.p_y, self.p_x]).T) c = [(r,g,b,min(self.track_certainty[i],1)) for i,(r,g,b) in enumerate(colors)] scatter.set_color(c) if display_mode == 'quick': # this is much faster, but doesn't work on all systems fig.canvas.draw() fig.canvas.flush_events() else: # this works on all systems, but is kinda slow pylab.pause(0.001) self.image *= decay
def main(): sdr = RtlSdr() print('Configuring SDR...') sdr.DEFAULT_ASYNC_BUF_NUMBER = 16 sdr.rs = 2.5e6 ## sampling rate sdr.fc = 100e6 ## center frequency sdr.gain = 10 print(' sample rate: %0.6f MHz' % (sdr.rs/1e6)) print(' center frequency %0.6f MHz' % (sdr.fc/1e6)) print(' gain: %d dB' % sdr.gain) print('Reading samples...') samples = sdr.read_samples(256*1024) print(' signal mean:', sum(samples)/len(samples)) filter = signal.firwin(5, 2* array([99.5,100.5])/sdr.rs,pass_zero=False) mpl.figure() for i in range(100): print('Testing spectrum plotting...') mpl.clf() signal2 = convolve(sdr.read_samples(256*1024),filter) psd = mpl.psd(signal2, NFFT=1024, Fc=sdr.fc/1e6, Fs=sdr.rs/1e6) mpl.pause(0.001) #mpl.plot(sdr.read_samples(256*1024)) mpl.show(block=False) print('Done\n') sdr.close()
def save_render_plot(imgs,label,save=None,res_vec=None,clean=False): if clean and len(imgs)==1: imsave(save,imgs[0]) return plt.clf() fig = plt.gcf() if not clean: fig.suptitle(label) subfig=1 t_imgsx = (math.ceil(float(len(imgs))/3)) t_imgsy = min(3,len(imgs)) for img in imgs: plt.subplot(t_imgsx,t_imgsy,subfig) if res_vec!=None: plt.title("Confidence: %0.2f%%" % (res_vec[subfig-1]*100.0)) plt.imshow(img) plt.axis('off') subfig+=1 if save!=None: plt.draw() plt.pause(0.1) if not clean: plt.savefig(save) else: plt.savefig(save,bbox_inches='tight') else: plt.show()
def plot2(k_new, d, data, classes, centers, errors ): pylab.clf() pylab.subplot( "121" ) draw_data( data, classes, centers ) draw_line( d , centers[k_new] , "y" ) pylab.subplot( "122" ) pylab.plot( range(len(errors)) , errors ) pylab.draw() pylab.pause(0.1)
def ManetPlot(): index_mob=0 index_route=00 plotting_time=0 pl.ion() fig,ax=pl.subplots() while (index_route<len_route)|(index_mob<len(time_plot)): # plot the nodes with the positions given by index_mob of x_plot and yplot pl.scatter(x_plot[index_mob],y_plot[index_mob],s=100,c='g') # print x_plot[index_mob],y_plot[index_mob] for i, txt in enumerate(n): pl.annotate(txt,(x_plot[index_mob, i]+10,y_plot[index_mob, i]+10)) pl.xlabel('x axis') pl.ylabel('y axis') # set axis limits pl.xlim(0.0, xRange) pl.ylim(0.0, yRange) ntemp=[] for index_temp in range(3,track_col[index_route]+1): ntemp.append(route_table[index_route,index_temp]) #------------------------------------------------------------------------------------------- if (route_table[index_route,1]!=-1): pl.plot(x_plot[index_mob,ntemp],y_plot[index_mob,ntemp],c='b') pl.scatter(x_plot[index_mob,ntemp],y_plot[index_mob,ntemp],s=100,c='r') else: pl.title("Route doesn't exist at "+str(plotting_time)+" Packet:"+str(route_table[index_route-1,2])) print time_plot[index_mob],route_table_time[index_route],ntemp,route_table[index_route,1:3] #------------------------------------------------------------------------------------------ # if the route_table_time is lesser than time plot, update the route if (time_plot[index_mob]>route_table_time[index_route]): pl.title("Route updation at "+str(plotting_time)+" Packet:"+str(route_table[index_route,2])) # print "Route updation at "+str(index_mob)+" "+str(time_plot[index_mob]) plotting_time=route_table_time[index_route] index_route+=1 # show the plot on the screen continue elif (time_plot[index_mob]<route_table_time[index_route]): pl.title("Position updation at "+str(time_plot[index_mob])+" Packet:"+str(route_table[index_route,2])) plotting_time=time_plot[index_mob] # print "Route updation at "+str(index_mob)+" "+str(time_plot[index_mob]) index_mob+=1 if (route_table_time[index_route]>time_plot[index_mob]): time_neighb=time_plot[index_mob] else: time_neighb=route_table_time[index_route] #------------------------------------------------------------------------------------------- print_neighbors(neighbor_nodes_time,time_neighb,x_plot[index_mob,:],y_plot[index_mob,:]) pl.show() pl.pause(.0005) # show the plot on the screen pl.clf()
def draw_graph(self): plt.clf() plt.xlim(0, 10) plt.ylim(0, 321) for index,player in enumerate(self.players): plt.plot(self.score_history[index],player.colour,label=player.name,linewidth=2.0) plt.legend(loc='upper left') plt.draw() plt.pause(.0001)
def plot_qs(x, u, qs, ts, L=25600, step=PLOT_STEP): for q, t in zip(qs, ts)[::step]: plt.clf() plt.plot(x, q) q_an = ic((x - u * t) % L) plt.plot(x, q_an) plt.ylim((-0.5, 1.5)) plt.pause(0.01) raw_input('Press enter to continue...')
def showBoard(self, board, pauseTime = 7): """display board """ pos=nx.spring_layout(board) nx.draw(board, pos) nx.draw_networkx_edge_labels(board, pos) pylab.ion() pylab.show() pylab.pause(pauseTime) pylab.close()
def plot1(K, d, data, classes, centers, errors ): pylab.clf() pylab.subplot( "121" ) draw_data( data, classes, centers ) for k in range(K): draw_line( d , centers[k] ) pylab.subplot( "122" ) pylab.plot( range(len(errors)) , errors ) pylab.draw() pylab.pause(0.1)
def Plotting(total): import numpy as np pl.style.use('seaborn-whitegrid') pl.figure(1) pl.scatter(np.linspace(0,len(total), len(total)), total) pl.xlabel('trials') pl.ylabel('success_rate, %') pl.title('Succes vs Trials (passed/trials)') pl.pause(3) pl.close()
def plot(robots, obstacles): """Plots the current configuration of robots.""" xs = [robot.body.get_position()[0] for robot in robots] ys = [robot.body.get_position()[1] for robot in robots] pl.plot(obstacles[:,0],obstacles[:,1],'gs',markersize=20.) pl.plot(xs,ys,'ro') pl.show(block=False) pl.pause(0.0000001) pl.close() return
def update_plot(self): plt.clf() if self.gridtype=='rast': nsr = self.ca.grid.node_vector_to_raster(self.ca.node_state) plt.imshow(nsr, interpolation='None', origin='lower') else: self.ca.grid.hexplot(self.ca.node_state) plt.draw() plt.pause(0.001)
# -*- coding: utf-8 -*- """ Created on Mon May 05 09:52:09 2014 @author: Jboeye """ import random as rnd import pylab as plt x = [] y = [] plt.ion() maxtime = 2000 title = 'random_output.txt' output = open(title, 'w') for t in range(maxtime): y_value = rnd.randint(0, 15) output.write(str(t) + '\t' + str(y_value) + '\n') x.append(t) y.append(y_value) plt.clf() graph = plt.plot(x, y, 'r')[0] plt.draw() plt.pause(0.0001) output.close()
def fast_process_day(base_folder, min_radius=3, max_radius=4): import pickle import pylab as pl try: tmpl_name = glob(base_folder + '*template_total.npz')[0] print tmpl_name with np.load(tmpl_name) as ld: mov_names_each = ld['movie_names'] f_results = glob(base_folder + '*results_analysis.npz') f_results.sort() A_s, C_s, YrA_s, Cn_s, b_s, f_s, shape = load_results(f_results) # B_s, lab_imgs, cm_s = threshold_components(A_s,shape, min_size=10,max_size=50,max_perc=.5) traces = [] traces_BL = [] traces_DFF = [] for idx, mov_names in enumerate(mov_names_each): A = A_s[idx] # C=C_s[idx][neurons[idx]] # YrA=YrA_s[idx][neurons[idx]] b = b_s[idx] f = f_s[idx] chunk_sizes = [] for mv in mov_names: base_name = os.path.splitext(os.path.split(mv)[-1])[0] with np.load(base_folder + base_name + '.npz') as ld: TT = len(ld['shifts']) chunk_sizes.append(TT) masks_ws,pos_examples,neg_examples=cse.utilities.extract_binary_masks_blob(A, min_radius, \ shape, num_std_threshold=1, minCircularity= 0.5, minInertiaRatio = 0.2,minConvexity = .8) #sizes=np.sum(masks_ws,(1,2)) #pos_examples=np.intersect1d(pos_examples,np.where(sizes<max_radius**2*np.pi)[0]) print len(pos_examples) # pl.close() # pl.imshow(np.mean(masks_ws[pos_examples],0)) pl.pause(.1) #A=A.tocsc()[:,pos_examples] traces, traces_DFF, traces_BL = generate_linked_traces( mov_names, chunk_sizes, A, b, f) np.savez(f_results[idx][:-4] + '_masks.npz', masks_ws=masks_ws, pos_examples=pos_examples, neg_examples=neg_examples, A=A.todense(), b=b, f=f) with open(f_results[idx][:-4] + '_traces.pk', 'w') as f: pickle.dump( dict(traces=traces, traces_BL=traces_BL, traces_DFF=traces_DFF), f) except: print 'Failed' return False return True
sz_y = 20 sz_z = 10 voxels = numpy.zeros((sz_x, sz_y, sz_z, 4)) for x in xrange(sz_x): for y in xrange(sz_y): for z in xrange(sz_z): #index 0 of voxel array is 'matter' concentration #marching cubes will look for when this concentration #crosses a particular threshold and output a surface xc = (float(x) / sz_x - 0.5) * 2.0 #create range from -1 to 1 yc = (float(y) / sz_y - 0.5) * 2.0 zc = (float(z) / sz_z - 0.5) * 2.0 voxels[x, y, z, 0] = xc**2 + yc**2 + zc**2 #define a sphere #index 1,2,3 are HSV color for that voxel voxels[x, y, z, 1:] = np.random.random((3)) import pylab as plt plt.ion() plt.show() ang = 0 while True: out = render(voxels, ang, ang) ang += 5 plt.clf() plt.ion() plt.imshow(out) plt.pause(0.1)
from pylab import plot, draw, pause from numpy import arange, sin, pi from time import time x = arange(0, 2 * pi, 0.01) tstart = time() line, = plot(x, sin(x)) for i in arange(1, 200): line.set_ydata(sin(x + i / 10.0)) draw() pause(0.001) fps_mpl = int(200 / (time() - tstart)) print('fps (mpl): %4d' % fps_mpl)
def FMM_discontinue(Etats,V,U,I,Bord,params,solve_quad,masque,Cas = False, iterations = False, Delta = False,plot = []) : """calcul avec une discontinuité (=ombre) """ (n,m) = U.shape Z = 2*np.ones((n,m)) it = 0 ITERATION = np.zeros((n,m)) CAS = np.zeros((n,m)) DELTA = np.zeros((n,m)) if len(plot)>0 : # plt.ion() plt.show() from matplotlib import cm while not((Etats==Z).all()) : k = np.argmin(V) i = k//m j = k - i*m # (i,j) sont les coordonnées du point Trial de valeur minimale Etats[i,j] = 2 if 1 in plot : plt.figure("plot Etats") plt.clf() plt.imshow(Etats,cmap=plt.cm.RdBu_r) plt.colorbar() plt.pause(0.01) if 2 in plot : plt.figure("plot U") plt.clf() plt.imshow(U,cmap=plt.cm.RdBu_r) plt.colorbar() plt.pause(0.01) ITERATION[i,j] = it it += 1 V[i,j] = np.inf vois = voisins_per(i,j,n,m) list_voisins = vois[0]+vois[1] for p in list_voisins : pi,pj = p if Etats[pi,pj] != 2 and not(Bord[pi,pj]) : Etats[pi,pj] = 1 q_gradx, q_grady, epsx, epsy = voisins_gradient_per(U,pi,pj) if (masque[pi,pj] == 1 and pi == i+1) or (masque[pi,pj] == 2 and pj == j-1) or (masque[pi,pj] == 3 and pi == i-1) or (masque[pi,pj] == 4 and pi == j+1) : None else : if (masque[pi,pj] == 1 and q_grady[0] == pi-1) : q_grady = pi+1,q_grady[1] elif (masque[pi,pj] == 2 and q_gradx[1] == pj+1) : q_gradx = q_gradx[0],pj-1 elif (masque[pi,pj] == 3 and q_grady[0] == pi+1) : q_grady = pi-1,q_grady[1] elif (masque[pi,pj] == 4 and q_gradx[1] == pj-1) : q_gradx = q_gradx[0],pj+1 u,cas,delta = solve_quad(U[q_gradx[0],q_gradx[1]],U[q_grady[0],q_grady[1]],I[pi,pj],epsx,epsy,params) if delta<0 : DELTA[pi,pj] = 1 CAS[pi,pj] = cas U[pi,pj] = u # actualisation de la valeur de p V[pi,pj] = u res = [U] if Cas : res.append(CAS) if iterations : res.append(ITERATION) if Delta : res.append(DELTA) return(res)
def plot_(img): pl.imshow(img) # ,cmap=pl.cm.binary pl.pause(.001) pl.draw()
def contador(): i = 0 with daq.Task() as task: task.co_channels.add_co_pulse_chan_time( "Dev13/ctr0", name_to_assign_to_channel="pwmOut", high_time=periodoPWM / 2, low_time=periodoPWM / 2) task.timing.cfg_implicit_timing( sample_mode=daq.constants.AcquisitionType.CONTINUOUS, samps_per_chan=700) task.start() temperatura = medir_temp() inicialtime = time.time() finaltime = inicialtime + periodoPWM estado_actual = True activa_salida_digital(estado_actual) i_term = 0 last_error = 0 while (True): temperatura = 0.8 * temperatura + 0.2 * medir_temp() ''' guardar temp ''' listTemp.append(temperatura) #plt.scatter(i,data[1],c='b') print("Temperatura:", temperatura) np.savetxt('Temperatura' + 'kp_' + str(kp) + 'ki_' + str(ki) + 'kd_' + str(kd) + 'sp_' + str(setpoint) + '.txt', listTemp, delimiter=' ') i += 1 #c = ferror(temperatura,setpoint,kp) c, i_term = PID_(temperatura, setpoint, kp, ki, kd, i_term, last_error) tiempo_encendido = periodoPWM * (1 - c) / 2 tiempo_apagado = periodoPWM * (1 + c) / 2 sampleH = daq.types.CtrTime(high_time=tiempo_encendido, low_time=tiempo_apagado) C_.append(c) ten_.append(tiempo_encendido) tap_.append(tiempo_apagado) np.savetxt('C_' + 'kp_' + str(kp) + 'ki_' + str(ki) + 'kd_' + str(kd) + 'sp_' + str(setpoint) + '.txt', C_, delimiter=' ') np.savetxt('ten_' + 'kp_' + str(kp) + 'ki_' + str(ki) + 'kd_' + str(kd) + 'sp_' + str(setpoint) + '.txt', ten_, delimiter=' ') np.savetxt('tap_' + 'kp_' + str(kp) + 'ki_' + str(ki) + 'kd_' + str(kd) + 'sp_' + str(setpoint) + '.txt', tap_, delimiter=' ') #plt.title('Setpoint:', setpoint) plt.subplot(212) plt.scatter(i, temperatura, c='r', label='temperatura') plt.grid(True) plt.subplot(221) plt.scatter(i, c, c='b', label='c') plt.grid(True) plt.subplot(222) plt.scatter(i, tiempo_encendido, c='g', label='tiempo_encendido') plt.scatter(i, tiempo_apagado, c='y', label='tiempo_apagado') plt.grid(True) plt.pause(0.05) print('c=', c) print('tiempo_encendido=', tiempo_encendido) print('tiempo_apagado=', tiempo_apagado) if i % 10 == 0: task.write(sampleH) time.sleep(0.15 * periodoPWM) if time.time() > finaltime: inicialtime = time.time() finaltime = inicialtime + periodoPWM estado_actual = not estado_actual activa_salida_digital(estado_actual) task.wait_until_done task.stop()
def animate_transtree(tt, **kwargs): ''' Plot an animation of the transmission tree; see TransTree.animate() for documentation ''' # Settings animate = kwargs.get('animate', True) verbose = kwargs.get('verbose', False) msize = kwargs.get('markersize', 10) sus_color = kwargs.get('sus_color', [0.5, 0.5, 0.5]) fig_args = kwargs.get('fig_args', dict(figsize=(24, 16))) axis_args = kwargs.get( 'axis_args', dict(left=0.10, bottom=0.05, right=0.85, top=0.97, wspace=0.25, hspace=0.25)) plot_args = kwargs.get('plot_args', dict(lw=2, alpha=0.5)) delay = kwargs.get('delay', 0.2) font_size = kwargs.get('font_size', 18) colors = kwargs.get('colors', None) cmap = kwargs.get('cmap', 'parula') pl.rcParams['font.size'] = font_size if colors is None: colors = sc.vectocolor(tt.pop_size, cmap=cmap) # Initialization n = tt.n_days + 1 frames = [list() for i in range(n)] tests = [list() for i in range(n)] diags = [list() for i in range(n)] quars = [list() for i in range(n)] # Construct each frame of the animation for i, entry in enumerate(tt.detailed): # Loop over every person frame = sc.objdict() tdq = sc.objdict() # Short for "tested, diagnosed, or quarantined" # This person became infected if entry: source = entry['source'] target = entry['target'] target_date = entry['date'] if source: # Seed infections and importations won't have a source source_date = tt.detailed[source]['date'] else: source = 0 source_date = 0 # Construct this frame frame.x = [source_date, target_date] frame.y = [source, target] frame.c = colors[source] frame.i = True # If this person is infected frames[target_date].append(frame) # Handle testing, diagnosis, and quarantine tdq.t = target tdq.d = target_date tdq.c = colors[target] date_t = entry.t.date_tested date_d = entry.t.date_diagnosed date_q = entry.t.date_known_contact if ~np.isnan(date_t) and date_t < n: tests[int(date_t)].append(tdq) if ~np.isnan(date_d) and date_d < n: diags[int(date_d)].append(tdq) if ~np.isnan(date_q) and date_q < n: quars[int(date_q)].append(tdq) # This person did not become infected else: frame.x = [0] frame.y = [i] frame.c = sus_color frame.i = False frames[0].append(frame) # Configure plotting fig = pl.figure(**fig_args) pl.subplots_adjust(**axis_args) ax = fig.add_subplot(1, 1, 1) # Create the legend ax2 = pl.axes([0.85, 0.05, 0.14, 0.9]) ax2.axis('off') lcol = colors[0] na = np.nan # Shorten pl.plot(na, na, '-', c=lcol, **plot_args, label='Transmission') pl.plot(na, na, 'o', c=lcol, markersize=msize, **plot_args, label='Source') pl.plot(na, na, '*', c=lcol, markersize=msize, **plot_args, label='Target') pl.plot(na, na, 'o', c=lcol, markersize=msize * 2, fillstyle='none', **plot_args, label='Tested') pl.plot(na, na, 's', c=lcol, markersize=msize * 1.2, **plot_args, label='Diagnosed') pl.plot(na, na, 'x', c=lcol, markersize=msize * 2.0, label='Known contact') pl.legend() # Plot the animation pl.sca(ax) for day in range(n): pl.title(f'Day: {day}') pl.xlim([0, n]) pl.ylim([0, tt.pop_size]) pl.xlabel('Day') pl.ylabel('Person') flist = frames[day] tlist = tests[day] dlist = diags[day] qlist = quars[day] if verbose: print(i, flist) for f in flist: if verbose: print(f) pl.plot(f.x[0], f.y[0], 'o', c=f.c, markersize=msize, **plot_args) # Plot sources pl.plot(f.x, f.y, '-', c=f.c, **plot_args) # Plot transmission lines if f.i: # If this person is infected pl.plot(f.x[1], f.y[1], '*', c=f.c, markersize=msize, **plot_args) # Plot targets for tdq in tlist: pl.plot(tdq.d, tdq.t, 'o', c=tdq.c, markersize=msize * 2, fillstyle='none') # Tested; No alpha for this for tdq in dlist: pl.plot(tdq.d, tdq.t, 's', c=tdq.c, markersize=msize * 1.2, **plot_args) # Diagnosed for tdq in qlist: pl.plot(tdq.d, tdq.t, 'x', c=tdq.c, markersize=msize * 2.0) # Quarantine; no alpha for this pl.plot([0, day], [0.5, 0.5], c='k', lw=5) # Plot the endless march of time if animate: # Whether to animate pl.pause(delay) return fig
pl.ylim(C.min() * 1.1, C.max() * 1.1) #AGREGRA UNA LEYENDA pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="Coseno") pl.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="Seno") pl.legend(loc='upper left') #AGREGRA UNA ANOTACION EN UN PUNTO CONOCIDO t = 2 * np.pi / 3 #Para coseno------------------------------------------------------------------------------------ pl.plot([t, t], [-t, 0], color='blue', linewidth=2.5, linestyle="--") #pl.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--") pl.scatter([t, ], [np.cos(t), ], 50, color='blue') #DEFINE LAS CARACTERISTICAS DEN PUNTO (CIRCULO) pl.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',#DATOS A IMPRIMIR DEL TEXTO xy=(t, np.sin(t)), xycoords='data', #COORDENADAS DE REFERENCIA PARA LA FLECHA Y EL TEXTO xytext=(+10, +30), textcoords='offset points', fontsize=16,#INDICAN POSICION DEL TEXTO arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) #DIRECCION DE LA FLECHA #Para seno-------------------------------------------------------------------------------------- pl.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--") pl.scatter([t, ],[np.sin(t), ], 50, color='red') pl.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))#DIRECCION DE LA FLECHA # Mostrar resultado en pantalla (Con 2 segundos de muestreo) pl.pause(100)
for day in range(365): if birthdays[day] > 1: matched = True if matched == True: successes += 1 #print("Trial", trial+1, "of", trials, (trial+1)*100/trials, "% | Matched: ", str(matched)) return float(successes) * 100.000000000 / float(trials) n = 0 points = [] pylab.show() while n <= i: prob = birthdayProbability(n, trials) points.append(prob) pylab.scatter(n, prob, c='r') pylab.plot(points, c='b') pylab.pause(0.001) if (n % 10 == 0): print("Probability for n =", n, "is", prob) #if(n==0): pylab.pause(10) n += 1 #print(birthdayProbability(23, 10000))
def Cluster(self): NCluster = self.NCluster nk = self.NCluster DoPlot = self.DoPlot x, y, s = self.X, self.Y, self.S x0, x1 = np.min(x), np.max(x) #0.9*np.min(x),1.1*np.max(x) y0, y1 = np.min(y), np.max(y) #0.9*np.min(y),1.1*np.max(y) Dx = 1e-2 #5*np.abs(x1-x0) Dy = 1e-2 #5*np.abs(y1-y0) x0, x1 = x0 - Dx, x1 + Dx y0, y1 = y0 - Dy, y1 + Dy # for i in range(x.shape[0]): # print "(%6.2f, %6.2f)"%(x[i]*1000,y[i]*1000) #xx,yy=np.mgrid[x0:x1:40j,y0:y1:40j] Np = 100 xx, yy = np.mgrid[x0:x1:Np * 1j, y0:y1:Np * 1j] sigx = .5 * (x0 - x1) / nk sigy = .5 * (y0 - y1) / nk #sigx=1.*(x0-x1)/nk #sigy=1.*(y0-y1)/nk xnode = [] ynode = [] ss = np.zeros(xx.shape, dtype=xx.dtype) ss0 = np.zeros(xx.shape, dtype=xx.dtype) dx, dy = (x1 - x0) / Np, (y1 - y0) / Np C = 1. / (2. * np.pi * sigx * sigy) for i in range(x.shape[0]): ss += s[i] * C * np.exp(-((xx - x[i])**2 / (2. * sigx**2) + (yy - y[i])**2 / (2. * sigy**2))) * dx * dy ss0 += C * np.exp(-((xx - x[i])**2 / (2. * sigx**2) + (yy - y[i])**2 / (2. * sigy**2))) * dx * dy # xr=np.random.rand(1000) # yr=np.random.rand(1000) # C=1./(2.*np.pi*sigx*sigy) # for i in range(xr.shape[0]): # ss0+=C*np.exp(-((xx-xr[i])**2/sigx**2+(yy-yr[i])**2/sigy**2)) # ss0/=xr.shape[0] # ssn=ss/ss0#(ss-ss0)/ss0 #ss/=np.sqrt(ss0) #ss+=np.random.randn(*ss.shape)*1e-6 #ssn=ss # pylab.scatter(xx,yy,marker="s",c=ss,s=50) # pylab.scatter(x,y,c=s,s=np.sqrt(s)*50) # pylab.colorbar() # pylab.draw() # #time.sleep(1) # #return vmin, vmax = np.min(ss), np.max(ss) #print #print vmin,vmax if DoPlot: import pylab pylab.ion() pylab.imshow(ss.reshape((Np, Np)).T[::-1, :], vmin=vmin, vmax=vmax, extent=(x0, x1, y0, y1)) pylab.scatter(self.X, self.Y) #,marker="s",c=ss,s=50,vmin=vmin,vmax=vmax) pylab.xlim(x0, x1) pylab.ylim(y0, y1) pylab.draw() pylab.show(False) pylab.pause(1) for i in range(nk): ind = np.where(ss == np.max(ss)) xnode.append(xx[ind]) ynode.append(yy[ind]) ss -= ss[ind] * np.exp(-((xx - xnode[-1])**2 / (sigx)**2 + (yy - ynode[-1])**2 / (sigy)**2)) if DoPlot: pylab.clf() #pylab.scatter(xx,yy,marker="s",c=ss,s=50)#,vmin=vmin,vmax=vmax) #pylab.scatter(xnode[-1],ynode[-1],marker="s",vmin=vmin,vmax=vmax) pylab.imshow(ss.reshape((Np, Np)).T[::-1, :], vmin=vmin, vmax=vmax, extent=(x0, x1, y0, y1)) pylab.scatter(xnode, ynode, marker="s", color="red", vmin=vmin, vmax=vmax) #pylab.scatter(x,y,marker="o")#,vmin=vmin,vmax=vmax) #pylab.colorbar() pylab.xlim(x0, x1) pylab.ylim(y0, y1) pylab.draw() pylab.show() pylab.pause(0.1) if DoPlot: pylab.ioff() xnode = np.array(xnode) ynode = np.array(ynode) KK = {} keys = [] for i in range(nk): key = "%3.3i" % i keys.append(key) KK[key] = {"ListCluster": []} for i in range(x.shape[0]): d = np.sqrt((x[i] - xnode)**2 + (y[i] - ynode)**2) ind = np.where(d == np.min(d))[0][0] (KK[keys[ind]])["ListCluster"].append(i) self.xnode = xnode self.ynode = ynode if DoPlot: pylab.clf() Dx = Dy = 0.01 extent = (np.min(x) - Dx, np.max(x) + Dx, np.min(y) - Dy, np.max(y) + Dy) self.PlotTessel(extent) #self.infile_cluster="%s.cluster"%self.TargetList #f=file(self.infile_cluster,"w") return KK
dms = f.mes[i][1:] - f.mes[i][0:-1] dmr = f.me[1:] - f.me[0:-1] plt.plot(f.ms[i][cs], f.Ns[i][cs] / dms[cs], 'go-') plt.plot(f.mr[i][cr], f.Mr[i][cr] / dmr[cr], 'ko-') for j in range(len(f.me)): plt.plot([f.me[j], f.me[j]], [1e-4, 1e9], 'k--') mto = f.mto(f.tout[i]) plt.plot([mto, mto], [1e-4, 1e9], 'k-') plt.show() plt.draw plt.pause(0.05) plt.savefig('mf_%04d.png' % i) if (plotm): plt.ion() plt.clf() plt.axes([0.12, 0.12, 0.8, 0.8]) # plt.xscale('log') # plt.yscale('log') plt.ylim(0.1, 2) # plt.xlim(2,e4) plt.ylabel(r'$M(t)$') plt.xlabel(r'$t\,{\rm [Myr]}$') Nstot = np.zeros(len(f.tout)) Mstot = np.zeros(len(f.tout))
linewidth=0.3) pl.plot(step_hist, value_hist_test, color='dodgerblue', linewidth=0.3) pl.plot(step_hist, value_hist_cv, color='magenta', linewidth=1) pl.plot(step_hist, value_hist_train_ma, color='tomato', linewidth=1.5) pl.plot(step_hist, value_hist_test_ma, color='royalblue', linewidth=1.5) pl.plot(step_hist, value_hist_cv_ma, color='black', linewidth=1.5) pl.pause(1e-10) # save if some complicated rules if saving: current_score = 0 if value_test[-1] < 0.01 or value_cv[-1] < 0.01 \ else np.average([value_test[-1], value_cv[-1]]) saving_score = current_score if saving_score < current_score else saving_score if saving_score == current_score and saving_score > 0.05: saver.save(sess, 'saved_models/lstm-v2-avg_score{:.3f}'.format( current_score), global_step=step) print( 'Model saved. Average score: {:.2f}'.format(current_score)) pl.figure(2)
def get_behavior_traces(fname, t0, t1, freq, ISI, draw_rois=False, plot_traces=False, mov_filt_1d=True, window_hp=201, window_lp=3, interpolate=True, EXPECTED_ISI=.25): """ From hdf5 movies extract eyelid closure and wheel movement Parameters ---------- fname: str file name of the hdf5 file t0,t1: float. Times of beginning and end of trials (in general 0 and 8 for our dataset) to build the absolute time vector freq: float frequency used to build the final time vector ISI: float inter stimulu interval draw_rois: bool whether to manually draw the eyelid contour plot_traces: bool whether to plot the traces during extraction mov_filt_1d: bool whether to filter the movie after extracting the average or ROIs. The alternative is a 3D filter that can be very computationally expensive window_lp, window_hp: ints number of frames to be used to median filter the data. It is needed because of the light IR artifact coming out of the eye Returns ------- res: dict dictionary with fields 'eyelid': eyelid trace 'wheel': wheel trace 'time': absolute tim vector 'trials': corresponding indexes of the trials 'trial_info': for each trial it returns start trial, end trial, time CS, time US, trial type (CS:0 US:1 CS+US:2) 'idx_CS_US': idx trial CS US 'idx_US': idx trial US 'idx_CS': idx trial CS """ CS_ALONE = 0 US_ALONE = 1 CS_US = 2 meta_inf = fname[:-7] + 'data.h5' time_abs = np.linspace(t0, t1, freq * (t1 - t0)) T = len(time_abs) t_us = 0 t_cs = 0 n_samples_ISI = np.int(ISI * freq) t_uss = [] ISIs = [] eye_traces = [] wheel_traces = [] trial_info = [] tims = [] with h5py.File(fname) as f: with h5py.File(meta_inf) as dt: rois = np.asarray(dt['roi'], np.float32) trials = f.keys() trials.sort(key=lambda (x): np.int(x.replace('trial_', ''))) trials_idx = [np.int(x.replace('trial_', '')) - 1 for x in trials] trials_idx_ = [] for tr, idx_tr in zip(trials[:], trials_idx[:]): if plot_traces: pl.cla() print tr trial = f[tr] mov = np.asarray(trial['mov']) if draw_rois: pl.imshow(np.mean(mov, 0)) pl.xlabel('Draw eye') pts = pl.ginput(-1) pts = np.asarray(pts, dtype=np.int32) data = np.zeros(np.shape(mov)[1:], dtype=np.int32) # if CV_VERSION == 2: #lt = cv2.CV_AA # elif CV_VERSION == 3: lt = cv2.LINE_AA cv2.fillConvexPoly(data, pts, (1, 1, 1), lineType=lt) rois[0] = data pl.close() pl.imshow(np.mean(mov, 0)) pl.xlabel('Draw wheel') pts = pl.ginput(-1) pts = np.asarray(pts, dtype=np.int32) data = np.zeros(np.shape(mov)[1:], dtype=np.int32) # if CV_VERSION == 2: #lt = cv2.CV_AA # elif CV_VERSION == 3: lt = cv2.LINE_AA cv2.fillConvexPoly(data, pts, (1, 1, 1), lineType=lt) rois[1] = data pl.close() # eye_trace=np.mean(mov*rois[0],axis=(1,2)) # mov_trace=np.mean((np.diff(np.asarray(mov,dtype=np.float32),axis=0)**2)*rois[1],axis=(1,2)) mov = np.transpose(mov, [0, 2, 1]) mov = mov[:, :, ::-1] if mov.shape[0] > 0: ts = np.array(trial['ts']) if np.size(ts) > 0: assert np.std( np.diff(ts) ) < 0.005, 'Time stamps of behaviour are unreliable' if interpolate: new_ts = np.linspace(0, ts[-1, 0] - ts[0, 0], np.shape(mov)[0]) if dt['trials'][idx_tr, -1] == US_ALONE: t_us = np.maximum( t_us, dt['trials'][idx_tr, 3] - dt['trials'][idx_tr, 0]) mmm = mov[:n_samples_ISI].copy() mov = mov[:-n_samples_ISI] mov = np.concatenate([mmm, mov]) elif dt['trials'][idx_tr, -1] == CS_US: t_cs = np.maximum( t_cs, dt['trials'][idx_tr, 2] - dt['trials'][idx_tr, 0]) t_us = np.maximum( t_us, dt['trials'][idx_tr, 3] - dt['trials'][idx_tr, 0]) t_uss.append(t_us) ISI = t_us - t_cs ISIs.append(ISI) n_samples_ISI = np.int(ISI * freq) else: t_cs = np.maximum( t_cs, dt['trials'][idx_tr, 2] - dt['trials'][idx_tr, 0]) new_ts = new_ts tims.append(new_ts) else: start, end, t_CS, t_US = dt['trials'][ idx_tr, :-1] - dt['trials'][idx_tr, 0] f_rate = np.median(np.diff(ts[:, 0])) ISI = t_US - t_CS idx_US = np.int(t_US / f_rate) idx_CS = np.int(t_CS / f_rate) fr_before_US = np.int((t_US - start - .1) / f_rate) fr_after_US = np.int((end - .1 - t_US) / f_rate) idx_abs = np.arange(-fr_before_US, fr_after_US) time_abs = idx_abs * f_rate assert np.abs(ISI - EXPECTED_ISI) < .01, str( np.abs(ISI - EXPECTED_ISI) ) + ':the distance form CS and US is different from what expected' # trig_US= # new_ts= mov_e = cb.movie(mov * rois[0][::-1].T, fr=1 / np.mean(np.diff(new_ts))) mov_w = cb.movie(mov * rois[1][::-1].T, fr=1 / np.mean(np.diff(new_ts))) x_max_w, y_max_w = np.max(np.nonzero(np.max(mov_w, 0)), 1) x_min_w, y_min_w = np.min(np.nonzero(np.max(mov_w, 0)), 1) x_max_e, y_max_e = np.max(np.nonzero(np.max(mov_e, 0)), 1) x_min_e, y_min_e = np.min(np.nonzero(np.max(mov_e, 0)), 1) mov_e = mov_e[:, x_min_e:x_max_e, y_min_e:y_max_e] mov_w = mov_w[:, x_min_w:x_max_w, y_min_w:y_max_w] # mpart=mov[:20].copy() # md=cse.utilities.mode_robust(mpart.flatten()) # N=np.sum(mpart<=md) # mpart[mpart>md]=md # mpart[mpart==0]=md # mpart=mpart-md # std=np.sqrt(np.sum(mpart**2)/N) # thr=md+10*std # # thr=np.minimum(255,thr) # return mov if mov_filt_1d: mov_e = np.mean(mov_e, axis=(1, 2)) window_hp_ = window_hp window_lp_ = window_lp if plot_traces: pl.plot((mov_e - np.mean(mov_e)) / (np.max(mov_e) - np.min(mov_e))) else: window_hp_ = (window_hp, 1, 1) window_lp_ = (window_lp, 1, 1) bl = signal.medfilt(mov_e, window_hp_) mov_e = signal.medfilt(mov_e - bl, window_lp_) if mov_filt_1d: eye_ = np.atleast_2d(mov_e) else: eye_ = np.atleast_2d(np.mean(mov_e, axis=(1, 2))) wheel_ = np.concatenate([ np.atleast_1d(0), np.nanmean(np.diff(mov_w, axis=0)**2, axis=(1, 2)) ]) if np.abs(new_ts[-1] - time_abs[-1]) > 1: raise Exception( 'Time duration is significantly larger or smaller than reference time' ) wheel_ = np.squeeze(wheel_) eye_ = np.squeeze(eye_) f1 = scipy.interpolate.interp1d(new_ts, eye_, bounds_error=False, kind='linear') eye_ = np.array(f1(time_abs)) f1 = scipy.interpolate.interp1d(new_ts, wheel_, bounds_error=False, kind='linear') wheel_ = np.array(f1(time_abs)) if plot_traces: pl.plot((eye_) / (np.nanmax(eye_) - np.nanmin(eye_)), 'r') pl.plot( (wheel_ - np.nanmin(wheel_)) / np.nanmax(wheel_), 'k') pl.pause(.01) trials_idx_.append(idx_tr) eye_traces.append(eye_) wheel_traces.append(wheel_) trial_info.append(dt['trials'][idx_tr, :]) res = dict() res['eyelid'] = eye_traces res['wheel'] = wheel_traces res['time'] = time_abs - np.median(t_uss) res['trials'] = trials_idx_ res['trial_info'] = trial_info res['idx_CS_US'] = np.where( map(int, np.array(trial_info)[:, -1] == CS_US))[0] res['idx_US'] = np.where( map(int, np.array(trial_info)[:, -1] == US_ALONE))[0] res['idx_CS'] = np.where( map(int, np.array(trial_info)[:, -1] == CS_ALONE))[0] return res
def compute_metrics_motion_correction(fname, final_size_x, final_size_y, swap_dim, pyr_scale=.5, levels=3, winsize=100, iterations=15, poly_n=5, poly_sigma=1.2 / 5, flags=0, play_flow=False, resize_fact_flow=.2, template=None): # cv2.OPTFLOW_FARNEBACK_GAUSSIAN import scipy vmin, vmax = -1, 1 m = cm.load(fname) max_shft_x = np.int(np.ceil((np.shape(m)[1] - final_size_x) / 2)) max_shft_y = np.int(np.ceil((np.shape(m)[2] - final_size_y) / 2)) max_shft_x_1 = -((np.shape(m)[1] - max_shft_x) - (final_size_x)) max_shft_y_1 = -((np.shape(m)[2] - max_shft_y) - (final_size_y)) if max_shft_x_1 == 0: max_shft_x_1 = None if max_shft_y_1 == 0: max_shft_y_1 = None # print ([max_shft_x,max_shft_x_1,max_shft_y,max_shft_y_1]) m = m[:, max_shft_x:max_shft_x_1, max_shft_y:max_shft_y_1] print('Local correlations..') img_corr = m.local_correlations(eight_neighbours=True, swap_dim=swap_dim) print(m.shape) if template is None: tmpl = cm.motion_correction.bin_median(m) else: tmpl = template # tmpl = tmpl[max_shft_x:-max_shft_x,max_shft_y:-max_shft_y] print('Compute Smoothness.. ') smoothness = np.sqrt( np.sum(np.sum(np.array(np.gradient(np.mean(m, 0)))**2, 0))) smoothness_corr = np.sqrt( np.sum(np.sum(np.array(np.gradient(img_corr))**2, 0))) print('Compute correlations.. ') correlations = [] count = 0 for fr in m: if count % 100 == 0: print(count) count += 1 correlations.append( scipy.stats.pearsonr(fr.flatten(), tmpl.flatten())[0]) print('Compute optical flow .. ') m = m.resize(1, 1, resize_fact_flow) norms = [] flows = [] count = 0 for fr in m: if count % 100 == 0: print(count) count += 1 flow = cv2.calcOpticalFlowFarneback(tmpl, fr, None, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags) if play_flow: pl.subplot(1, 3, 1) pl.cla() pl.imshow(fr, vmin=0, vmax=300, cmap='gray') pl.title('movie') pl.subplot(1, 3, 3) pl.cla() pl.imshow(flow[:, :, 1], vmin=vmin, vmax=vmax) pl.title('y_flow') pl.subplot(1, 3, 2) pl.cla() pl.imshow(flow[:, :, 0], vmin=vmin, vmax=vmax) pl.title('x_flow') pl.pause(.05) n = np.linalg.norm(flow) flows.append(flow) norms.append(n) np.savez(fname[:-4] + '_metrics', flows=flows, norms=norms, correlations=correlations, smoothness=smoothness, tmpl=tmpl, smoothness_corr=smoothness_corr, img_corr=img_corr) return tmpl, correlations, flows, norms, smoothness
hes[i, i] = 1.0 / (vector[i] * np.log(10)) i = i + 1 return hes k: int = 0 subnewton: double = 10 flag = 1 while subnewton / 2 > 0.00000000000000000000000000000000000000000000000000000000000000000000000000001: dx, w = np.hsplit( np.dot( np.linalg.inv( np.vstack((np.hstack((maxentropygt2(x), A.T)), np.hstack((A, np.zeros((rank, rank))))))), np.hstack((-maxentropygt1(x), np.zeros(rank)))), [n]) subnewton = np.dot(np.dot(dx.T, maxentropygt2(x)), dx) print('牛顿减少量', subnewton) t = 1 aerf = 0.4 beita = 0.6 print('the circle of k', k) pylab.semilogx(subnewton, k, 'ro') pylab.pause(0.05) while maxentropy( x + np.multiply(t, dx)) > maxentropy(x) - aerf * t * subnewton: t = beita * t print('in circle, the variety of t', t) x = x + np.multiply(t, dx) k = k + 1 print(x)
#normalize norm = np.trapz(abs(psi_t)**2) psi_t = psi_t / norm #figure out the indeces at which we get to 1e-15s and 1e-16s to pause and save fig time1 = 1e-15 time2 = 1e-16 ind1 = time1 / h ind1 = int(ind1) ind2 = time2 / h ind2 = int(ind2) figure() for i in range(steps): #calculate v = B.psi(x,t) v = b1 * psi_t[1:N] + b2 * (psi_t[2:N + 1] + psi_t[0:N - 1]) #solve for x using Gauss elim and backsub for tridiagnonal matrix psi_t[1:N] = banded(A, v, 1, 1) the_time = (i + 1) * h #create animation clf() plot(x, psi_t.real) xlabel('$x$ meters') ylabel('$\psi(x,t)$') title('Wavefunction at time t = {0:.2e}'.format(the_time)) draw() if i == ind1 or i == ind2: pause(10) #allow me to take screen shot else: pause(0.01)
train_gen.start() fig, ((ax00, ax01), (ax10, ax11)) = plt.subplots(nrows=2, ncols=2) for i in range(10): grabbed = False while not grabbed: (data1, data2), (label1, label2), grabbed = train_gen.load_data() ax00.imshow(data1.get(), cmap='gray') ax00.axis('off') ax01.imshow(label1.get(), cmap='gray') ax01.axis('off') ax10.imshow(data2.get(), cmap='gray') ax10.axis('off') ax11.imshow(label2.get(), cmap='gray') ax11.axis('off') plt.pause(1e-2) plt.show() train_gen.stop()
ax.set_title("Panel %d" % panel_id) for i_ref in range(len(df_p)): #ref = refls_predict_bypanel[panel_id][i_ref] ref = df_p.iloc[i_ref] i1, i2, j1, j2 = ref['bbox'] rect = plt.Rectangle(xy=(i1, j1), width=i2 - i1, height=j2 - j1, fc='none', ec='Deeppink') plt.gca().add_patch(rect) #mask = ref['shoebox'].mask.as_numpy_array()[0] #int_mask[j1:j2, i1:i2] = np.logical_or(mask == 5, int_mask[j1:j2, i1:i2]) #bg_mask[j1:j2, i1:i2] = np.logical_or(mask == 19, bg_mask[j1:j2, i1:i2]) plt.draw() plt.pause(pause) #im.set_data(int_mask) #plt.title("panel%d: integration mask" % panel_id) #im.set_clim(0, 1) #plt.draw() #plt.pause(pause) #im.set_data(bg_mask) #plt.title("panel%d: background mask" % panel_id) #im.set_clim(0, 1) #plt.draw() #plt.pause(pause) all_paths.append(fpath) all_Amats.append(crystal.get_A()) if rank == 0: print("Rank%d: writing" % rank)
# print(xs.shape, ys.shape) clf() figure() while True: newy = sin(time) average = updateAverage(average, newy) runAvg = runningAvg(average, newy, time + 1, FACTOR) complexAvg = moreComplex(average, newy, time + 1) if time == 0: xs[0] = time ys[0][0] = newy ys[1][0] = average ys[2][0] = runAvg ys[3, 0] = complexAvg else: xs = np.append(xs, time) newy = [[newy], [average], [runAvg], [complexAvg]] ys = np.append(ys, newy, axis=1) time += 1 for i in range(len(ys)): plot(xs, ys[i]) legend(["orig" if i == 0 else "avg {}".format(i) for i in range(len(ys))]) draw() pause(0.005) if time == 50: break show()
x[j] = j * dx u0[j] = 2.0*math.exp(-0.5*((x[j]-x0)/s)**2) #prepare animated plot pylab.ion() line, = pylab.plot(x, u0, '-k') pylab.ylim(-4.0,4.0) pylab.xlabel('x(m)') pylab.ylabel('u') #perform the evolution t = 0.0 while t < tmax: #update plot line.set_ydata(u0) pylab.title('Pulse in two strings: t (s) = %5f' % t) pylab.draw() pylab.pause(0.1) # leap frog method #derivatives at interior points for j in range(N): if j < N/2: v1[j] = v0[j] + dt * c1 * (u0[j+1] - u0[j])/dx else: v1[j] = v0[j] + dt * c2 * (u0[j+1] - u0[j])/dx for j in range(1,N): if j < N/2: u1[j] = u0[j] + dt * c1 * (v1[j] - v1[j-1])/dx else: u1[j] = u0[j] + dt * c2 * (v1[j] - v1[j-1])/dx #boundary conditions u1[0] = u1[N] = 0.0
def manually_refine_components(Y, xxx_todo_changeme, A, C, Cn, thr=0.9, display_numbers=True, max_number=None, cmap=None, **kwargs): """Plots contour of spatial components against a background image and allows to interactively add novel components by clicking with mouse Args: Y: ndarray movie in 2D (dx,dy): tuple dimensions of the square used to identify neurons (should be set to the galue of gsiz) A: np.ndarray or sparse matrix Matrix of Spatial components (d x K) Cn: np.ndarray (2D) Background image (e.g. mean, correlation) thr: scalar between 0 and 1 Energy threshold for computing contours (default 0.995) display_number: Boolean Display number of ROIs if checked (default True) max_number: int Display the number for only the first max_number components (default None, display all numbers) cmap: string User specifies the colormap (default None, default colormap) Returns: A: np.ndarray matrix A os estimated spatial component contributions C: np.ndarray array of estimated calcium traces """ (dx, dy) = xxx_todo_changeme if issparse(A): A = np.array(A.todense()) else: A = np.array(A) d1, d2 = np.shape(Cn) d, nr = np.shape(A) if max_number is None: max_number = nr x, y = np.mgrid[0:d1:1, 0:d2:1] pl.imshow(Cn, interpolation=None, cmap=cmap) cm = com(A, d1, d2) Bmat = np.zeros((np.minimum(nr, max_number), d1, d2)) for i in range(np.minimum(nr, max_number)): indx = np.argsort(A[:, i], axis=None)[::-1] cumEn = np.cumsum(A[:, i].flatten()[indx]**2) cumEn /= cumEn[-1] Bvec = np.zeros(d) Bvec[indx] = cumEn Bmat[i] = np.reshape(Bvec, np.shape(Cn), order='F') T = np.shape(Y)[-1] pl.close() fig = pl.figure() ax = pl.gca() ax.imshow(Cn, interpolation=None, cmap=cmap, vmin=np.percentile(Cn[~np.isnan(Cn)], 1), vmax=np.percentile(Cn[~np.isnan(Cn)], 99)) for i in range(np.minimum(nr, max_number)): pl.contour(y, x, Bmat[i], [thr]) if display_numbers: for i in range(np.minimum(nr, max_number)): ax.text(cm[i, 1], cm[i, 0], str(i + 1)) A3 = np.reshape(A, (d1, d2, nr), order='F') while True: pts = fig.ginput(1, timeout=0) if pts != []: print(pts) xx, yy = np.round(pts[0]).astype(np.int) coords_y = np.array(list(range(yy - dy, yy + dy + 1))) coords_x = np.array(list(range(xx - dx, xx + dx + 1))) coords_y = coords_y[(coords_y >= 0) & (coords_y < d1)] coords_x = coords_x[(coords_x >= 0) & (coords_x < d2)] a3_tiny = A3[coords_y[0]:coords_y[-1] + 1, coords_x[0]:coords_x[-1] + 1, :] y3_tiny = Y[coords_y[0]:coords_y[-1] + 1, coords_x[0]:coords_x[-1] + 1, :] dy_sz, dx_sz = np.shape(a3_tiny)[:-1] y2_tiny = np.reshape(y3_tiny, (dx_sz * dy_sz, T), order='F') a2_tiny = np.reshape(a3_tiny, (dx_sz * dy_sz, nr), order='F') y2_res = y2_tiny - a2_tiny.dot(C) y3_res = np.reshape(y2_res, (dy_sz, dx_sz, T), order='F') a__, c__, center__, b_in__, f_in__ = greedyROI( y3_res, nr=1, gSig=[ np.floor(old_div(dx_sz, 2)), np.floor(old_div(dy_sz, 2)) ], gSiz=[dx_sz, dy_sz]) a_f = np.zeros((d, 1)) idxs = np.meshgrid(coords_y, coords_x) a_f[np.ravel_multi_index(idxs, (d1, d2), order='F').flatten()] = a__ A = np.concatenate([A, a_f], axis=1) C = np.concatenate([C, c__], axis=0) indx = np.argsort(a_f, axis=None)[::-1] cumEn = np.cumsum(a_f.flatten()[indx]**2) cumEn /= cumEn[-1] Bvec = np.zeros(d) Bvec[indx] = cumEn bmat = np.reshape(Bvec, np.shape(Cn), order='F') pl.contour(y, x, bmat, [thr]) pl.pause(.01) elif pts == []: break nr += 1 A3 = np.reshape(A, (d1, d2, nr), order='F') return A, C
# Ticks en x(Impresión de intervalos, cantidad de datos mostrados en el eje) pl.xticks(np.linspace(-8, 8, 17, endpoint=True)) # Establecer límites del eje y (Divisiones en Y) pl.ylim(-1.0, 1.0) # Ticks en y (Impresión de intervalos, cantidad de datos mostrados en el eje) pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) '''Otra opcion de determinar los limites a imprimir pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) pl.yticks([-1, 0, +1]) ''' ax = pl.gca() # gca stands for 'get current axis' #ax.spines['right'].set_color('none') #ax.spines['top'].set_color('none') #ax.xaxis.set_ticks_position('bottom') #ax.spines['bottom'].set_position(('data',0)) #ax.yaxis.set_ticks_position('left') #ax.spines['left'].set_position(('data',0)) # Guardar la figura usando 72 puntos por pulgada # savefig("exercice_2.png", dpi=72) #Indicamos los espacios entre los bordes de grafica y las graficas #pl.xlim(X.min() * 1.1, X.max() * 1.1) pl.ylim(C.min() * 1.1, C.max() * 1.1) # Mostrar resultado en pantalla (Con 2 segundos de muestreo) pl.pause(10)
x1, x2, y1, y2 = bb_on_panel[i_spot] patch = plt.Rectangle(xy=(x1, y1), width=x2 - x1, height=y2 - y1, fc='none', ec='r') plt.gca().add_patch(patch) plt.title("Panel=%d" % pid) # get the ground truth background plane and plot if args.savefigdir is not None: plt.savefig( os.path.join(args.savefigdir, "_figure%d.png" % pid)) plt.draw() plt.pause(args.plot) r_on_panel = Rpp[pid] x, y, _ = prediction_utils.xyz_from_refl(r_on_panel) x = np.array(x) - 0.5 y = np.array(y) - 0.5 Hi_on_panel = np.array(Hi)[np.array(bbox_panel_ids) == pid] for i_spot, (x1, x2, y1, y2) in enumerate(bb_on_panel): inX = np.logical_and(x1 < x, x < x2) inY = np.logical_and(y1 < y, y < y2) in_bb = inX & inY if not any(in_bb): continue pos = np.where(in_bb)[0]
# length is zero, quit the loop image_len = struct.unpack('<L', connection.read( struct.calcsize('<L')))[0] if not image_len: break # Construct a stream to hold the image data and read the image # data from the connection image_stream = io.BytesIO() image_stream.write(connection.read(image_len)) # Rewind the stream, open it as an image with PIL and do some # processing on it image_stream.seek(0) file_bytes = pl.asarray( bytearray(image_stream.read()), dtype=pl.uint8) # convert to numpy byte-like array image = cv.imdecode(file_bytes, cv.IMREAD_COLOR) image = cv.cvtColor(image, cv.COLOR_BGR2RGB) print( f'Image is {image.shape[0]}x{image.shape[1]}x{image.shape[2]}') if img is None: img = pl.imshow(image) else: img.set_data(image) pl.pause(0.0001) # image.verify() # print('Image is verified') finally: pl.show() connection.close() server_socket.close()
state = sim.step() # will perform A* actions # save data & label states[step, :] = rgb2gray(state.pob).reshape(opt.state_siz) labels[step] = state.action epi_step += 1 if step % opt.prog_freq == 0: print(step) if opt.disp_on: if win_all is None: import pylab as pl pl.figure() win_all = pl.imshow(state.screen) pl.figure() win_pob = pl.imshow(state.pob) else: win_all.set_data(state.screen) win_pob.set_data(state.pob) pl.pause(opt.disp_interval) pl.draw() # 2. save to disk print('saving data ...') np.savetxt(opt.states_fil, states, delimiter=',') np.savetxt(opt.labels_fil, labels, delimiter=',') print("states saved to " + opt.states_fil) print("labels saved to " + opt.labels_fil)
def view_patches(Yr, A, C, b, f, d1, d2, YrA=None, secs=1): """view spatial and temporal components (secs=0 interactive) Parameters: ----------- Yr: np.ndarray movie in format pixels (d) x frames (T) A: sparse matrix matrix of spatial components (d x K) C: np.ndarray matrix of temporal components (K x T) b: np.ndarray spatial background (vector of length d) f: np.ndarray temporal background (vector of length T) d1,d2: np.ndarray frame dimensions YrA: np.ndarray ROI filtered residual as it is given from update_temporal_components If not given, then it is computed (K x T) secs: float number of seconds in between component scrolling. secs=0 means interactive (click to scroll) imgs: np.ndarray background image for contour plotting. Default is the image of all spatial components (d1 x d2) See Also: ------------ ..image:: doc/img/ """ pl.ion() nr, T = C.shape nb = f.shape[0] A2 = A.copy() A2.data **= 2 nA2 = np.sqrt(np.array(A2.sum(axis=0))).squeeze() if YrA is None: Y_r = np.array(A.T * np.matrix(Yr) - (A.T * np.matrix(b[:, np.newaxis])) * np.matrix( f[np.newaxis]) - (A.T.dot(A)) * np.matrix(C) + C) else: Y_r = YrA + C A = A.todense() bkgrnd = np.reshape(b, (d1, d2) + (nb,), order='F') fig = pl.figure() thismanager = pl.get_current_fig_manager() thismanager.toolbar.pan() print('In order to scroll components you need to click on the plot') sys.stdout.flush() for i in range(nr + 1): if i < nr: ax1 = fig.add_subplot(2, 1, 1) pl.imshow(np.reshape(old_div(np.array(A[:, i]), nA2[i]), (d1, d2), order='F'), interpolation='None') ax1.set_title('Spatial component ' + str(i + 1)) ax2 = fig.add_subplot(2, 1, 2) pl.plot(np.arange(T), np.squeeze( np.array(Y_r[i, :])), 'c', linewidth=3) pl.plot(np.arange(T), np.squeeze( np.array(C[i, :])), 'r', linewidth=2) ax2.set_title('Temporal component ' + str(i + 1)) ax2.legend(labels=['Filtered raw data', 'Inferred trace']) if secs > 0: pl.pause(secs) else: pl.waitforbuttonpress() fig.delaxes(ax2) else: ax1 = fig.add_subplot(2, 1, 1) pl.imshow(bkgrnd[:, :, i - nr], interpolation='None') ax1.set_title('Spatial background ' + str(i - nr + 1)) ax2 = fig.add_subplot(2, 1, 2) pl.plot(np.arange(T), np.squeeze(np.array(f[i - nr, :]))) ax2.set_title('Temporal background ' + str(i - nr + 1))
frame = 0 #plt.clf() plt.figure() plt.plot(x, phi) plt.xlim([0, 1]) plt.ylim([-0.0005, 0.0005]) plt.xlabel("Position, $x$") plt.ylabel("Displacement, $\phi(x)$") plt.title("Piano string displacement at t=%.5f" % t) plt.grid() #save the plot for certain times if t > 0.1 and save == 4: plt.savefig("q2_t=100ms.png", dpi=600) save += 1 elif t > 0.012 and save == 3: plt.savefig("q2_t=12ms.png", dpi=600) save += 1 elif t > 0.006 and save == 2: plt.savefig("q2_t=6ms.png", dpi=600) save += 1 elif t > 0.004 and save == 1: plt.savefig("q2_t=4ms.png", dpi=600) save += 1 elif t > 0.002 and save == 0: plt.savefig("q2_t=2ms.png", dpi=600) save += 1 plt.draw() plt.pause(0.01)
def key_press_callback(self, event): 'whenever a key is pressed' if not event.inaxes: return if event.key == "d": 'Delete point under mouse' self._ind = self.get_ind_under_point(event) if self._ind == None: return del self.pointx[self._ind] del self.pointy[self._ind] del self.pointyerr[self._ind] self.point.remove() self.pointerror[0].remove() self.canvas.draw() self.point, _, self.pointerror = self.ax.errorbar(self.pointx, self.pointy, yerr = self.pointyerr, fmt=".k", capsize=0, elinewidth=0.5, color = cmap[2], ms=self.epsilon, picker=self.epsilon, label='cont_pnt') elif event.key == 'y': "Insert evenly spaced points - every 100'th pixel" self.pointx, self.pointy, self.pointyerr, self.point, self.pointerror = methods.insert_points(self.pointx, self.pointy, self.pointyerr, self.wave, self.wave_temp, self.flux, self.flux_temp, self.fluxerror, self.ax, self.point, self.pointerror, spacing = self.spacing / 2.0, pick_epsilon = self.epsilon) self.canvas.draw() if event.key == 'u': "Insert evenly spaced points - every 50'th pixel" self.pointx, self.pointy, self.pointyerr, self.point, self.pointerror = methods.insert_points(self.pointx, self.pointy, self.pointyerr, self.wave, self.wave_temp, self.flux, self.flux_temp, self.fluxerror, self.ax, self.point, self.pointerror, spacing = self.spacing / 4.0) self.canvas.draw() elif event.key == 't': 'Filter points by low-order legendre fitting and clipping values of highest sigma iteratively until continuum is found' self.pointx, self.pointy, self.pointyerr, self.point, self.pointerror, self.chebfitval, self.leg = methods.filtering(self.pointx, self.pointy, self.pointyerr, self.wave, self.wave_temp, self.flux, self.flux_temp, self.ax, self.point, self.pointerror, self.leg, tolerance=self.tolerance, leg_order=self.leg_order, division=self.division) self.canvas.draw() elif event.key == 'enter': 'Sort spline points and interpolate between marked continuum points' self.continuum, self.leg, self.con = methods.spline_interpolation(self.pointx, self.pointy, self.wave, self.wave_temp, self.flux, self.flux_temp, self.ax, self.leg, self.con, self.chebfitval, endpoints = self.endpoint, endpoint_order = self.endpoint_order) self.canvas.draw() elif event.key=='m': 'Mask areas where signal is present' self.wave_temp, self.flux_temp, self.diff, self.error, self.over = \ methods.mask(self.pointx, self.pointy, self.wave, self.wave_temp, self.flux, self.fluxerror, self.flux_temp, self.continuum, self.ax, self.diff, self.error, self.over, self.chebfitval, exclude_width=self.exclude_width, sigma_mask=self.sigma_mask, lower_mask_bound = self.lover_mask ) self.canvas.draw() elif event.key == 'a': 'Local linear regression' self.continuum, self.llr = methods.llr(self.wave, self.wave_temp, self.flux, self.flux_temp, self.ax, self.llr) self.canvas.draw() elif event.key == 'i': 'Iterate over points, filter, spline, mask' self.con_err = [] sigma, val, i = np.std(self.flux), np.median(self.flux), 0 # while sigma > val / 1e3 and i < 150: while i < 30: i += 1 if i <= 50: pause(0.001) self.pointx, self.pointy, self.pointyerr, self.point, self.pointerror = methods.insert_points(self.pointx, self.pointy, self.pointyerr, self.wave, self.wave_temp, self.flux, self.flux_temp, self.fluxerror, self.ax, self.point, self.pointerror, spacing = self.spacing, pick_epsilon = self.epsilon) self.canvas.draw() pause(0.001) self.pointx, self.pointy, self.pointyerr, self.point, self.pointerror, self.chebfitval, self.leg = methods.filtering(self.pointx, self.pointy, self.pointyerr, self.wave, self.wave_temp, self.flux, self.flux_temp, self.ax, self.point, self.pointerror, self.leg, tolerance=self.tolerance, leg_order=self.leg_order, division=self.division, pick_epsilon = self.epsilon) self.canvas.draw() pause(0.001) self.continuum, self.leg, self.con = methods.spline_interpolation(self.pointx, self.pointy, self.wave, self.wave_temp, self.flux, self.flux_temp, self.ax, self.leg, self.con, self.chebfitval, endpoints = self.endpoint, endpoint_order = self.endpoint_order) self.canvas.draw() self.con_err.append(self.continuum) pause(0.001) self.wave_temp, self.flux_temp, self.diff, self.error, self.over = \ methods.mask(self.pointx, self.pointy, self.wave, self.wave_temp, self.flux, self.fluxerror, self.flux_temp, self.continuum, self.ax, self.diff, self.error, self.over, self.chebfitval, exclude_width=self.exclude_width, sigma_mask=self.sigma_mask, lower_mask_bound = self.lover_mask ) else: self.pointx, self.pointy, self.pointyerr, self.point, self.pointerror = methods.insert_points(self.pointx, self.pointy, self.pointyerr, self.wave, self.wave_temp, self.flux, self.flux_temp, self.fluxerror, self.ax, self.point, self.pointerror, spacing = self.spacing, pick_epsilon = self.epsilon) self.pointx, self.pointy, self.pointyerr, self.point, self.pointerror, self.chebfitval, self.leg = methods.filtering(self.pointx, self.pointy, self.pointyerr, self.wave, self.wave_temp, self.flux, self.flux_temp, self.ax, self.point, self.pointerror, self.leg, tolerance=self.tolerance, leg_order=self.leg_order, division=self.division, pick_epsilon = self.epsilon) self.continuum, self.leg, self.con = methods.spline_interpolation(self.pointx, self.pointy, self.wave, self.wave_temp, self.flux, self.flux_temp, self.ax, self.leg, self.con, self.chebfitval, endpoints = self.endpoint, endpoint_order = self.endpoint_order) self.con_err.append(self.continuum) self.wave_temp, self.flux_temp, self.diff, self.error, self.over = \ methods.mask(self.pointx, self.pointy, self.wave, self.wave_temp, self.flux, self.fluxerror, self.flux_temp, self.continuum, self.ax, self.diff, self.error, self.over, self.chebfitval, exclude_width=self.exclude_width, sigma_mask=self.sigma_mask, lower_mask_bound = self.lover_mask ) if i > 1: sigma = abs(np.std(np.median(self.con_err, axis= 0) - np.median(self.con_err[:-1], axis= 0))) print(i) # print i, abs(np.std(np.median(self.con_err, axis= 0) - np.median(self.con_err[:-1], axis= 0))), val/ 1e3 self.i = i # from gen_methods import mytotal from astropy.stats import sigma_clip # sigma_clip(self.con_err, sig = 3, axis=2, iters=None, copy = True, cenfunc=np.ma.median, stdfunc=np.ma.std) self.con_err = np.array(self.con_err) print np.shape(self.con_err) # from gen_methods import smooth # from scipy.signal import savgol_filter # clipped_value = sigma_clip(self.con_err, sigma = 3, axis=0, iters=3, copy = True, cenfunc=np.ma.median, stdfunc=np.ma.std) # self.continuum = savgol_filter(clipped_value.mean(axis=0), 101, 2) # print np.shape(self.continuum) # self.stderror = savgol_filter(clipped_value.std(axis=0), 101, 2)/np.sqrt(i) self.continuum = np.mean(self.con_err, axis= 0) self.stderror = np.std(self.con_err,axis=0)#/np.sqrt(i) self.con.remove() self.con = None xsh_norm.clear(self) self.canvas.draw() self.con, = self.ax.plot(self.wave, self.continuum, lw=self.linewidth_over, label='continuum', zorder = 10, color = cmap[2], alpha = 0.8) for n in [1, 2, 3]: self.ax.plot(self.wave, self.continuum+n*self.stderror, lw=self.linewidth_over/2., label='continuum', zorder = 10, color = cmap[2], alpha = 0.8) self.ax.plot(self.wave, self.continuum-n*self.stderror, lw=self.linewidth_over/2., label='continuum', zorder = 10, color = cmap[2], alpha = 0.8) elif event.key == 'n': 'Apply xsh_norm' from scipy.interpolate import interp1d self.spline = interp1d(self.wave, self.continuum, bounds_error=False) xsh_norm.clear(self) self.canvas.draw() # self.fig.set_size_inches(14,10) plt.savefig(self.filename + "_norm.pdf") self.flux /= self.continuum self.flux_ori /= self.spline(self.wave_ori) self.fluxerror /= self.continuum self.fluxerror_ori /= self.spline(self.wave_ori) if hasattr(self, 'stderror'): self.stderror /= self.continuum if not hasattr(self, 'stderror'): self.stderror = 0.1*np.ones_like(self.continuum) stderror = interp1d(self.wave, self.stderror, bounds_error=False) self.stderror = stderror(self.wave_ori) self.fig.clf() self.ax = self.fig.add_subplot(111) self.ax.set_ylim((-0.5,1.5)) y1 = np.ones(np.shape(self.wave)) self.line, = self.ax.plot(self.wave_ori, self.flux_ori, color= cmap[0], drawstyle='steps-mid', lw=self.linewidth, label='normalised spectrum', zorder = 1, rasterized=True) self.line1, = self.ax.plot(self.wave, y1, color=cmap[2], drawstyle='steps-mid', lw=self.linewidth_over,label='1', zorder = 10, alpha=1.0, rasterized=True) elif event.key == 'w': 'Write to file' print 'Writing to file '+self.filename+'_norm.npy' data_array = np.array([self.wave_ori, self.flux_ori, self.fluxerror_ori, self.bpmap, self.stderror, self.spline(self.wave_ori)]) np.save(self.filename+"_norm", data_array) # self.fitsfile[0].data = self.flux # self.fitsfile[1].data = self.fluxerror # self.fitsfile.writeto(self.filename+'_norm.fits', clobber = True) # if hasattr(self, 'stderror'): # from astropy.io import fits # fits.append(self.filename+'_norm.fits', self.stderror, self.fitsfile[1].header) self.ax.relim() self.ax.autoscale_view(True,True,True) self.canvas.draw()
def plot_process(): while True: global plot_queue data,samp_rate,fft_step,f0,clear,show,png,npy,title,xlabel,ylabel,color = plot_queue.get() if clear: plt.clf() if data is None: return matplotlib.rcParams.update({'font.size': 18}) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) #1D Graphs if len(data.shape) == 1: if samp_rate > 1: if f0 > 0: x = np.arange((f0 - samp_rate/2)/1e6,(f0 + samp_rate/2)/1e6, samp_rate/len(data)/1e6) elif samp_rate > 1: x = np.arange(0,len(data)) * 1e3 / samp_rate else: x = np.arange(0,len(data)) x = x[:len(data)] plt.plot(x, data, color=color) plt.xlabel(xlabel) plt.ylabel(ylabel) else: plt.plot(data) # 2D Plots (stft) elif len(data.shape) == 2: plt.xlabel(xlabel) plt.ylabel(ylabel) plt.set_cmap("jet") if f0 > 0: extent = [ (f0 - samp_rate/2)/1e6, (f0 + samp_rate/2)/1e6, 1e3 * len(data) * float(fft_step) / samp_rate, 0] im = plt.imshow(data,interpolation='bilinear', extent=extent, aspect='auto') else: im = plt.imshow(data,interpolation='bilinear', aspect='auto') plt.colorbar(im) # dump if png != "": plt.savefig(png,dpi=100) if npy != "": np.save(npy, data) if show: #plt.show() #raw_input("press return to continue") #plt.ion() plt.draw() plt.pause(.1)