def plot_topo_xsec(current_data): from pylab import find, ravel x = current_data.x y = current_data.y dy = current_data.dy ij = find((y <= dy / 2.) & (y > -dy / 2.)) x_slice = ravel(x)[ij] b_slice = ravel(b(current_data))[ij] return x_slice, b_slice
def plot_topo_xsec(current_data): from pylab import find,ravel x = current_data.x y = current_data.y dy = current_data.dy ij = find((y <= dy/2.) & (y > -dy/2.)) x_slice = ravel(x)[ij] b_slice = ravel(b(current_data))[ij] return x_slice, b_slice
def slice_y(current_data): from pylab import find,ravel x = current_data.x y = current_data.y dx = current_data.dx q = current_data.q ij = find((x <= longitude+dx/2.) & (x > longitude-dx/2.)) y_slice = ravel(y)[ij] eta_slice = ravel(q[3,:,:])[ij] return y_slice, eta_slice
def slice_xp(current_data): from pylab import find,ravel x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q ij = find((y <= latitude+dy+dy/2.) & (y > latitude+dy-dy/2.)) x_slice = ravel(x)[ij] eta_slice = ravel(q[3,:,:])[ij] return x_slice, eta_slice
def slice_x(current_data): from pylab import find,ravel x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q ij = find((y <= latitude+dy/2.) & (y > latitude-dy/2.)) x_slice = ravel(x)[ij] eta_slice = ravel(q[3,:,:])[ij] print "+++ min eta = ",eta_slice.min() return x_slice, eta_slice
def xsec(current_data): # Return x value and surface eta at this point, along y=0 from pylab import find, ravel x = current_data.x y = current_data.y dy = current_data.dy ij = find((y <= dy / 2.) & (y > -dy / 2.)) x_slice = ravel(x)[ij] eta_slice = ravel(plot_eta(current_data))[ij] return x_slice, eta_slice
def xsec(current_data): # Return x value and surface eta at this point, along y=0 from pylab import find,ravel x = current_data.x y = current_data.y dy = current_data.dy ij = find((y <= dy/2.) & (y > -dy/2.)) x_slice = ravel(x)[ij] eta_slice = ravel(plot_eta(current_data))[ij] return x_slice, eta_slice
def xsec(current_data): # Return x value and surface eta at this point, along y=0 from pylab import find,ravel x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q ij = find((y <= y0+dy/2.+1e-8) & (y > y0-dy/2.)) x_slice = ravel(x)[ij] eta_slice = ravel(q[3,:,:])[ij] return x_slice, eta_slice
def xsec_hu(current_data): # Return x value and discharge at this point, along y=0 from pylab import find,ravel,where,sqrt x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q hu = q[1,:] ij = find((y <= 0.76+dy/2.) & (y > 0.76-dy/2.)) x_slice = ravel(x)[ij] hu_slice = ravel(hu)[ij] return x_slice, hu_slice
def xsec(current_data): # Return x value and surface eta at this point, along y=0 from pylab import where, ravel x = current_data.x y = ravel(current_data.y) dy = current_data.dy q = current_data.q ij = where((y <= y0 + dy / 2. + 1e-8) & (y > y0 - dy / 2.))[0] x_slice = ravel(x)[ij] eta_slice = ravel(q[3, :, :])[ij] return x_slice, eta_slice
def xsec(current_data): # Return x value and surface eta at this point, along y=0 from pylab import ravel x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q ij = numpy.argwhere((y <= dy / 2.) & (y > -dy / 2.)) x_slice = ravel(x)[ij] eta_slice = ravel(q[3, :, :])[ij] return x_slice, eta_slice
def B_x(current_data): from pylab import find,ravel x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q ij = find((y <= latitude+dy+dy/2.) & (y > latitude+dy-dy/2.)) x_slice = ravel(x)[ij] eta_slice = ravel(q[3,:,:])[ij] h_slice = ravel(q[0,:,:])[ij] B_slice = eta_slice - h_slice return x_slice, B_slice
def slice_x(current_data): from pylab import find,ravel,where x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q ij = find((y <= latitude+dy/2.) & (y > latitude-dy/2.)) x_slice = ravel(x)[ij] eta_slice = ravel(q[3,:,:])[ij] h_slice = ravel(q[0,:,:])[ij] hu_slice = ravel(q[1,:,:])[ij] u_slice = where(h_slice>0, hu_slice/h_slice, 0.) return x_slice, u_slice
def slice_y(current_data): from pylab import find,ravel,where x = current_data.x y = current_data.y dx = current_data.dx q = current_data.q ij = find((x <= longitude+dx/2.) & (x > longitude-dx/2.)) y_slice = ravel(y)[ij] eta_slice = ravel(q[3,:,:])[ij] h_slice = ravel(q[0,:,:])[ij] hv_slice = ravel(q[2,:,:])[ij] v_slice = where(h_slice>0, hv_slice/h_slice, 0.) return y_slice, hv_slice
def ysec(current_data): # Return x value and surface eta at this point, along y=0 from pylab import find,ravel x = current_data.x y = current_data.y dx = current_data.dx q = current_data.q t = current_data.t xlower = current_data.xlower xupper = current_data.xupper ij = find((x <= dx/2.) & (x > -dx/2.)) y_slice = ravel(y)[ij] eta_slice = ravel(q[3,:,:])[ij] #print 'data' #print y_slice #fname = 'surface%d'%int(t)+'.txt' fname = r'/Users/huitang/clawpack-5.2.0/geoclaw/examples/tsunami/bowl-radial/_output/'+'surface_t=%d'%int(t)+'_ylower=%d'%int(y[1,1])+'.txt' fname2 = r'/Users/huitang/clawpack-5.2.0/geoclaw/examples/tsunami/bowl-radial/_output/location'+'_ylower=%d'%int(y[1,1])+'.txt' fname3 = r'/Users/huitang/clawpack-5.2.0/geoclaw/examples/tsunami/bowl-radial/_output/'+'momentums_t=%d'%int(t)+'_ylower=%d'%int(y[1,1])+'.txt' fname4 = r'/Users/huitang/clawpack-5.2.0/geoclaw/examples/tsunami/bowl-radial/_output/'+'depth_t=%d'%int(t)+'_ylower=%d'%int(y[1,1])+'.txt' savetxt(fname3,ravel(q[2,:,:])[ij]) savetxt(fname,ravel(q[3,:,:])[ij]) savetxt(fname4,ravel(q[0,:,:])[ij]) savetxt(fname2,ravel(y)[ij]) print '***********************************************' #print y[1] print ravel(q[0,:,:])[ij] #print y_slice #print y[1,1] #print xlower #print eta_slice return y_slice, eta_slice
def B_y(current_data): from pylab import find,ravel x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q dx = current_data.dx q = current_data.q ij = find((x <= longitude+dx/2.) & (x > longitude-dx/2.)) y_slice = ravel(y)[ij] eta_slice = ravel(q[3,:,:])[ij] h_slice = ravel(q[0,:,:])[ij] B_slice = eta_slice - h_slice return y_slice, B_slice
def xsec_B(current_data): # Return x value and B at this point, along y=0 from pylab import find, ravel, where, sqrt x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q h = q[0, :] eta = q[3, :] B = eta - h ij = find((y <= dy / 2.) & (y > -dy / 2.)) x_slice = ravel(x)[ij] B_slice = ravel(B)[ij] return x_slice, B_slice
def xsec(current_data): # Return x value and surface depth at this point, along y=0 from pylab import where, ravel x = current_data.x y = ravel(current_data.y) dy = current_data.dy q = current_data.q ij = where((y <= dy / 1.) & (y > -dy / 1.)) x_slice = ravel(x)[ij] ij1 = where((x_slice > 40.40) | (x_slice < 40.0)) x_slice = x_slice[ij1] depth_slice = ravel(q[0, :, :])[ij] depth_slice = depth_slice[ij1] return x_slice, depth_slice
def xsec_B(current_data): # Return x value and B at this point, along y=0 from pylab import find,ravel,where,sqrt x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q h = q[0,:] eta = q[3,:] B = eta - h ij = find((y <= dy/2.) & (y > -dy/2.)) x_slice = ravel(x)[ij] B_slice = ravel(B)[ij] return x_slice, B_slice
def pcolor_matrix_pylab(A, fname='pcolor_matrix_matplotlib'): """ pcolor_matrix_pylab() implements a matlab-like 'pcolor' function to display the large elements of a matrix in pseudocolor using the Python Imaging Library. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!' logging.error( 'pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!' ) return 0 try: import numpy pylab.clf() x = pylab.arange(A.shape[0]) X, Y = pylab.meshgrid(x, x) xmin = min(pylab.ravel(X)) xmax = max(pylab.ravel(X)) pylab.xlim(xmin, xmax) ymin = min(pylab.ravel(Y)) ymax = max(pylab.ravel(Y)) pylab.ylim(ymin, ymax) pylab.axis('off') pylab.pcolor(X, Y, pylab.transpose(A)) #, shading='flat') pylab.clim(0.0, 1.0) plotfile = '%s.png' % (fname) myplotfile = open(plotfile, 'w') pylab.savefig(myplotfile) myplotfile.close() return 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.' % ( plotfile) logging.error( 'pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.', (plotfile)) return 0
def Boxplot ( x, ax=None, offset=0.005, **kwargs ): """Creates a Tufte boxplot :Parameters: *x* values to be summarized *ax* target axes *offset* offset to mark central part and median gap :Optional keyword arguments: See pylab.boxplot """ if ax is None: ax = pl.gca() # call a boxplot and manipulate it # how to get the offset right? if hasattr (x,'shape'): if len(x.shape)==1: if hasattr(x[0], 'shape'): x = list(x) else: x = [x,] elif len(x.shape) == 2: nr, nc = x.shape if nr==1: x = [x] elif nc==1: x = [x.ravel()] else: x = [x[:,i] for i in xrange(nc)] else: raise ValueError, "input x can have no more than 2 dimensions" if not hasattr(x[0],'__len__'): x = [x] positions = kwargs.setdefault ( 'positions', range(1,len(x)+1) ) pdist = max(positions)-min(positions) offs = 0.5*float(pdist)/len(positions) if kwargs.setdefault('vert', 0 ) == 1: ax.set_ylim ( positions[0]-offs, positions[-1]+offs ) ax.set_yticks ( positions ) else: ax.set_xlim ( positions[0]-offs, positions[-1]+offs ) ax.set_xticks ( positions ) c = kwargs.setdefault ( 'color', [0,0,0] ) c = dvis.color.colorsequence ( c ) for i,pos in enumerate ( positions ): d = pl.ravel(x[i]) kwargs['color'] = c[i%len(c)] ax.add_artist ( BoxplotArtist ( pos, calculate_boxplot_stats ( d, **kwargs ), offset, **kwargs ) )
def xsec(current_data): # Return x value and surface eta at this point, along y=0 from pylab import find, ravel x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q aux = current_data.aux ij = find((y <= dy / 2.) & (y > -dy / 2.)) x_slice = ravel(x)[ij] gamma_slice = ravel(aux[0, :, :])[ij] pinf_slice = ravel(aux[1, :, :])[ij] rho_slice = ravel(q[0, :, :])[ij] momx_slice = ravel(q[1, :, :])[ij] momy_slice = ravel(q[2, :, :])[ij] ene_slice = ravel(q[3, :, :])[ij] P_slice = (gamma_slice - 1.0) * (ene_slice - 0.5 * (momx_slice**2 + momy_slice**2) / rho_slice) P_slice = P_slice - gamma_slice * pinf_slice # Convert to Psi and centimeters P_slice = P_slice * 0.000145038 - 14.6959488 x_slice = 100 * x_slice return x_slice, P_slice
def xsec_s(current_data): # Return x value and speed at this point, along y=0 from pylab import find, ravel, where, sqrt x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q h = q[0, :] dry_tol = 0.001 u = where(h > dry_tol, q[1, :] / h, 0.) v = where(h > dry_tol, q[2, :] / h, 0.) s = sqrt(u**2 + v**2) s = s / sqrt(9.81 / 0.97) # so comparable to eta ij = find((y <= dy / 2.) & (y > -dy / 2.)) x_slice = ravel(x)[ij] s_slice = ravel(s)[ij] return x_slice, s_slice
def xsec_s(current_data): # Return x value and speed at this point, along y=0 from pylab import find,ravel,where,sqrt x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q h = q[0,:] dry_tol = 0.001 u = where(h>dry_tol, q[1,:]/h, 0.) v = where(h>dry_tol, q[2,:]/h, 0.) s = sqrt(u**2 + v**2) s = s / sqrt(9.81/0.97) # so comparable to eta ij = find((y <= dy/2.) & (y > -dy/2.)) x_slice = ravel(x)[ij] s_slice = ravel(s)[ij] return x_slice, s_slice
def plot_contour_lines(plot_data, xy_data=None, show_regression=False, \ show_equation=False, smooth_steps=0, num_contour_lines=10, \ label_contours=False, line_cmap=cm.hot, fill_cmap=cm.gray,dark=True, graph_shape='rect', prob_axes=False, **kwargs): """helper plots one or more series of contour line data calls the initializing functions, doesn't output figure takes: plot_data, xy_data, show_regression, show_equation, smooth, num_contour_lines, label_contours, line_cmap, fill_cmap, graph_shape, and **kwargs passed on to init_graph_display. plot_data = (x_bin, y_bin, data_matrix dot_colors) """ if prob_axes: extent = (0, 1, 0, 1) else: a = gca() extent = a.get_xlim() + a.get_ylim() #init graph display, rectangular due to needed colorbar space init_graph_display(graph_shape=graph_shape, dark=dark, **kwargs) #plots the contour data for x_bin, y_bin, data in plot_data: orig_max = max(ravel(data)) scaled_data = (data / orig_max * 255).astype('b') if smooth_steps and (Image is not None): orig_shape = data.shape im = Image.fromstring('L', data.shape, scaled_data) for i in range(smooth_steps): im = im.filter(ImageFilter.BLUR) new_data = fromstring(im.tostring(), 'b') data = reshape(new_data.astype('i') / 255.0 * orig_max, orig_shape) if fill_cmap is not None: im = imshow(data, interpolation='bicubic', extent=extent, \ origin='lower', cmap=fill_cmap) result = contour(x_bin, y_bin, data, num_contour_lines, origin='lower', linewidth=2, extent=extent, cmap=line_cmap) if label_contours: clabel(result, fmt='%1.1g') #add the colorbar legend to the side cb = colorbar() cb.ax.axisbg = 'black' if show_regression: equation = plot_regression_line(xy_data[0], xy_data[1], prob_axes=prob_axes) if show_equation: add_regression_equations([equation])
def xsec(current_data): # Return x value and surface depth at this point, along y=0 from pylab import where, ravel x = current_data.x y = ravel(current_data.y) dy = current_data.dy q = current_data.q frameno= str(current_data.frameno) ij = where((y <= dy/1.) & (y > -dy/1.)) x_slice = ravel(x)[ij] ij1 = where((x_slice > 40.40) | (x_slice < 40.0)) x_slice = x_slice[ij1] depth_slice = ravel(q[0, :, :])[ij] depth_slice = depth_slice[ij1] profile_arr = np.array([np.transpose(x_slice), np.transpose(depth_slice)]) data_frame = pandas.DataFrame(profile_arr.T) data_frame.to_csv(frameno+'_profile.csv') return x_slice, depth_slice
def pcolor_matrix_pylab(A, fname='pcolor_matrix_matplotlib'): """ pcolor_matrix_pylab() implements a matlab-like 'pcolor' function to display the large elements of a matrix in pseudocolor using the Python Imaging Library. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!' logging.error('pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!') return 0 try: import numpy pylab.clf() x = pylab.arange(A.shape[0]) X, Y = pylab.meshgrid(x,x) xmin = min(pylab.ravel(X)) xmax = max(pylab.ravel(X)) pylab.xlim(xmin, xmax) ymin = min(pylab.ravel(Y)) ymax = max(pylab.ravel(Y)) pylab.ylim(ymin, ymax) pylab.axis('off') pylab.pcolor(X, Y, pylab.transpose(A))#, shading='flat') pylab.clim(0.0, 1.0) plotfile = '%s.png' % (fname) myplotfile = open(plotfile,'w') pylab.savefig(myplotfile) myplotfile.close() return 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.' % (plotfile) logging.error('pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.', (plotfile)) return 0
def apply_mask(x): """ Gets arrays with NaN from MAT files and applies python masked_where """ f = pl.find(pl.isnan(x) == 1) l1, l2 = x.shape x = pl.ravel(x) x[f] = 0 x.shape = (l1,l2) x = pl.ma.masked_where(x == 0, x) return x
def __call__(self, lon, lat, inverse=False): """ Calling a Proj class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y native map projection coordinates (in meters). If optional keyword 'inverse' is True (default is False), the inverse transformation from x/y to lon/lat is performed. For cylindrical equidistant projection ('cyl'), this does nothing (i.e. x,y == lon,lat). lon,lat can be either scalar floats or N arrays. """ if self.projection == "cyl": # for cyl x,y == lon,lat return lon, lat # if inputs are numarray arrays, get shape and typecode. try: shapein = lon.shape lontypein = lon.typecode() lattypein = lat.typecode() except: shapein = False # make sure inputs have same shape. if shapein and lat.shape != shapein: raise ValueError, "lon, lat must be scalars or numarrays with the same shape" if shapein: x = N.ravel(lon).tolist() y = N.ravel(lat).tolist() if inverse: outx, outy = self._inv(x, y) else: outx, outy = self._fwd(x, y) outx = N.reshape(N.array(outx, lontypein), shapein) outy = N.reshape(N.array(outy, lattypein), shapein) else: if inverse: outx, outy = self._inv(lon, lat) else: outx, outy = self._fwd(lon, lat) return outx, outy
def __call__(self, lon, lat, inverse=False): """ Calling a Proj class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y native map projection coordinates (in meters). If optional keyword 'inverse' is True (default is False), the inverse transformation from x/y to lon/lat is performed. For cylindrical equidistant projection ('cyl'), this does nothing (i.e. x,y == lon,lat). lon,lat can be either scalar floats or N arrays. """ if self.projection == 'cyl': # for cyl x,y == lon,lat return lon, lat # if inputs are numarray arrays, get shape and typecode. try: shapein = lon.shape lontypein = lon.typecode() lattypein = lat.typecode() except: shapein = False # make sure inputs have same shape. if shapein and lat.shape != shapein: raise ValueError, 'lon, lat must be scalars or numarrays with the same shape' if shapein: x = N.ravel(lon).tolist() y = N.ravel(lat).tolist() if inverse: outx, outy = self._inv(x, y) else: outx, outy = self._fwd(x, y) outx = N.reshape(N.array(outx, lontypein), shapein) outy = N.reshape(N.array(outy, lattypein), shapein) else: if inverse: outx, outy = self._inv(lon, lat) else: outx, outy = self._fwd(lon, lat) return outx, outy
def plot_contour_lines(plot_data, xy_data=None, show_regression=False, \ show_equation=False, smooth_steps=0, num_contour_lines=10, \ label_contours=False, line_cmap=cm.hot, fill_cmap=cm.gray,dark=True, graph_shape='rect', prob_axes=False, **kwargs): """helper plots one or more series of contour line data calls the initializing functions, doesn't output figure takes: plot_data, xy_data, show_regression, show_equation, smooth, num_contour_lines, label_contours, line_cmap, fill_cmap, graph_shape, and **kwargs passed on to init_graph_display. plot_data = (x_bin, y_bin, data_matrix dot_colors) """ if prob_axes: extent = (0,1,0,1) else: a = gca() extent = a.get_xlim()+a.get_ylim() #init graph display, rectangular due to needed colorbar space init_graph_display(graph_shape=graph_shape, dark=dark, **kwargs) #plots the contour data for x_bin,y_bin,data in plot_data: orig_max = max(ravel(data)) scaled_data = (data/orig_max*255).astype('b') if smooth_steps and (Image is not None): orig_shape = data.shape im = Image.fromstring('L', data.shape, scaled_data) for i in range(smooth_steps): im = im.filter(ImageFilter.BLUR) new_data = fromstring(im.tostring(), 'b') data = reshape(new_data.astype('i')/255.0 * orig_max, orig_shape) if fill_cmap is not None: im = imshow(data, interpolation='bicubic', extent=extent, \ origin='lower', cmap=fill_cmap) result=contour(x_bin,y_bin,data, num_contour_lines, origin='lower',linewidth=2, extent=extent, cmap=line_cmap) if label_contours: clabel(result, fmt='%1.1g') #add the colorbar legend to the side cb = colorbar() cb.ax.axisbg = 'black' if show_regression: equation=plot_regression_line(xy_data[0],xy_data[1],prob_axes=prob_axes) if show_equation: add_regression_equations([equation])
def describe_vars(d): m = mc.Model(d) df = pandas.DataFrame(columns=["type", "value", "logp"], index=[n.__name__ for n in m.nodes], dtype=object) for n in m.nodes: k = n.__name__ df.ix[k, "type"] = type(n).__name__ if hasattr(n, "value"): rav = pl.ravel(n.value) if len(rav) == 1: df.ix[k, "value"] = n.value elif len(rav) > 1: df.ix[k, "value"] = "%.1f, ..." % rav[0] df.ix[k, "logp"] = getattr(n, "logp", pl.nan) return df.sort("logp")
def describe_vars(d): m = mc.Model(d) df = pd.DataFrame(columns=['type', 'value', 'logp'], index=[n.__name__ for n in m.nodes], dtype=object) for n in m.nodes: k = n.__name__ df.ix[k, 'type'] = type(n).__name__ if hasattr(n, 'value'): rav = pl.ravel(n.value) if len(rav) == 1: df.ix[k, 'value'] = n.value elif len(rav) > 1: df.ix[k, 'value'] = '%.1f, ...' % rav[0] df.ix[k, 'logp'] = getattr(n, 'logp', pl.nan) return df.sort('logp')
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 xsec(current_data): # Return x value and surface eta at this point, along y=0 from pylab import find,ravel x = current_data.x y = current_data.y dy = current_data.dy q = current_data.q aux = current_data.aux ij = find((y <= dy/2.) & (y > -dy/2.)) x_slice = ravel(x)[ij] gamma_slice = ravel(aux[0,:,:])[ij] pinf_slice = ravel(aux[1,:,:])[ij] rho_slice = ravel(q[0,:,:])[ij] momx_slice = ravel(q[1,:,:])[ij] momy_slice = ravel(q[2,:,:])[ij] ene_slice = ravel(q[3,:,:])[ij] P_slice = (gamma_slice - 1.0)*(ene_slice - 0.5*(momx_slice**2 + momy_slice**2)/rho_slice) P_slice = P_slice - gamma_slice*pinf_slice # Convert to Psi and centimeters P_slice = P_slice*0.000145038 - 14.6959488 x_slice = 100*x_slice return x_slice, P_slice
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]
w = 0.4 h = 0.22 ax = [] images = [] vmin = 1e40 vmax = -1e40 for i in range(Nr): for j in range(Nc): pos = [0.075 + j*1.1*w, 0.18 + i*1.2*h, w, h] a = fig.add_axes(pos) if i > 0: a.set_xticklabels([]) # Make some fake data with a range that varies # somewhat from one plot to the next. data =((1+i+j)/10.0)*pylab.rand(10,20)*1e-6 dd = pylab.ravel(data) # Manually find the min and max of all colors for # use in setting the color scale. vmin = min(vmin, amin(dd)) vmax = max(vmax, amax(dd)) images.append(a.imshow(data, cmap=cmap)) ax.append(a) # Set the first image as the master, with all the others # observing it for changes in cmap or norm. norm = colors.normalize(vmin=vmin, vmax=vmax) for i, im in enumerate(images): im.set_norm(norm) if i > 0: images[0].add_observer(im)
def draw_arrow(pair, alpha=alpha, ec=ec, labelcolor=labelcolor): #set the length of the arrow if display == 'length': length = max_head_length+(max_arrow_length-max_head_length)*\ data[pair]/sf else: length = max_arrow_length #set the transparency of the arrow if display == 'alph': alpha = min(data[pair] / sf, alpha) else: alpha = alpha #set the width of the arrow if display == 'width': scale = data[pair] / sf width = max_arrow_width * scale head_width = max_head_width * scale head_length = max_head_length * scale else: width = max_arrow_width head_width = max_head_width head_length = max_head_length fc = colors[pair] ec = ec or fc x_scale, y_scale = deltas[pair] x_pos, y_pos = positions[pair] arrow(ax, x_pos, y_pos, x_scale*length, y_scale*length, \ fc=fc, ec=ec, alpha=alpha, width=width, head_width=head_width, \ head_length=head_length, **arrow_params) #figure out coordinates for text #if drawing relative to base: x and y are same as for arrow #dx and dy are one arrow width left and up #need to rotate based on direction of arrow, use x_scale and y_scale #as sin x and cos x? sx, cx = y_scale, x_scale alo = arrow_label_offset = 3.5 * max_arrow_width where = label_positions[pair] if where == 'left': orig_position = array([[alo, alo]]) elif where == 'absolute': orig_position = array([[max_arrow_length / 2.0, alo]]) elif where == 'right': orig_position = array([[length - alo, alo]]) elif where == 'center': orig_position = array([[length / 2.0, alo]]) else: raise ValueError, "Got unknown position parameter %s" % where M = array([[cx, sx], [-sx, cx]]) coords = dot(orig_position, M) + [[x_pos, y_pos]] x, y = ravel(coords) orig_label = rate_labels[pair] label = '$%s_{_{\mathrm{%s}}}$' % (orig_label[0], orig_label[1:]) text(x, y, label, size=label_text_size, ha='center', va='center', \ color=labelcolor or fc)
# add cyclic points slp = p.zeros((slpin.shape[0], slpin.shape[1], slpin.shape[2] + 1), p.Float64) slp[:, :, 0:-1] = slpin slp[:, :, -1] = slpin[:, :, 0] u = p.zeros((uin.shape[0], uin.shape[1], uin.shape[2] + 1), p.Float64) u[:, :, 0:-1] = uin u[:, :, -1] = uin[:, :, 0] v = p.zeros((vin.shape[0], vin.shape[1], vin.shape[2] + 1), p.Float64) v[:, :, 0:-1] = vin v[:, :, -1] = vin[:, :, 0] longitudes.append(360.) longitudes = p.array(longitudes) # make 2-d grid of lons, lats lons, lats = p.meshgrid(longitudes, latitudes) print 'min/max slp,u,v' print min(p.ravel(slp)), max(p.ravel(slp)) print min(p.ravel(uin)), max(p.ravel(uin)) print min(p.ravel(vin)), max(p.ravel(vin)) print 'dates' print datelabels # make orthographic basemap. m = Basemap(resolution='c', projection='ortho', lat_0=60., lon_0=-60.) p.ion() # interactive mode on. uin = p.squeeze(udata[ntime1:ntime2 + 1, 0, :, :]) vin = p.squeeze(vdata[ntime1:ntime2 + 1, 0, :, :]) datelabels = dates[ntime1:ntime2 + 1] # make orthographic basemap. m = Basemap(resolution='c', projection='ortho', lat_0=60., lon_0=-60.) p.ion() # interactive mode on. # create figure, add axes (leaving room for colorbar on right) fig = p.figure()
################################################# fig1 = plt.figure(1,figsize=(15,8),facecolor='w') ################################################################################### oe2 = sp.loadmat('/home/rsoutelino/prod/grl_msc/proc/psiobs_OEII.mat') psiob = oe2.pop('psiob') xgi = oe2.pop('xgi'); ygi = oe2.pop('ygi'); uo = oe2.pop('uo'); vo = oe2.pop('vo'); s = 2; # masking f = pl.find(pl.isnan(psiob) == 1); a, b = psiob.shape; psiob = pl.ravel(psiob); uo = pl.ravel(uo); vo = pl.ravel(vo); psiob[f] = 0; uo[f] = 0; vo[f] = 0; psiob.shape = (a,b); uo.shape = (a,b); vo.shape = (a,b) psiob = pl.ma.masked_where(psiob == 0, psiob) uo = pl.ma.masked_where(uo == 0, uo) vo = pl.ma.masked_where(vo == 0, vo) g = 1 p1 = plt.subplot(131) #con = m.contourf(xgi,ygi,psigo,scale,linewidth=0,alpha = 0.5); m.quiver(xgi[::g,::g], ygi[::g,::g], uo[::g,::g]*s, vo[::g,::g]*s, scale=10); m.contourf(xb,yb,zb,colors=('0.9'),linewidth=0); m.drawcoastlines(zorder=5) m.drawcountries(zorder=4)
ulcornery = dy * (ny - 1) urcornerx = dx * (nx - 1) urcornery = dy * (ny - 1) llcornerlon, llcornerlat = awips221(llcornerx, llcornery, inverse=True) lrcornerlon, lrcornerlat = awips221(lrcornerx, lrcornery, inverse=True) urcornerlon, urcornerlat = awips221(urcornerx, urcornery, inverse=True) ulcornerlon, ulcornerlat = awips221(ulcornerx, ulcornery, inverse=True) print '4 corners of AWIPS grid 221:' print llcornerlon, llcornerlat print lrcornerlon, lrcornerlat print urcornerlon, urcornerlat print ulcornerlon, ulcornerlat print 'from GRIB docs' print '(see http://www.nco.ncep.noaa.gov/pmb/docs/on388/tableb.html)' print ' -145.5 1.0' print ' -68.318 0.897' print ' -2.566 46.352' print ' 148.639 46.635' # compute lons and lats for the whole AWIPS grid 221 (377x249). import time t1 = time.clock() lons, lats = awips221.makegrid(nx, ny) t2 = time.clock() print 'compute lats/lons for all points on AWIPS 221 grid (%sx%s)' % (nx, ny) print 'max/min lons' print min(N.ravel(lons)), max(N.ravel(lons)) print 'max/min lats' print min(N.ravel(lats)), max(N.ravel(lats)) print 'took', t2 - t1, 'secs'
def draw(board): return all(ravel(board != '.'))
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]
# parallels/meridians # illustrates special-case polar-centric projections. from matplotlib.toolkits.basemap import Basemap from pylab import title, colorbar, show, axes, cm, load, arange, \ figure, ravel, meshgrid # read in topo data (on a regular lat/lon grid) # longitudes go from 20 to 380. etopo = load('etopo20data.gz') lons = load('etopo20lons.gz') lats = load('etopo20lats.gz') print 'min/max etopo20 data:' print min(ravel(etopo)),max(ravel(etopo)) # these are the 4 polar projections projs = ['laea','stere','aeqd','ortho'] # short names # long names projnames = ['Lambert Azimuthal Equal Area','Stereographic','Azimuthal Equidistant','Orthographic'] # loop over hemispheres, make a 4-panel plot for each hemisphere # showing all four polar projections. for hem in ['North','South']: if hem == 'South': lon_0 = 130. lon_0_ortho = lon_0 - 180. lat_0 = -90. bounding_lat = -20. elif hem == 'North': lon_0 = -90.
from pylab import show,arange,draw,figure,load,ravel,cm,axes,\ colorbar,title,gca,pi,meshgrid import matplotlib.colors as colors # read in topo data (on a regular lat/lon grid) # longitudes go from 20 to 380. topodatin = load('etopo20data.gz') lonsin = load('etopo20lons.gz') latsin = load('etopo20lats.gz') # shift data so lons go from -180 to 180 instead of 20 to 380. topoin, lons = shiftgrid(180., topodatin, lonsin, start=False) lats = latsin print 'min/max etopo20 data:' print min(ravel(topoin)), max(ravel(topoin)) # create new figure fig = figure() # setup cylindrical equidistant map projection (global domain). m = Basemap(llcrnrlon=-180.,llcrnrlat=-90,urcrnrlon=180.,urcrnrlat=90.,\ resolution='c',area_thresh=10000.,projection='cyl') ax = fig.add_axes([0.1, 0.1, 0.7, 0.7]) # plot image over map. im = m.imshow(topoin, cm.jet) l, b, w, h = ax.get_position() cax = axes([l + w + 0.05, b, 0.05, h]) # setup colorbar axes. colorbar(cax=cax) # draw colorbar axes(ax) # make the original axes current again m.drawcoastlines() #m.drawcountries()
dat = sp.loadmat('/home/rsoutelino/prod/grl_msc/proc/aviso_omar.mat') mag = dat.pop('mag') lon = dat.pop('lon') lat = dat.pop('lat') um = dat.pop('um') vm = dat.pop('vm') tt = dat.pop('tt') Vab = dat.pop('Vab') Vcf = dat.pop('Vcf') lon, lat = m(lon, lat) # masking f = pl.find(pl.isnan(mag) == 1) a, b = mag.shape mag = pl.ravel(mag) um = pl.ravel(um) vm = pl.ravel(vm) mag[f] = 0 um[f] = 0 vm[f] = 0 mag.shape = (a, b) um.shape = (a, b) vm.shape = (a, b) mag = pl.ma.masked_where(mag == 0, mag) um = pl.ma.masked_where(um == 0, um) vm = pl.ma.masked_where(vm == 0, vm) print " " print "Loading etopo data ....... " etopo = sp.loadmat('/home/rsoutelino/prod/grl_msc/proc/etopo2_atlsul.mat')
ulcornery = dy * (ny - 1) urcornerx = dx * (nx - 1) urcornery = dy * (ny - 1) llcornerlon, llcornerlat = awips221(llcornerx, llcornery, inverse=True) lrcornerlon, lrcornerlat = awips221(lrcornerx, lrcornery, inverse=True) urcornerlon, urcornerlat = awips221(urcornerx, urcornery, inverse=True) ulcornerlon, ulcornerlat = awips221(ulcornerx, ulcornery, inverse=True) print "4 corners of AWIPS grid 221:" print llcornerlon, llcornerlat print lrcornerlon, lrcornerlat print urcornerlon, urcornerlat print ulcornerlon, ulcornerlat print "from GRIB docs" print "(see http://www.nco.ncep.noaa.gov/pmb/docs/on388/tableb.html)" print " -145.5 1.0" print " -68.318 0.897" print " -2.566 46.352" print " 148.639 46.635" # compute lons and lats for the whole AWIPS grid 221 (377x249). import time t1 = time.clock() lons, lats = awips221.makegrid(nx, ny) t2 = time.clock() print "compute lats/lons for all points on AWIPS 221 grid (%sx%s)" % (nx, ny) print "max/min lons" print min(N.ravel(lons)), max(N.ravel(lons)) print "max/min lats" print min(N.ravel(lats)), max(N.ravel(lats)) print "took", t2 - t1, "secs"
################################################# fig1 = plt.figure(1,figsize=(15,8),facecolor='w') ################################################################################### oe1 = sp.loadmat('/home/rsoutelino/prod/grl_msc/proc/psigeo_OEI.mat') psigo = oe1.pop('psigo') xgi = oe1.pop('xgi'); ygi = oe1.pop('ygi'); xgi,ygi = m(xgi,ygi) uctd = oe1.pop('uctd'); vctd = oe1.pop('vctd'); # masking f = pl.find(pl.isnan(psigo) == 1); a, b = psigo.shape; psigo = pl.ravel(psigo); uctd = pl.ravel(uctd); vctd = pl.ravel(vctd); psigo[f] = 0; uctd[f] = 0; vctd[f] = 0; psigo.shape = (a,b); uctd.shape = (a,b); vctd.shape = (a,b) psigo = pl.ma.masked_where(psigo == 0, psigo) uctd = pl.ma.masked_where(uctd == 0, uctd) vctd = pl.ma.masked_where(vctd == 0, vctd) g = 1 p1 = plt.subplot(131) #con = m.contourf(xgi,ygi,psigo,scale,linewidth=0,alpha = 0.5); m.quiver(xgi[::g,::g],ygi[::g,::g],uctd[::g,::g]*s,vctd[::g,::g]*s,scale=10); m.contourf(xb,yb,zb,colors=('0.9'),linewidth=0); m.drawcoastlines(zorder=5) m.drawcountries(zorder=4)
def draw_arrow(pair, alpha=alpha, ec=ec, labelcolor=labelcolor): #set the length of the arrow if display == 'length': length = max_head_length+(max_arrow_length-max_head_length)*\ data[pair]/sf else: length = max_arrow_length #set the transparency of the arrow if display == 'alph': alpha = min(data[pair]/sf, alpha) else: alpha=alpha #set the width of the arrow if display == 'width': scale = data[pair]/sf width = max_arrow_width*scale head_width = max_head_width*scale head_length = max_head_length*scale else: width = max_arrow_width head_width = max_head_width head_length = max_head_length fc = colors[pair] ec = ec or fc x_scale, y_scale = deltas[pair] x_pos, y_pos = positions[pair] arrow(ax, x_pos, y_pos, x_scale*length, y_scale*length, \ fc=fc, ec=ec, alpha=alpha, width=width, head_width=head_width, \ head_length=head_length, **arrow_params) #figure out coordinates for text #if drawing relative to base: x and y are same as for arrow #dx and dy are one arrow width left and up #need to rotate based on direction of arrow, use x_scale and y_scale #as sin x and cos x? sx, cx = y_scale, x_scale alo = arrow_label_offset = 3.5*max_arrow_width where = label_positions[pair] if where == 'left': orig_position = array([[alo, alo]]) elif where == 'absolute': orig_position = array([[max_arrow_length/2.0, alo]]) elif where == 'right': orig_position = array([[length-alo, alo]]) elif where == 'center': orig_position = array([[length/2.0, alo]]) else: raise ValueError, "Got unknown position parameter %s" % where M = array([[cx, sx],[-sx,cx]]) coords = dot(orig_position, M) + [[x_pos, y_pos]] x, y = ravel(coords) orig_label = rate_labels[pair] label = '$%s_{_{\mathrm{%s}}}$' % (orig_label[0], orig_label[1:]) text(x, y, label, size=label_text_size, ha='center', va='center', \ color=labelcolor or fc)
slpin = 0.01*p.squeeze(slpdata[ntime1:ntime2+1,:,:]) uin = p.squeeze(udata[ntime1:ntime2+1,0,:,:]) vin = p.squeeze(vdata[ntime1:ntime2+1,0,:,:]) datelabels = dates[ntime1:ntime2+1] # add cyclic points slp = p.zeros((slpin.shape[0],slpin.shape[1],slpin.shape[2]+1),p.Float64) slp[:,:,0:-1] = slpin; slp[:,:,-1] = slpin[:,:,0] u = p.zeros((uin.shape[0],uin.shape[1],uin.shape[2]+1),p.Float64) u[:,:,0:-1] = uin; u[:,:,-1] = uin[:,:,0] v = p.zeros((vin.shape[0],vin.shape[1],vin.shape[2]+1),p.Float64) v[:,:,0:-1] = vin; v[:,:,-1] = vin[:,:,0] longitudes.append(360.); longitudes = p.array(longitudes) # make 2-d grid of lons, lats lons, lats = p.meshgrid(longitudes,latitudes) print 'min/max slp,u,v' print min(p.ravel(slp)),max(p.ravel(slp)) print min(p.ravel(uin)),max(p.ravel(uin)) print min(p.ravel(vin)),max(p.ravel(vin)) print 'dates' print datelabels # make orthographic basemap. m = Basemap(resolution='c',projection='ortho',lat_0=60.,lon_0=-60.) p.ion() # interactive mode on. uin = p.squeeze(udata[ntime1:ntime2+1,0,:,:]) vin = p.squeeze(vdata[ntime1:ntime2+1,0,:,:]) datelabels = dates[ntime1:ntime2+1] # make orthographic basemap. m = Basemap(resolution='c',projection='ortho',lat_0=60.,lon_0=-60.) p.ion() # interactive mode on. # create figure, add axes (leaving room for colorbar on right) fig = p.figure()
################################################################################### oe2 = sp.loadmat('/home/rsoutelino/prod/grl_msc/proc/psiobs_OEII.mat') psiob = oe2.pop('psiob') xgi = oe2.pop('xgi') ygi = oe2.pop('ygi') uo = oe2.pop('uo') vo = oe2.pop('vo') s = 2 # masking f = pl.find(pl.isnan(psiob) == 1) a, b = psiob.shape psiob = pl.ravel(psiob) uo = pl.ravel(uo) vo = pl.ravel(vo) psiob[f] = 0 uo[f] = 0 vo[f] = 0 psiob.shape = (a, b) uo.shape = (a, b) vo.shape = (a, b) psiob = pl.ma.masked_where(psiob == 0, psiob) uo = pl.ma.masked_where(uo == 0, uo) vo = pl.ma.masked_where(vo == 0, vo) g = 1
# parallels/meridians # illustrates special-case polar-centric projections. from matplotlib.toolkits.basemap import Basemap from pylab import title, colorbar, show, axes, cm, load, arange, \ figure, ravel, meshgrid # read in topo data (on a regular lat/lon grid) # longitudes go from 20 to 380. etopo = load('etopo20data.gz') lons = load('etopo20lons.gz') lats = load('etopo20lats.gz') print 'min/max etopo20 data:' print min(ravel(etopo)), max(ravel(etopo)) # these are the 4 polar projections projs = ['laea', 'stere', 'aeqd', 'ortho'] # short names # long names projnames = [ 'Lambert Azimuthal Equal Area', 'Stereographic', 'Azimuthal Equidistant', 'Orthographic' ] # loop over hemispheres, make a 4-panel plot for each hemisphere # showing all four polar projections. for hem in ['North', 'South']: if hem == 'South': lon_0 = 130. lon_0_ortho = lon_0 - 180. lat_0 = -90.