def run(): filepath = os.path.expanduser( "~/works/prgrms/pythondev/pySpectrumFileFormat/testData/test01.trc") traceFile = TraceFile(filepath) # for pulseID in range(1,1450,1): # header, times_ms, data = traceFile.readTrace(pulseID) # # maximum = max(data) # # if maximum > 1000.0: # print pulseID #traceFile.readHeader() #traceFile.printHeader() pulseID = 1 # First plot. dummy_header, times_ms, data = traceFile.readTrace(pulseID) dummy_line, = pylab.plot(times_ms, data) pylab.title("pulseID: %i" % (pulseID)) pylab.xlabel(r"Time (ms)") pylab.ylabel(r"Pulse height (mV)") def click(event): global pulseID if event.button == 1: pulseID += 1 elif event.button == 3: pulseID -= 1 if pulseID < 1: pulseID = 1 dummy_header, times_ms, data = traceFile.readTrace(pulseID) pylab.plot(times_ms, data, hold=False) # # update the data. # line.set_xdata(times_ms) # # line.set_ydata(data) # # redraw the canvas pylab.title("pulseID: %i" % (pulseID)) pylab.draw() #register this function with the event handler. pylab.connect('button_press_event', click) pylab.show()
def ms_cursor(self, index=None, block=True): if index: try: index = index if type(index) is int else self.energy.index( index) energy = index except ValueError: print( '{} is not an available energy\nTry one of these:'.format( index)) print(self.energy) return y = self.counts[index] else: y = self.counts_sum energy = '{}-{}'.format(self.energy[0], self.energy[-1]) x = self.ypts fig, ax = plt.subplots() c = SnaptoCursor(ax, x, y) connect('motion_notify_event', c.mouse_move) ax.plot(x, y, 'r') ax.set_xlabel('Point') ax.set_ylabel('Ion Count') ax.set_title('Mass Spectrum at {}eV'.format(energy)) plt.xlim(0, max(x)) plt.show(block=block)
def __init__(self, data, auto_mask, savedir): self.savedir = savedir self.fig = pylab.figure() self.ax = self.fig.add_subplot(111) self.ax.set_title('Select ROI to mask. Press \'m\' to mask, \'u\' to unmask or \'w\' to save and exit ') self.canvas = self.ax.figure.canvas #self.data = n.log10(data) self.data = data self.lx, self.ly = shape(self.data) self.mask = auto_mask self.masked_data = numpy.ma.masked_array(self.data,self.mask) self.points = [] self.key = [] self.x = 0 self.y = 0 self.xy = [] self.xx = [] self.yy = [] self.ind = 0 self.img = self.ax.imshow(self.masked_data,origin='lower',interpolation='nearest',animated=True) self.lc,=self.ax.plot((0,0),(0,0),'-+w',color='black',linewidth=1.5,markersize=8,markeredgewidth=1.5) self.lm,=self.ax.plot((0,0),(0,0),'-+w',color='black',linewidth=1.5,markersize=8,markeredgewidth=1.5) self.ax.set_xlim(0,self.lx) self.ax.set_ylim(0,self.ly) for i in range(self.lx): for j in range(self.ly): self.points.append([i,j]) cidb = pylab.connect('button_press_event', self.on_click) cidk = pylab.connect('key_press_event',self.on_click) cidm = pylab.connect('motion_notify_event',self.on_move)
def jpg_display(self): # Measure time t0 = time.time() print("Displaying... be patient", file=sys.stderr) # Display self.ax = pylab.figure(1, figsize=(12, 12)) #self.ax = pylab.figure(1,figsize=(9,9)) pylab.imshow(self.jpg_region) # Change ax to arcmin self.ax_to_arcmin(ds=2.0) pylab.xlabel("x[arcmin]") pylab.ylabel("y[arcmin]") pylab.title(self.ctile) nameA = self.ctile + "_figA.png" nameB = self.ctile + "_figB.png" self.figAname = os.path.join(self.datapath, self.ctile, nameA) self.figBname = os.path.join(self.datapath, self.ctile, nameB) pylab.savefig(self.figAname, transparent=True, dpi=100, bbox_inches='tight') print("Done in %s sec." % (time.time() - t0), file=sys.stderr) print("Wrote Fig A, %s " % (self.figAname), file=sys.stderr) # Draw the search zone self.draw_zone(n=8) # register this function with the event handler pylab.connect('button_press_event', self.get_object) pylab.show() return
def span_selector(img): """Program to choose ROI. Load 2D array img, plot it, and allow the user to draw a QUADRATIC ROI.""" fig, ax = plt.subplots() x_size, y_size = np.shape(img) x_from, x_to = int(3. / 8 * x_size), int(5. / 8 * x_size) y_from, y_to = int(3. / 8 * y_size), int(5. / 8 * y_size) medianROI = np.median(img[x_from:x_to, y_from:y_to]) stdROI = np.std(img[x_from:x_to, y_from:y_to]) ax.imshow(img, cmap=cm.gray, vmin=medianROI - 25 * stdROI, vmax=medianROI + 25 * stdROI) ax.set_title("Press left mouse button and drag to choose ROI") # Nota bene: This class is a variation of RectangleSelector. # With a constraint on only quadratic ROIs being possible. # See file classes.py for this class. toggle_selector.RS = QuadraticSelector(ax, onselect, drawtype="box", rectprops=dict(edgecolor='red', linewidth=3, fill=False)) connect('key_press_event', toggle_selector) show() # fig.close() return toggle_selector.RS.getQuad()
def initialMatch(self, maxDeltaMag=1.5): fig = pyl.figure('Full Image', figsize=(self.windowSize, self.windowSize)) sp = fig.add_subplot(111) implot = pyl.imshow(self._normer(self.imagedata)) implot.set_cmap('hot') #plot the catalog sources pyl.scatter(self._refSourcePix[:, 0], self._refSourcePix[:, 1], c='g', s=15) #pyl.scatter(self.imageSources[:,0]-1, self.imageSources[:,1]-1,c='b',alpha = 0.5) #plot the actual on image sources self.circles = [] for i in range(len(self.imageSources)): circle = Circle(self.imageSources[i, :2] - np.ones(2), 20, facecolor="none", edgecolor='b', linestyle='dashed', linewidth=2, alpha=0.75, zorder=10) sp.add_patch(circle) self.circles.append(circle) sp.invert_yaxis() sp.set_xlim(0, self.imagedata.shape[1]) sp.set_ylim(0, self.imagedata.shape[1]) pyl.connect('button_press_event', self._getStar) pyl.show()
def __init__(self, tree, size_method, color_method, string_method=str, iter_method=iter, margin=0.0): """create a tree map from tree, using itermethod(node) to walk tree, size_method(node) to get object size and color_method(node) to get its color. Optionally provide a string method called on a node to show which node has been clicked (default str) and a margin (proportion in [0,0.5)""" self.size_method = size_method self.iter_method = iter_method self.color_method = color_method self.string_method = string_method self.areas = {} self.margin = margin self.ax = pylab.subplot(111) pylab.subplots_adjust(left=0, right=1, top=1, bottom=0) self.addnode(tree) pylab.disconnect(pylab.get_current_fig_manager().toolbar._idDrag) pylab.connect('motion_notify_event', self.show_node_label) pylab.connect('button_press_event', self.zoom_selected)
def plot_box(x, y, nbins=10, c=None, s=None, label=None, info=None, alpha=1.0, marker='o', vmin=None, vmax=None, legend=True): # x, y, c, s = rand(4, 100) fig = figure() ax = fig.add_subplot(111) (hist, bins) = np.histogram(x, bins=nbins) ind = np.digitize(x, bins) data = [] positions = [] for i in range(1, nbins+1): y_slice = y[ind == i] if y_slice.size > 10: # y_mean = np.median(y_slice) # y_upper = np.percentile(y_slice, 75) # y_lower = np.percentile(y_slice, 25) # data.append((y_mean, y_mean, y_upper, y_lower)) data.append(y_slice) positions.append((bins[i-1] + bins[i])/2) if legend: ax.boxplot(data, positions=[round(p,2) for p in positions], widths=0.055) ax.set_xlim(0,0.5) else: scatter(x, y, 100*s, c, alpha=alpha, marker=marker, vmin=vmin, vmax=vmax, label='_nolegend_') #fig.savefig('pscoll.eps') if label is not None: af = AnnoteFinder(x, y, label, info=info) connect('button_press_event', af)
def plot(self, lat=0., lon=0., bigmap=False, ax=None, show=True, draw_countries=True, **kwargs): from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # lon_0, lat_0 are the center point of the projection. # resolution = 'l' means use low resolution coastlines. if bigmap: m = Basemap(projection='hammer', lon_0=lon, resolution='c', ax=ax) else: m = Basemap(projection='ortho', lon_0=lon, lat_0=lat, resolution='l', ax=ax) #m = Basemap(width=width,height=width,projection='aeqd', # lat_0=lat,lon_0=lon, resolution='l', ax=ax) if draw_countries: m.drawcountries(linewidth=0.5) m.drawcoastlines() m.drawmapboundary(fill_color='white') #m.drawmapboundary() m.fillcontinents(color='#D3D3D3', lake_color='#D3D3D3', zorder=0) # light gray # draw parallels and meridians. m.drawparallels(np.arange(-90., 120., 30.)) m.drawmeridians(np.arange(0., 390., 30.)) # , lat=0, lon=0, bigmap=False,circles=(30, 90), circles_around=None, lines=None, self.plot_(m, lat=lat, lon=lon, bigmap=bigmap, **kwargs) #plt.title('Full Disk Orthographic Projection') def on_press(event): global lat_press, lon_press lon_press, lat_press = m(event.xdata, event.ydata, 'inverse') print 'position press lat: %.2f lon: %.2f' % (lat_press, lon_press) def on_release(event): lon_release, lat_release = m(event.xdata, event.ydata, 'inverse') dist_km = gps2DistAzimuth(lat_press, lon_press, lat_release, lon_release)[0] / 1000. dist_degree = gps2DistDegree(lat_press, lon_press, lat_release, lon_release) if dist_km > 0.1: print 'position release lat: %.2f lon: %.2f' % (lat_release, lon_release) print 'Distance between points: %.2f degree or %.2f km' % ( dist_degree, dist_km) plt.connect('button_press_event', on_press) plt.connect('button_release_event', on_release) if show: plt.show()
def __init__(self, datatype, filenames, options): self.hfile = list() self.legend_text = list() for f in filenames: self.hfile.append(open(f, "r")) self.legend_text.append(f) self.block_length = options.block self.start = options.start self.sample_rate = options.sample_rate self.datatype = datatype if self.datatype is None: self.datatype = datatype_lookup[options.data_type] self.sizeof_data = self.datatype( ).nbytes # number of bytes per sample in file self.axis_font_size = 16 self.label_font_size = 18 self.title_font_size = 20 self.text_size = 22 # Setup PLOT self.fig = figure(1, figsize=(16, 9), facecolor='w') rcParams['xtick.labelsize'] = self.axis_font_size rcParams['ytick.labelsize'] = self.axis_font_size self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size) self.text_block = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length), weight="heavy", size=self.text_size) self.text_sr = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate), weight="heavy", size=self.text_size) self.make_plots() self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True) self.button_left = Button(self.button_left_axes, "<") self.button_left_callback = self.button_left.on_clicked( self.button_left_click) self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True) self.button_right = Button(self.button_right_axes, ">") self.button_right_callback = self.button_right.on_clicked( self.button_right_click) self.xlim = self.sp_f.get_xlim() self.manager = get_current_fig_manager() connect('key_press_event', self.click) show()
def logplot(self, show_sliceplots=True): from zoom_colorbar import zoom_colorbar x_min = self.params['x_min'] x_max = self.params['x_max'] y_min = self.params['y_min'] y_max = self.params['y_max'] self.show_data = zeros( (self.params['x_steps'], self.params['y_steps'])) self.minimum_intensity = inf for j in range(self.params['y_steps']): for i in range(self.params['x_steps']): avg = self.bin_data[i, j, 3] if avg > 0.0: self.show_data[i, j] = avg else: self.show_data[i, j] = 0.0 if (avg < self.minimum_intensity and avg > 0): self.minimum_intensity = avg #self.show_data = transpose(log(self.show_data + self.minimum_intensity / 2.0)) fig = figure() self.fig = fig connect('pick_event', self.log_lin_select) if show_sliceplots: ax = fig.add_subplot(221, label='qxqz_plot') fig.sx = fig.add_subplot(222, label='sx', picker=True) fig.sx.xaxis.set_picker(True) fig.sx.yaxis.set_picker(True) fig.sz = fig.add_subplot(223, label='sz', picker=True) fig.sz.xaxis.set_picker(True) fig.sz.yaxis.set_picker(True) self.RS = RectangleSelector(ax, self.onselect, drawtype='box', useblit=True) fig.slice_overlay = None else: ax = fig.add_subplot(111, label='qxqz_plot') fig.ax = ax ax.set_title(self.params['description']) connect('key_press_event', self.toggle_selector) transformed_show_data = transpose( log(self.show_data + self.minimum_intensity / 2.0)) im = ax.imshow(transformed_show_data, interpolation='nearest', aspect='auto', origin='lower', cmap=cm.jet, extent=(x_min, x_max, y_min, y_max)) fig.im = im ax.set_xlabel(self.xlabel) ax.set_ylabel(self.ylabel) zoom_colorbar(im) figure(fig.number) fig.canvas.draw() return im
def test(): x = range(10) y = range(10) annotes = ['a', 'b', 'c', 'd', 'GRB1010101', 'f', 'g', 'h', 'i', 'j'] scatter(x,y) af = AnnoteFinder(x,y, annotes) connect('button_press_event', af)
def graphWin(self, xLabel, yLabel, Title): xlabel(xLabel) ylabel(yLabel) title(Title) grid(True) connect('button_press_event', self.on_click) mng = pyplot.get_current_fig_manager() mng.window.showMaximized() show()
def labelindex(i,x,y,ax,display=False): if ax==None: ax=plt.gca() indexstrings = [str(ind) for ind in i] if display ==True: for i in zip(indexstrings,x,y): print i af = AnnoteFinder(x,y,indexstrings,axis=ax) pylab.connect('button_press_event', af) return
def labelindex(i, x, y, ax, display=False): if ax == None: ax = plt.gca() indexstrings = [str(ind) for ind in i] if display == True: for i in zip(indexstrings, x, y): print i af = AnnoteFinder(x, y, indexstrings, axis=ax) pylab.connect('button_press_event', af) return
def testcolor(): x = range(10) y = range(10) z = range(10) annotes = ['a', 'b', 'c', 'd', 'GRB1010101', 'f', 'g', 'h', 'i', 'j'] from Plotting import ColorScatter ColorScatter.ColorScatter(x,y,z,cmap='cool') af = AnnoteFinder(x,y, annotes) connect('button_press_event', af)
def __init__(self, data, auto_mask, savedir): '''The constructor initializes all the variables and creates the plotting window. **Input arguments:** - *data*: NxM array The background to be masked - an averaged (static) scattering image. - *auto_mask*: NxM array The default mask, masking all the bad pixels. - *savedir*: string Directory where the mask file will be saved. ''' self.mask_saved = False self.savedir = savedir self.fig = figure() title('Select ROI to mask. Press m to mask or w to save and exit ') self.ax = self.fig.add_subplot(111) # Check button for logscale switching self.cbax = self.fig.add_axes([0.01, 0.8, 0.1, 0.15]) self.cb_log = CheckButtons(self.cbax, ('log',), (False,)) self.cb_log.on_clicked(self.toggle_logscale) self.log_flag = False self.canvas = self.ax.figure.canvas #self.data = n.log10(data) self.raw_data = data.copy() self.data = data self.lx, self.ly = shape(self.data) self.auto_mask = auto_mask self.mask = auto_mask self.masked_data = n.ma.masked_array(self.data,self.mask) self.points = [] self.key = [] self.x = 0 self.y = 0 self.xy = [] self.xx = [] self.yy = [] self.ind = 0 self.img = self.ax.imshow(self.masked_data,origin='lower',interpolation='nearest',animated=True) self.colorbar = colorbar(self.img,ax=self.ax) self.lc,=self.ax.plot((0,0),(0,0),'-+w',color='black',linewidth=1.5,markersize=8,markeredgewidth=1.5) self.lm,=self.ax.plot((0,0),(0,0),'-+w',color='black',linewidth=1.5,markersize=8,markeredgewidth=1.5) self.ax.set_xlim(0,self.lx) self.ax.set_ylim(0,self.ly) for i in range(self.lx): for j in range(self.ly): self.points.append([i,j]) cidb = connect('button_press_event', self.on_click) cidk = connect('key_press_event',self.on_click) cidm = connect('motion_notify_event',self.on_move)
def main(): parser = argparse.ArgumentParser(description='') parser.add_argument('--MC','-Q', help='Quantum training file', nargs='+') parser.add_argument('--ED','-C', help='Classical training file', nargs='+') parser.add_argument('--clamped', help='Clamped simulation', default=False, action='store_true') args = vars(parser.parse_args()) if 'MC' in args.keys(): skip = 3 # skip estimators we don't care about for filename in args['MC']: fparams = ssexyhelp.getReduceParamMap(filename) data = np.loadtxt(filename) headers = Hfile.getHeaders(filename) if not(args['clamped']): (first, last) = (headers.index('X0'), headers.index('sX0')) else: (first, last) = (headers.index('sX0'), len(headers)) aves = np.zeros(last-first) stds = np.zeros(last-first) for i, c in enumerate(range(first, last)): cdata = data[~np.isnan(data[:,c]),c] aves[i] = np.mean(cdata) stds[i] = np.amax(MCstat.bin(cdata[np.newaxis].T)) if 'ED' in args.keys(): for filename in args['ED']: fparams = ssexyhelp.getReduceParamMap(filename) ED = np.loadtxt(filename) print ED print aves print stds colors = ["#66CAAE", "#CF6BDD", "#E27844", "#7ACF57", "#92A1D6", "#E17597", "#C1B546"] fig = pl.figure(1, figsize=(10,5)) pl.connect('key_press_event',kevent.press) ax = pl.subplot(111) ax.plot((ED-aves)/stds, color=colors[0])#, lw=2, m='o', ls='')#, label=r'$data$') pl.ylabel(r'$(ED-MC)/\Delta_{MC}$') pl.xlabel(r'$Averages$') lgd = pl.legend(loc = 'best') lheaders = [] for head in Hfile.getHeaders(args['ED'][0]): lheaders += [r'$%s$' %head] pl.xticks(range(len(lheaders)), lheaders, rotation='vertical') #lgd.draggable(state=True) #lgd.draw_frame(False) pl.tight_layout() pl.show()
def __init__(self, ax, cursor='vertical'): # cursor can be vertical, horizontal or cross self.ax = ax self.lx = None; self.ly = None self.cursor = cursor if cursor != 'vertical': self.lx = ax.axhline(color='k') # the horiz line if cursor != 'horizontal': self.ly = ax.axvline(color='k') # the vert line pylab.connect('motion_notify_event', self.mouse_move) pylab.connect('button_press_event', self.mouse_click)
def plot_scatter(x, y, c=None, s=None, label=None, info=None, alpha=1.0, marker='o', vmin=None, vmax=None, legend=True): # x, y, c, s = rand(4, 100) if legend: scatter(x, y, 100*s, c, alpha=alpha, marker=marker, vmin=vmin, vmax=vmax) else: scatter(x, y, 100*s, c, alpha=alpha, marker=marker, vmin=vmin, vmax=vmax, label='_nolegend_') #fig.savefig('pscoll.eps') if label is not None: af = AnnoteFinder(x, y, label, info=info) connect('button_press_event', af)
def __init__(self, ax, cursor='vertical'): # cursor can be vertical, horizontal or cross self.ax = ax self.lx = None self.ly = None self.cursor = cursor if cursor != 'vertical': self.lx = ax.axhline(color='k') # the horiz line if cursor != 'horizontal': self.ly = ax.axvline(color='k') # the vert line pylab.connect('motion_notify_event', self.mouse_move) pylab.connect('button_press_event', self.mouse_click)
def main(): parser = argparse.ArgumentParser(description='') parser.add_argument('--quant', '-Q', help='Quantum training file', nargs='+') parser.add_argument('--class', '-C', help='Classical training file', nargs='+') args = vars(parser.parse_args()) colors = ["#66CAAE", "#CF6BDD", "#E27844", "#7ACF57", "#92A1D6", "#E17597", "#C1B546"] #fig = pl.figure(1, figsize=(10,5)) f, (ax1, ax2) = pl.subplots(2) pl.connect('key_press_event',kevent.press) # ---------------------------------------------------------------------- cdata = {} for filename in args['class']: data = np.loadtxt(filename) LL = np.amin(data[1:,0]) seed = int(filename[:-4].split('_')[-1]) cdata[seed] = LL # ---------------------------------------------------------------------- qdata = {} for filename in args['quant']: data = np.loadtxt(filename) LL = np.amin(data[1:,0]) seed = int(filename[:-4].split('_')[-1]) qdata[seed] = LL # ---------------------------------------------------------------------- cLL = [] qLL = [] for cseed in cdata.keys(): if cseed in qdata.keys(): cLL += [cdata[cseed]] qLL += [qdata[cseed]] cLL = np.array(cLL) qLL = np.array(qLL) ax1.scatter(cLL, qLL) ax1.set_xlabel(r'$LL_{class}$') ax1.set_ylabel(r'$LL_{quant}$') ax2.scatter(cLL, cLL-qLL) ax2.set_xlabel(r'$Classical \, LL$') ax2.set_ylabel(r'$LL_{class} - LL_{quant}$') #lgd = pl.legend(loc = 'best') #lgd.draggable(state=True) #lgd.draw_frame(False) pl.tight_layout() pl.show()
def __init__(self, datatype, filename, options): self.hfile = open(filename, "r") self.block_length = options.block self.start = options.start self.sample_rate = options.sample_rate self.psdfftsize = options.psd_size self.specfftsize = options.spec_size self.dospec = options.enable_spec # if we want to plot the spectrogram self.datatype = datatype if self.datatype is None: self.datatype = datatype_lookup[options.data_type] self.sizeof_data = self.datatype().nbytes # number of bytes per sample in file self.axis_font_size = 16 self.label_font_size = 18 self.title_font_size = 20 self.text_size = 22 # Setup PLOT self.fig = figure(1, figsize=(16, 12), facecolor='w') rcParams['xtick.labelsize'] = self.axis_font_size rcParams['ytick.labelsize'] = self.axis_font_size self.text_file = figtext(0.10, 0.95, ("File: %s" % filename), weight="heavy", size=self.text_size) self.text_file_pos = figtext(0.10, 0.92, "File Position: ", weight="heavy", size=self.text_size) self.text_block = figtext(0.35, 0.92, ("Block Size: %d" % self.block_length), weight="heavy", size=self.text_size) self.text_sr = figtext(0.60, 0.915, ("Sample Rate: %.2f" % self.sample_rate), weight="heavy", size=self.text_size) self.make_plots() self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True) self.button_left = Button(self.button_left_axes, "<") self.button_left_callback = self.button_left.on_clicked(self.button_left_click) self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True) self.button_right = Button(self.button_right_axes, ">") self.button_right_callback = self.button_right.on_clicked(self.button_right_click) self.xlim = numpy.array(self.sp_iq.get_xlim()) self.manager = get_current_fig_manager() connect('draw_event', self.zoom) connect('key_press_event', self.click) show()
def logplot(self, show_sliceplots=True): from zoom_colorbar import zoom_colorbar x_min = self.params['x_min'] x_max = self.params['x_max'] y_min = self.params['y_min'] y_max = self.params['y_max'] self.show_data = zeros((self.params['x_steps'],self.params['y_steps'])) self.minimum_intensity = inf for j in range(self.params['y_steps']): for i in range(self.params['x_steps']): avg = self.bin_data[i,j,3] if avg > 0.0: self.show_data[i,j] = avg else: self.show_data[i,j] = 0.0 if (avg < self.minimum_intensity and avg > 0): self.minimum_intensity = avg #self.show_data = transpose(log(self.show_data + self.minimum_intensity / 2.0)) fig = figure() self.fig = fig connect('pick_event', self.log_lin_select) if show_sliceplots: ax = fig.add_subplot(221, label='qxqz_plot') fig.sx = fig.add_subplot(222, label='sx', picker=True) fig.sx.xaxis.set_picker(True) fig.sx.yaxis.set_picker(True) fig.sz = fig.add_subplot(223, label='sz', picker=True) fig.sz.xaxis.set_picker(True) fig.sz.yaxis.set_picker(True) self.RS = RectangleSelector(ax, self.onselect, drawtype='box', useblit=True) fig.slice_overlay = None else: ax = fig.add_subplot(111, label='qxqz_plot') fig.ax = ax ax.set_title(self.params['description']) connect('key_press_event', self.toggle_selector) transformed_show_data = transpose(log(self.show_data + self.minimum_intensity / 2.0)) im = ax.imshow(transformed_show_data, interpolation='nearest', aspect='auto', origin='lower',cmap=cm.jet, extent=(x_min,x_max,y_min,y_max)) fig.im = im ax.set_xlabel(self.xlabel) ax.set_ylabel(self.ylabel) zoom_colorbar(im) figure(fig.number) fig.canvas.draw() return im
def __call__(self, n=1, timeout=30, debug=False): """ Blocking call to retrieve n coordinate pairs through mouse clicks. """ # just for printing the coordinates self.debug = debug # make sure the user isn't messing with us assert isinstance(n, int), "Requires an integer argument" # connect the click events to the on_click function call self.cid = _pylab.connect('button_press_event', self.on_click) # initialize the list of click coordinates self.clicks = [] # wait for n clicks counter = 0 while len(self.clicks) < n: # key step: yield the processor to other threads _wx.Yield(); # rest for a moment _time.sleep(0.1) # check for a timeout counter += 1 if counter > timeout/0.1: print "ginput timeout"; break; # All done! Disconnect the event and return what we have _pylab.disconnect(self.cid) self.cid = None return self.clicks
def createInteractivePlot(screen, refs, rho): global ip_refs, ip_xray, ip_rho, ip_rx, ip_ry ip_refs = refs ip_xray = screen ip_rho = rho ip_rx, ip_ry = [0],[0] ip_rx[-1] = (1550/FF,2040/FF) ip_ry[-1] = (1550/FF,2040/FF) ip_fig = pl.figure(figsize=(0.7*5.12*2, 0.7*6.12*1)) ip_fxray = pl.subplot(121) ip_freal = pl.subplot(122) ip_toggle_selector.RS = RectangleSelector(ip_fxray,line_select_callback,drawtype='box',useblit=True, button=[1,3]) pl.connect('key_press_event', ip_toggle_selector) update_plot()
def __init__(self, datatype, filenames, options): self.hfile = list() self.legend_text = list() for f in filenames: self.hfile.append(open(f, "r")) self.legend_text.append(f) self.block_length = options.block self.start = options.start self.sample_rate = options.sample_rate self.datatype = datatype if self.datatype is None: self.datatype = datatype_lookup[options.data_type] self.sizeof_data = self.datatype().nbytes # number of bytes per sample in file self.axis_font_size = 16 self.label_font_size = 18 self.title_font_size = 20 self.text_size = 22 # Setup PLOT self.fig = figure(1, figsize=(16, 9), facecolor='w') rcParams['xtick.labelsize'] = self.axis_font_size rcParams['ytick.labelsize'] = self.axis_font_size self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size) self.text_block = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length), weight="heavy", size=self.text_size) self.text_sr = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate), weight="heavy", size=self.text_size) self.make_plots() self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True) self.button_left = Button(self.button_left_axes, "<") self.button_left_callback = self.button_left.on_clicked(self.button_left_click) self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True) self.button_right = Button(self.button_right_axes, ">") self.button_right_callback = self.button_right.on_clicked(self.button_right_click) self.xlim = self.sp_f.get_xlim() self.manager = get_current_fig_manager() connect('key_press_event', self.click) show()
def ScatterPSF(self, event): """ Display function that you shouldn't call directly. """ ca = pyl.gca() if event is not None: me = event.mouseevent if self.starsScat != None: self.starsScat.remove() self.starsScat = None npoints = len(self.points[:, 0]) showingbool = np.array(self.showing).astype(np.bool) pointsshowing = self.points[showingbool, :] ranks = np.zeros(len(pointsshowing[:, 0])) if event is not None: args = np.argsort(np.abs(me.xdata - pointsshowing[:, 0])) else: args = np.argsort(np.abs(0.0 - pointsshowing[:, 0])) for ii in range(len(args)): ranks[args[ii]] += ii if event is not None: args = np.argsort(np.abs(me.ydata - pointsshowing[:, 1])) else: args = np.argsort(np.abs(0.0 - pointsshowing[:, 1])) for ii in range(len(args)): ranks[args[ii]] += ii args = np.arange(npoints)[showingbool] self.selected_star = np.argmin(ranks[np.argsort(pointsshowing[:, 0])]) arg = args[np.argsort(pointsshowing[:, 0])[self.selected_star]] self.starsScat = self.sp4.scatter(self.starsFlatR[arg], self.starsFlatF[arg], facecolor='none', edgecolor='b', zorder=10) self.sp4.set_xlim(0, self.moffatWidth) self.sp4.set_ylim(0, 1.02) self.sp5.imshow(self.subsecs[arg]) #self.sp5.set_xlabel("x,y = {:.1f}, {:.1f}".format(self.points[:, 4][arg],self.points[:, 5][arg])) self.ScatterPSFCommon(arg) if event is not None: if me.button == 3: self.goodStars[arg] = not self.goodStars[arg] self.ScatterPSFCommon(arg) self.conn1 = self.sp1.callbacks.connect('ylim_changed', self.PSFrange) self.conn3 = pyl.connect('key_press_event', self.ScatterPSF_keys) ## The above two lines need to be here again. ## This allows for zooming/inspecting in whatever order, over & over. pyl.sca(ca) pyl.draw()
def PSFrange(self, junkAx): """ Display function that you shouldn't call directly. """ #ca=pyl.gca() pyl.sca(self.sp1) newLim = [self.sp1.get_xlim(), self.sp1.get_ylim()] self.psfPlotLimits = newLim[:] w = np.where((self.points[:, 0] >= self.psfPlotLimits[0][0]) & (self.points[:, 0] <= self.psfPlotLimits[0][1]) & (self.points[:, 1] >= self.psfPlotLimits[1][0]) & (self.points[:, 1] <= self.psfPlotLimits[1][1]))[0] if self.starsScat != None: self.starsScat.remove() self.starsScat = None for ii in range(len(self.showing)): if self.showing[ii]: self.moffPatchList[ii][0].remove() for ii in range(len(self.showing)): if ii not in w: self.showing[ii] = 0 else: self.showing[ii] = 1 for ii in range(len(self.showing)): if self.showing[ii]: self.moffPatchList[ii] = self.sp4.plot(self.moffr, self.moffs[ii]) x_lim_max = np.max(self.moffr) + 1 self.sp4.set_xlim(0, self.moffatWidth) self.sp4.set_ylim(0, 1.02) self.conn2 = pyl.connect('pick_event', self.ScatterPSF) self.conn3 = pyl.connect('key_press_event', self.ScatterPSF_keys) self._fwhm_lim = self.sp1.get_xlim() self._chi_lim = self.sp1.get_ylim() ## The above two lines need to be here again. ## This allows for zooming/inspecting in whatever order, over & over. pyl.draw()
def plot(self, lat=0., lon=0., bigmap=False, ax=None, show=True, draw_countries=True, **kwargs): from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # lon_0, lat_0 are the center point of the projection. # resolution = 'l' means use low resolution coastlines. if bigmap: m = Basemap(projection='hammer', lon_0=lon, resolution='c', ax=ax) else: m = Basemap(projection='ortho', lon_0=lon, lat_0=lat, resolution='l', ax=ax) #m = Basemap(width=width,height=width,projection='aeqd', # lat_0=lat,lon_0=lon, resolution='l', ax=ax) if draw_countries: m.drawcountries(linewidth=0.5) m.drawcoastlines() m.drawmapboundary(fill_color='white') #m.drawmapboundary() m.fillcontinents(color='#D3D3D3', lake_color='#D3D3D3', zorder=0) # light gray # draw parallels and meridians. m.drawparallels(np.arange(-90., 120., 30.)) m.drawmeridians(np.arange(0., 390., 30.)) # , lat=0, lon=0, bigmap=False,circles=(30, 90), circles_around=None, lines=None, self.plot_(m, lat=lat, lon=lon, bigmap=bigmap, **kwargs) #plt.title('Full Disk Orthographic Projection') def on_press(event): global lat_press, lon_press lon_press, lat_press = m(event.xdata, event.ydata, 'inverse') print 'position press lat: %.2f lon: %.2f' % (lat_press, lon_press) def on_release(event): lon_release, lat_release = m(event.xdata, event.ydata, 'inverse') dist_km = gps2DistAzimuth(lat_press, lon_press, lat_release, lon_release)[0] / 1000. dist_degree = gps2DistDegree(lat_press, lon_press, lat_release, lon_release) if dist_km > 0.1: print 'position release lat: %.2f lon: %.2f' % (lat_release, lon_release) print 'Distance between points: %.2f degree or %.2f km' % (dist_degree, dist_km) plt.connect('button_press_event', on_press) plt.connect('button_release_event', on_release) if show: plt.show()
def __init__(self, img): imshape = img.shape self.figure = P.imshow(img, extent=(0,imshape[1],imshape[0],0)) P.title('Removal of radial distortion') P.xlabel('Select sets of three points with left mouse button,\nclick right button to process.') P.connect('button_press_event', self.button_press) P.connect('motion_notify_event', self.mouse_move) self.img = N.atleast_3d(img) self.points = [] self.centre = ((N.array(self.img.shape)-1)/2.)[:2][::-1] self.height = imshape[0] self.width = imshape[1] self.make_cursorline() self.figure.axes.set_autoscale_on(False) P.show() P.close()
def main(): # setup the command line parser options parser = argparse.ArgumentParser(description='') parser.add_argument('filenames', help='Training output files', nargs='+') args = parser.parse_args() filenames = args.filenames pl.connect('key_press_event',kevent.press) ddata = {} for filename in filenames: rdata = np.loadtxt(filename) if len(rdata.shape)> 1: pindex = (-1,0) else: pindex = (0) #(nr, nc) = rdata.shape fparams = ssexyhelp.getReduceParamMap(filename) (alpha, Ns, beta, delta) = (fparams['alpha'], fparams['N'] , fparams['b'], fparams['delta']) seed = int(findKbV(fparams, '')) if not(delta in ddata.keys()): ddata[delta] = np.zeros(30) else: ddata[delta][seed] = rdata[pindex] fig = pl.figure(1, figsize=(13,6)) ax = pl.subplot(111) colors = ["#66CAAE", "#CF6BDD", "#E27844", "#7ACF57", "#92A1D6", "#E17597", "#C1B546",'b'] i = 0 for delta, data in ddata.iteritems(): ax.plot(range(len(data)), data, color=colors[i], lw=3, ls='-', label = r'$\Delta = %0.2f$' %delta) i += 1 pl.xlabel('Instance') pl.ylabel('LL') pl.legend(loc = 'best') pl.title(r'$\beta=%0.2f \, \alpha=%0.2f $' %(beta, alpha), fontsize = 20) pl.tight_layout() pl.show()
def plot(objVectors, centroidIDs, clusterIDs, generation, run, params): """ plots 'objVectors' and emphasizes the solutions indicated by 'centroidIDs'. In case of 2 objectives, the clusters, given by clusterIDs, are plotted by connecting every point with the centroid of its cluster as well. The return parameter is an objective of type 'onClick' which allows to later on ask which objective vector the user has picked. """ if (len(objVectors > 0)) and (len(objVectors[0, :]) == 2): # plot all points h, = plt.plot(objVectors[:, 0], objVectors[:, 1], 'x') # plot centroids differently plt.plot(objVectors[centroidIDs, 0], objVectors[centroidIDs, 1], 'o' + plt.get(h, 'color')) s = plt.axis() # get size of plot for annotations # plot the centroids's ids as well for i in centroidIDs: plt.text(objVectors[i, 0] + (0.1 / (s[1] - s[0])), objVectors[i, 1] + (0.1 / (s[3] - s[2])), i, color=plt.get(h, 'color')) # connect all points with the centroids of their cluster for i in range(len(objVectors[:, 0])): x = [objVectors[i, 0], objVectors[centroidIDs[clusterIDs[i]], 0]] y = [objVectors[i, 1], objVectors[centroidIDs[clusterIDs[i]], 1]] plt.plot(x, y, ':' + plt.get(h, 'color'), linewidth=0.25) beautify2DPlot(generation, run) # allow for interactive clicking: if params.interaction == 1: # 1) add possibility to get objective vector and ids by clicking right: #annotes = range(len(objVectors)) #af = AnnoteFinder.AnnoteFinder(objVectors[:,0],objVectors[:,1], annotes) #connect('button_press_event', af) # 2) choose best solution by clicking left: oc = onClick.onClick(objVectors) connect('button_press_event', oc) return oc else: parallelCoordinatesPlot(objVectors, generation, run, params) # allow for interactive clicking: if params.interaction == 1: # 1) add possibility to get objective vector and ids by clicking right: annotes = range(len(objVectors)) af = AnnoteFinder.AnnoteFinder(objVectors[:, 0], objVectors[:, 1], annotes) connect('button_press_event', af) # 2) choose best solution by clicking left: oc = onClick.onClick(objVectors) connect('button_press_event', oc) return oc
def three_point_test(): import collections points = collections.deque(maxlen=3) def add_point(event): x, y = event.xdata, event.ydata points.append((x, y)) pylab.cla() pylab.scatter(*zip(*points)) pylab.xlim(-10, 10) pylab.ylim(-10, 10) pylab.draw() if len(points) < 3: return c, r = three_point_circle(*points) cir = pylab.Circle(c, r) pylab.gca().add_patch(cir) for p in points: angle = angle_at_point(c, p) if angle < 0: angle += 2*np.pi if angle >= np.pi: angle = angle - np.pi print np.degrees(angle) dx, dy = np.array((np.cos(angle), np.sin(angle))) pylab.text(p[0], p[1], "%.2f"%np.degrees(angle)) pylab.arrow(p[0], p[1], dx, dy) pylab.show() #pylab.scatter(*zip(a, b, c)) #c, r = three_point_circle(a, b, c) #print c, r pylab.xlim(-10, 10) pylab.ylim(-10, 10) pylab.connect('button_release_event', add_point) pylab.show()
def display(data=None, orient='LPS', overlay=None, colormap=cm.gray, pixdim=None): "mri=img.decimate(nim, 5)" "ex. slice.plot(mri)" import sys print sys.argv if data == None: try: fn=sys.argv[1] from mri import img data = img.read(fn) except AttributeError: print 'not passing data arg' print('lets plot random data') from numpy import random data = random.randn(10,10,10) try: data.qform print 'think its a nifti volume' nim = data mrdata = nim.data print shape(mrdata) pixdim = nim.voxdim[::-1] except AttributeError: if pixdim != None: print 'using user supplied pixeldimensions', pixdim else: print 'probably not a nifti volume. using voxel units instead of actual distance units' pixdim = [1.0,1.0,1.0]; #unitless mrdata = data fig = figure() subplots_adjust(left=.15, bottom=.15,right=1, top=.95,wspace=.25, hspace=.35) ax1 = fig.add_subplot(221);#axis('off') #colorbar(fig,ax=ax1) xlabel('Anterior (A->P 1st Dim)');ylabel('Right (R->L 2nd Dim)') ax2 = fig.add_subplot(222);#axis('off') xlabel('Inferior (I->S Dim)');ylabel('Anterior (A->P 1st Dim)') ax3 = fig.add_subplot(223);#axis('off') xlabel('Infererior (I->S 3rd dim)');ylabel('Right (R->L 2nd Dim)') coord = fig.add_subplot(224);axis('off') tracker = IndexTracker(mrdata, ax1, ax2, ax3, colormap, pixdim, overlay, coord) fig.canvas.mpl_connect('scroll_event', tracker.onscroll) cid = connect('button_press_event', tracker.click) show() return tracker
def change_colormap(image): ''' takes matplotlib.image.AxesImage instance as argument, then displays a plot of all colormaps in cm module. Click on one to change the image colormap to the selection ''' ioff() rc('text', usetex=False) a=outer(arange(0,1,0.01),ones(10)) fig = figure(figsize=(10,5)) subplots_adjust(top=0.8,bottom=0.05,left=0.01,right=0.99) maps=[m for m in cm.datad.keys() if not m.endswith("_r")] maps.sort() l=len(maps)+1 i=1 for m in maps: subplot(1,l,i) axis("off") imshow(a,aspect='auto',cmap=get_cmap(m),origin="lower") title(m,rotation=90,fontsize=10) i=i+1 def clicker(event): if event.inaxes: cname = event.inaxes.title.get_text() print cname image.set_cmap(get_cmap(cname)) fignum = image.figure.number fig = figure(fignum) show() draw() return connect('button_press_event',clicker) show() draw() ion() return
def Initialize(self): """ Load and display bitmap figure, and start data collection process. """ #Load and show data plot im = imread(self.ImageFile) imshow(flipud(im), origin="lower") self.EventId = connect("button_press_event", self.GetPosition) #Get toolbar handle self.ToolBar = get_current_fig_manager().toolbar print "First click on (x_min, y_min), then (x_min, y_max) and finally (x_max, y_min). This is used for calibration. Then click on all the datapoints. Right click when finished."
def change_colormap(image): ''' takes matplotlib.image.AxesImage instance as argument, then displays a plot of all colormaps in cm module. Click on one to change the image colormap to the selection ''' ioff() rc('text', usetex=False) a = outer(arange(0, 1, 0.01), ones(10)) fig = figure(figsize=(10, 5)) subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99) maps = [m for m in cm.datad.keys() if not m.endswith("_r")] maps.sort() l = len(maps) + 1 i = 1 for m in maps: subplot(1, l, i) axis("off") imshow(a, aspect='auto', cmap=get_cmap(m), origin="lower") title(m, rotation=90, fontsize=10) i = i + 1 def clicker(event): if event.inaxes: cname = event.inaxes.title.get_text() print cname image.set_cmap(get_cmap(cname)) fignum = image.figure.number fig = figure(fignum) show() draw() return connect('button_press_event', clicker) show() draw() ion() return
def __init__(self, norder = 2): """Initializes the class when returning an instance. Pass it the polynomial order. It will set up two figure windows, one for the graph the other for the coefficent interface. It will then initialize the coefficients to zero and plot the (not so interesting) polynomial.""" self.order = norder self.c = M.zeros(self.order,'f') self.ax = [None]*(self.order-1)#M.zeros(self.order-1,'i') #Coefficent axes self.ffig = M.figure() #The first figure window has the plot self.replotf() self.cfig = M.figure() #The second figure window has the row = M.ceil(M.sqrt(self.order-1)) for n in xrange(self.order-1): self.ax[n] = M.subplot(row, row, n+1) M.setp(self.ax[n],'label', n) M.plot([0],[0],'.') M.axis([-1, 1, -1, 1]); self.replotc() M.connect('button_press_event', self.click_event)
def click(event): """ Handle mouse click in the main matplotlib overview window, opens single monitor window called from: display input: event structure output: None """ from pylab import get_current_fig_manager,get,gcf,figure,clf,connect,show tb = get_current_fig_manager().toolbar if event.button==1 and event.inaxes and tb.mode == '': g = event.inaxes # Determine number of clicked axis ax = get(gcf(),'axes') jused = 0 for j in range(0, len(FSlist)): FS = FSlist[j] if g==FS['axes']: h=figure() clf() FS=display_single(FS) connect('key_press_event', keypress) jused = j FSlist[jused]['axes']=g show()
def plot(objVectors, centroidIDs, clusterIDs, generation, run, params): """ plots 'objVectors' and emphasizes the solutions indicated by 'centroidIDs'. In case of 2 objectives, the clusters, given by clusterIDs, are plotted by connecting every point with the centroid of its cluster as well. The return parameter is an objective of type 'onClick' which allows to later on ask which objective vector the user has picked. """ if (len(objVectors > 0)) and (len(objVectors[0,:]) == 2): # plot all points h, = plt.plot(objVectors[:,0],objVectors[:,1], 'x') # plot centroids differently plt.plot(objVectors[centroidIDs,0], objVectors[centroidIDs, 1], 'o' + plt.get(h, 'color')) s = plt.axis() # get size of plot for annotations # plot the centroids's ids as well for i in centroidIDs: plt.text(objVectors[i,0] + (0.1/(s[1]-s[0])), objVectors[i,1] + (0.1/(s[3]-s[2])), i, color=plt.get(h, 'color')) # connect all points with the centroids of their cluster for i in range(len(objVectors[:,0])): x = [objVectors[i,0], objVectors[centroidIDs[clusterIDs[i]],0]] y = [objVectors[i,1], objVectors[centroidIDs[clusterIDs[i]],1]] plt.plot(x, y, ':' + plt.get(h, 'color'), linewidth=0.25) beautify2DPlot(generation, run) # allow for interactive clicking: if params.interaction == 1: # 1) add possibility to get objective vector and ids by clicking right: #annotes = range(len(objVectors)) #af = AnnoteFinder.AnnoteFinder(objVectors[:,0],objVectors[:,1], annotes) #connect('button_press_event', af) # 2) choose best solution by clicking left: oc = onClick.onClick(objVectors) connect('button_press_event', oc) return oc else: parallelCoordinatesPlot(objVectors, generation, run, params) # allow for interactive clicking: if params.interaction == 1: # 1) add possibility to get objective vector and ids by clicking right: annotes = range(len(objVectors)) af = AnnoteFinder.AnnoteFinder(objVectors[:,0],objVectors[:,1], annotes) connect('button_press_event', af) # 2) choose best solution by clicking left: oc = onClick.onClick(objVectors) connect('button_press_event', oc) return oc
def __init__(self, norder=2): """Initializes the class when returning an instance. Pass it the polynomial order. It will set up two figure windows, one for the graph the other for the coefficent interface. It will then initialize the coefficients to zero and plot the (not so interesting) polynomial.""" self.order = norder self.c = M.zeros(self.order, 'f') self.ax = [None] * (self.order - 1 ) #M.zeros(self.order-1,'i') #Coefficent axes self.ffig = M.figure() #The first figure window has the plot self.replotf() self.cfig = M.figure() #The second figure window has the row = M.ceil(M.sqrt(self.order - 1)) for n in xrange(self.order - 1): self.ax[n] = M.subplot(row, row, n + 1) M.setp(self.ax[n], 'label', n) M.plot([0], [0], '.') M.axis([-1, 1, -1, 1]) self.replotc() M.connect('button_press_event', self.click_event)
def spectrum_cursor_on(self, print_flag=True): """ Turn on cursor binding. When set, a click on button 2 print the x and y cursor values (if the print_flag is set), and append them in the field curs_val of the spectrum. This field is a list of 2 elements lists. It is turned off using cursor_off """ def click(event): if event.button == 2: self.curs_val.append([event.xdata, event.ydata]) if print_flag: print 'x = %e y = %e' % (event.xdata, event.ydata) if self.cid is not None: self.cursor_off() self.cid = pylab.connect('button_press_event', click)
def plot_map(self): """ Method does the plotting of the map of the circuit note: master file should have the following text in it Buscoords buscoords.dss, where buscoords.dss contains the x and y coordinates for each bus to be plotted :return: """ fig = pyl.figure() # get x and y coordinates of the branch to be drawn # the branch is a line so it is defined with pairs of # from and to coordinates x1 = self.branch.x y1 = self.branch.y x2 = self.branch.xto y2 = self.branch.yto pyl.axes().set_aspect('equal', 'datalim') # don't want to see any ticks on the x-axis or the y-axis pyl.xticks([]) pyl.yticks([]) # set the limits of the map plot pyl.xlim(x1.min(), x1.max()) pyl.ylim(y1.min(), y1.max()) # take the from x and y coordinates and the to x and y coordinates # and put them together (zip) as a python sequence object segments = [ ( (thisx1, thisy1), (thisx2, thisy2) ) for thisx1, thisy1, thisx2, thisy2 in zip(x1,y1,x2,y2)] # make a LineCollection of the segments, with width indicating the number # of phases line_segments = LineCollection(segments, linewidths = self.branch.nphases*1.5, linestyle = 'solid', picker = 5) pyl.gca().add_collection(line_segments) # setup the pick events to highlight the voltage plot, circuit map, # and to display the branch info in the text box # note: a pick event is usually a mouse click within a certain radius # of the actual points on the plots pyl.connect('pick_event', self.highlight_voltage_plot) pyl.connect('pick_event', self.highlight_map) pyl.connect('pick_event', self.print_branch_info) self.mapfig = fig # plot a yellow circle at the 'to' bus of the line segment if clicked on with # the mouse self.mapselected, = pyl.plot([x2[0]], [y2[0]], 'o', ms=12, alpha=0.4, color='yellow', visible=False)
def plot_voltage(self): fig = py.figure() def t(x): return x.transpose() #scale factor gets us to 120V from the kvbase which is set in the .dss file scalefactor = 1 / self.branch.kvbase * 120 / 1000 x = self.branch.distance y = t(t(abs(self.branch.Vto)) * scalefactor) py.plot(x, y, '*', markersize=5, picker=5) # the following code will scale the size dot by the number of phases # it's nice, but it makes the code slow # size = (self.branch.nphases + 1) ** 2 # scatter(self.branch.distance, abs(self.branch.Vto[:,0]), s = size, c = 'r', picker=5) # scatter(self.branch.distance, abs(self.branch.Vto[:,1]), s = size, c = 'g', picker=5) # scatter(self.branch.distance, abs(self.branch.Vto[:,2]), s = size, c = 'b', picker=5) # setup the pick events to highlight the voltage plot, circuit map, # and to display the branch info in the text box # note: a pick event is usually a mouse click within a certain radius # of the actual points on the plots # note: all three methods get called on any pick event py.connect('pick_event', self.highlight_voltage_plot) py.connect('pick_event', self.highlight_map) py.connect('pick_event', self.print_branch_info) self.fig = fig self.selected, = py.plot(x[0:3], y[0], 'o', ms=12, alpha=0.7, color='yellow', visible=False) ax = fig.add_subplot(111) ax.set_xticklabels([]) ax.set_xlabel('distance') ax.set_ylabel('Voltage (120V base)') ax.set_title('Primary Voltages by phase') for o in fig.findobj(text.Text): o.set_fontsize(18) # set the limits (x and y) of the plot to contain all of the points py.xlim(x[x > 0].min(), x.max()) py.ylim(y[y > 0].min(), y.max())
def generatePlots(self, fig): """ a method that generates cyclone origin plots """ pylab.figure(fig.getNum()) self.p.plotOrigin() fig.next() pylab.connect('button_press_event', self.on_click) pylab.figure(fig.getNum()) self.p.plotOriginCounts() fig.next() pylab.connect('button_press_event', self.on_click) pylab.figure(fig.getNum()) self.p.plotOriginCells() fig.next() pylab.connect('button_press_event', self.on_click) pylab.figure(fig.getNum()) self.p.plotOriginCellsHist() fig.next() self.cellFigNo = fig.getNum() fig.next() self.p.plot3DOriginCounts()
#get and print estimated means and covariances est_mean1=est_gmm.get_nth_mean(0) est_mean2=est_gmm.get_nth_mean(1) est_mean3=est_gmm.get_nth_mean(2) est_cov1=est_gmm.get_nth_cov(0) est_cov2=est_gmm.get_nth_cov(1) est_cov3=est_gmm.get_nth_cov(2) est_coef=est_gmm.get_coef() print est_mean1 print est_cov1 print est_mean2 print est_cov2 print est_mean3 print est_cov3 print est_coef #plot real GMM, data and estimated GMM min_gen=min(min(generated)) max_gen=max(max(generated)) plot_real=empty(0) plot_est=empty(0) for i in arange(min_gen, max_gen, 0.001): plot_real=append(plot_real, array([exp(real_gmm.cluster(array([i]))[3])])) plot_est=append(plot_est, array([exp(est_gmm.cluster(array([i]))[3])])) real_plot=plot(arange(min_gen, max_gen, 0.001), plot_real, "b") est_plot=plot(arange(min_gen, max_gen, 0.001), plot_est, "r") real_hist=hist(generated.transpose(), bins=50, normed=True, fc="gray") legend(("Real GMM", "Estimated GMM")) connect('key_press_event', util.quit) show()
def ScatterPSF_keys(self, event): """ Display function that you shouldn't call directly. """ doClose = False self._increment = 0 key = event.key npoints = len(self.points[:, 0]) showingbool = np.array(self.showing).astype(np.bool) pointsshowing = self.points[showingbool] npointsshowing = len(pointsshowing[:, 0]) args = np.arange(npoints)[showingbool] arg = args[np.argsort(pointsshowing[:, 0])[self.selected_star]] ca = pyl.gca() if self.starsScat != None: self.starsScat.remove() self.starsScat = None if key in ['d', 'a', 'left', 'right']: # Move forwards/backwards through points ## The below might seem overly complicated, ## but doing it this way ensures that you continue ## from same/next point after zooming. ## Hang on, no, this doesn't make it continue at the right point ## after a zoom. hm, fix later. if key == 'd' or key == 'right': self._increment = +1 elif key == 'a' or key == 'left': self._increment = -1 else: pass self.selected_star = (self.selected_star + self._increment) % npointsshowing arg = args[np.argsort( self.points[:, 0][showingbool])[self.selected_star]] self.ScatterPSFCommon(arg) elif key in ['w', 'up', 'down']: # Remove a point. self.goodStars[arg] = not self.goodStars[arg] self.ScatterPSFCommon(arg) #pyl.sca(self.sp1) #self.sp1.set_xlim(xlim) #self.sp1.set_ylim(ylim) ##pyl.sca(ca) elif key in ['c', 'C']: doClose = True colour = 'b' if self.goodStars[arg] else 'r' self.starsScat = self.sp4.scatter(self.starsFlatR[arg], self.starsFlatF[arg], edgecolor=colour, facecolor='none', zorder=10) self.sp4.set_xlim(0, self.moffatWidth) self.sp4.set_ylim(0, 1.02) self.sp5.imshow(self.subsecs[arg]) #self.sp5.set_xlabel("x,y = {:.1f}, {:.1f}".format(self.points[:, 4][arg],self.points[:, 5][arg])) self.conn1 = self.sp1.callbacks.connect('ylim_changed', self.PSFrange) self.conn2 = pyl.connect('pick_event', self.ScatterPSF) ## The above two lines need to be here again. ## This allows for zooming/inspecting in whatever order, over & over. pyl.sca(ca) pyl.draw() if doClose: pyl.close()
def __call__(self, moffatWidth, moffatSNR, initAlpha=5., initBeta=2., repFact=3, xWidth=51, yWidth=51, bgRadius=20.0, ftol=1.49012e-8, quickFit=True, autoTrim=False, noVisualSelection=False, verbose=False, printStarInfo=False, saveFigure=False): self.moffatWidth = moffatWidth self.moffatSNR = moffatSNR self.initAlpha = initAlpha self.initBeta = initBeta self.repFact = repFact self.bgRadius = bgRadius self.fwhms = [] self.points = [] self.moffs = [] self.moffr = np.linspace(0, self.moffatWidth, self.moffatWidth * 3) self.starsFlatR = [] self.starsFlatF = [] self.subsecs = [] self.goodStars = [] self.starsScat = None self.printStarInfo = printStarInfo self.saveFigure = saveFigure print('Fitting stars with moffat profiles...') print(' X Y chi a b FWHM') for j in range(len(self.XWIN_IMAGE)): if self.FLUX_AUTO[j] / self.FLUXERR_AUTO[j] > self.moffatSNR: if self.XWIN_IMAGE[j] - 1 - ( moffatWidth + 1) < 0 or self.XWIN_IMAGE[j] - 1 + ( moffatWidth + 1 ) >= self.data.shape[1] or self.YWIN_IMAGE[j] - 1 - ( moffatWidth + 1) < 0 or self.YWIN_IMAGE[j] - 1 + ( moffatWidth + 1) >= self.data.shape[0]: continue #this psf object creator has to be here. It's to do with the way PSF objects are initialized. Some time #in the future I will adjust this for a small speed boost. mpsf = psf.modelPSF(np.arange(xWidth), np.arange(yWidth), alpha=self.initAlpha, beta=self.initBeta, repFact=self.repFact) mpsf.fitMoffat(self.data, self.XWIN_IMAGE[j], self.YWIN_IMAGE[j], boxSize=self.moffatWidth, verbose=verbose, bgRadius=self.bgRadius, ftol=ftol, quickFit=quickFit) fwhm = mpsf.FWHM(fromMoffatProfile=True) #norm=Im.normalise(mpsf.subsec,[self.z1,self.z2]) if self.minGoodVal is not None: norm = self.normer( np.clip(mpsf.subSec, self.minGoodVal, np.max(mpsf.subSec))) else: norm = self.normer(mpsf.subSec) if (fwhm is not None) and not (np.isnan(mpsf.beta) or np.isnan(mpsf.alpha)): print( ' {: 8.2f} {: 8.2f} {:3.2f} {: 5.2f} {: 5.2f} {: 5.2f} ' .format(self.XWIN_IMAGE[j], self.YWIN_IMAGE[j], mpsf.chiFluxNorm, mpsf.alpha, mpsf.beta, fwhm)) self.subsecs.append(norm * 1.) self.goodStars.append(True) self.moffs.append(mpsf.moffat(self.moffr) * 1.) self.starsFlatR.append( psf.downSample2d(mpsf.repRads, mpsf.repFact)) self.starsFlatF.append( (mpsf.subSec - mpsf.bg) / (mpsf.moffat(0) * mpsf.A)) self.moffs[len(self.moffs) - 1] /= np.max( self.moffs[len(self.moffs) - 1]) self.points.append([ fwhm, mpsf.chi, mpsf.alpha, mpsf.beta, self.XWIN_IMAGE[j], self.YWIN_IMAGE[j], mpsf.bg ]) self.points = np.array(self.points) self.goodStars = np.array(self.goodStars) FWHM_mode_width = 1.0 #could be 0.5 just as well ab_std_width = 2.0 if autoTrim: print('\nDoing auto star selection.') #first use Frasermode on the distribution of FWHM to get a good handle on the true FWHM of stars #select only those stars with FWHM of +-1 pixel of the mode. bg = bgFinder.bgFinder(self.points[:, 0]) mode = bg('median') w = np.where(np.abs(self.points[:, 0] - mode) > FWHM_mode_width) self.goodStars[w] = False #now mean select on both moffat a and b parameters to get only those with common shapes w = np.where(self.goodStars) mean_a = np.mean(self.points[w][:, 2]) std_a = np.std(self.points[w][:, 2]) mean_b = np.mean(self.points[w][:, 3]) std_b = np.std(self.points[w][:, 3]) w = np.where( (np.abs(self.points[:, 0] - mode) > FWHM_mode_width) | (np.abs(self.points[:, 2] - mean_a) > ab_std_width * std_a) | (np.abs(self.points[:, 3] - mean_b) > ab_std_width * std_b)) self.goodStars[w] = False #now eliminate the ones with sources nearby for ii in range(len(self.goodStars)): dist = ((self.XWIN_IMAGE - self.points[ii, 4])**2 + (self.YWIN_IMAGE - self.points[ii, 5])**2)**0.5 args = np.argsort(dist) dist = dist[args] #print self.points[ii,4:6],dist if dist[1] < moffatWidth: self.goodStars[ii] = False """ #now print out the number of pixels that are 3-sigma above the naive expectation of the moffat profile itself mpsf = psf.modelPSF(np.arange(xWidth), np.arange(yWidth), alpha=mean_a, beta=mean_b, repFact=self.repFact) print 'Fitting amplitudes to each good star.' for ii in range(len(self.moffs)): if self.goodStars[ii]: mpsf.fitMoffat(self.data, self.XWIN_IMAGE[ii], self.YWIN_IMAGE[ii], boxSize = self.moffatWidth, fixAB = True) a,b = int(self.YWIN_IMAGE[ii]-yWidth/2),int(self.YWIN_IMAGE[ii]+yWidth/2)+1 c,d = int(self.XWIN_IMAGE[ii]-xWidth/2),int(self.XWIN_IMAGE[ii]+xWidth/2)+1 x,y = self.XWIN_IMAGE[ii]-int(self.XWIN_IMAGE[ii])+xWidth/2+1.0, self.YWIN_IMAGE[ii]-int(self.YWIN_IMAGE[ii])+yWidth/2+1.0 cut = self.data[a:b,c:d] removed = mpsf.remove(self.XWIN_IMAGE[ii]-0.5,self.YWIN_IMAGE[ii]-0.5, mpsf.A, self.data)[a:b,c:d]-mpsf.bg print ii,len(np.where( np.abs(removed/cut**0.5)>3)[0]) exit() """ self.figPSF = pyl.figure('Point Source Selector') self.sp1 = pyl.subplot2grid((4, 4), (0, 1), colspan=3, rowspan=2) pyl.scatter(self.points[:, 0], self.points[:, 1], picker=True) pyl.title( 'Select PSF range with zoom,\n' + 'inspect stars (a = next, d = previous, w = toggle on/off,\n' + 'or left/right click to show/toggle),\n' + 'then close the plot window.') self.sp2 = pyl.subplot2grid((4, 4), (2, 1), colspan=3, sharex=self.sp1, rowspan=1) bins = np.arange(np.min(self.points[:, 0]), np.max(self.points[:, 0]) + 0.5, 0.5) pyl.hist(self.points[:, 0], bins=bins) pyl.xlabel('FWHM (pix)') self.sp3 = pyl.subplot2grid((4, 4), (0, 0), rowspan=2, sharey=self.sp1) print(self.points[:, 1]) chiIsNan = np.isnan(self.points[:, 1]) if chiIsNan.any(): message = ('Bad (NaN) Chi value for star(s) at ' + '{}.\n'.format([(self.points[i, 4], self.points[i, 5]) for i in np.where(chiIsNan)[0]]) + 'This is likely due to bad data nearby ' + '(edge of chip or similar).\n' 'Please trim catalog to remove these sources.') raise ValueError(message) pyl.hist(self.points[:, 1], bins=30, orientation='horizontal') pyl.ylabel('RMS') self.sp4 = pyl.subplot2grid((4, 4), (2, 0), rowspan=2) self.moffPatchList = [] self.showing = [] self.selected_star = -1 for j in range(len(self.moffs)): self.moffPatchList.append( self.sp4.plot(self.moffr, self.moffs[j], zorder=0)) self.showing.append(1) self.sp4.set_xlim(0, 30) self.sp4.set_ylim(0, 1.02) self.sp5 = pyl.subplot2grid((4, 4), (3, 1)) self.sp5.set_aspect('equal') self.psfPlotLimits = [self.sp1.get_xlim(), self.sp1.get_ylim()] self.conn1 = self.sp1.callbacks.connect('ylim_changed', self.PSFrange) self.conn2 = pyl.connect('pick_event', self.ScatterPSF) self.conn3 = pyl.connect('key_press_event', self.ScatterPSF_keys) self.conn4 = pyl.connect('close_event', self.HandleClose) self.ScatterPSF(None) if not noVisualSelection: pyl.show() self._fwhm_lim = self.sp1.get_xlim() self._chi_lim = self.sp1.get_ylim() w = np.where((self.points[:, 0] > self._fwhm_lim[0]) & (self.points[:, 0] < self._fwhm_lim[1]) & (self.points[:, 1] > self._chi_lim[0]) & (self.points[:, 1] < self._chi_lim[1]) & (self.goodStars == True)) pyl.clf() pyl.close() goodFits = self.points[w] goodMeds = np.median(goodFits[:4], axis=0) goodSTDs = np.std(goodFits[:4], axis=0) return (goodFits, goodMeds, goodSTDs)
title('Data',size=10) # plot PRC for SVM subplot(223) PRC_evaluation=PRCEvaluation() PRC_evaluation.evaluate(svm.classify(),labels) PRC = PRC_evaluation.get_PRC() plot(PRC[:,0], PRC[:,1]) fill_between(PRC[:,0],PRC[:,1],0,alpha=0.1) text(0.55,mean(PRC[:,1])/3,'auPRC = %.5f' % PRC_evaluation.get_auPRC()) grid(True) xlabel('Precision') ylabel('Recall') title('LibSVM (Gaussian kernel, C=%.3f) PRC curve' % svm.get_C1(),size=10) # plot PRC for LDA subplot(224) PRC_evaluation.evaluate(lda.classify(),labels) PRC = PRC_evaluation.get_PRC() plot(PRC[:,0], PRC[:,1]) fill_between(PRC[:,0],PRC[:,1],0,alpha=0.1) text(0.55,mean(PRC[:,1])/3,'auPRC = %.5f' % PRC_evaluation.get_auPRC()) grid(True) xlabel('Precision') ylabel('Recall') title('LDA (gamma=%.3f) PRC curve' % lda.get_gamma(),size=10) connect('key_press_event', util.quit) show()
else: def click(event): print [event.key] if event.key == 'm': mode = raw_input('Enter new mode: ') for k in plots: try: d = data_mode(plt_data[k], mode) plots[k].set_data(d) except(ValueError): print 'Unrecognized plot mode' p.draw() elif event.key == 'd': max = raw_input('Enter new max: ') try: max = float(max) except(ValueError): max = None drng = raw_input('Enter new drng: ') try: drng = float(drng) except(ValueError): drng = None for k in plots: _max,_drng = max, drng if _max is None or _drng is None: d = plots[k].get_array() if _max is None: _max = d.max() if _drng is None: _drng = _max - d.min() plots[k].set_clim(vmin=_max-_drng, vmax=_max) print 'Replotting...' p.draw() p.connect('key_press_event', click) p.show()
def plot_lightbox(background=None, background_mask=None, cmap_bg='gray', overlay=None, overlay_mask=None, cmap_overlay='autumn', vlim=(0.0, None), vlim_type=None, do_stretch_colors=False, add_info=True, add_hist=True, add_colorbar=True, fig=None, interactive=None, nrows=None, ncolumns=None, slices=None, slice_title="k=%(islice)s" ): """Very basic plotting of 3D data with interactive thresholding. `background`/`overlay` and corresponding masks could be nifti files names or `SpatialImage` objects, or 3D `ndarrays`. If no mask is provided, only non-0 elements are plotted. Notes ----- No care is taken to deduce the orientation (e.g. Left-to-Right, Posterior-to-Anterior) of fMRI volumes. Therefore all input volumes should be in the same orientation. Parameters ---------- do_stretch_colors : bool, optional Stratch color range to the data (not just to visible data) vlim : tuple, optional 2 element tuple of low/upper bounds of values to plot vlim_type : None or 'symneg_z' If not None, then vlim would be treated accordingly: symneg_z z-score values of symmetric normal around 0, estimated by symmetrizing negative part of the distribution, which often could be assumed when total distribution is a mixture of by-chance performance normal around 0, and some other in the positive tail ncolumns : int or None Explicit starting number of columns into which position the slice renderings. If None, square arrangement would be used nrows : int or None Explicit starting number of rows into which position the slice renderings. If None, square arrangement would be used add_hist : bool or tuple (int, int) If True, add histogram and position automagically. If a tuple -- use as (row, column) add_info : bool or tuple (int, int) If True, add information and position automagically. If a tuple -- use as (row, column). slices : None or list of int If not to plot whole volume, what slices to plot. slice_title : None or str Desired title of slices. Use string comprehension and assume `islice` variable present with current slice index. Available colormaps are presented nicely on http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps TODO: * Make interface more attractive/usable * allow multiple overlays... or just unify for them all to be just a list of entries * handle cases properly when there is only one - background/overlay """ def handle_arg(arg): """Helper which would read in SpatialImage if necessary """ if isinstance(arg, basestring): arg = nb.load(arg) argshape = arg.get_shape() # Assure that we have 3D (at least) if len(argshape)<3: arg = nb.Nifti1Image( arg.get_data().reshape(argshape + (1,)*(3-len(argshape))), arg.get_affine(), arg.get_header()) if isinstance(arg, np.ndarray): if len(arg.shape) != 3: raise ValueError, "For now just handling 3D volumes" return arg bg = handle_arg(background) if isinstance(bg, SpatialImage): # figure out aspect # fov = (np.array(bg.header['pixdim']) * bg.header['dim'])[3:0:-1] # aspect = fov[1]/fov[2] # just scale by voxel-size ratio (extent is disabled) bg_hdr = bg.get_header() aspect = bg_hdr.get_zooms()[2] / bg_hdr.get_zooms()[1] bg = bg.get_data() else: aspect = 1.0 bg_mask = None if bg is not None: bg_mask = handle_arg(background_mask) if isinstance(bg_mask, SpatialImage): bg_mask = bg_mask.get_data() if bg_mask is not None: bg_mask = bg_mask != 0 else: bg_mask = bg != 0 func = handle_arg(overlay) if func is not None: if isinstance(func, SpatialImage): func = func.get_data() func_mask = handle_arg(overlay_mask) if isinstance(func_mask, SpatialImage): func_mask = func_mask.get_data() #[..., ::-1, :] # XXX if func_mask is not None: func_mask = func_mask != 0 else: func_mask = func != 0 # Lets assure that that we are dealing with <= 3D for v in (bg, bg_mask, func, func_mask): if v is not None: if v.ndim > 3: # we could squeeze out first bogus dimensions if np.all(np.array(v.shape[3:]) == 1): v.shape = v.shape[:3] else: raise ValueError, \ "Original shape of some data is %s whenever we " \ "can accept only 3D images (or ND with degenerate " \ "first dimensions)" % (v.shape,) # process vlim vlim = list(vlim) vlim_orig = vlim[:] add_dist2hist = [] if isinstance(vlim_type, basestring): if vlim_type == 'symneg_z': func_masked = func[func_mask] fnonpos = func_masked[func_masked<=0] fneg = func_masked[func_masked<0] # take together with sign-reverted negative values fsym = np.hstack((-fneg, fnonpos)) nfsym = len(fsym) # Estimate normal std under assumption of mean=0 std = np.sqrt(np.mean(abs(fsym)**2)) # convert vlim assuming it is z-scores for i,v in enumerate(vlim): if v is not None: vlim[i] = std * v # add a plot to histogram add_dist2hist = [(lambda x: nfsym/(np.sqrt(2*np.pi)*std) \ *np.exp(-(x**2)/(2*std**2)), {})] else: raise ValueError, 'Unknown specification of vlim=%s' % vlim + \ ' Known is: symneg' class Plotter(object): """ TODO """ #_store_attribs = ('vlim', 'fig', 'bg', 'bg_mask') def __init__(self, _locals): """TODO""" self._locals = _locals self.fig = _locals['fig'] def do_plot(self): """TODO""" # silly yarik didn't find proper way vlim = self._locals['vlim'] bg = self._locals['bg'] bg_mask = self._locals['bg_mask'] ncolumns = self._locals['ncolumns'] nrows = self._locals['nrows'] add_info = self._locals['add_info'] add_hist = self._locals['add_hist'] slices = self._locals['slices'] slice_title = self._locals['slice_title'] if np.isscalar(vlim): vlim = (vlim, None) if vlim[0] is None: vlim = (np.min(func), vlim[1]) if vlim[1] is None: vlim = (vlim[0], np.max(func)) if __debug__ and 'PLLB' in debug.active: debug('PLLB', "Maximum %g at %s, vlim is %s" % (np.max(func), np.where(func==np.max(func)), str(vlim))) invert = vlim[1] < vlim[0] if invert: vlim = (vlim[1], vlim[0]) print "Not yet fully supported" # adjust lower bound if it is too low # and there are still multiple values ;) func_masked = func[func_mask] if vlim[0] < np.min(func_masked) and \ np.min(func_masked) != np.max(func_masked): vlim = list(vlim) vlim[0] = np.min(func[func_mask]) vlim = tuple(vlim) bound_above = (max(vlim) < np.max(func)) bound_below = (min(vlim) > np.min(func)) # # reverse the map if needed cmap_ = cmap_overlay if not bound_below and bound_above: if cmap_.endswith('_r'): cmap_ = cmap_[:-2] else: cmap_ += '_r' func_cmap = eval("pl.cm.%s" % cmap_) bg_cmap = eval("pl.cm.%s" % cmap_bg) if do_stretch_colors: clim = (np.min(func), np.max(func))#vlim else: clim = vlim # # figure out 'extend' for colorbar and threshold string extend, thresh_str = { (True, True) : ('both', 'x in [%.3g, %.3g]' % tuple(vlim)), (True, False): ('min', 'x in [%.3g, +inf]' % vlim[0]), (False, True): ('max', 'x in (-inf, %.3g]' % vlim[1]), (False, False): ('neither', 'none') }[(bound_below, bound_above)] # # Figure out subplots dshape = func.shape if slices is None: slices = range(func.shape[0]) nslices = len(slices) # more or less square alignment ;-) if ncolumns is None: ncolumns = int(np.sqrt(nslices)) ndcolumns = ncolumns nrows = max(nrows, int(np.ceil(nslices*1.0/ncolumns))) # Check if additional column/row information was provided # and extend nrows/ncolumns for v in (add_hist, add_info): if v and not isinstance(v, bool): ncolumns = max(ncolumns, v[1]+1) nrows = max(nrows, v[0]+1) # Decide either we need more cells where to add hist and/or info nadd = bool(add_info) + bool(add_hist) while ncolumns*nrows - (nslices + nadd) < 0: ncolumns += 1 locs = ['' for i in xrange(ncolumns*nrows)] # Fill in predefined locations for v,vl in ((add_hist, 'hist'), (add_info, 'info')): if v and not isinstance(v, bool): locs[ncolumns*v[0] + v[1]] = vl # Fill in slices for islice in slices: locs[locs.index('')] = islice # Fill the last available if necessary if add_hist and isinstance(add_hist, bool): locs[locs.index('')] = 'hist' if add_info and isinstance(add_info, bool): locs[locs.index('')] = 'info' Pioff() if self.fig is None: self.fig = pl.figure(facecolor='white', figsize=(4*ncolumns, 4*nrows)) fig = self.fig fig.clf() # # how to threshold images thresholder = lambda x: np.logical_and(x>=vlim[0], x<=vlim[1]) ^ invert # # Draw all slices self.slices_ax = [] im0 = None for islice in slices[::-1]: #range(nslices)[::-1]: ax = fig.add_subplot(nrows, ncolumns, locs.index(islice) + 1, frame_on=False) self.slices_ax.append(ax) ax.axison = False slice_bg_nvoxels = None if bg is not None: slice_bg = bg[:, :, islice] slice_bg_ = np.ma.masked_array(slice_bg, mask=np.logical_not(bg_mask[:, :, islice])) #slice_bg<=0) slice_bg_nvoxels = len(slice_bg_.nonzero()[0]) if __debug__: debug('PLLB', "Plotting %i background elements in slice %i" % (slice_bg_nvoxels, islice)) slice_sl = func[:, :, islice] in_thresh = thresholder(slice_sl) out_thresh = np.logical_not(in_thresh) slice_sl_ = np.ma.masked_array(slice_sl, mask=np.logical_or(out_thresh, np.logical_not(func_mask[:, :, islice]))) slice_func_nvoxels = len(slice_sl_.nonzero()[0]) if __debug__: debug('PLLB', "Plotting %i foreground elements in slice %i" % (slice_func_nvoxels, islice)) kwargs = dict(aspect=aspect, origin='upper') #extent=(0, slice_bg.shape[0], # 0, slice_bg.shape[1])) # paste a blank white background first, since otherwise # recent matplotlib screws up those masked imshows im = ax.imshow(np.ones(slice_sl_.shape).T, cmap=bg_cmap, **kwargs) im.set_clim((0,1)) # ax.clim((0,1)) if slice_bg_nvoxels: ax.imshow(slice_bg_.T, # let's stay close to the ugly truth ;-) #interpolation='bilinear', interpolation='nearest', cmap=bg_cmap, **kwargs) if slice_func_nvoxels: alpha = slice_bg_nvoxels and 0.9 or 1.0 im = ax.imshow(slice_sl_.T, interpolation='nearest', cmap=func_cmap, alpha=alpha, **kwargs) im.set_clim(*clim) im0 = im if slice_title: pl.title(slice_title % locals()) # func_masked = func[func_mask] # # Add summary information func_thr = func[np.logical_and(func_mask, thresholder(func))] if add_info and len(func_thr): self.info_ax = ax = fig.add_subplot(nrows, ncolumns, locs.index('info')+1, frame_on=False) # cb = pl.colorbar(shrink=0.8) # #cb.set_clim(clim[0], clim[1]) ax.axison = False #if add_colorbar: # cb = pl.colorbar(im, shrink=0.8, pad=0.0, drawedges=False, # extend=extend, cmap=func_cmap) stats = {'v':len(func_masked), 'vt': len(func_thr), 'm': np.mean(func_masked), 'mt': np.mean(func_thr), 'min': np.min(func_masked), 'mint': np.min(func_thr), 'max': np.max(func_masked), 'maxt': np.max(func_thr), 'mm': np.median(func_masked), 'mmt': np.median(func_thr), 'std': np.std(func_masked), 'stdt': np.std(func_thr), 'sthr': thresh_str} pl.text(0, 0.5, """ Original: voxels = %(v)d range = [%(min).3g, %(max).3g] mean = %(m).3g median = %(mm).3g std = %(std).3g Thresholded: %(sthr)s: voxels = %(vt)d range = [%(mint).3g, %(maxt).3g] median = %(mt).3g mean = %(mmt).3g std = %(stdt).3g """ % stats, horizontalalignment='left', verticalalignment='center', transform = ax.transAxes, fontsize=14) cb = None if add_colorbar and im0 is not None: kwargs_cb = {} #if add_hist: # kwargs_cb['cax'] = self.hist_ax self.cb_ax = cb = pl.colorbar( im0, #self.hist_ax, shrink=0.8, pad=0.0, drawedges=False, extend=extend, cmap=func_cmap, **kwargs_cb) cb.set_clim(*clim) # Add histogram if add_hist: self.hist_ax = fig.add_subplot(nrows, ncolumns, locs.index('hist') + 1, frame_on=True) minv, maxv = np.min(func_masked), np.max(func_masked) if minv<0 and maxv>0: # then make it centered on 0 maxx = max(-minv, maxv) range_ = (-maxx, maxx) else: range_ = (minv, maxv) H = np.histogram(func_masked, range=range_, bins=31) # API changed since v0.99.0-641-ga7c2231 halign = externals.versions['matplotlib'] >= '1.0.0' \ and 'mid' or 'center' H2 = pl.hist(func_masked, bins=H[1], align=halign, facecolor='#FFFFFF', hold=True) for a, kwparams in add_dist2hist: dbin = (H[1][1] - H[1][0]) pl.plot(H2[1], [a(x) * dbin for x in H2[1]], **kwparams) if add_colorbar and cb: cbrgba = cb.to_rgba(H2[1]) for face, facecolor, value in zip(H2[2], cbrgba, H2[1]): if not thresholder(value): color = '#FFFFFF' else: color = facecolor face.set_facecolor(color) fig.subplots_adjust(left=0.01, right=0.95, hspace=0.25) # , bottom=0.01 if ncolumns - int(bool(add_info) or bool(add_hist)) < 2: fig.subplots_adjust(wspace=0.4) else: fig.subplots_adjust(wspace=0.1) Pion() def on_click(self, event): """Actions to perform on click """ if id(event.inaxes) != id(plotter.hist_ax): return xdata, ydata, button = event.xdata, event.ydata, event.button vlim = self._locals['vlim'] if button == 1: vlim[0] = xdata elif button == 3: vlim[1] = xdata elif button == 2: vlim[0], vlim[1] = vlim[1], vlim[0] self.do_plot() plotter = Plotter(locals()) plotter.do_plot() if interactive is None: interactive = mpl_backend_isinteractive # Global adjustments if interactive: # if pl.matplotlib.is_interactive(): pl.connect('button_press_event', plotter.on_click) pl.show() plotter.fig.plotter = plotter return plotter.fig
def click(event): global cnt if event.button == 3: lon,lat = map(event.xdata, event.ydata, inverse=True) if opts.osys == 'eq': lon = (360 - lon) % 360 lon *= a.img.deg2rad; lat *= a.img.deg2rad ra,dec = ephem.hours(lon), ephem.degrees(lat) x,y,z = a.coord.radec2eq((ra,dec)) flx = h[(x,y,z)] print '#%d (RA,DEC): (%s, %s), Jy: %f' % (cnt, ra, dec, flx) cnt += 1 elif event.button==2: lon,lat = map(event.xdata, event.ydata, inverse=True) if opts.osys == 'eq': lon = (360 - lon) % 360 lon *= a.img.deg2rad; lat *= a.img.deg2rad ra,dec = ephem.hours(lon), ephem.degrees(lat) x,y,z = a.coord.radec2eq((ra,dec)) #flx = h[(x,y,z)] crd = [mk_arr(c, dtype=n.double) for c in (x,y,z)] px,wgts = h.crd2px(*crd, **{'interpolate':1}) flx = n.sum(h[px],axis=-1) print '#%d (RA,DEC): (%s, %s), Jy: %f (4px sum)' % (cnt, ra, dec, flx) cnt += 1 else: return #register this function with the event handler p.connect('button_press_event', click) p.show()