def update(self): #print "UPDATE" if not fignum_exists(self.figure.number): return try: self.window.after_cancel(self.update_after) except: pass self.update_after = self.figure.canvas.manager.window.after(1000, self.update) if len(self.objects) == 0: self.axis.clear() self.text = self.axis.text(0.5,0.5,"No objects tracked") self.text.set_horizontalalignment("center") self.text.set_verticalalignment("center") self.figure.canvas.draw() return if toolkit.db.UT and toolkit.db.UTt: t = time.time() - toolkit.db.UTt + toolkit.db.UT elif toolkit.db.UT: t = toolkit.db.UT else: t= time.time() #figure(self.figure.number) self.axis.clear() planet = Circle((0,0),600000,color="blue") self.axis.add_artist(planet) for celestial in self.objects: if celestial.ref != self.ref or celestial.orbit == None: continue xpos = [] ypos = [] for ta in self.linspace: rv = celestial.orbit.plot2D(ta) xpos.append(rv[0]) ypos.append(rv[1]) plotOrbit = self.axis.plot(xpos,ypos,color="red") rv,vv = celestial.orbit.eph2D(t) #print rv,vv self.scat = (rv,vv) plotPos = self.axis.scatter(rv[0],rv[1],color="green") #print "Pos",rv self.axis.relim() self.axis.autoscale_view(True,True,True) #xlim = self.axis.get_xlim() #ylim = self.axis.get_ylim() #minlim = min((xlim[0],ylim[0])) #maxlim = max((xlim[1],ylim[1])) #self.axis.set_ylim((minlim,maxlim)) #self.axis.set_xlim((minlim,maxlim)) #if xlim[0] > ylim[0]: # self.axis.set_ylim(xlim) #else: # self.axis.set_xlim(ylim) self.figure.canvas.draw()
def kp(event): key = event.key.lower() codes = list( '1234567890QWERTYUIOP'.lower() ) if key in codes: target = int( codes.index( key ) ) + 1 elif key == '[': target = event.canvas.figure.number - 1 elif key == ']': target = event.canvas.figure.number + 1 else: target = None if target != None and pylab.fignum_exists( target ): look( target )
def kp(event): key = event.key.lower() codes = list('1234567890QWERTYUIOP'.lower()) if key in codes: target = int(codes.index(key)) + 1 elif key == '[': target = event.canvas.figure.number - 1 elif key == ']': target = event.canvas.figure.number + 1 else: target = None if target != None and pylab.fignum_exists(target): look(target)
def kp(event): if not isinstance( event.key, str ): return key = event.key.lower() if key.startswith( 'alt+' ): key = key[ 4: ] codes = list( '1234567890QWERTYUIOP'.lower() ) if key in codes: target = int( codes.index( key ) ) + 1 elif key == '[': target = event.canvas.figure.number - 1 elif key == ']': target = event.canvas.figure.number + 1 else: target = None if target != None and pylab.fignum_exists( target ): look( target )
def search_handles( handles, reclevel=0 ): out = [] if reclevel >= 10: zark # allows `debug` of apparent indefinite recursion try: handles = list( handles ) except: handles = [ handles ] for h in handles: if isinstance( h, ( int, float ) ): if h == 0: h = pylab.get_fignums() elif pylab.fignum_exists( h ): h = pylab.figure( h ) while hasattr( h, 'axes' ) and h.axes is not h: h = h.axes # this was intended to grab the children of a figure, but it can also grab the parent of an AxesImage.... try: h = list( h ) except: out.append( h ) else: out.extend( search_handles( h, reclevel=reclevel+1 ) ) return out
def update(self): #print "UPDATE" if not fignum_exists(self.figure.number): return self.update_after = self.figure.canvas.manager.window.after(1000, self.update) if len(self.objects) == 0: self.axis.clear() self.text = self.axis.text(0.5,0.5,"No objects tracked") self.text.set_horizontalalignment("center") self.text.set_verticalalignment("center") self.figure.canvas.draw() return if toolkit.db.UT and toolkit.db.UTt: t = time.time() - toolkit.db.UTt + toolkit.db.UT elif toolkit.db.UT: t = toolkit.db.UT else: t= time.time() #figure(self.figure.number) self.axis.clear() #planet = Circle((0,0),self.ref.radius,color=self.ref.c,edgecolor="black",linewidth=1.0) #self.axis.add_artist(planet) # Add a scatter for improved visibility if the artist is too tiny. plotPos = self.axis.scatter(0,0,s=40,color=self.ref.c,edgecolor="black") for celestial in self.objects: if celestial.ref != self.ref or celestial.orbit == None: continue xpos = [] ypos = [] for ta in self.linspace: rv = celestial.orbit.plot(ta) xpos.append(rv[0]) ypos.append(rv[1]) plotOrbit = self.axis.plot(xpos,ypos,color=celestial.c) rv,vv = celestial.eph(t) self.scat = (rv,vv) plotPos = self.axis.scatter(rv[0],rv[1],color=celestial.c,edgecolor="black") self.axis.relim() self.axis.autoscale_view(True,True,True) self.figure.canvas.draw()
def plotss(self, xlim=[None,None], ylim=[None,None], fig=1, only='all'): oplot = False if (fignum_exists(fig)): oplot = True symbols = ['d', '+', '*'] index = np.random.randint(0,len(symbols)) symbol = symbols[index] else: symbol = 'o' fig = figure(fig) ax = subplot(111) if (only == 'all'): ax.errorbar(self.mx[:,0],self.d02, yerr=self.d02Err, fmt='r-'+symbol) ax.errorbar(self.mx[:,1],self.d13, yerr=self.d13Err, fmt='b-'+symbol) ax.errorbar(self.mx[:,0],self.d01, yerr=self.d01Err, fmt='g-'+symbol) ax.errorbar(self.mx[0:-1,1],self.d10, yerr=self.d10Err, fmt='k-'+symbol) leg = ax.legend((r'$d_{02}/3$',r'$d_{13}/5$',r'$d_{01}$',r'$d_{10}$'), 'upper right') elif (only == 'd02'): ax.errorbar(self.mx[:,0],self.d02, yerr=self.d02Err, fmt='r-'+symbol) leg = ax.legend('d02 / 3', 'upper right') elif(only == 'd13'): ax.errorbar(self.mx[:,1],self.d13, yerr=self.d13Err, fmt='b-'+symbol) leg = ax.legend('d13 / 5', 'upper right') elif(only == 'd010'): mfc = 'orange' if oplot else None ms = 2 if oplot else None ax.errorbar(self.mx[:,0],self.d01, yerr=self.d01Err, fmt='g'+symbol, mfc=mfc) ax.errorbar(self.mx[0:-1,1],self.d10, yerr=self.d10Err, fmt='k'+symbol, mfc=mfc) leg = ax.legend((r'$d_{01}$',r'$d_{10}$'), 'upper right') ax.grid(False) ax.set_xlabel('Frequency') ax.set_ylabel(r'$d \, (\mu Hz)$') ax.set_title(r'Small Separations') ax.set_ylim(ylim) ax.set_xlim(xlim) plt.show()
def continous_measurement(): #plt.figure() #plt.grid() #plt.ion() start_time = time.time() value = read_daq(sample_rate=40000) fig, ax = plt.subplots(1, 1) line, = ax.plot(time.time() - start_time, value, '.b') ax.set_xlim(0, 10) #times = [time.time()-start_time] times = [0] values = [value] while plt.fignum_exists(fig.number): values.append(read_daq(sample_rate=40000)) times.append(times[-1] + 1) #times.append(time.time()-start_time) line.set_data(times, values) ax.set_ylim(min(np.array(values)), max(np.array((values)))) ax.set_xlim(times[-1] - 10, times[-1]) fig.canvas.draw() fig.canvas.flush_events() plt.pause(0.05)
def log_tracked(image, tracked_roi, cached, template_f, response_f): timeout = 1e-6 tracking_figure_axes = results.tracking_figure_axes tracking_figure = results.tracking_figure tracking_figure_title = results.tracking_figure_title response_figure_axes = results.response_figure_axes tracking_rectangle = results.tracking_rectangle gt_rectangle = results.gt_rectangle template_axes = results.template_axes if not results.initialized: # pylab.ion() # interactive mode on tracking_figure = results.tracking_figure = pylab.figure() gs = pylab.GridSpec(1, 3, width_ratios=[3, 1, 1]) tracking_figure_axes = results.tracking_figure_axes = tracking_figure.add_subplot(gs[0]) tracking_figure_axes.set_title("Tracked object (and ground truth)") template_axes = results.template_axes = tracking_figure.add_subplot(gs[1]) template_axes.set_title("Template") response_figure_axes = results.response_figure_axes = tracking_figure.add_subplot(gs[2]) response_figure_axes.set_title("Response") tracking_rectangle = results.tracking_rectangle = pylab.Rectangle((0, 0), 0, 0) tracking_rectangle.set_color((1, 1, 0, 0.5)) tracking_figure_axes.add_patch(tracking_rectangle) gt_rectangle = results.gt_rectangle = pylab.Rectangle((0, 0), 0, 0) gt_rectangle.set_color((0, 0, 1, 0.5)) tracking_figure_axes.add_patch(gt_rectangle) tracking_figure_title = results.tracking_figure_title = tracking_figure.suptitle("") pylab.show(block=False) elif tracking_figure is None: return # we simply go faster by skipping the drawing elif not pylab.fignum_exists(tracking_figure.number): print("From now on drawing will be omitted, " "so that computation goes faster") results.omitted_at_frame_number = loader.frame_number() results.tracking_figure = None return tracking_figure_axes.imshow(image) tracking_rectangle.set_bounds(tracked_roi[0] - tracked_roi[2] / 2, tracked_roi[1] - tracked_roi[3] / 2, tracked_roi[2], tracked_roi[3]) gt = loader.get_gt_bounding_box() gt_rectangle.set_bounds(gt[0], gt[1], gt[2], gt[3]) if template_f is not None: template_axes.imshow(template_f, cmap=pylab.cm.hot) if response_f is not None: response_figure_axes.imshow(response_f, cmap=pylab.cm.hot) tracking_rectangle.set_color((0 if not cached else 1, 0.5 if not cached else 0, 0, 0.7 if not cached else 0.2)) tracking_figure_title.set_text("Frame {}".format(loader.frame_number())) pylab.draw() if results.initialized: pylab.savefig(loader.get_log_dir() + 'image%05i.jpg' % loader.frame_number(), bbox_inches='tight') pylab.waitforbuttonpress(timeout=timeout) results.initialized = True return
def plot(self, coords='auto', proj='auto', labels=True, extras=True, isExtra=0): x, y, xname, yname = None, None, None, None if coords == 'auto': if self.v.ndim == 2: if not self.x is None and self.x.ndim == 2: x, xname = self.x, 'x' elif not self.d is None and self.d.ndim == 2: x, xname = self.d, 'd' elif not self.tnum is None and self.tnum.ndim == 2: x, xname = self.tnum, 'tnum' elif not self.y is None and self.y.ndim == 2: x, xname = self.y, 'y' if not self.y is None and self.y.ndim == 2: y, yname = self.y, 'y' elif not self.z is None and self.z.ndim == 2: y, yname = self.z, 'z' elif self.v.ndim == 1: if not self.d is None and self.d.ndim == 1: x, xname = self.d, 'd' elif not self.t is None and self.t.ndim == 1: x, xname = self.t, 't' elif not self.x is None and self.x.ndim == 1: x, xname = self.x, 'x' elif not self.y is None and self.y.ndim == 1: x, xname = self.y, 'y' elif not self.z is None and self.z.ndim == 1: x, xname = self.z, 'z' if self.v.ndim==2 and proj=='auto' and xname=='x' and yname=='y' and\ np.all(x>=-360) and np.all(x<=360) and np.all(y>=-90) and np.all(y<=90): proj = True else: proj = False # # about x distance: --> better do this during slice # xUnitsAdd='' # if xname=='d' and (x.max()-x.min())>3e3: # x=x/1.e3 # xUnitsAdd=r'$\mathrm{\times10^3}$ ' if hasattr(self, 'fig') and pl.fignum_exists(self.fig.number): pass else: self.init_figure() # try: self.fig # except: # print 'starting new fig !!' # self.init_figure() ### useProj=0 if proj and not isExtra: if not hasattr( self, 'map') or self.map_info_get() != self.map_info_current: # make a new projection: if not self.config['axes.axis']: self.config['axes.axis'] = x.min(), x.max(), y.min( ), y.max() print 'NEW PRJ !!' self.init_projection() ### useProj=1 if self.v.ndim == 2: if isinstance(self.v, tuple): self.draw_vector_field(x, y, self.v[0], self.v[1]) else: self.draw_scalar_field(x, y, self.v) if not isExtra: self.draw_colorbar() if labels: tit = '%s (%s)' % (self.info['v']['name'], self.info['v']['units']) if not self.t is None: tit += ' $\\bullet$ %s' % self.t.strftime('%Y-%m-%d %H:%M') tit += ' $\\bullet$ %s' % self.info['v']['slice'] self.draw_label('title', tit) if not proj: ###not useProj: #xlab = '%s (%s%s)'%(self.info[xname]['name'],xUnitsAdd,self.info[xname]['units']) xlab = '%s (%s)' % (self.info[xname]['name'], self.info[xname]['units']) ylab = '%s (%s)' % (self.info[yname]['name'], self.info[yname]['units']) self.draw_label('xlabel', xlab) self.draw_label('ylabel', ylab) if proj and not isExtra: print 'WILL DRAW PROJECTION', self.info['v'] self.draw_projection() else: self.draw_1d(x, self.v) if labels: xlab = '%s (%s)' % (self.info[xname]['name'], xUnitsAdd, self.info[xname]['units']) tit = '%s (%s)' % (self.info['v']['name'], self.info['v']['units']) self.draw_label('xlabel', xlab) self.draw_label('title', tit) if self.extra and extras: for e in self.extra: e.fig = self.fig e.ax = self.ax e.handles = self.handles if hasattr(self, 'map'): e.map = self.map e.map_info_copy(self) print 'will plot extras...' e.plot(labels=False, isExtra=1) print e.config['1d.plot']
def plot_tracking(frame, pos, target_sz, should_resize_image, im, ground_truth): global \ tracking_figure, tracking_figure_title, tracking_figure_axes, \ tracking_rectangle, gt_point, \ z_figure_axes, response_figure_axes timeout = 1e-6 #timeout = 0.05 # uncomment to run slower if frame == 0: #pylab.ion() # interactive mode on tracking_figure = pylab.figure() gs = pylab.GridSpec(1, 3, width_ratios=[3, 1, 1]) tracking_figure_axes = tracking_figure.add_subplot(gs[0]) tracking_figure_axes.set_title("Tracked object (and ground truth)") z_figure_axes = tracking_figure.add_subplot(gs[1]) z_figure_axes.set_title("Template") response_figure_axes = tracking_figure.add_subplot(gs[2]) response_figure_axes.set_title("Response") tracking_rectangle = pylab.Rectangle((0, 0), 0, 0) tracking_rectangle.set_color((1, 0, 0, 0.5)) tracking_figure_axes.add_patch(tracking_rectangle) gt_point = pylab.Circle((0, 0), radius=5) gt_point.set_color((0, 0, 1, 0.5)) tracking_figure_axes.add_patch(gt_point) tracking_figure_title = tracking_figure.suptitle("") pylab.show(block=False) elif tracking_figure is None: return # we simply go faster by skipping the drawing elif not pylab.fignum_exists(tracking_figure.number): #print("Drawing window closed, end of game. " # "Have a nice day !") #sys.exit() print("From now on drawing will be omitted, " "so that computation goes faster") tracking_figure = None return global z, response tracking_figure_axes.imshow(im, cmap=pylab.cm.gray) rect_y, rect_x = tuple(pos - target_sz/2.0) rect_height, rect_width = target_sz if should_resize_image: rect_y = rect_y * 2 rect_x = rect_x * 2 rect_height = rect_height * 2 rect_width = rect_width * 2 tracking_rectangle.set_xy((rect_x, rect_y)) tracking_rectangle.set_width(rect_width) tracking_rectangle.set_height(rect_height) if len(ground_truth) > 0: gt = ground_truth[frame] gt_y, gt_x = gt gt_point.center = (gt_x, gt_y) if tracker.z is not None: z_figure_axes.imshow(tracker.z, cmap=pylab.cm.hot) if tracker.response is not None: response_figure_axes.imshow(tracker.response, cmap=pylab.cm.hot) tracking_figure_title.set_text("Frame %i (out of %i)" % (frame + 1, len(ground_truth))) if debug and False and (frame % 1) == 0: print("Tracked pos ==", pos) #tracking_figure.canvas.draw() # update pylab.draw() pylab.waitforbuttonpress(timeout=timeout) return
def plot_tracking(frame, pos, target_sz, im, ground_truth): global tracking_figure, tracking_figure_title, tracking_figure_axes, tracking_rectangle, gt_point,\ z_figure_axes, response_figure_axes, z, response timeout = 1e-6 # timeout = 0.05 # uncomment to run slower if frame == 0: # pylab.ion() # interactive mode on tracking_figure = pylab.figure() gs = pylab.GridSpec(1, 3, width_ratios=[3, 1, 1]) tracking_figure_axes = tracking_figure.add_subplot(gs[0]) tracking_figure_axes.set_title("Tracked object (and ground truth)") z_figure_axes = tracking_figure.add_subplot(gs[1]) z_figure_axes.set_title("Template") response_figure_axes = tracking_figure.add_subplot(gs[2]) response_figure_axes.set_title("Response") tracking_rectangle = pylab.Rectangle((0, 0), 0, 0) tracking_rectangle.set_color((1, 0, 0, 0.5)) tracking_figure_axes.add_patch(tracking_rectangle) gt_point = pylab.Circle((0, 0), radius=5) gt_point.set_color((0, 0, 1, 0.5)) tracking_figure_axes.add_patch(gt_point) tracking_figure_title = tracking_figure.suptitle("") pylab.show(block=False) elif tracking_figure is None: return # we simply go faster by skipping the drawing elif not pylab.fignum_exists(tracking_figure.number): # print("Drawing window closed, end of game. " # "Have a nice day !") # sys.exit() print("From now on drawing will be omitted, " "so that computation goes faster") tracking_figure = None return tracking_figure_axes.imshow(im, cmap=pylab.cm.gray) rect_y, rect_x = tuple(pos - target_sz / 2.0) rect_height, rect_width = target_sz tracking_rectangle.set_xy((rect_x, rect_y)) tracking_rectangle.set_width(rect_width) tracking_rectangle.set_height(rect_height) if len(ground_truth) > 0: gt = ground_truth[frame] gt_y, gt_x = gt gt_point.center = (gt_x, gt_y) if z is not None: z_figure_axes.imshow(z, cmap=pylab.cm.hot) if response is not None: response_figure_axes.imshow(response, cmap=pylab.cm.hot) tracking_figure_title.set_text("Frame %i (out of %i)" % (frame + 1, len(ground_truth))) if debug and False and (frame % 1) == 0: print("Tracked pos ==", pos) # tracking_figure.canvas.draw() # update pylab.draw() pylab.waitforbuttonpress(timeout=timeout) return
def update(self): #print "UPDATE" if not fignum_exists(self.figure.number): return self.figure.canvas.manager.window.after(1000, self.update) if len(self.objects) == 0: self.axis.clear() self.text = self.axis.text(0.5,0.5,0.5,"No objects tracked") self.text.set_horizontalalignment("center") self.text.set_verticalalignment("center") self.figure.canvas.draw() self.notrack = True return if toolkit.db.UT and toolkit.db.UTt: t = time.time() - toolkit.db.UTt + toolkit.db.UT elif toolkit.db.UT: t = toolkit.db.UT else: t= time.time() #figure(self.figure.number) #self.axis.clear() if self.notrack: self.notrack = False self.axis.clear() scale=600000 u, v = mgrid[0:2*pi:20j, 0:pi:10j] x=cos(u)*sin(v)*scale y=sin(u)*sin(v)*scale z=cos(v)*scale self.sphere = self.axis.plot_wireframe(x, y, z, color="r") for celestial,plots in self.objects.items(): if celestial.ref != self.ref or celestial.orbit == None: continue xpos = [] ypos = [] zpos = [] for ta in self.linspace: rv = celestial.orbit.plot(ta) xpos.append(rv[0]) ypos.append(rv[1]) zpos.append(rv[2]) if not plots[0]: plots[0] = self.axis.plot(xpos,ypos,zpos,color="red")[0] else: plots[0].set_data(xpos,ypos) plots[0].set_3d_properties(zpos) rv,vv = celestial.eph(t) #print rv,vv #self.scat = (rv,vv) if not plots[1]: plots[1] = self.axis.scatter(rv[0],rv[1],rv[2],color="green") else: #plots[1].set_data(rv[0],rv[1],rv[2]) plots[1].set_offsets([[rv[0],rv[1]]]) plots[1].set_3d_properties([rv[2]],"z") #print "Pos",rv self.axis.relim() xlim = self.axis.get_xlim() ylim = self.axis.get_ylim() m = max(abs(xlim[0]),abs(xlim[1]),abs(ylim[0]),abs(ylim[1])) lim = (-m,m) self.axis.set_xlim(lim) self.axis.set_ylim(lim) self.axis.set_zlim(lim) #self.axis.autoscale_view(True,True,True,True) #xlim = self.axis.get_xlim() #ylim = self.axis.get_ylim() #minlim = min((xlim[0],ylim[0])) #maxlim = max((xlim[1],ylim[1])) #self.axis.set_ylim((minlim,maxlim)) #self.axis.set_xlim((minlim,maxlim)) #if xlim[0] > ylim[0]: # self.axis.set_ylim(xlim) #else: # self.axis.set_xlim(ylim) self.figure.canvas.draw()
def plot(self,coords='auto',proj='auto',labels=True,extras=True,isExtra=0,**kargs): ax=kargs.pop('ax',None) if ax: self.ax=ax parent=kargs.pop('inherit',0) if parent: self.inherit(parent) isExtra=1 if isExtra: labels=False debug_lev=kargs.pop('debug_level',0) self.set_param(**kargs) try: if isinstance(self.v,tuple): ndim=self.v[0].ndim vshape=self.v[0].shape else: ndim=self.v.ndim vshape=self.v.shape except: ndim=0 vshape=() x,y,xname,yname=None,None,None,None if coords=='auto': if ndim==2: if not self.x is None and (self.x.ndim==2 or self.x.size==vshape[1]): x,xname=self.x,'x' elif not self.d is None and (self.d.ndim==2 or self.d.size==vshape[1]): x,xname=self.d,'d' elif not self.t is None and (self.t.ndim==2 or self.t.size==vshape[1]): x,xname=self.t,'t' elif not self.tnum is None and (self.tnum.ndim==2 or self.tnum.size==vshape[1]): x,xname=self.tnum,'tnum' elif not self.y is None and (self.y.ndim==2 or self.y.size==vshape[1]): x,xname=self.y,'y' if not self.y is None and (self.y.ndim==2 or self.y.size==vshape[0]): y,yname=self.y,'y' elif not self.z is None and (self.z.ndim==2 or self.z.size==vshape[0]): y,yname=self.z,'z' elif ndim==1: y,yname=self.v,'v' if not self.d is None and self.d.ndim==1: x,xname=self.d,'d' elif not self.t is None and (calc.isarray(self.t) and self.t.ndim==1): x,xname=self.t,'t' elif not self.x is None and self.x.ndim==1: x,xname=self.x,'x' elif not self.y is None and self.y.ndim==1: x,xname=self.y,'y' elif not self.z is None and self.z.ndim==1: y,yname=self.z,'z' x,xname=self.v,'v' if ndim==2 and proj=='auto' and xname=='x' and yname=='y' and\ np.all(x>=-360) and np.all(x<=360) and np.all(y>=-90) and np.all(y<=90): proj=True elif proj=='auto': proj=False if hasattr(self,'fig') and pl.fignum_exists(self.fig.number): if isExtra: pass else: if debug_lev==2: print ' -> will clear axes' self.clear_axes() else: if hasattr(self,'ax'): if debug_lev==2: print ' -> will use previous ax' self.init_figure(ax=self.ax) else: if debug_lev==2: print ' -> will create new fig' self.init_figure() if proj and not isExtra: if not hasattr(self,'map') or self.map_info_get()!=self.map_info_current: # make a new projection: if not self.config['axes.axis'] and not x is None: self.config['axes.axis']=x.min(),x.max(),y.min(),y.max() if debug_lev==2: print ' -> new projection needed' self.init_projection(debug_level=debug_lev) ### useProj=1 # set labels: xlab=ylab=vlab='' if not xname is None: xunits=self.info[xname]['units'] if xunits in (None,'Unk'): xlab = '%s'%self.info[xname]['name'] else: xlab = '%s (%s)'%(self.info[xname]['name'],xunits) if not yname is None: yunits=self.info[yname]['units'] if yunits in (None,'Unk'): ylab = '%s'%self.info[yname]['name'] else: ylab = '%s (%s)'%(self.info[yname]['name'],yunits) vunits=self.info['v']['units'] if vunits in (None,'Unk'): vlab = '%s'%self.info['v']['name'] else: vlab = '%s (%s)'%(self.info['v']['name'],vunits) if ndim==2: if debug_lev==2: print ' -> will draw 2d' if isinstance(self.v,tuple): self.draw_vector_field(x,y,self.v[0],self.v[1]) else: self.draw_scalar_field(x,y,self.v) if not isExtra: lc =self.config['field.linecolors'] # check if only one color: if isinstance(lc,basestring): oneColor=1 else: try: oneColor=len(lc)==1 except: oneColor=0 if not (self.config['field.plot']=='contour' and oneColor): self.draw_colorbar() if labels: tit=vlab if not self.t is None: if isinstance(self.t,datetime.datetime): tit+=' $\\bullet$ %s'%self.t.strftime('%Y-%m-%d %H:%M') else: tit+=' $\\bullet$ %s to %s'%(self.t[0,0].strftime('%Y-%m-%d %H:%M'),self.t[0,-1].strftime('%Y-%m-%d %H:%M')) if not self.info['v']['slice'] in (None,'Unk'): tit+=' $\\bullet$ %s'%self.info['v']['slice'] if not tit=='Unk': self.draw_label('title',tit) if not proj:###not useProj: if not xlab=='Unk': self.draw_label('xlabel',xlab) if not ylab=='Unk': self.draw_label('ylabel',ylab) elif ndim==1: if debug_lev==2: print ' -> will draw 1d' self.draw_1d(x,y) if labels: if not xlab=='Unk': self.draw_label('xlabel',xlab) if yname=='v': if not vlab=='Unk': self.draw_label('title',vlab) else: if not ylab=='Unk': self.draw_label('ylabel',ylab) if proj and not isExtra: if debug_lev==2: print ' -> will draw projection', self.info['v'] self.draw_projection() if self.extra and extras: for e in self.extra: e.inherit(self) if debug_lev==2: print ' -> will plot extras' e.plot(isExtra=1,debug_level=debug_lev)
def plot(self, coords='auto', proj='auto', labels=True, extras=True, isExtra=0, **kargs): ax = kargs.pop('ax', None) cbax = kargs.pop('cbax', None) if ax: self.ax = ax axp = ax.get_position() self.config[ 'axes.position'] = axp.x0, axp.y0, axp.width, axp.height if cbax: self.cbax = cbax axp = cbax.get_position() self.config[ 'colorbar.ax_position'] = axp.x0, axp.y0, axp.width, axp.height parent = kargs.pop('inherit', 0) if parent: self.inherit(parent) isExtra = 1 if isExtra: labels = False debug_lev = kargs.pop('debug_level', 0) self.set_param(**kargs) # make vfield vars 2d to simplify the process: if isinstance(self.v, tuple) and self.v[0].ndim == 1: self.x = self.x[:, np.newaxis] self.y = self.y[:, np.newaxis] self.v = self.v[0][:, np.newaxis], self.v[1][:, np.newaxis] try: if isinstance(self.v, tuple): ndim = self.v[0].ndim vshape = self.v[0].shape else: ndim = self.v.ndim vshape = self.v.shape except: ndim = 0 vshape = () x, y, xname, yname = None, None, None, None if coords == 'auto': if ndim == 2: if not self.x is None and (self.x.ndim == 2 or self.x.size == vshape[1]): x, xname = self.x, 'x' elif not self.d is None and (self.d.ndim == 2 or self.d.size == vshape[1]): x, xname = self.d, 'd' elif not self.t is None and (self.t.ndim == 2 or self.t.size == vshape[1]): x, xname = self.t, 't' elif not self.tnum is None and (self.tnum.ndim == 2 or self.tnum.size == vshape[1]): x, xname = self.tnum, 'tnum' elif not self.y is None and (self.y.ndim == 2 or self.y.size == vshape[1]): x, xname = self.y, 'y' if xname != 'y' and not self.y is None and ( self.y.ndim == 2 or self.y.size == vshape[0]): y, yname = self.y, 'y' elif not self.z is None and (self.z.ndim == 2 or self.z.size == vshape[0]): y, yname = self.z, 'z' elif ndim == 1: y, yname = self.v, 'v' if not self.d is None and self.d.ndim == 1: x, xname = self.d, 'd' elif not self.t is None and (calc.isarray(self.t) and self.t.ndim == 1): x, xname = self.t, 't' elif not self.x is None and self.x.ndim == 1: x, xname = self.x, 'x' elif not self.y is None and self.y.ndim == 1: x, xname = self.y, 'y' elif not self.z is None and self.z.ndim == 1: y, yname = self.z, 'z' x, xname = self.v, 'v' if ndim==2 and proj=='auto' and xname=='x' and yname=='y' and\ np.all(x>=-360) and np.all(x<=360) and np.all(y>=-90) and np.all(y<=90): proj = True elif proj == 'auto': proj = False try: isFig = pl.fignum_exists(self.fig.number) isAxFig = pl.fignum_exists(self.ax.figure.number) except: isFig = True isAxFig = True if hasattr(self, 'fig') and isFig: if isExtra: pass else: if debug_lev == 2: print(' -> will clear axes') self.clear_axes() else: if hasattr(self, 'ax') and isAxFig: if debug_lev == 2: print(' -> will use previous ax') if hasattr(self, 'cbax'): self.init_figure(ax=self.ax, cbax=self.cbax) else: self.init_figure(ax=self.ax) else: if debug_lev == 2: print(' -> will create new fig') self.init_figure() if proj and not isExtra: if not hasattr(self, 'map') or not self.map or self.map_info_get( ) != self.map_info_current: # make a new projection: if not self.config['axes.axis'] and not x is None: self.config['axes.axis'] = x.min(), x.max(), y.min( ), y.max() if debug_lev == 2: print(' -> new projection needed') self.init_projection(debug_level=debug_lev) # set labels: xlab = ylab = vlab = '' if not xname is None: xunits = self.info[xname]['units'] if xunits in (None, 'Unk'): xlab = '%s' % self.info[xname]['name'] else: xlab = '%s (%s)' % (self.info[xname]['name'], xunits) if not yname is None: yunits = self.info[yname]['units'] if yunits in (None, 'Unk'): ylab = '%s' % self.info[yname]['name'] else: ylab = '%s (%s)' % (self.info[yname]['name'], yunits) vunits = self.info['v']['units'] if vunits in (None, 'Unk'): vlab = '%s' % self.info['v']['name'] else: vlab = '%s (%s)' % (self.info['v']['name'], vunits) # vfield, 1d or 2d if np.iscomplexobj(self.v): if debug_lev == 2: print(' -> will draw vfield') self.draw_vector_field(x, y, np.real(self.v), np.imag(self.v)) # scalar: else: if ndim == 2: if debug_lev == 2: print(' -> will draw 2d') self.draw_scalar_field(x, y, self.v) if not isExtra: if debug_lev == 2: print(' -> will draw colorbar') self.draw_colorbar() elif ndim == 1: if debug_lev == 2: print(' -> will draw 1d') self.draw_1d(x, y) # add labels: if labels: if ndim == 2: tit = vlab if not self.t is None: #if isinstance(self.t,datetime.datetime): # now netcdftime.num2date returns array or netcdftime.datetime # obkjects instead of datetime.datetime import netcdftime if isinstance(self.t, datetime.datetime) or isinstance( self.t, netcdftime.datetime): tit += ' $\\bullet$ %s' % self.t.strftime( '%Y-%m-%d %H:%M') else: tit += ' $\\bullet$ %s to %s' % ( self.t[0, 0].strftime('%Y-%m-%d %H:%M'), self.t[0, -1].strftime('%Y-%m-%d %H:%M')) if not self.info['v']['slice'] in (None, 'Unk'): tit += ' $\\bullet$ %s' % self.info['v']['slice'] if not tit == 'Unk': self.draw_label('title', tit) if not proj: ###not useProj: if not xlab == 'Unk': self.draw_label('xlabel', xlab) if not ylab == 'Unk': self.draw_label('ylabel', ylab) elif ndim == 1: if not xlab == 'Unk': self.draw_label('xlabel', xlab) if yname == 'v': if not vlab == 'Unk': self.draw_label('title', vlab) else: if not ylab == 'Unk': self.draw_label('ylabel', ylab) if proj and not isExtra: if debug_lev == 2: print(' -> will draw projection', self.info['v']) self.draw_projection() if self.extra and extras: for e in self.extra: e.inherit(self) if debug_lev == 2: print(' -> will plot extras') e.plot(isExtra=1, debug_level=debug_lev)
def plot_coarse_group(group, clobber=False, plot_cands=True, use_kurto=False, fignum=2): """ Produce the waterfall plot for the beams at very coarse resolution. TODO -- make version without candidates. """ fnames = sorted(glob.glob(mkroot + 'fil/%s_ea*.fil' % group)) if use_kurto: fnames = filter(lambda f: f.endswith('_kur.fil'), fnames) else: fnames = filter(lambda f: not f.endswith('_kur.fil'), fnames) if len(fnames) == 0: if use_kurto: print 'No kurtosis for %s.' % (group) else: print 'No non-kurtosis for %s.' % (group) return base = os.path.split(fnames[0])[-1].split('_ea')[0] suffix = '_kur' if use_kurto else '' if plot_cands: suffix += '_cands' plot_name = '/data/kerrm/plots/%s_coarse%s.png' % (base, suffix) if (not clobber) and os.path.isfile(plot_name): return sncut = 10 if plot_cands: l, r = fnames[0].replace("vlite_fb", "cands").replace('fil', 'cand').split("ea") cand_fnames = sorted(glob.glob('*'.join((l, r[2:])))) else: cand_fnames = [] # make full list -- for case we have more candidates than fils fil_antennas = [os.path.basename(x).split('_')[3] for x in fnames] cand_antennas = [os.path.basename(x).split('_')[3] for x in cand_fnames] all_antennas = sorted(set(fil_antennas).union(cand_antennas)) all_fnames = [] for antenna in all_antennas: fname = [x for x in fnames if antenna in x] fil_fname = None if len(fname) == 0 else fname[0] fname = [x for x in cand_fnames if antenna in x] cand_fname = None if len(fname) == 0 else fname[0] all_fnames.append((fil_fname, cand_fname)) fil_fnames = [x[0] for x in all_fnames] cand_fnames = [x[1] for x in all_fnames] has_cands = sum((x is not None for x in cand_fnames)) > 0 all_cands = [load_cands(fname, sncut=sncut) for fname in cand_fnames] if plot_cands and has_cands: coincidence(all_cands) msncuts = [1, 10, 15, 20, 30, 50] msizes = [2, 3, 7, 11, 14, 18] mwidths = [3, 10, 30, 100, 300, 1000] colors = get_tableau20(only_dark=True) width_colors = [ colors[5], colors[3], colors[4], colors[1], colors[0], colors[2] ] figx = 14 figy = 3.0 * len(all_antennas) if pl.fignum_exists(fignum): x, y = pl.gcf().get_size_inches() if x != figx or y != figy: pl.close(fignum) pl.figure(fignum, (figx, figy)) else: pl.clf() else: pl.figure(fignum, (figx, figy)) pl.subplots_adjust(top=0.99, bottom=0.16 if len(fnames) == 1 else 0.08, left=0.05, right=0.98, hspace=0.02) grid_shape = 2 * len(all_antennas), 5 pl.clf() if plot_cands: fig2_axes = pl.subplot2grid(grid_shape, (0, 4), rowspan=2 * len(fnames)) fig2_axes.set_xscale('log') fig2_axes.set_yscale('log') fig2_axes.yaxis.set_label_position('right') import pysigproc from analyze_fb import fb_avg tmin = np.inf tmax = 0 fil_axes = [] cand_axes = [] for i, antenna in enumerate(all_antennas): fname, cand_fname = all_fnames[i] print i, antenna, fname, cand_fname if fname is not None: spf = pysigproc.SigprocFile(fname) data, freqs, times = fb_avg(fname) if tmax < times[-1] + (times[1] - times[0]): tmax = times[-1] + (times[1] - times[0]) if times[0] < tmin: tmin = times[0] if plot_cands: ax = pl.subplot2grid(grid_shape, (2 * i, 0), colspan=4) else: ax = pl.subplot(len(all_antennas), 1, i + 1) fil_axes.append(ax) if fname is not None: ax.imshow(data, extent=[times[0], times[-1], freqs[0], freqs[-1]], vmin=0.9, vmax=1.1, cmap='Greys', aspect='auto', origin='lower') ax.set_ylabel('Freq (MHz)') ax.text(times[int(len(times) * 0.95)], 328, 'ea%02d' % spf.telescope_id, size='large', color='white') if not plot_cands and i == len(all_antennas) - 1: ax.set_xlabel('Elapsed Time (s)') else: ax.set_xticks([]) ax.set_yticks([330, 340, 350]) if not plot_cands: continue axcand = pl.subplot2grid(grid_shape, (2 * i + 1, 0), colspan=4) cand_axes.append(axcand) cands = all_cands[i] cand_times = np.asarray([cand.peak_time for cand in cands]) dms = np.asarray([cand.dm for cand in cands]) sns = np.asarray([cand.sn for cand in cands]) sizes = np.ones_like(sns) * 1 for msn, msz in zip(msncuts, msizes): sizes[sns > msn] = msz**2 widths = np.asarray([cand.width for cand in cands]) * 1e3 # in ms c = np.empty((len(widths), 3)) for imw in xrange(len(mwidths)): c[widths < mwidths[-(imw + 1)]] = width_colors[len(mwidths) - (imw + 1)] fat_pulse_count = np.sum(widths >= mwidths[-1]) if fat_pulse_count > 0: print 'Have %d fat pulses for %s.' % (fat_pulse_count, group) c[widths >= mwidths[-1]] = width_colors[-1] axcand.set_yscale('log') cm = coincidence_mask = np.asarray( [cand.beam_mask.sum() > 1 for cand in cands]) if len(cm) > 0: cm &= widths < mwidths[-1] axcand.scatter(cand_times[~cm], dms[~cm], c=c[~cm], marker='o', s=sizes[~cm], alpha=0.5) axcand.scatter(cand_times[cm], dms[cm], c=c[cm], marker='*', s=sizes[cm], alpha=0.8) axcand.set_ylabel('DM') if i == len(fnames) - 1: axcand.set_xlabel('Elapsed Time (s)') else: axcand.set_xticks([]) if len(cm) > 0: fig2_axes.scatter(dms[~cm], widths[~cm], marker='o', s=sizes[~cm], label=all_antennas[i], alpha=0.5, color=colors[i % len(colors)]) fig2_axes.scatter(dms[cm], widths[cm], marker='*', s=sizes[cm], label=all_antennas[i], alpha=0.8, color=colors[i % len(colors)]) #pl.figtext(0.40,0.02,'Elapsed Time (s)',size='large',rotation='horizontal') if plot_cands: dms = np.logspace(np.log10(2), 3, 100) dm_widths = 4.15e-3 * (0.320**-2 - (0.320 + 0.064 / 6250)**-2) * dms * 1e3 fig2_axes.plot(dms, dm_widths, alpha=0.5) fig2_axes.plot([1e2, 1e2], [1, 10], color='k', ls='-', lw=1, alpha=0.5) fig2_axes.plot([1e2, 1e3], [10, 10], color='k', ls='-', lw=1, alpha=0.5) fig2_axes.set_ylabel('Width (ms)') fig2_axes.set_xlabel('DM') fig2_axes.axis([3, 1001, 1, 1000]) for axcand in cand_axes: axcand.axis([tmin, tmax, 3, 1001]) #pl.figtext(0.40,0.02,'Dispersion Measure',size='large',rotation='horizontal') """ legend_lines = [mlines.Line2D([],[],color=colors[i],marker='o',markersize=msizes[2],alpha=0.5,label=antennas[i],ls=' ') for i in xrange(len(antennas))] axlegend = pl.axes([0.10,0.96,0.88,0.05]) axlegend.axis('off') pl.legend(handles=legend_lines,mode='expand',ncol=len(antennas),frameon=False,loc='upper right') """ pl.savefig(plot_name)
def plotr(self, xlim=[None,None], ylim=[None,None], fig=1, only='all'): oplot = False if (fignum_exists(fig)): oplot = True symbols = ['d', '+', '*'] index = np.random.randint(0,len(symbols)) symbol = symbols[index] else: symbol = 'o' fig = figure(fig) ax = subplot(111) if (only == 'all'): ax.errorbar(self.mx[0:-1,0],self.r02, yerr=self.r02Err, fmt='r-'+symbol) ax.errorbar(self.mx[0:-1,1],self.r13, yerr=self.r13Err, fmt='b-'+symbol) ax.errorbar(self.mx[:,0],self.r01, yerr=self.r01Err, fmt='g-'+symbol) ax.errorbar(self.mx[0:-1,1],self.r10, yerr=self.r10Err, fmt='k-'+symbol) leg = ax.legend((r'$r_{02}$',r'$r_{13}$',r'$r_{01}$',r'$r_{10}$')) elif (only == 'r02'): ax.errorbar(self.mx[0:-1,0],self.r02, yerr=self.r02Err, fmt='r-'+symbol) leg = ax.legend((r'$r_{02}$',r'$r_{13}$',r'$r_{01}$',r'$r_{10}$')) elif(only == 'r13'): ax.errorbar(self.mx[0:-1,1],self.r13, yerr=self.r13Err, fmt='b-'+symbol) leg = ax.legend((r'$r_{02}$',r'$r_{13}$',r'$r_{01}$',r'$r_{10}$')) elif(only == 'r010'): mfc = 'orange' if oplot else None ms = 2 if oplot else None ax.errorbar(self.mx[:,0],self.r01, yerr=self.r01Err, fmt='g'+symbol, mfc=mfc) ax.errorbar(self.mx[0:-1,1],self.r10, yerr=self.r10Err, fmt='k'+symbol, mfc=mfc) leg = ax.legend((r'$r_{02}$',r'$r_{13}$',r'$r_{01}$',r'$r_{10}$')) ax.grid(False) ax.set_xlabel('Frequency') ax.set_ylabel('ratio') ax.set_title(r'Ratios') ax.set_ylim(ylim) ax.set_xlim(xlim) plt.show() ## ## Plot the dr as a function of frequency (stub!) ## def plotdr(self, xlim=[None,None], ylim=[None,None]): if (self.type == 'm'): if (self.star=='A'): fig = plt.figure(5) else: fig = plt.figure(9) ax = fig.add_subplot(211) ax.plot(self.mx[0:-1,0],(self.r02 - self.r13),'r-o') leg = ax.legend((r'$dr$'), 'upper left') ax.grid(False) ax.set_xlabel('Frequency') ax.set_ylabel(r'$dr \, (\mu Hz)$') if (self.star=='A'): ax.set_title(r'(modelo;*A)') else: ax.set_title(r'(modelo;*B)') ax.set_ylim(ylim) ax.set_xlim(xlim) plt.show() else: if (self.star=='A'): fig = plt.figure(5) else: fig = plt.figure(9) ax = fig.add_subplot(212) ax.plot(self.mx[0:-1,0],self.r02-self.r13,'r-o') leg = ax.legend((r'$dr$'), 'upper left') ax.grid(False) ax.set_xlabel('Frequency') ax.set_ylabel(r'$dr \, (\mu Hz)$') if (self.star=='A'): ax.set_title(r'(observacoes;*A)') else: ax.set_title(r'(observacoes;*B)') ax.set_ylim(ylim) ax.set_xlim(xlim) plt.show() ## ## Plot the second differences as a function of frequency (stub!) ## def plotsd(self, xlim=[None,None], ylim=[None,None]): if (self.type == 'm'): if (self.star=='A'): fig = plt.figure(6) else: fig = plt.figure(10) ax = fig.add_subplot(111) ax.errorbar(self.mx[0:-1,:], self.D2[:,:], fmt='-o') leg = ax.legend(('l=0', 'l=1', 'l=2', 'l=3'), 'lower right') ax.grid(False) ax.set_xlabel('Frequency') ax.set_ylabel(r'$\Delta_{\ell} \, (\mu Hz)$') if (self.star=='A'): ax.set_title(r'Second differences $\Delta_2$ (modelo;*A)') else: ax.set_title(r'Second differences $\Delta_2$ (modelo;*B)') ax.set_ylim(ylim) ax.set_xlim(xlim) plt.show() else: if (self.star=='A'): fig = plt.figure(6) else: fig = plt.figure(10) ax = fig.add_subplot(111) for i in range(self.Nl): lbl = 'l='+str(i) ax.errorbar(self.mx[0:-2,i], self.D2[0:-1,i], yerr=self.D2Err[0:-1,i], fmt='-o', label=lbl) leg=ax.legend(loc='lower center') ax.grid(False) ax.set_xlabel('Frequency') ax.set_ylabel(r'$\Delta_{\ell} \, (\mu Hz)$') if (self.star=='A'): ax.set_title(r'Large Separation $\Delta_l$ (observacoes;*A)') else: ax.set_title(r'Large Separation $\Delta_l$ (observacoes;*B)') ax.set_ylim(ylim) ax.set_xlim(xlim) plt.show() ## ## Relative differences to observations (stub!) ## def relative (self, obs, plot=True, xlim=[None,None], ylim=[None,None]): self.rel1 = (self.Dl- obs.Dl) / obs.Dl self.rel2 = (self.d02- obs.d02) / obs.d02 self.rel3 = (self.d13- obs.d13) / obs.d13 if (plot): #for i in range(3): fig = plt.figure(i) ax = fig.add_subplot(111) ax.plot(self.rel, self.D2[:,:], fmt='-o') #leg = ax.legend(('l=0', 'l=1', 'l=2', 'l=3'), 'lower right') ax.grid(False) #ax.set_xlabel('Frequency') #ax.set_ylabel(r'$\Delta_{\ell} \, (\mu Hz)$') #ax.set_title(r'Second differences $\Delta_2$ (modelo;*A)') ax.set_ylim(ylim) ax.set_xlim(xlim) plt.show()
return os.path.join(figurepath, x) def savefig(savename, **kwargs): """ Save both a png and a pdf version of the image """ pl.savefig(p3(savename.replace("pdf","png")), **kwargs) pl.savefig(p3(savename.replace("png","pdf")), **kwargs) zoomargs = {'x': 49.31, 'y':-0.35, 'width': 0.55, 'height':0.34} # copied from projection_figures zoomargs = {'x': 49.23, 'y': -0.28, 'width':1, 'height':0.5} zoomargs = dict(x=49.27, y=-0.32, width=0.9, height=0.4) for fignum in (1,2,3): if pl.fignum_exists(fignum): pl.close(fignum) Vizier.ROW_LIMIT = 999999 ysos = Vizier.get_catalogs('J/ApJ/706/83/ysos')['J/ApJ/706/83/ysos'] masers = Vizier.query_region('W51', radius='2 deg', catalog='J/A+A/291/261/table1')['J/A+A/291/261/table1'] masers2 = Vizier.query_region('W51', radius='2 deg', catalog='J/MNRAS/418/1689/table2')['J/MNRAS/418/1689/table2'] radec = [coordinates.SkyCoord(r,d,unit=('deg','deg'),frame='icrs') for r,d in zip(masers2['RAJ2000'],masers2['DEJ2000'])] glon,glat = np.array(zip(*[(rd.galactic.l.degree, rd.galactic.b.degree) for rd in radec])) # Added 5/23/2014
def echelle (self, dnu=None, nu0=0.0, fig=None): """ Plot the echelle diagram of the object frequencies. Parameters ---------- dnu : mean large separation. By default, delta_nu() is run to calculate it from l=0 frequencies. The user can input any other value. nu0 : reference frequency fig : identification of the Figure window for overplotting (experimental) """ import numpy as np from pylab import figure, subplot, errorbar, minorticks_on, show from pylab import setp, gca from pylab import fignum_exists if (dnu == None): try: dnu = self.dnu except AttributeError: self.delta_nu() dnu = self.dnu if (fignum_exists(fig)): colors = ['b', 'r', 'g', 'y'] index = np.random.randint(0,len(colors)) color = colors[index] else: color = 'k' face = 'w' if color=='k' else color figure(fig) ax = subplot(111) nuMODdnu = self.mx % (dnu - nu0) idx0 = self.mx[:,0] != 0. idx1 = self.mx[:,1] != 0. idx2 = self.mx[:,2] != 0. try: idx3 = self.mx[:,3] != 0. except IndexError: pass print idx3 l0,cl,bl = errorbar(nuMODdnu[idx0,0], self.mx[idx0,0], xerr=self.mxErr[idx0,0], fmt=color +'*', ms=8, capsize=2) l1,cl,bl = errorbar(nuMODdnu[idx1,1], self.mx[idx1,1], xerr=self.mxErr[idx1,1],fmt=color +'o', mfc=face, ms=6) l2,cl,bl = errorbar(nuMODdnu[idx2,2], self.mx[idx2,2], xerr=self.mxErr[idx2,2],fmt=color +'d', mfc=face, ms=7,capsize=2) try: l3,cl,bl = errorbar(nuMODdnu[idx3,3], self.mx[idx3,3], xerr=self.mxErr[idx3,3],fmt=color +'s', mfc=face, ms=6,capsize=3) ax.legend((r'$\ell=0$', r'$\ell=1$', r'$\ell=2$', r'$\ell=3$'), frameon=False, numpoints=1) except IndexError: ax.legend((r'$\ell=0$', r'$\ell=1$', r'$\ell=2$'), frameon=False, numpoints=1) ax.set_xlabel(r'$\nu$ ' + 'mod' + r' $\Delta\nu \, (\mu Hz)$', fontsize=20, labelpad=15) ax.set_ylabel(r'$\nu \, (\mu Hz)$', fontsize=20, labelpad=15) ax.set_title(r'$\Delta \nu =$' + str(dnu)[0:6], fontsize=22) #ax.set_ylim([1600,3500]) #ax.set_xlim([20,140]) setp(ax.get_xticklabels(), fontsize=18) setp(ax.get_yticklabels(), fontsize=18) leg = gca().get_legend() ltext = leg.get_texts() setp(ltext, fontsize=18) minorticks_on() show()
def plot(self,coords='auto',proj='auto',labels=True,extras=True,isExtra=0,**kargs): ax=kargs.pop('ax',None) cbax=kargs.pop('cbax',None) if ax: self.ax=ax axp=ax.get_position() self.config['axes.position']=axp.x0,axp.y0,axp.width,axp.height if cbax: self.cbax=cbax axp=cbax.get_position() self.config['colorbar.ax_position']=axp.x0,axp.y0,axp.width,axp.height parent=kargs.pop('inherit',0) if parent: self.inherit(parent) isExtra=1 if isExtra: labels=False debug_lev=kargs.pop('debug_level',0) self.set_param(**kargs) # make vfield vars 2d to simplify the process: if isinstance(self.v,tuple) and self.v[0].ndim==1: self.x=self.x[:,np.newaxis] self.y=self.y[:,np.newaxis] self.v=self.v[0][:,np.newaxis],self.v[1][:,np.newaxis] try: if isinstance(self.v,tuple): ndim=self.v[0].ndim vshape=self.v[0].shape else: ndim=self.v.ndim vshape=self.v.shape except: ndim=0 vshape=() x,y,xname,yname=None,None,None,None if coords=='auto': if ndim==2: if not self.x is None and (self.x.ndim==2 or self.x.size==vshape[1]): x,xname=self.x,'x' elif not self.d is None and (self.d.ndim==2 or self.d.size==vshape[1]): x,xname=self.d,'d' elif not self.t is None and (self.t.ndim==2 or self.t.size==vshape[1]): x,xname=self.t,'t' elif not self.tnum is None and (self.tnum.ndim==2 or self.tnum.size==vshape[1]): x,xname=self.tnum,'tnum' elif not self.y is None and (self.y.ndim==2 or self.y.size==vshape[1]): x,xname=self.y,'y' if xname!='y' and not self.y is None and (self.y.ndim==2 or self.y.size==vshape[0]): y,yname=self.y,'y' elif not self.z is None and (self.z.ndim==2 or self.z.size==vshape[0]): y,yname=self.z,'z' elif ndim==1: y,yname=self.v,'v' if not self.d is None and self.d.ndim==1: x,xname=self.d,'d' elif not self.t is None and (calc.isarray(self.t) and self.t.ndim==1): x,xname=self.t,'t' elif not self.x is None and self.x.ndim==1: x,xname=self.x,'x' elif not self.y is None and self.y.ndim==1: x,xname=self.y,'y' elif not self.z is None and self.z.ndim==1: y,yname=self.z,'z' x,xname=self.v,'v' if ndim==2 and proj=='auto' and xname=='x' and yname=='y' and\ np.all(x>=-360) and np.all(x<=360) and np.all(y>=-90) and np.all(y<=90): proj=True elif proj=='auto': proj=False try: isFig=pl.fignum_exists(self.fig.number) isAxFig=pl.fignum_exists(self.ax.figure.number) except: isFig=True isAxFig=True if hasattr(self,'fig') and isFig: if isExtra: pass else: if debug_lev==2: print(' -> will clear axes') self.clear_axes() else: if hasattr(self,'ax') and isAxFig: if debug_lev==2: print(' -> will use previous ax') if hasattr(self,'cbax'): self.init_figure(ax=self.ax,cbax=self.cbax) else: self.init_figure(ax=self.ax) else: if debug_lev==2: print(' -> will create new fig') self.init_figure() if proj and not isExtra: if not hasattr(self,'map') or not self.map or self.map_info_get()!=self.map_info_current: # make a new projection: if not self.config['axes.axis'] and not x is None: self.config['axes.axis']=x.min(),x.max(),y.min(),y.max() if debug_lev==2: print(' -> new projection needed') self.init_projection(debug_level=debug_lev) # set labels: xlab=ylab=vlab='' if not xname is None: xunits=self.info[xname]['units'] if xunits in (None,'Unk'): xlab = '%s'%self.info[xname]['name'] else: xlab = '%s (%s)'%(self.info[xname]['name'],xunits) if not yname is None: yunits=self.info[yname]['units'] if yunits in (None,'Unk'): ylab = '%s'%self.info[yname]['name'] else: ylab = '%s (%s)'%(self.info[yname]['name'],yunits) vunits=self.info['v']['units'] if vunits in (None,'Unk'): vlab = '%s'%self.info['v']['name'] else: vlab = '%s (%s)'%(self.info['v']['name'],vunits) # vfield, 1d or 2d if np.iscomplexobj(self.v): if debug_lev==2: print(' -> will draw vfield') self.draw_vector_field(x,y,np.real(self.v),np.imag(self.v)) # scalar: else: if ndim==2: if debug_lev==2: print(' -> will draw 2d') self.draw_scalar_field(x,y,self.v) if not isExtra: if debug_lev==2: print(' -> will draw colorbar') self.draw_colorbar() elif ndim==1: if debug_lev==2: print(' -> will draw 1d') self.draw_1d(x,y) # add labels: if labels: if ndim==2: tit=vlab if not self.t is None: #if isinstance(self.t,datetime.datetime): # now netcdftime.num2date returns array or netcdftime.datetime # obkjects instead of datetime.datetime import netcdftime if isinstance(self.t,datetime.datetime) or isinstance(self.t,netcdftime.datetime): tit+=' $\\bullet$ %s'%self.t.strftime('%Y-%m-%d %H:%M') else: try: tit+=' $\\bullet$ %s to %s'%(self.t[0,0].strftime('%Y-%m-%d %H:%M'),self.t[0,-1].strftime('%Y-%m-%d %H:%M')) except: tit+=' *Unknown date*' if not self.info['v']['slice'] in (None,'Unk'): tit+=' $\\bullet$ %s'%self.info['v']['slice'] if not tit=='Unk': self.draw_label('title',tit) if not proj:###not useProj: if not xlab=='Unk': self.draw_label('xlabel',xlab) if not ylab=='Unk': self.draw_label('ylabel',ylab) elif ndim==1: if not xlab=='Unk': self.draw_label('xlabel',xlab) if yname=='v': if not vlab=='Unk': self.draw_label('title',vlab) else: if not ylab=='Unk': self.draw_label('ylabel',ylab) if proj and not isExtra: if debug_lev==2: print(' -> will draw projection', self.info['v']) self.draw_projection() if self.extra and extras: for e in self.extra: e.inherit(self) if debug_lev==2: print(' -> will plot extras') e.plot(isExtra=1,debug_level=debug_lev)
def plot(self,coords='auto',proj='auto',labels=True,extras=True,isExtra=0): x,y,xname,yname=None,None,None,None if coords=='auto': if self.v.ndim==2: if not self.x is None and self.x.ndim==2: x,xname=self.x,'x' elif not self.d is None and self.d.ndim==2: x,xname=self.d,'d' elif not self.tnum is None and self.tnum.ndim==2: x,xname=self.tnum,'tnum' elif not self.y is None and self.y.ndim==2: x,xname=self.y,'y' if not self.y is None and self.y.ndim==2: y,yname=self.y,'y' elif not self.z is None and self.z.ndim==2: y,yname=self.z,'z' elif self.v.ndim==1: if not self.d is None and self.d.ndim==1: x,xname=self.d,'d' elif not self.t is None and self.t.ndim==1: x,xname=self.t,'t' elif not self.x is None and self.x.ndim==1: x,xname=self.x,'x' elif not self.y is None and self.y.ndim==1: x,xname=self.y,'y' elif not self.z is None and self.z.ndim==1: x,xname=self.z,'z' if self.v.ndim==2 and proj=='auto' and xname=='x' and yname=='y' and\ np.all(x>=-360) and np.all(x<=360) and np.all(y>=-90) and np.all(y<=90): proj=True else: proj=False # # about x distance: --> better do this during slice # xUnitsAdd='' # if xname=='d' and (x.max()-x.min())>3e3: # x=x/1.e3 # xUnitsAdd=r'$\mathrm{\times10^3}$ ' if hasattr(self,'fig') and pl.fignum_exists(self.fig.number): pass else: self.init_figure() # try: self.fig # except: # print 'starting new fig !!' # self.init_figure() ### useProj=0 if proj and not isExtra: if not hasattr(self,'map') or self.map_info_get()!=self.map_info_current: # make a new projection: if not self.config['axes.axis']: self.config['axes.axis']=x.min(),x.max(),y.min(),y.max() print 'NEW PRJ !!' self.init_projection() ### useProj=1 if self.v.ndim==2: if isinstance(self.v,tuple): self.draw_vector_field(x,y,self.v[0],self.v[1]) else: self.draw_scalar_field(x,y,self.v) if not isExtra: self.draw_colorbar() if labels: tit = '%s (%s)'%(self.info['v']['name'],self.info['v']['units']) if not self.t is None: tit+=' $\\bullet$ %s'%self.t.strftime('%Y-%m-%d %H:%M') tit+=' $\\bullet$ %s'%self.info['v']['slice'] self.draw_label('title',tit) if not proj:###not useProj: #xlab = '%s (%s%s)'%(self.info[xname]['name'],xUnitsAdd,self.info[xname]['units']) xlab = '%s (%s)'%(self.info[xname]['name'],self.info[xname]['units']) ylab = '%s (%s)'%(self.info[yname]['name'],self.info[yname]['units']) self.draw_label('xlabel',xlab) self.draw_label('ylabel',ylab) if proj and not isExtra: print 'WILL DRAW PROJECTION', self.info['v'] self.draw_projection() else: self.draw_1d(x,self.v) if labels: xlab = '%s (%s)'%(self.info[xname]['name'],xUnitsAdd,self.info[xname]['units']) tit = '%s (%s)'%(self.info['v']['name'],self.info['v']['units']) self.draw_label('xlabel',xlab) self.draw_label('title',tit) if self.extra and extras: for e in self.extra: e.fig=self.fig e.ax=self.ax e.handles=self.handles if hasattr(self,'map'): e.map=self.map e.map_info_copy(self) print 'will plot extras...' e.plot(labels=False,isExtra=1) print e.config['1d.plot']