def close(self): self.finished = True disconnect(self.connection) for l in self.lines: l.remove() draw()
def get_initparams_from_mouse( halfwidth=5.0 ): """ Assuming you've already plotted the data you want to fit, this function makes a list of initparams from your mouse clicks on the peaks you want to fit. """ print 'Picking peaks only (not peaks and widths; see code)' peaks_or_peakswidths='p' #peaks_or_peakswidths = raw_input('Pick only peaks (p) or peaks and widths (pw)') if peaks_or_peakswidths=='p': if True: # explitly use "connect" to get points peaks = [] # this will be a list of dictionaries of xloc and height of each peak def click(event): print 'you clicked', event.xdata peaks.append({'xloc':event.xdata, 'ymax':event.ydata}) cid = plt.connect('button_press_event', click) raw_input('Click on the peaks you want to fit, then press Enter to continue.\n') plt.disconnect(cid) else: # use ginput print ('Click on the peaks you want to fit, then press Enter to continue.\n') points = plt.ginput(-1) peaks = [{'xloc':p[0], 'ymax':p[1]} for p in points] elif peaks_or_peakswidths=='pw': print 'This function is not yet implemented' peaks = [] else: print 'Incorrect input.' peaks = [] initparams=[0.0] # this is the initial guess at yoffset for peak in peaks: initparams.append(peak['ymax']) initparams.append( halfwidth ) initparams.append(peak['xloc']) return initparams
def onKey(event): global init_done if event.key == "q" or event.key == "escape": print "exiting now" sys.exit(0) if event.key == " ": if init_done: plt.disconnect('key_release_event') track()
def onclick(event): global cid2 # event from matplotlib x = event.xdata; y = event.ydata xndx = np.where(mass_vec_edges < x)[0][-1] yndx = np.where(age_vec_edges < y)[0][-1] mass = np.int(mass_vec[xndx]) age = np.int(age_vec[yndx]) mass_str = str(mass).zfill(3) age_str = str(age).zfill(4) name_str = path + "spec_" + ATM_TYPE + "_mass_" + mass_str + "_age_" + age_str + ".txt" print name_str data = np.loadtxt(name_str) this_Si_vec = data[1:,0] this_Si_vec_edges = get_cell_edges(this_Si_vec) yval_edges = np.array([-1.,1.]) xval_edges = this_Si_vec_edges xvalA,yvalA = np.meshgrid(xval_edges,yval_edges) zvalA = np.zeros_like(xvalA) for ii in range(len(this_Si_vec)): zvalA[0,ii] = this_Si_vec[ii] plt.figure(2,figsize=(8,3)) plt.pcolor(xvalA,yvalA,zvalA,edgecolors='k') hh = plt.gci() ax2 = plt.gca() loc = plticker.MultipleLocator(base=0.5) ax.xaxis.set_major_locator(loc) ax2.set_xlim([min(xval_edges),max(xval_edges)]) plt.gca().yaxis.set_major_locator(plt.NullLocator()) title_str = 'Mass: ' + str(mass) + ' Mjup; Age: ' + str(age) + ' Myr; ' + \ ' Click to select the initial entropy.' plt.title(title_str) plt.xlabel('Initial Entropy (kB/baryon)') def onclick2(event2): x2 = event2.xdata; y2 = event2.ydata print x2, this_Si_vec_edges rgb = hh.cmap(hh.norm(x2))[:-1] # last element is alpha (transparency) xndx2 = np.where(this_Si_vec_edges < x2)[0][-1] print len(this_Si_vec_edges),'****',name_str this_spec_row_ndx = 1+xndx2 print this_spec_row_ndx this_spec = data[this_spec_row_ndx,1:] plt.figure(3,figsize=(6,6)) plt.plot(lambdas,this_spec,color=rgb) plt.xlabel('Wavelength (microns)') plt.ylabel('Flux (mJy)') print "***********", x2, rgb, this_spec_row_ndx, this_spec[:5] plt.show() plt.ion() if not cid2 is None: plt.disconnect(cid2) cid2 = plt.connect('button_press_event',onclick2) plt.show()
def on_click(event): if event.button is MouseButton.LEFT: print('disconnecting callback') plt.disconnect(binding_id)
tuple_vmax=(np.nan, np.nan), tuple_title=('monitor.min() / monitor', 'Data after normalization'), tuple_scale=('linear', 'log'), xlabel=('Frame number', 'Frame number'), ylabel=('Counts (a.u.)', 'Rocking dimension'), is_orthogonal=not use_rawdata, reciprocal_space=True) fig.savefig(savedir + 'monitor_S' + str(scans[scan_nb]) + '_' + str(nz) + '_' + str(ny) + '_' + str(nx) + binning_comment + '.png') if flag_interact: cid = plt.connect('close_event', close_event) fig.waitforbuttonpress() plt.disconnect(cid) plt.close(fig) plt.ioff() comment = comment + '_norm' ######################## # crop/pad/center data # ######################## nz, ny, nx = np.shape(data) if center_fft != 'skip': print('\nData shape before cropping / padding:', nz, ny, nx) data, mask, pad_width, q_vector, frames_logical = \ pru.center_fft(data=data, mask=mask, frames_logical=frames_logical, centering=centering, detector=detector, fft_option=center_fft, pad_size=pad_size, fix_bragg=fix_bragg, fix_size=fix_size, q_values=q_values)
def on_click(event): if event.button is MouseButton.LEFT: print("Disconnecting Call Back") plt.disconnect(binding_id)
def clicker4(event): global mask, aid, bid, cid, did, eid, fid if event.inaxes: if event.button == 1: if (event.x > 1042 and event.x < 1342 and event.y > 12 and event.y < 68): nt = 0 txt = '' for i in range(int(len(mask) / 2)): t1 = float(mask[nt]) + barytime0 t2 = float(mask[nt + 1]) + barytime0 if t1 < 2.4e6: t1 += 2.4e6 if t2 < 2.4e6: t2 += 2.4e6 txt += str(t1) + ',' + str(t2) + '\n' nt += 2 txt = txt.strip() print('\n' + txt) plt.disconnect(aid) plt.disconnect(bid) plt.disconnect(cid) plt.disconnect(did) plt.disconnect(eid) plt.disconnect(fid) plotlc()
def clicker3(event): global mask, aid, bid, cid, did, eid, fid if event.inaxes: if event.button == 1: if (event.x > 723 and event.x < 1022 and event.y > 12 and event.y < 68): mask = [] plt.disconnect(aid) plt.disconnect(bid) plt.disconnect(cid) plt.disconnect(did) plt.disconnect(eid) plt.disconnect(fid) plotlc()
s = np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) def on_move(event): # get the x and y pixel coords x, y = event.x, event.y if event.inaxes: ax = event.inaxes # the axes instance print('data coords %f %f' % (event.xdata, event.ydata)) def on_click(event): # get the x and y coords, flip y from top to bottom x, y = event.x, event.y if event.button == 1: if event.inaxes is not None: print('data coords %f %f' % (event.xdata, event.ydata)) binding_id = plt.connect('motion_notify_event', on_move) plt.connect('button_press_event', on_click) if "test_disconnect" in sys.argv: print("disconnecting console coordinate printout...") plt.disconnect(binding_id) plt.show()
print("Mean Outgoing: " + str(statistics.mean(src_subnet_traffic.values()))) print("Median Outgoing: " + str(statistics.median(src_subnet_traffic.values()))) print("Variance Outgoing: " + str(statistics.variance(src_subnet_traffic.values()))) print("Mean Incoming: " + str(statistics.mean(dst_subnet_traffic.values()))) print("Median Incoming: " + str(statistics.median(dst_subnet_traffic.values()))) print("Variance Incoming: " + str(statistics.variance(dst_subnet_traffic.values()))) # Prepare plot fig, ax = plt.subplots(1, 1) n, bins, patches = ax.hist(packets, bins=range(-200, 1600, 50), normed=False, facecolor="green", alpha=0.5) plt.xlabel("Packet Size") plt.ylabel("Count") plt.title("Packet Size") plt.disconnect(10) ax.set_xticks(range(-200, 1600, 200)) ax.set_yticks(range(0, 12000, 500)) ax.grid(True) if len(sys.argv) > 2: plt.savefig(sys.argv[2]) bin_counts = {} counter = 0 for pckt in packets: start = 1 counter += 1 # print(str(counter) + ": " + str(pckt)) while pckt > (start * 50): start += 1
def key_events(self, event): """ Key Event loop - hit 'q' to quit the loop """ global ncuarf, nxcuar,uu self.event = event rd = self.radius if event.key == 'u': # Get a reference point while True: try: xm = event.xdata #print 'UUU:',xm,min(nxcuar),max(nxcuar),len(nxcuar) ix = np.searchsorted(nxcuar,xm) y = ncuarf[ix-rd:ix+rd] x = np.arange(ix-rd,ix+rd) try: peakidx = np.argmax(y) except: print 'key needs to be "m" in this subplot.' break center = x[peakidx] width = abs(x[-1]-x[1])/2. height = y[peakidx] #print 'WW',width,len(nxcuar),xm,ix,len(ncuarf) cen = spu.recenter([center],nxcuar,width=5) #print 'xcc:',xm,peakidx,cen,height,nxcuar[cen[0]] # find the reference value from the reference list uu = self.aid_match (nxcuar[cen[0]], self.match) print 'Coord:',xm,', "Line list entry":',uu if not uu: print '\a \n*** ERROR: Reference line not found. Try again.' break ax = self.subu ax.hold(True) h1 = height+20 h2 = h1 + height/10 pl.vlines(uu,ymin=h1,ymax=h2,color='r') #ax.vlines(uu,ymin=h1,ymax=h2,color='r') pl.show() break except IndexError: print 'Indx' break except TypeError: print 'TYerr' break else: break if event.key == 'm': while True: try: xm = event.xdata nx = self.nsum y = self.lpix[xm-20:xm+20] x = np.arange(xm-20,xm+20) try: peakidx = np.argmax(y) except: print 'Error:: key needs to be "u" in this subplot.' break #print 'peakidx',peakidx center = x[peakidx] height = y[peakidx] width = abs(x[-1]-x[1])/2. cen = spu.recenter([center],self.lpix,width=width) if uu<0: print 'Error: Need to mark a ref line first in the reference subplot.' break print 'Center pix::',cen,' Reference:',uu ax = self.subm ax.hold(True) h1 = height+20 h2 = h1 + height/10 ax.vlines(cen,ymin=h1 ,ymax=h2 ,color='r') #pl.vlines(cen,ymin=height+20,ymax=height+20+height/10,color='r') self.pixs.append(cen[0]) self.users.append(uu) #print self.users uu = -99 pl.show() break except IndexError: print 'Indx' break except TypeError: print 'TYerr' break else: break if event.key == 'r': # Residual plot pixs = self.pixs diff = self.z(pixs)-self.users fig2 = pl.figure() ax_single = fig2.add_subplot(111) line2 = ax_single.plot(pixs,diff,'+') fig2.show() #pl.plot(pixs,diff) # Delete pair in (self.pixs,self.users) if event.key == 'd': # Delete point in fig2 (Residual plot) # Note not working at the moment. Need to get events from # figure 2.... don;t know yet how to. x = event.xdata indx = np.searchsorted(self.pixs,x) print indx,self.pixs[indx] if event.key == 'f': z= self.fit_peaks(self.pixs,self.users) if z == None: return for k,(p,w) in enumerate(zip(self.pixs,self.users)): print k,p,z(p),w,'%.2f'%(z(p)-w) # Fit the peaks find matches with cuar, refit xpeaks = self.xpeaks fit = z(xpeaks) # Find users pixs,users = self.fit2user(xpeaks,fit, self.match) # Fit again. Use a Chebyshev polynomial since we should have # many (>5) lines. z= self.fit_peaks(pixs,users,fitname='chebyshev',order=4) print '\n ....New fit.....' for k,(p,w) in enumerate(zip(pixs,users)): print k,p,z(p),w,'%.2f'%(z(p)-w) pixs,users,z = self.clipData(pixs,users,z,clip=4) #indx = np.searchsorted(xpeaks,pixs) print ' >>>>>>NUMBER OF points after clipping:',len(pixs) #hh = self.xfluxs[indx] ipix = np.asarray(np.around(pixs),dtype=int) hh = self.lpix[ipix+1] ax = self.subm ax.hold(True) ax.vlines(pixs,ymin=hh+20,ymax=hh+20+hh/7.,color='r') self.pixs = list(pixs) self.users = list(users) self.z = z pl.draw() if event.key == 'h': print '\n Winter. Keystrokes available:' print ' u: Mark a line in the upper subplot.' print ' m: Mark the "u" associated line in the pixel (lower) subplot.' print ' l: List tuples (pix, wavelength) of lines already marked.' print ' r: Plot residuals in a new figure.' print ' f: Fit the (pix,wavelength) tuples.' print ' q: Quit' if event.key == 'a': """ Not working yet """ # Add reference line list self.fitdata = self.z(range(self.lpix.size)) #pixs,users = wcal.add_linelist(self.ll) pixs = list(self.pixs) user = list(self.users) pix.extend(pixs) user.extend(users) order = np.argsort(pix) pix = list(np.asarray(pix)[order]) user = list(np.asarray(user)[order]) fit = list(self.z(pix)) #pix,fit,user = wc.weedoutDups(pix,fit,user) self.pixs = pix self.users = user fit = np.asarray(fit) user = np.asarray(user) # The new scale is. szf = len(ncuarf) cd = (10423.-3053.)/szf yy = self.lpix for p,u in zip(pix,user): ix = (u-3053)/cd if ix >= szf: continue height = ncuarf[ix] print p,u self.subu.vlines(u,ymin=height,ymax=height+2600,color='r') self.subm.vlines(p,ymin=yy[p],ymax=yy[p]+4000,color='r') #pl.draw() if event.key == 'q': pl.disconnect(self.cid) pl.close('all') if event.key == 'l': # List the current pairs k = 1 for p,w in zip(self.pixs,self.users): print k,p,w k +=1
if ratio > 0.5: arc = Arc((x, y), r * 2, r * 2, 0, np.rad2deg(theta2), np.rad2deg(theta1)) else: arc = Arc((x, y), r * 2, r * 2, 0, np.rad2deg(theta1), np.rad2deg(theta2)) else: if ratio < 0.5: arc = Arc((x, y), r * 2, r * 2, 0, np.rad2deg(theta2), np.rad2deg(theta1)) else: arc = Arc((x, y), r * 2, r * 2, 0, np.rad2deg(theta1), np.rad2deg(theta2)) ax.add_patch(arc) canvas.draw() # connecting the plot to the above function onmove = plt.connect('motion_notify_event', on_move) plt.disconnect(onmove) # finds the circles defining center and radius given two points def find_circle(x1, y1, x2, y2): x3, y3 = find_circular_inverse(x2, y2) m12 = np.reciprocal((y2 - y1) / (x2 - x1)) * -1 m23 = np.reciprocal((y3 - y2) / (x3 - x2)) * -1 mid12x = (x2 + x1) / 2 mid12y = (y2 + y1) / 2 mid23x = (x3 + x2) / 2 mid23y = (y3 + y2) / 2 b12 = mid12y - (m12 * mid12x) b23 = mid23y - (m23 * mid23x) x = (b23 - b12) / (m12 - m23) # m12 * x + b12 = m23 * x + b23 y = (m12 * x) + b12
def clicker1(event): global mask, aid, bid, cid, did, eid, fid if event.inaxes: if event.button == 1: if (event.x > 601 and event.x < 801 and event.y > 492 and event.y < 522): print("Masked pixels cleared!") plt.disconnect(aid) plt.disconnect(bid) plt.disconnect(cid) plt.disconnect(did) plt.disconnect(eid) plt.disconnect(fid) mask = [] plt.clf() plotimage() return
def clicker1(event): global mask, aid, bid, cid, did, eid, fid if event.inaxes: if event.button == 1: if (event.x > 83 and event.x < 383 and event.y > 12 and event.y < 68): if kepio.fileexists(rinf): mask = [] lines = kepio.openascii(rinf, 'r', logf, verb) for line in lines: line = line.strip().split(',') try: float(line[0]) float(line[1]) if barytime0 > 2.4e6: mask.append(float(line[0]) - barytime0) mask.append(float(line[1]) - barytime0) else: mask.append(float(line[0]) - barytime0 - 2.4e6) mask.append(float(line[1]) - barytime0 - 2.4e6) except: message = 'ERROR -- KEPRANGE: ascii format of ranges ' message += 'file not recognized.' kepmsg.err(logf, message, False) plt.disconnect(aid) plt.disconnect(bid) plt.disconnect(cid) plt.disconnect(did) plt.disconnect(eid) plt.disconnect(fid) plotlc() else: print('WARNING -- KEPRANGE: input ranges file does not' ' exist or was not provided') return
t = np.arange(0.0, 1.0, 0.01) s = np.sin(2*np.pi*t) fig, ax = plt.subplots() ax.plot(t, s) def on_move(event): # get the x and y pixel coords x, y = event.x, event.y if event.inaxes: ax = event.inaxes # the axes instance print('data coords %f %f' % (event.xdata, event.ydata)) def on_click(event): # get the x and y coords, flip y from top to bottom x, y = event.x, event.y if event.button == 1: if event.inaxes is not None: print('data coords %f %f' % (event.xdata, event.ydata)) binding_id = plt.connect('motion_notify_event', on_move) plt.connect('button_press_event', on_click) if "test_disconnect" in sys.argv: print("disconnecting console coordinate printout...") plt.disconnect(binding_id) plt.show()
def clicker2(event): global mask, aid, bid, cid, did, eid, fid, done if event.inaxes: if event.button == 1: if (event.x > 601 and event.x < 801 and event.y > 422 and event.y < 482): print("Mask definition loaded successfully!") plt.disconnect(aid) plt.disconnect(bid) plt.disconnect(cid) plt.disconnect(did) plt.disconnect(eid) plt.disconnect(fid) try: lines = kepio.openascii(mfile, 'r', None, False) for line in lines: mask = [] work = line.strip().split('|') y0 = int(work[3]) x0 = int(work[4]) work = work[5].split(';') for i in range(len(work)): y = int(work[i].split(',')[0]) + y0 x = int(work[i].split(',')[1]) + x0 mask.append(str(x) + ',' + str(y)) plt.clf() plotimage() except: errmsg = ('ERROR -- KEPMASK: Cannot open or read mask ' 'file ' + mfile) kepmsg.err('kepmask.log', errmsg, True) return