def updatePress(self, event): if debug_SnaptoCursor: not_inaxes = not event.inaxes print( 'SnaptoCursor.updatePress() not .inaxes=%s' ' .key=%s .button=%s .dblclick=%s self.id=%s' '' % (not_inaxes, event.key, event.button, event.dblclick, self.id)) if not event.inaxes: return # Make sure the main window is in focus, else event.key will # be NULL, even if clicks are registered! cursor_set_event = False if self.id == 1: # Cursor 1 is moved by this kind of event if event.button == 1 and event.key == "shift": cursor_set_event = True elif self.id == 2: # Was originally: event.key == "control" if event.button == 3: cursor_set_event = True if not cursor_set_event: return x, y = event.xdata, event.ydata indx = pylab.searchsorted(self.x, [x])[0] self.xpos = self.x[indx] self.ypos = self.y[indx] client.queue.put("update")
def interpolateLin(y,x,xNew): """ linear interpolation of y[x] onto y[xNew] Linearly extrapolates if outside range """ xInd = M.clip(M.searchsorted(x,xNew)-1,0,len(x)-2) xFract = (xNew-x[xInd])/(x[xInd+1]-x[xInd]) return y[xInd]+xFract*(y[xInd+1]-y[xInd])
def rc(self,z): """ Comoving line of sight distance interpolate (linear for now) """ i = M.searchsorted(self._z,z)-1 f = (z-self._z[i]) / self._dz d = self._rc[i] + f*(self._rc[i+1]-self._rc[i]) return M.where(z==0,0,d)
def interpolateLinLog(y,x,xNew): """ linear interpolation in LOG space of y[x] onto y[xNew] Linearly extrapolates if outside range """ logx = M.log(x) logy = M.log(y) logxNew = M.log(xNew) logxInd = M.clip(M.searchsorted(logx,logxNew)-1,0,len(logx)-2) logxFract = (logxNew-logx[logxInd])/(logx[logxInd+1]-logx[logxInd]) return M.exp(logy[logxInd]+logxFract*(logy[logxInd+1]-logy[logxInd]))
def mouse_move(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata indx = searchsorted(self.x, [x])[0] x = self.x[indx] y = self.y[indx] # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y)) # print ('x=%1.2f, y=%1.2f'%(x,y)) plt.draw()
def norm_hist_bins(y, bins=10, normed='height'): """Just like the matplotlib mlab.hist, but can normalize by height. normed can be 'area' (produces matplotlib behavior, area is 1), any False value (no normalization), or any True value (normalization). Original docs from matplotlib: Return the histogram of y with bins equally sized bins. If bins is an array, use the bins. Return value is (n,x) where n is the count for each bin in x If normed is False, return the counts in the first element of the return tuple. If normed is True, return the probability density n/(len(y)*dbin) If y has rank>1, it will be raveled Credits: the Numeric 22 documentation """ y = asarray(y) if len(y.shape)>1: y = ravel(y) if not iterable(bins): ymin, ymax = min(y), max(y) if ymin==ymax: ymin -= 0.5 ymax += 0.5 if bins==1: bins=ymax dy = (ymax-ymin)/bins bins = ymin + dy*arange(bins) n = searchsorted(sort(y), bins) n = diff(concatenate([n, [len(y)]])) if normed: if normed == 'area': db = bins[1]-bins[0] else: db = 1.0 return 1/(len(y)*db)*n, bins else: return n, bins
def updatePress(self, event): if not event.inaxes: return # make sure the main window is in focus, # else event.key will be NULL, even if clicks are registered! if self.id == 1: if event.key != "shift": return if self.id == 2: if event.key != "control": return x, y = event.xdata, event.ydata indx = pylab.searchsorted(self.x, [x])[0] self.xpos = self.x[indx] self.ypos = self.y[indx] client.queue.put("update")
def format_contour_array(data, points_per_cell=20, bulk=0.8): """Formats [x,y] series of data into x_bins, y_bins and data for contour(). data: 2 x n array of float representing x,y coordinates points_per_cell: average points per unit cell in the bulk of the data, default 3 bulk: fraction containing the 'bulk' of the data in x and y, default 0.8 (i.e. 80% of the data will be used in the calculation). returns: x-bin, y-bin, and a square matrix of frequencies to be plotted WARNING: Assumes x and y are in the range 0-1. """ #bind x and y data data_x = sort(data[0]) #note: numpy sort returns a sorted copy data_y = sort(data[1]) num_points = len(data_x) #calculate the x and y bounds holding the bulk of the data low_prob = (1-bulk)/2.0 low_tail = int(num_points*low_prob) high_tail = int(num_points*(1-low_prob)) x_low = data_x[low_tail] x_high = data_x[high_tail] y_low = data_y[low_tail] y_high = data_y[high_tail] #calculate the side length in the bulk that holds the right number of #points delta_x = x_high - x_low delta_y = y_high - y_low points_in_bulk = num_points * bulk #approximate: assumes no correlation area_of_bulk = delta_x * delta_y points_per_area = points_in_bulk/area_of_bulk side_length = sqrt(points_per_cell / points_per_area) #correct the side length so we get an integer number of bins. num_bins = int(1/side_length) corrected_side_length = 1.0/num_bins #figure out how many items are in each grid square in x and y # #this is the tricky part, because contour() takes as its data matrix #the points at the vertices of each cell, rather than the points at #the centers of each cell. this means that if we were going to make #a 3 x 3 grid, we actually have to estimate a 4 x 4 matrix that's offset #by half a unit cell in both x and y. # #if the data are between 0 and 1, the first and last bin in our range are #superfluous because searchsorted will put items before the first #bin into bin 0, and items after the last bin into bin n+1, where #n is the maximum index in the original array. for example, if we #have 3 bins, the values .33 and .66 would suffice to find the centers, #because anything below .33 gets index 0 and anything above .66 gets index #2 (anything between them gets index 1). incidentally, this prevents #issues with floating-point error and values slightly below 0 or above 1 #that might otherwise arise. # #however, for our 3 x 3 case, we actually want to start estimating at the #cell centered at 0, i.e. starting at -.33/2, so that we get the four #estimates centered at (rather than starting at) 0, .33, .66, and 1. #because the data are constrained to be between 0 and 1, we will need to #double the counts at the edges (and quadruple them at the corners) to get #a fair estimate of the density. csl = corrected_side_length #save typing below eps = csl/10 #don't ever want max value to be in the list precisely half_csl = .5*csl bins = arange(half_csl, 1+half_csl-eps, csl) x_coords = searchsorted(bins, data[0]) y_coords = searchsorted(bins, data[1]) #matrix has dimension 1 more than num bins, b/c can be above largest matrix = zeros((num_bins+1, num_bins+1)) #for some reason, need to swap x and y to match up with normal #scatter plots for coord in zip(y_coords, x_coords): matrix[coord] += 1 #we now have estimates of the densities at the edge of each of the #n x n cells in the grid. for example, if we have a 3 x 3 grid, we have #16 densities, one at the center of each grid cell (0, .33, .66, 1 in each #dimension). need to double the counts at edges to reflect places where #we can't observe data because of range restrictions. matrix[0]*=2 matrix[:,0]*=2 matrix[-1]*=2 matrix[:,-1]*=2 #return adjusted_bins as centers, rather than boundaries, of the range x_bins = csl*arange(num_bins+1) return x_bins, x_bins, matrix
def interp(datain,lonsin,latsin,lonsout,latsout,checkbounds=False,mode='nearest',cval=0.0,order=3): """ dataout = interp(datain,lonsin,latsin,lonsout,latsout,mode='constant',cval=0.0,order=3) interpolate data (datain) on a rectilinear lat/lon grid (with lons=lonsin lats=latsin) to a grid with lons=lonsout, lats=latsout. datain is a rank-2 array with 1st dimension corresponding to longitude, 2nd dimension latitude. lonsin, latsin are rank-1 arrays containing longitudes and latitudes of datain grid in increasing order (i.e. from Greenwich meridian eastward, and South Pole northward) lonsout, latsout are rank-2 arrays containing lons and lats of desired output grid (typically a native map projection grid). If checkbounds=True, values of lonsout and latsout are checked to see that they lie within the range specified by lonsin and latsin. Default is False, and values outside the borders are handled in the manner described by the 'mode' parameter (default mode='nearest', which means the nearest boundary value is used). See section 20.2 of the numarray docs for information on the 'mode' keyword. See numarray.nd_image.map_coordinates documentation for information on the other optional keyword parameters. The order keyword can be 0 for nearest neighbor interpolation (nd_image only allows 1-6) - if order=0 bounds checking is done even if checkbounds=False. """ # lonsin and latsin must be monotonically increasing. if lonsin[-1]-lonsin[0] < 0 or latsin[-1]-latsin[0] < 0: raise ValueError, 'lonsin and latsin must be increasing!' # optionally, check that lonsout,latsout are # within region defined by lonsin,latsin. # (this check is always done if nearest neighbor # interpolation (order=0) requested). if checkbounds or order == 0: if min(pylab.ravel(lonsout)) < min(lonsin) or \ max(pylab.ravel(lonsout)) > max(lonsin) or \ min(pylab.ravel(latsout)) < min(latsin) or \ max(pylab.ravel(latsout)) > max(latsin): raise ValueError, 'latsout or lonsout outside range of latsin or lonsin' # compute grid coordinates of output grid. delon = lonsin[1:]-lonsin[0:-1] delat = latsin[1:]-latsin[0:-1] if max(delat)-min(delat) < 1.e-4 and max(delon)-min(delon) < 1.e-4: # regular input grid. xcoords = (len(lonsin)-1)*(lonsout-lonsin[0])/(lonsin[-1]-lonsin[0]) ycoords = (len(latsin)-1)*(latsout-latsin[0])/(latsin[-1]-latsin[0]) else: # irregular (but still rectilinear) input grid. lonsoutflat = pylab.ravel(lonsout) latsoutflat = pylab.ravel(latsout) ix = pylab.searchsorted(lonsin,lonsoutflat)-1 iy = pylab.searchsorted(latsin,latsoutflat)-1 xcoords = pylab.zeros(ix.shape,'f') ycoords = pylab.zeros(iy.shape,'f') for n,i in enumerate(ix): if i < 0: xcoords[n] = -1 # outside of range on lonsin (lower end) elif i >= len(lonsin)-1: xcoords[n] = len(lonsin) # outside range on upper end. else: xcoords[n] = float(i)+(lonsoutflat[n]-lonsin[i])/(lonsin[i+1]-lonsin[i]) xcoords = pylab.reshape(xcoords,lonsout.shape) for m,j in enumerate(iy): if j < 0: ycoords[m] = -1 # outside of range of latsin (on lower end) elif j >= len(latsin)-1: ycoords[m] = len(latsin) # outside range on upper end else: ycoords[m] = float(j)+(latsoutflat[m]-latsin[j])/(latsin[j+1]-latsin[j]) ycoords = pylab.reshape(ycoords,latsout.shape) coords = [ycoords,xcoords] # interpolate to output grid using numarray.nd_image spline filter. if order: return nd_image.map_coordinates(datain,coords,mode=mode,cval=cval,order=order) else: # nearest neighbor interpolation if order=0. # uses index arrays, so first convert to numarray. datatmp = pylab.array(datain,datain.typecode()) xi = pylab.around(xcoords).astype('i') yi = pylab.around(ycoords).astype('i') return datatmp[yi,xi]
compare_time=oldtime+(plotdict["min_skip_secs"]*onesec) if(compare_time > key): #if (record['bmnum'] == beamdir) or (beamdir == 16 ): #print "Beam %d Skipping key:" % (record['bmnum']),key,compare_time,p.num2date(key),p.num2date(compare_time) #pass continue totalpwr=0 record=test.data[key] if (record['bmnum'] == beamdir) or (beamdir == 16 ): # print "Plotting key:",key,p.num2date(key) if plot: x_numsecs=0 if (beamdir == 16) or use_int_time: x_numsecs=record['intt.us']*1E-6+record['intt.sc'] else: index=p.searchsorted(beamkeys,key) test1_numsecs=N.inf try: test2_numsecs=(beamkeys[index+1]-beamkeys[index])/onesec except: test2_numsecs=N.inf beam_interval=min(test1_numsecs,test2_numsecs) x_numsecs=beam_interval if not use_int_time: if min_plot_numsecs is not None: if x_numsecs < min_plot_numsecs: x_numsecs=min_plot_numsecs else: test_num_secs=record['intt.us']*1E-6+record['intt.sc'] if test_num_secs > x_numsecs: x_numsecs=test_num_secs if max_plot_numsecs is not None: if x_numsecs > max_plot_numsecs: x_numsecs=max_plot_numsecs
def interp(datain,lonsin,latsin,lonsout,latsout,checkbounds=False,mode='nearest',cval=0.0,order=3): """ dataout = interp(datain,lonsin,latsin,lonsout,latsout,mode='constant',cval=0.0,order=3) interpolate data (datain) on a rectilinear lat/lon grid (with lons=lonsin lats=latsin) to a grid with lons=lonsout, lats=latsout. datain is a rank-2 array with 1st dimension corresponding to longitude, 2nd dimension latitude. lonsin, latsin are rank-1 Numeric arrays containing longitudes and latitudes of datain grid in increasing order (i.e. from Greenwich meridian eastward, and South Pole northward) lonsout, latsout are rank-2 Numeric arrays containing lons and lats of desired output grid (typically a native map projection grid). If checkbounds=True, values of lonsout and latsout are checked to see that they lie within the range specified by lonsin and latsin. Default is False, and values outside the borders are handled in the manner described by the 'mode' parameter (default mode='nearest', which means the nearest boundary value is used). See section 20.2 of the numarray docs for information on the 'mode' keyword. See numarray.nd_image.map_coordinates documentation for information on the other optional keyword parameters. The order keyword can be 0 for nearest neighbor interpolation (nd_image only allows 1-6) - if order=0 bounds checking is done even if checkbounds=False. """ # lonsin and latsin must be monotonically increasing. if lonsin[-1]-lonsin[0] < 0 or latsin[-1]-latsin[0] < 0: raise ValueError, 'lonsin and latsin must be increasing!' # optionally, check that lonsout,latsout are # within region defined by lonsin,latsin. # (this check is always done if nearest neighbor # interpolation (order=0) requested). if checkbounds or order == 0: if min(pylab.ravel(lonsout)) < min(lonsin) or \ max(pylab.ravel(lonsout)) > max(lonsin) or \ min(pylab.ravel(latsout)) < min(latsin) or \ max(pylab.ravel(latsout)) > max(latsin): raise ValueError, 'latsout or lonsout outside range of latsin or lonsin' # compute grid coordinates of output grid. delon = lonsin[1:]-lonsin[0:-1] delat = latsin[1:]-latsin[0:-1] if max(delat)-min(delat) < 1.e-4 and max(delon)-min(delon) < 1.e-4: # regular input grid. xcoords = (len(lonsin)-1)*(lonsout-lonsin[0])/(lonsin[-1]-lonsin[0]) ycoords = (len(latsin)-1)*(latsout-latsin[0])/(latsin[-1]-latsin[0]) else: # irregular (but still rectilinear) input grid. lonsoutflat = pylab.ravel(lonsout) latsoutflat = pylab.ravel(latsout) ix = pylab.searchsorted(lonsin,lonsoutflat)-1 iy = pylab.searchsorted(latsin,latsoutflat)-1 xcoords = pylab.zeros(ix.shape,'f') ycoords = pylab.zeros(iy.shape,'f') for n,i in enumerate(ix): if i < 0: xcoords[n] = -1 # outside of range on lonsin (lower end) elif i >= len(lonsin)-1: xcoords[n] = len(lonsin) # outside range on upper end. else: xcoords[n] = float(i)+(lonsoutflat[n]-lonsin[i])/(lonsin[i+1]-lonsin[i]) xcoords = pylab.reshape(xcoords,lonsout.shape) for m,j in enumerate(iy): if j < 0: ycoords[m] = -1 # outside of range of latsin (on lower end) elif j >= len(latsin)-1: ycoords[m] = len(latsin) # outside range on upper end else: ycoords[m] = float(j)+(latsoutflat[m]-latsin[j])/(latsin[j+1]-latsin[j]) ycoords = pylab.reshape(ycoords,latsout.shape) coords = [ycoords,xcoords] # interpolate to output grid using numarray.nd_image spline filter. if order: return nd_image.map_coordinates(datain,coords,mode=mode,cval=cval,order=order) else: # nearest neighbor interpolation if order=0. # uses index arrays, so first convert to numarray. datatmp = pylab.array(datain,datain.typecode()) xi = pylab.around(xcoords).astype('i') yi = pylab.around(ycoords).astype('i') return datatmp[yi,xi]