Пример #1
0
def get_era_winds(m, rawdatapath, start_year, end_year, start_month,  end_month, xyres):

	wind_data = Dataset(rawdatapath+'/WINDS/ERA/DATA/ERAI_WINDS_MONTHLY_1979-2014.nc', 'r')
	lats = wind_data.variables['latitude'][::-1]
	lons = wind_data.variables['longitude'][:]
	time = wind_data.variables['time'][:]/(24.*30.)
	time = time-time[0]
	time=time.reshape(time.shape[0]/12,12)
	u10 = wind_data.variables['u10'][:, ::-1, :]
	v10 = wind_data.variables['v10'][:, ::-1, :]
	u10=u10.reshape(u10.shape[0]/12, 12,u10.shape[1],u10.shape[2])
	v10=v10.reshape(v10.shape[0]/12, 12, v10.shape[1],v10.shape[2])

	u10_winter_mean= np.mean(u10[start_year-1979:end_year-1979+1,start_month:end_month+1], axis=tuple(range(0, 2)))
	v10_winter_mean= np.mean(v10[start_year-1979:end_year-1979+1,start_month:end_month+1], axis=tuple(range(0, 2)))


	u10_winter_meanS, lonsS = shiftgrid(180.,u10_winter_mean,lons,start=False)
	v10_winter_meanS, lonsS = shiftgrid(180.,v10_winter_mean,lons,start=False)

	u10_winter_meanSC, lonsSC = addcyclic(u10_winter_meanS, lonsS)
	v10_winter_meanSC, lonsSC = addcyclic(v10_winter_meanS, lonsS)

	xyres=100

	xvel,yvel,xptsW,yptsW = m.transform_vector(u10_winter_meanSC,v10_winter_meanSC,lonsSC,lats,xyres,xyres,returnxy=True,masked=True)
	wind_speed = sqrt((xvel**2) + (yvel**2))


	wind_speed = sqrt((xvel**2) + (yvel**2))
	return xptsW, yptsW, xvel, yvel, wind_speed
Пример #2
0
def region_plot(fname, fname2, time, output_dir, julday):

	ncfile = nc.Dataset(fname,'r')

	fig = plt.figure(figsize=(20.48,10.24))
	ax = plt.axes([0,0,1,1],frameon=False)
	ax.set_axis_off()

	# set up a Basemap
	latrng = (-90.0,90.0)
	lonrng = (0,360)

	m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1],
        llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h',
        area_thresh=800,fix_aspect=False)

	lats = ncfile.variables["yu_ocean"][:]
	lons = ncfile.variables["xu_ocean"][:]
	u = ncfile.variables["u"][time,0,:,:]

	ncfile2 = nc.Dataset(fname2,'r')
	v = ncfile2.variables["v"][time,0,:,:]

	lons2 = lons

	u = ma.array(u)
	u = ma.masked_where(u <= -10.0, u)
	u = ma.masked_where(u >= 10.0, u)
	u = ma.masked_where(u == 0.0, u)

	u, lons = addcyclic(u, lons)

	v = ma.array(v)
	v = ma.masked_where(v <= -10.0, v)
	v = ma.masked_where(v >= 10.0, v)
	v = ma.masked_where(v == 0.0, v)

	v, lons2 = addcyclic(v, lons2)

	field = ((u**2 + v**2)**0.5)
	field = np.log(field)

	x,y = m(*np.meshgrid(lons[:],lats[:]))

	# cm.Blues looks pretty good
	colorMap = mpl.cm.Blues
	m.drawmapboundary(fill_color='white')
	nlevs = 256 
	clevs = np.linspace(-4.0,0.5,num=nlevs)
	
	cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False )
	m.fillcontinents(color='black', lake_color='black', zorder=1)
	save_file = "%s/%f.png" % (output_dir,julday)
	plt.savefig(save_file)
	
	ncfile.close()
Пример #3
0
    def plot(self):

        self.data, lonwrap = addcyclic(self.data, self.lons)

        # Sort latitudes and data
        lat_idx = np.argsort(self.lats)
        self.lats = self.lats[lat_idx]
        self.data = self.data[lat_idx]

        data_lon_min = min(lonwrap)
        data_lon_max = max(lonwrap)
        data_lat_min = min(self.lats)
        data_lat_max = max(self.lats)

        new_lons = np.arange(data_lon_min - 1.0, data_lon_max + 1.0, 1.0)
        new_lats = np.arange(data_lat_min - 1.0, data_lat_max + 1.0, 1.0)

        x, y = self.m(*np.meshgrid(new_lons[:], new_lats[:]))

        # Two pass interpolation to deal with the mask.
        # First pass does bilinear, the next does nearest neighbour
        # interpolation.
        # It's not clear this is working, and the problem is likely
        # solved by ensuring the right mask is used!
        data_bl = interp(self.data, lonwrap[:], self.lats[:], x, y, order=1)
        data_nn = interp(self.data, lonwrap[:], self.lats[:], x, y, order=0)

        data_bl[data_nn.mask == 1] = data_nn[data_nn.mask == 1]

        if self.parameters.has_key("color_levels"):
            self.__print_custom_color_plot(x, y, data_bl)
        else:
            self.__print_cmap_plot(x, y, data_bl)

        return self.main_render
Пример #4
0
def doplot(nc_file=None,varname=None,vmin=None,vmax=None,
           title=None):
    lons=nc_file.variables['lon'][...]
    lats=nc_file.variables['lat'][...]
    vals=nc_file.variables[varname]
    vals.set_auto_maskandscale(True)
    vals=vals[...]
    vals,lons=shiftgrid(180.,vals,lons,start=False)
    vals,lons=addcyclic(vals,lons)
    fig,ax = plt.subplots(1,1)
    ax.cla()
    cmap=cm.RdBu_r
    cmap.set_over('y')
    cmap.set_under('k')
    the_norm=Normalize(vmin=vmin,vmax=vmax,clip=False)
    params=dict(projection='moll',lon_0= 0,resolution='c')
    m = Basemap(**params)
    x, y = m(*np.meshgrid(lons, lats))
    im=m.pcolormesh(x,y,vals,cmap=cmap,norm=the_norm,ax=ax)
    cb=m.colorbar(im,extend='both',location='bottom')
    m.drawcoastlines()
    m.drawparallels(np.arange(-90.,120.,30.))
    m.drawmeridians(np.arange(0.,420.,60.))
    ax.set_title(title)
    return fig,m,ax,vals,lons
Пример #5
0
def test_run_hgt():
  #long term mean
  fname_mean = '/data01/forONR/hgt.mon.1981-2010.ltm.nc'
  lev_500 = 5 #level of 500hPa
  month = 8 #august
  
  dataMean = netCDF4.Dataset(fname_mean,'r')
  hgtMean = dataMean.variables['hgt'][month,lev_500,:,:] #lat,lon
  #hgtMean += dataMean.variables['hgt'][month-1,lev_500,:,:]
  #hgtMean += dataMean.variables['hgt'][month-2,lev_500,:,:]
  #hgtMean /= 3.
  latMean = dataMean.variables['lat'][:]*np.pi/180. #stored in degrees!
  lonMean = dataMean.variables['lon'][:]*np.pi/180.
  dataMean.close()
  
  nlat = len(latMean)
  nlon = len(lonMean)
  var = np.zeros((nlat,nlon), dtype=float)
  
  #mpas files
  #fnames = []
  fnames = sorted(glob.glob('/arctic1/nick/cases/vduda/x4/x4.t.output.2006-08-*'))
  fnames.extend(sorted(glob.glob('/arctic1/nick/cases/vduda/x4.t.output.2006-08-15*')))
  #fnames = sorted(glob.glob('/arctic1/nick/cases/vduda/x4/*.output.2006-08*'))
  counter = 0
  for iFile, fpath in enumerate(fnames):
    data = output_data.open_netcdf_data(fpath)
    nEdgesOnCell = data.variables['nEdgesOnCell'][:];
    cellsOnCell = data.variables['cellsOnCell'][:]-1;
    latCell = data.variables['latCell'][:];
    lonCell = data.variables['lonCell'][:];
    nTimes = len(data.dimensions['Time'])
    #nTimes = 1 #3
    
    nCells = len(latCell)
    geop_mpas = np.zeros(nCells,dtype=float)
    
    for iTime in xrange(nTimes):
      #get average value for mesh over these times so can even anomaly different meshes together
      output_data.print_xtime(data, iTime)
      hgt_mpas = data.variables['height_500hPa'][iTime,:]
      #average here to avoid summing to large number over many times
      geop_mpas += mpas_hgt2geopotential(nCells, hgt_mpas, latCell)/nTimes
      
    llMap = makeMap_ll2mpas(latMean, lonMean, latCell, lonCell, nEdgesOnCell, cellsOnCell)
    var += calc_diff_field(hgtMean, geop_mpas, llMap, nlat, nlon)
    #print var
    counter = counter+1
    
    data.close()
    
  var /= counter
  #var = hgtMean
  # add wrap-around point in longitude.
  var, lonMean = addcyclic(var, lonMean)
  np.savez('tmp.dat',var,latMean,lonMean)
  lats,lons = np.meshgrid(latMean, lonMean)
  lats *= 180./np.pi; lons *= 180./np.pi
  plot_anomaly_ll(lats, lons, np.transpose(var))
Пример #6
0
def region_plot(fname, time, output_dir, julday):

    #print "fname = %s, day = %d\n" % (fname, time);

	ncfile = nc.Dataset(fname,'r')

	fig = plt.figure(figsize=(20.48,10.24))
	ax = plt.axes([0,0,1,1],frameon=False)
	ax.set_axis_off()

	# set up a Basemap
	latrng = (-90.0,90.0)
	lonrng = (0,360)

	m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1],
        llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h',
        area_thresh=800,fix_aspect=False)

	# for mom output
	lats = ncfile.variables["yt_ocean"][:]
	lons = ncfile.variables["xt_ocean"][:]
	field = ncfile.variables["eta_t"][time,:,:]

	aveNcfile = nc.Dataset('ocean_eta_annual.nc','r')
	average = aveNcfile.variables["eta_t"][0,:,:]

	field = field - average

	field = ma.array(field)
	field = ma.masked_where(field == -1.0e10, field)
	field = ma.masked_where(field<= -10,field)
	field = ma.masked_where(field>= 100, field)

	field, lons = addcyclic(field, lons)

	#field_min = np.min(field) 
	#field_max = np.max(field)

	x,y = m(*np.meshgrid(lons[:],lats[:]))

	colorMap = colormaps.make_colormap({0.:'#191970',  0.2:'#448BB9',  0.35:'#1e90ff', 0.5:'w', 0.6:'#F8BC4E', 0.7:'#ffa500', 0.8:'#ff8c00',0.9:'#F56D2E',  1.0:'#CC4000'}) 

	m.drawmapboundary(fill_color='white')
	nlevs = 256
	clevs = np.linspace(-0.8,0.8,num=nlevs)
	
	cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False )
	m.fillcontinents(color='black', lake_color='black', zorder=1)
	save_file = "%s/%f.png" % (output_dir,julday)
	plt.savefig(save_file)
	
	#plt.show()
	ncfile.close()
Пример #7
0
def project_SkyMap_Mollweide( skymap , Pnorm=1 , Qnorm=1
                              , Ppath=None , Qpath=None ):

    Pw , lonsw = addcyclic( skymap.P , skymap.sky.lons )
    Qw , lonsw = addcyclic( skymap.Q , skymap.sky.lons )
    meshlon , meshlat = pylab.meshgrid( lonsw , skymap.sky.lats )

    projection = Basemap( projection='moll' , lon_0=180 , resolution='c' )
#    projection = Basemap( projection='ortho' , lat_0=60 , lon_0=180 , resolution='c' )
    projection.drawmapboundary()
    x , y = projection( meshlon , meshlat )

    if Ppath == None :
        pass
    else :
        fig = pyplot.figure( figsize = (8,8) )
        ax = fig.add_axes( [ 0.05 , 0.15 , 0.8 , 0.8 ] )
        projection.contourf( x , y , Pnorm*Pw , 30 )
        projection.drawmeridians( numpy.arange(0,360,30) )
        projection.drawparallels( numpy.arange(-90,90,30) , labels=[1,0,0,0] )
        pos = ax.get_position()
        l , b , w , h = pos.bounds
        cax = pyplot.axes( [ l+w+0.03 , b , 0.04 , h ] )
        pyplot.colorbar( cax=cax , orientation='vertical' , format='%.1e' )
        pylab.savefig( Ppath )

    if Qpath == None :
        pass
    else :
        fig = pyplot.figure( figsize = (8,8) )
        ax = fig.add_axes( [ 0.05 , 0.15 , 0.8 , 0.8 ] )
        projection.contourf( x , y , Qnorm*Qw , 30 )
        projection.drawmeridians( numpy.arange(0,360,30) )
        projection.drawparallels( numpy.arange(-90,90,30) , labels=[1,0,0,0] )
        pos = ax.get_position()
        l , b , w , h = pos.bounds
        cax = pyplot.axes( [ l+w+0.03 , b , 0.04 , h ] )
        pyplot.colorbar( cax=cax , orientation='vertical' )
        pylab.savefig( Qpath )
    return
Пример #8
0
 def plotMap(self,figdir=''):
     if not self.gotpix:
         self.getPixels()
     lats = self.sky.lats
     lons = self.sky.lons
     pixpw , lonsw = addcyclic( self.pixp , lons )
     pixqw , lonsw = addcyclic( self.pixq , lons )
     meshlon, meshlat = pylab.meshgrid( lonsw , lats )
     projection = Basemap(projection='moll',lon_0=180,resolution='c')
     x , y = projection( meshlon , meshlat )
     projection.contourf( x,y, pixpw , 30)
     projection.drawmeridians(numpy.arange(0,360,30))
     projection.drawparallels(numpy.arange(-90,90,30))
     projection.drawmapboundary()
     figname = self.outfileprefix + '-' + self.maptype + 'real.png'
     pylab.savefig( ( figdir + figname ) )
     projection.contourf( x,y, pixqw , 30)
     projection.drawmeridians(numpy.arange(0,360,30))
     projection.drawparallels(numpy.arange(-90,90,30))
     projection.drawmapboundary()
     figname = self.outfileprefix + '-' + self.maptype + 'imag.png'
     pylab.savefig( ( figdir + figname ) )
Пример #9
0
def shade_coord(xin,yin,datain=None,lon0=None):
	from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic
	from mcmath import edges

	# invert lat coords if they are descending instead of ascending
	if yin[-1] < yin[0]:
		yin = yin[::-1]
		if datain is not None:
			ydimloc = np.where(yin.size == np.array(datain.shape))[0]
			if len(ydimloc) == 0:
				raise MCPlotError("no dimension in 'datain' matches length of 'yin'")
			y_ind = []
			for i in xrange(datain.ndim):
				y_ind.append(slice(None))
			y_ind[ydimloc[0]] = slice(None,None,-1)
			datain = datain[y_ind]
	yedg = edges(yin)
	
	# convert xin to -180:180 range; roll and addcyclic as needed to have lon0 as central lon
	xedg = edges(xin)
	xspan = xedg[-1] - xedg[0]
	if ((xspan < 365.) & (xspan > 355.)):
		xin = np.where(xin >= 180,xin-360,xin)
		roll_ind = np.where(xin < np.roll(xin,1))[0]
		if len(roll_ind) == 0:
			raise MCPlotError("can't find pivot between +180 and -180 in xin")
		xin = np.roll(xin,-roll_ind)
		if datain is not None:
			xdimloc = np.where(xin.size == np.array(datain.shape))[-1]
			if len(xdimloc) == 0:
				raise MCPlotError("no dimension in 'datain' matches length of 'xin'")
			datain = np.roll(datain,-roll_ind,axis=xdimloc)

			if (lon0 is not None):
				(datain,xin) = addcyclic(datain,xin)
				(datain,xin) = shiftgrid(lon0-180,datain,xin)

			xedg = edges(xin)

			## Fix for keeping the squares near the edges of global maps filled just to the edge (map boundary)
			if (lon0 is not None):
				if xedg[0] < (lon0-180):
					xedg[0] = lon0-180
				if xedg[-1] > (lon0+180):
					xedg[-1] = lon0+180

			return [xedg,yedg,datain,xin,yin]
		else:
			xedg = edges(xin)

	return [xedg,yedg,datain,xin,yin]
Пример #10
0
def region_plot(fname, time, output_dir, julday):

	ncfile = nc.Dataset(fname,'r')

	fig = plt.figure(figsize=(20,10))
	ax = plt.axes([0,0,1,1],frameon=False)
	ax.set_axis_off()

	# set up a Basemap
	latrng = (-90.0,90.0)
	lonrng = (0,360)

	m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1],
        llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h',
        area_thresh=800,fix_aspect=False)

	# for ofam salinity 
	lats = ncfile.variables["yt_ocean"][:]
	lons = ncfile.variables["xt_ocean"][:]
	field = ncfile.variables["salt"][time,0,:,:]

	aveNcfile = nc.Dataset('ocean_salt_annual.nc','r')
	average = aveNcfile.variables["salt"][0,0,:,:]
	
	field = field - average

	field = ma.array(field)
	field = ma.masked_where(field == -1.0e10, field)
	field = ma.masked_where(field<= -10,field)
	field = ma.masked_where(field>= 100, field)

	field, lons = addcyclic(field, lons)

	x,y = m(*np.meshgrid(lons[:],lats[:]))

	colorMap =  colormaps.make_colormap({0.:'#010233', 0.3:'#01034B',0.4:'#02035F',0.42:'#28297B', 0.45:'#3B3D8E', 0.5:'w', 0.55:'#B32222',0.58:'#731515',0.6:'#600202',0.7:'#4B0202', 1.0:'#330101'})  # red to blue

	m.drawmapboundary(fill_color='white')
	nlevs = 256 
	clevs = np.linspace(-2,2,num=nlevs)
	
	cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False )
	m.fillcontinents(color='black', lake_color='black', zorder=1)
	save_file = "%s/%f.png" % (output_dir,julday)

	plt.savefig(save_file)
	ncfile.close()
Пример #11
0
def test_plot():
  fname_mean = '/data01/forONR/hgt.mon.1981-2010.ltm.nc'  
  dataMean = netCDF4.Dataset(fname_mean,'r')
  latMean = dataMean.variables['lat'][:]
  lonMean = dataMean.variables['lon'][:]
  dataMean.close()
  
  nlat = len(latMean)
  nlon = len(lonMean)
  var = np.zeros((nlat,nlon), dtype=float)
  for iLat in xrange(nlat):
    for iLon in xrange(nlon):
      var[iLat, iLon] = lonMean[iLon] #latMean[iLat]
  
  var, lonMean = addcyclic(var, lonMean)
  lats,lons = np.meshgrid(latMean, lonMean)
  plot_anomaly_ll(lats, lons, np.transpose(var))
Пример #12
0
def region_plot(fname, time, output_dir, julday):

	ncfile = nc.Dataset(fname,'r')

	fig = plt.figure(figsize=(20.48,10.24))
	ax = plt.axes([0,0,1,1],frameon=False)
	ax.set_axis_off()

	# set up a Basemap
	latrng = (-90.0,90.0)
	lonrng = (0,360)

	m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1],
        llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h',
        area_thresh=800,fix_aspect=False)

	# for salinity
	lats = ncfile.variables["yt_ocean"][:]
	lons = ncfile.variables["xt_ocean"][:]
	field = ncfile.variables["salt"][time,0,:,:]

	field = ma.array(field)
	field = ma.masked_where(field == -1.0e10, field)
	field = ma.masked_where(field<= -10,field)
	field = ma.masked_where(field>= 100, field)

	field, lons = addcyclic(field, lons)

	#field_min = np.min(field) 
	#field_max = np.max(field)
	
	x,y = m(*np.meshgrid(lons[:],lats[:]))

	# do one with jet colormap
	colorMap = mpl.cm.jet
	
	m.drawmapboundary(fill_color='white')
	nlevs = 256
	clevs = np.linspace(28,38,num=nlevs)
	
	cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False )
	m.fillcontinents(color='black', lake_color='black', zorder=1)
	save_file = "%s/%f.png" % (output_dir,julday)
	plt.savefig(save_file)
	
	ncfile.close()
Пример #13
0
def expand_longitude(
    test_lon,orig_lon,orig_data):
    """
    Makes a cyclic array using basemap and expands the longitudes to give the buffer aroud the edge needed 
    for the area weighted re-gridding.
    """
    import numpy as np
    from mpl_toolkits.basemap import addcyclic, shiftgrid
    import copy
    # shift the grid of the emissions so it fits with the test longitude grid
    # first, find the value of the orig long grid nearest to the test long grid
    if len(orig_data.shape) != 2:
        raise Exception, 'Data array must be two-dimensional'
    idx = (np.abs(orig_lon-test_lon[0])).argmin()
    start = orig_lon[idx]
    orig_data_temp,orig_lon_temp=addcyclic(orig_data,orig_lon)
    orig_data_temp,orig_lon_temp=shiftgrid(start,orig_data_temp,orig_lon_temp)
    test_dlon = test_lon[1] - test_lon[0]
    orig_dlon = orig_lon[1] - orig_lon[0]
    extra_cells=np.int(test_dlon/orig_dlon)+2
    # NOTE: DATA AND LOGITUDE HAVE BEEN MADE CYCLIC, ORIGIN IS THAT CLOSEST IN ORIG TO THE START OF TEST
    new_lon   = np.linspace(orig_lon_temp[0] - extra_cells*orig_dlon,\
                              orig_lon_temp[-2]+(extra_cells)*orig_dlon,\
                              len(orig_lon)+2*extra_cells)
    lon_index = np.arange(-1*extra_cells,len(new_lon)-extra_cells,1,dtype=np.int)
    new_data = np.zeros((orig_data.shape[0],len(new_lon)))
    i = 0
    while i < len(new_lon):
        # ignore cyclic grid here for length, since orig_data_temp[0] == orig_data_temp[1], but
        # we don't want to replicate that
        new_data[:,i] = copy.deepcopy(orig_data_temp[:,lon_index[i]%orig_data.shape[1]])
        i+=1
    del idx
    del i
    del start
    del orig_data_temp
    del orig_lon_temp
    del test_dlon
    del orig_dlon
    del test_lon
    del orig_lon
    del orig_data
    del extra_cells
    del lon_index
    return new_lon,new_data
Пример #14
0
 def __transform_lons(self,bbox,lons,var):
     """ Take Bounding box longitudes and transform them for sensible
     Basemap plotting.
     
     bbox: Bounding Box ... values will change in there
     lons: numpy array of longitudes
     var: numpy array of field to be plotted
     """
     
     to_360 = lambda x: ( x % 360. )
     
     # Put everything into a range greater 0 right away
     lon_min = to_360(bbox.lon_min)
     lon_max = to_360(bbox.lon_max)
     lons = to_360(lons)
     
     # If lon_min is greater than lon_max after transformation
     if lon_min > lon_max:
         lon_max += 360.
     
     # If both are the same i.e. 360 degree print
     if lon_min == lon_max:
         lon_max += 360.
     
     # If lon_max greater than 360, remap longitudes to that range
     if lon_max > 360.:
         idx = lons < lon_min
         lons[idx] = lons[idx] + 360.
     
     bbox.lon_min = lon_min
     bbox.lon_max = lon_max
     
     # Ensure longitudes are ascending, and shuffle field with same indices
     idx = np.argsort(lons)
     lons = lons[idx]
     var = var[:,idx]
     var, lons = addcyclic(var,lons)
     
     return bbox,lons,var
Пример #15
0
    def _meshgrid(self, data_array):
        """
        given some data, returns the np.meshgrid associated
        lons and lats + addcyclic longitude if proj is 'spstere'
        or 'npstere'
        """

        latitudes = self.dset_domain['latitudes'].data
        longitudes = self.dset_domain['longitudes'].data

        if self.proj in ['npstere','spstere','moll']:
            """
            if north polar or south polar stereographic projection
            we take care of the discontinuity at Greenwich using the
            `addcyclic` function of basemap
            """
            data_array, lon = addcyclic(data_array, longitudes)
            lons, lats = np.meshgrid(lon, latitudes)
        else:
            lons, lats = np.meshgrid(longitudes, latitudes)

        return lons, lats, data_array
Пример #16
0
lats, uwnd, vwnd = order_latdim(lats, uwnd, vwnd)

# Create a VectorWind instance to handle the computation of streamfunction and
# velocity potential.
w = VectorWind(uwnd, vwnd)

# Compute the streamfunction and velocity potential. Also use the bundled
# tools to re-shape the outputs to the 4D shape of the wind components as they
# were read off files.
sf, vp = w.sfvp()
sf = recover_data(sf, uwnd_info)
vp = recover_data(vp, uwnd_info)

# Pick out the field for December and add a cyclic point (the cyclic point is
# for plotting purposes).
sf_dec, lons_c = addcyclic(sf[11], lons)
vp_dec, lons_c = addcyclic(vp[11], lons)

# Plot streamfunction.
m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90,
            urcrnrlon=360.01, urcrnrlat=90)
x, y = m(*np.meshgrid(lons_c, lats))
clevs = [-120, -100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 120]
m.contourf(x, y, sf_dec*1e-06, clevs, cmap=plt.cm.RdBu_r,
           extend='both')
m.drawcoastlines()
m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1,0,0,0])
m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0,0,0,1])
plt.colorbar(orientation='horizontal')
plt.title('Streamfunction ($10^6$m$^2$s$^{-1}$)', fontsize=16)
Пример #17
0
grid = AxesGrid(fig, [0.05,0.01,0.9,0.9],
                nrows_ncols=(3, 2),
		axes_pad=0.25,
		cbar_mode='single',
		cbar_pad=0.3,
		cbar_size=0.1,
                cbar_location='top',
                share_all=True,
		)

# create Basemap instance for Orthographic projection.
m = Basemap(lon_0=-90,lat_0=60,projection='ortho')
# add wrap-around point in longitude.
t2m = np.zeros((ntimes,nlats,nlons+1),np.float32)
for nt in range(ntimes):
    t2m[nt,:,:], lons = addcyclic(t2mvar[nt,:,:], lons1)
# convert to celsius.
t2m = t2m-273.15
# contour levels
clevs = np.arange(-30,30.1,2.)
lons, lats = np.meshgrid(lons, lats)
x, y = m(lons, lats)
# make subplots.
for nt,fcsthr in enumerate(fcsthrs):
    ax = grid[nt]
    m.ax = ax
    cs = m.contourf(x,y,t2m[nt,:,:],clevs,cmap=plt.cm.jet,extend='both')
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries()
    m.drawparallels(np.arange(-80,81,20))
    m.drawmeridians(np.arange(0,360,20))
Пример #18
0
print verifdates
lats = latitudes[:]
nlats = len(lats)
lons1 = longitudes[:]
nlons = len(lons1)

# unpack 2-meter temp forecast data.

t2mvar = data.variables['tmp2m']
t2min = t2mvar[0:ntimes,:,:]
t2m = np.zeros((ntimes,nlats,nlons+1),t2min.dtype)
# create Basemap instance for Orthographic projection.
m = Basemap(lon_0=-90,lat_0=60,projection='ortho')
# add wrap-around point in longitude.
for nt in range(ntimes):
    t2m[nt,:,:], lons = addcyclic(t2min[nt,:,:], lons1)
# convert to celsius.
t2m = t2m-273.15
# contour levels
clevs = np.arange(-30,30.1,2.)
lons, lats = np.meshgrid(lons, lats)
x, y = m(lons, lats)
# create figure.
fig=plt.figure(figsize=(6,8))
# make subplots.
for nt,fcsthr in enumerate(fcsthrs):
    ax = fig.add_subplot(321+nt)
    cs = m.contourf(x,y,t2m[nt,:,:],clevs,cmap=plt.cm.jet,extend='both')
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries()
    m.drawparallels(np.arange(-80,81,20))
Пример #19
0
# Compute components of rossby wave source: absolute vorticity, divergence,
# irrotational (divergent) wind components, gradients of absolute vorticity.
eta = w.absolutevorticity()
div = w.divergence()
uchi, vchi = w.irrotationalcomponent()
etax, etay = w.gradient(eta)

# Combine the components to form the Rossby wave source term. Re-shape the
# Rossby wave source array to the 4D shape of the wind components as they were
# read off files.
S = -eta * div - uchi * etax + vchi * etay
S = recover_data(S, uwnd_info)

# Pick out the field for December at 200 hPa and add a cyclic point (the
# cyclic point is for plotting purposes).
S_200, lons_c = addcyclic(S[11, 9], lons)

# Plot Rossby wave source.
m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90,
        urcrnrlon=360.01, urcrnrlat=90)
x, y = m(*np.meshgrid(lons_c, lats))
clevs = [-30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30]
m.contourf(x, y, S_200*1e11, clevs, cmap=plt.cm.RdBu_r,
        extend='both')
m.drawcoastlines()
m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1,0,0,0])
m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0,0,0,1])
plt.colorbar(orientation='horizontal')
plt.title('Rossby Wave Source ($10^{-11}$s$^{-1}$)', fontsize=16)
plt.show()
Пример #20
0
lats, uwnd, vwnd = order_latdim(lats, uwnd, vwnd)

# Create a VectorWind instance to handle the computation of streamfunction and
# velocity potential.
w = VectorWind(uwnd, vwnd)

# Compute the streamfunction and velocity potential. Also use the bundled
# tools to re-shape the outputs to the 4D shape of the wind components as they
# were read off files.
sf, vp = w.sfvp()
sf = recover_data(sf, uwnd_info)
vp = recover_data(vp, uwnd_info)

# Pick out the field for December at 200 hPa and add a cyclic point (the
# cyclic point is for plotting purposes).
sf_200, lons_c = addcyclic(sf[11, 9], lons)
vp_200, lons_c = addcyclic(vp[11, 9], lons)

# Plot streamfunction.
m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90,
        urcrnrlon=360.01, urcrnrlat=90)
x, y = m(*np.meshgrid(lons_c, lats))
clevs = [-120, -100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 120]
m.contourf(x, y, sf_200*1e-06, clevs, cmap=plt.cm.RdBu_r,
        extend='both')
m.drawcoastlines()
m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1,0,0,0])
m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0,0,0,1])
plt.colorbar(orientation='horizontal')
plt.title('Streamfunction ($10^6$m$^2$s$^{-1}$)', fontsize=16)
Пример #21
0
# irrotational (divergent) wind components, gradients of absolute vorticity.
eta = w.absolutevorticity()
div = w.divergence()
uchi, vchi = w.irrotationalcomponent()
etax, etay = w.gradient(eta)

# Combine the components to form the Rossby wave source term.
S = eta * -1. * div - uchi * etax + vchi * etay

# Pick out the field for December at 200 hPa.
time_constraint = iris.Constraint(month='Dec')
level_constraint = iris.Constraint(Level=[200])
add_month(S, 'time')
S_200 = S.extract(time_constraint & level_constraint)

# Plot Rossby wave source.
m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90,
        urcrnrlon=360.01, urcrnrlat=90)
lons, lats = S_200.coord('longitude'), S_200.coord('latitude')
S_200, lonsc = addcyclic(S_200.data, lons.points)
x, y = m(*np.meshgrid(lonsc, lats.points))
clevs = [-30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30]
m.contourf(x, y, S_200*1e11, clevs, cmap=plt.cm.RdBu_r, extend='both')
m.drawcoastlines()
m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1,0,0,0])
m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0,0,0,1])
plt.colorbar(orientation='horizontal')
plt.title('Rossby Wave Source ($10^{-11}$s$^{-1}$)', fontsize=16)
plt.show()

Пример #22
0
def mapdap(
    varname = 'hr24_prcp',
    bbox = '-180,-90,180,90',
    url = 'http://opendap.bom.gov.au:8080/thredds/dodsC/PASAP/atmos_latest.nc',
    timeindex = 'Default',
    imgwidth = 256,
    imgheight = 256,
    request = 'GetMap',
    time = 'Default',
    save_local_img = False,
    colorrange = (-4,4),
    palette = 'RdYlGn',
    colorbounds = 'Default',
    style = 'grid',
    ncolors = 10,
    mask = -999,
    plot_mask = True,
    mask_varname = 'mask',
    mask_value = 1.0
    ):
    """ Using Basemap, create a contour plot using some dap available data 
   
        Data is assumed to have dimensions [time,lat,lon] 
            TODO -- deal with other shapes
            TODO -- determine the dimension ordering using CF convention

        varname -- name of variable in opendap file
        bbox -- lonmin,latmin,lonmax,latmax for plot
        url -- OPEnDAP url
        timeindex -- time index to plot
        imgwidth,imgheight -- size of png image to return
        request -- 'GetMap','GetLegend','GetFullFigure'
        time -- time vale to plot. Assumes a particular format."%Y-%m-%dT%H:%M:%S"
        mask -- mask out these values
        if plot_mask is True, mask_varname and mask_value must be given
    
    """
    transparent = True
    lonmin,latmin,lonmax,latmax = tuple([float(a) for a in bbox.rsplit(',')])
   
    # It's not clear there is any point in this. Pydap doesn't actually
    # download data until you subscript 
    
    if url not in cache:
        dset = open_url(url)
    else:
        dset = cache[url]
    
    # Get the correct time.
    time_var = dset['time']
    time_units = time_var.attributes['units']
    available_times = np.array(time_var[:])
    
    

    # TODO there is a potential conflict here between time and timeindex.
    # On the one hand we want to allow using the actual time value.
    # On the other hand we want to make it easy to get a time index
    # without knowing the value.
    timestep=0
    if timeindex == 'Default':
        timestep=0
    else:
        timestep=int(timeindex)
    if time != 'Default':
        dtime = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%S" )
        reftime = date2num(dtime,time_units)
        timestep = np.where(available_times >= reftime)[0].min()

    # TODO Get only the section of the field we need to plot
    # TODO Determine lat/lon box indices and only download this slice

    # TODO Set default range (the below does not work)
    #colorrange = np.min(var),np.max(var)
    
    lat = dset['lat'][:]
    lon = dset['lon'][:]
    
    # CHANGED
    var = dset[varname][timestep,:,:]
 
    #xcoords = lonmin,lonmax
    #xcoords,lon,var = transform_lons(xcoords,lon,var)
 
    # TODO
    # Needs mre thought - the idea here is to only grab a slice of the data
    # Need to grab a slightly larger slice of data so that tiling works.
    #lat_idx = (lat > latmin) & (lat < latmax)
    #lon_idx = (lon > lonmin) & (lon < lonmax)
    #lat = dset['lat'][lat_idx]
    #lon = dset['lon'][lon_idx]
    #latdx1 = np.where(lat_idx)[0].min()
    #latdx2 = np.where(lat_idx)[0].max()
    #londx1 = np.where(lon_idx)[0].min()
    #londx2 = np.where(lon_idx)[0].max()
    #var = var[latdx1:latdx2+1,londx1:londx2+1]
    #var = dset[varname][timestep,latdx1:latdx2+1,londx1:londx2+1]

    # todo clean up this logic
    if 'mask' in dset.keys():
        if plot_mask:
            maskvar = dset['mask'][timestep,:,:]
            #maskvar = dset['mask'][timestep,latdx1:latdx2+1,londx1:londx2+1]
            varm = np.ma.masked_array(var,mask=maskvar)
            mask = varm.mask 
    else:
        varm = np.ma.masked_array(var,mask=np.isinf(var))

    xcoords = lonmin,lonmax
    # Call the trans_coords function to ensure that basemap is asked to
    # plot something sensible.
    xcoords,lon,varm = transform_lons(xcoords,lon,varm)
    lonmin,lonmax = xcoords
    varnc = dset[varname]

    try:
        var_units = varnc.attributes['units']
    except KeyError:
       var_units = '' 


    
    # Plot the data
    # For the basemap drawing we can't go outside the range of coordinates
    # WMS requires us to give an empty (transparent) image for these spurious lats
    
    # uc = upper corner, lc = lower corner
    bmapuclon=lonmax
    bmaplclon=lonmin
    bmapuclat=min(90,latmax)
    bmaplclat=max(-90,latmin)
    if bmaplclat==90:
        bmaplclat = 89.0
    if bmapuclat==-90:
        bmapuclat = -89.0

    # TODO set figsize etc here  
    fig = mpl.figure.Figure()
    canvas = FigureCanvas(fig)
    
    ax = fig.add_axes((0,0,1,1),frameon=False,axisbg='k',alpha=0,visible=False)
    m = Basemap(projection='cyl',resolution='c',urcrnrlon=bmapuclon,
        urcrnrlat=bmapuclat,llcrnrlon=bmaplclon,llcrnrlat=bmaplclat,
        suppress_ticks=True,fix_aspect=False,ax=ax)

    DPI=100.0

    # Convert the latitude extents to Basemap coordinates
    bmaplatmin,bmaplonmin = m(latmin,lonmin)
    bmaplatmax,bmaplonmax = m(latmax,lonmax)
    lon_offset1 = abs(bmaplclon - bmaplonmin)
    lat_offset1 = abs(bmaplclat - bmaplatmin)
    lon_offset2 = abs(bmapuclon - bmaplonmax)
    lat_offset2 = abs(bmapuclat - bmaplatmax)
    lon_normstart = lon_offset1 / abs(bmaplonmax - bmaplonmin)
    lat_normstart = lat_offset1 / abs(bmaplatmax - bmaplatmin)
    ax_xfrac = abs(bmapuclon - bmaplclon)/abs(bmaplonmax - bmaplonmin)
    ax_yfrac = abs(bmapuclat - bmaplclat)/abs(bmaplatmax - bmaplatmin)

    # Set plot_coords, the plot boundaries. If this is a regular WMS request,
    # the plot must fill the figure, with whitespace for invalid regions.
    # If it's a full figure, we need to make sure there is space for the legend
    # and also for the text.
    if request == 'GetFullFigure':
        coords = lonmin,latmin,lonmax,latmax
        plot_coords = figurePlotDims(imgheight,imgwidth,coords)
    else:
        plot_coords = (lon_normstart,lat_normstart,ax_xfrac,ax_yfrac)

    m = Basemap(projection='cyl',resolution='c',urcrnrlon=bmapuclon,
        urcrnrlat=bmapuclat,llcrnrlon=bmaplclon,llcrnrlat=bmaplclat,
        suppress_ticks=True,fix_aspect=False,ax=ax)

    ax = fig.add_axes(plot_coords,frameon=False,axisbg='k')

    m.ax = ax
    varm,lonwrap = addcyclic(varm,lon)
    x,y = m(*np.meshgrid(lonwrap[:],lat[:]))

    """ To plot custom colors
    rgb_cmap = mpl.colors.ListedColormap([  
            (0.0,0.0,0.0),
            (0.25,0.25,0.25),
            (0.3,0.25,0.25),
            (0.5,0.5,0.5),
            (0.6,0.5,0.5),
            (0.75,0.75,0.75),
            (0.75,0.85,0.75),
            (1.0,1.0,1.0) ],name='rgbcm')
    default_color_bounds = [-1,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0]
    default_norm = mpl.colors.BoundaryNorm(default_color_bounds, rgb_cmap.N)
    m.contourf(x,y,var,cmap=rgb_cmap,norm=default_norm)
    contours = m.contour(x,y,var,cmap=rgb_cmap,norm=default_norm)
    contours.clabel(colors='k')
    """
    colormap = mpl.cm.get_cmap(palette)
    # colormap = cmap_discretize(colormap,ncolors)
    # if colorbounds = 'Default':
    # colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment))
    # else:
    #    colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment))
    #    Do some checks on the size of the list, and fix if we can
    #    pass

    if style == 'contour':
        # Interpolate to a finer resolution
        # TODO: make this sensitive to the chosen domain
        increment = float(colorrange[1]-colorrange[0]) / float(ncolors-2)
        colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment))
        
        
        # CHANGED
        colormap = cmap_discretize(colormap,ncolors)
        
        colvs =[-999]+colorbounds+[999]
        lat_idx = np.argsort(lat)
        lat = lat[lat_idx]
        varm = varm[lat_idx,:]

        data_lonmin = min(lonwrap)
        data_lonmax = max(lonwrap)
        data_latmin = min(lat)
        data_latmax = max(lat)

        new_lons = np.arange(data_lonmin-1.0,data_lonmax+1.0,1.0)
        new_lats = np.arange(data_latmin-1.0,data_latmax+1.0,1.0)
        newx,newy = m(*np.meshgrid(new_lons[:],new_lats[:]))
        x = newx
        y = newy
        
        # Two pass interpolation to deal with the mask.
        # The first pass does a bilinear, the next pass does a nearest neighbour to keep the mask
        # These steps slow down the plotting significantly
        # It's not clear this is working, and the problem is likely solved by
        # ensuring the right mask is used!
        varm_bl = interp(varm, lonwrap[:], lat[:], newx, newy,order=1)
        varm_nn = interp(varm, lonwrap[:], lat[:], newx, newy,order=0)
        varm = varm_bl
        varm[varm_nn.mask == 1] = varm_nn[varm_nn.mask == 1]

        # contourf has an extent keyword (x0,x1,y0,y1)
        # return "mapdap\n"
        # STUCK it gets stuck here (in apache)        
        main_render = m.contourf(x,y,varm[:,:],colorbounds,extend='both',cmap=colormap,ax=ax)
        
        contours = m.contour(x,y,varm,colorbounds,colors='k',ax=ax)
        contours.clabel(colors='k',rightside_up=True,fmt='%1.1f',inline=True)
        
        
        
    elif style == 'grid':
        main_render = m.pcolormesh(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1],
            cmap=colormap,ax=ax)
    elif style == 'grid_threshold':
        increment = float(colorrange[1]-colorrange[0]) / float(ncolors)
        colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment))
        colornorm = mpl.colors.BoundaryNorm(colorbounds,colormap.N)
        main_render = m.pcolor(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1],
            cmap=colormap,ax=ax,norm=colornorm)
    else:
        main_render = m.pcolormesh(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1],
            cmap=colormap,ax=ax)


    fig.set_dpi(DPI)
    fig.set_size_inches(imgwidth/DPI,imgheight/DPI)

    title_font_size = 9
    tick_font_size = 8
    if request == 'GetFullFigure':
        # Default - draw 5 meridians and 5 parallels
        n_merid = 5
        n_para = 5

        # base depends on zoom
        mint = (lonmax - lonmin)/float(n_merid)
        base = mint
        meridians = [lonmin + i*mint for i in range(n_merid)]
        meridians = [ int(base * round( merid / base)) for merid in meridians]
        
        # Some sensible defaults for debugging
        #meridians = [45,90,135,180,-135,-90,-45]

        pint = int((latmax - latmin)/float(n_para))
        base = pint
        parallels = [latmin + i*pint for i in range(1,n_para+1)] 
        parallels = [ int(base * round( para / base)) for para in parallels]
        #parallels = [-60,-40,-20,0,20,40,60]
        #parallels = [((parallel + 180.) % 360.) - 180. for parallel in parallels]
        m.drawcoastlines(ax=ax)
        
        m.drawmeridians(meridians,labels=[0,1,0,1],fmt='%3.1f',fontsize=tick_font_size)
        m.drawparallels(parallels,labels=[1,0,0,0],fmt='%3.1f',fontsize=tick_font_size)
        m.drawparallels([0],linewidth=1,dashes=[1,0],labels=[0,1,1,1],fontsize=tick_font_size)
        titlex,titley = (0.05,0.98)
        
        # CHANGED 
        # STUCK getting an error somewhere in this function
        # title = get_pasap_plot_title(dset,varname=varname,timestep=timestep)
        title = "We're getting errors in the get title function"
        fig.text(titlex,titley,title,va='top',fontsize=title_font_size)
   
    colorbar_font_size = 8
    if request == 'GetLegendGraphic':
        # Currently we make the plot, and then if the legend is asked for
        # we use the plot as the basis for the legend. This is not optimal.
        # Instead we should be making the legend manually. However we need
        # to set up more variables, and ensure there is a sensible min and max.
        # See the plot_custom_colors code above
        fig = mpl.figure.Figure(figsize=(64/DPI,256/DPI))
        canvas = FigureCanvas(fig)
        # make some axes
        cax = fig.add_axes([0,0.1,0.2,0.8],axisbg='k')
        # put a legend in the axes
        
        
        cbar = fig.colorbar(main_render,cax=cax,extend='both',format='%1.1f')
        cbar.set_label(var_units,fontsize=colorbar_font_size)
        for t in cbar.ax.get_yticklabels():
            t.set_fontsize(colorbar_font_size)
        # i.e. you don't need to plot the figure...
        #fig.colorbar(filled_contours,cax=cax,norm=colornorm,boundaries=colvs,values=colvs,
        #   ticks=colorbounds,spacing='proportional')
    elif request == 'GetFullFigure':
        # Add the legend to the figure itself.
        # Figure layout parameters
        # plot_coords = tuple with (xi,yi,dx,dy)
        # legend_coords = tuple with (xi,yi,dx,dy) as per mpl convention
        # First change the plot coordinates so that they do not cover the whole image
        legend_coords = (0.8,0.1,0.02,plot_coords[3])
        cax = fig.add_axes(legend_coords,axisbg='k')
        cbar = fig.colorbar(main_render,cax=cax,extend='both')
        for t in cbar.ax.get_yticklabels():
            t.set_fontsize(colorbar_font_size)
        cbar.set_label(var_units,fontsize=colorbar_font_size)
        transparent=False
        # Experimenting here with custom color map and ticks. Assigning everything manually
        # (e.g. ticks=[-2,-1,0,1,2]) is easy. Doing it in an automated way given a range is
        # hard...
        #fig.colorbar(filled_contours,cax=cax,boundaries=colvs,ticks=colorbounds)
        #,norm=colornorm,#boundaries=colvs,values=colvs,        #extend='both')
           
    imgdata = StringIO.StringIO()
    fig.savefig(imgdata,format='png',transparent=transparent)
    
    if save_local_img:
        fig.savefig('map_plot_wms_output.png',format='png')
        return

    if url not in cache:
        cache[url] = dset

    value = imgdata.getvalue()

    #imgdata.close()
    fig = None
    
    
    return value
Пример #23
0
def transform_lons(coords,lon,f):
        """ Take bounding box longitudes and transform them so that basemap plots sensibly. """
        """
        Arguments
        coords -- a tuple compose of lonmin,lonmax
        lon -- numpy array of longitudes
        f -- numpy array of the field being plotted

        >>> trans_coords()

        This logic can probably be simplified as it was built incrementally to solve several
        display issues. See tests/allplots.shtml for the tests that drove this function.

        """
        x1,x2 = coords
        lont = lon
        
        # To handle 360 degree plots
        if x2 == x1:
            x2 = x1 + 360
       
        # Basemap doesn't always play well with negative longitudes so convert to 0-360
        lon2360 = lambda x: ((x + 360.) % 360.)
        if x2 < 0:
            x2 = lon2360(x2)
            x1 = lon2360(x1)
            lont = lon2360(lont)

        # If this has resulted in xmin greater than xmax, need to reorder
        if x2 < x1:
            x2 = x2 + 360
        
        # If the start lon is less than zero, then convert to -180:180
        # It's not clear this will ever be executed, given the above code
        if (x1 < 0) or (x2 == x1 and x2 == 180):
            x1 = ((x1 + 180.) % 360.) - 180.
            x2 = ((x2 + 180.) % 360.) - 180.
            lont = ((lont + 180.) % 360.) - 180.

        # If this has resulted in xmin greater than xmax, we need to reorder
        if x2 < x1:
            x2 = x2 + 360

        # If the x2 range is greater than 360 (plots that span both dl and pm)
        # then remap the longitudes to this range
        if x2 > 360:
           idx = lont < x1
           lont[idx] = lont[idx] + 360
       
        # Remap the longitudes for this case too
        if x1 < 0 and x2 > 180:
           idx = lont < x1
           lont[idx] = lont[idx] + 360
       
        # The special case of 0-360
        if x2 == x1:
            if x2 == 0:
                x1 = 0
                x2 = 360
            else:
                x2 = abs(x2)
                x1 = -x2
        
        coords = x1,x2
        # Ensure lons are ascending, and shuffle the field with the same indices
        idx = np.argsort(lont)
        lont = lont[idx]
        ft = f[:,idx]
        ft, lont = addcyclic(ft,lont)
        return coords,lont,ft
Пример #24
0
                        
m = Basemap( projection = 'cyl', \
            resolution = 'c' , \
            llcrnrlon = b.lon_min, \
            llcrnrlat = b.lat_min, \
            urcrnrlon = b.lon_max, \
            urcrnrlat = b.lat_max, \
            suppress_ticks = True, \
            fix_aspect = False, \
            ax = ax)
            
# From ContourPlot
lats = dset.get_lats()
data = dset.get_data()

data,lonwrap = addcyclic(dset.get_data(), dset.get_lons())
increment = float(crange[1] - crange[0]) / float(ncolors-2)
cbounds = list(np.arange(crange[0],crange[1] + increment, increment ))

colvs = [-999]+cbounds+[999]
        
# Sort latitudes and data
lat_idx = np.argsort(lats)
lats = lats[lat_idx]
data = data[lat_idx]
        
data_lon_min = min(lonwrap)
data_lon_max = max(lonwrap)
data_lat_min = min(lats)
data_lat_max = max(lats)
        
Пример #25
0
#-----------------END CALLING FUNCTION 3-----------------


#-----------------BEGIN PLOT-----------------
# read lats,lons.
lats = data.variables['latitude'][:]
lons1 = data.variables['longitude'][:]
nlats = len(lats)
nlons = len(lons1)

# create Basemap instance.
m =\
Basemap(projection='spstere',boundinglat=blat,lon_0=165,resolution='l')

# add wrap-around point in longitude.
prmsl_abs, lons = addcyclic(prmsl_abs, lons1)

# find x,y of map projection grid.
lons, lats = np.meshgrid(lons, lats)
x, y = m(lons, lats)

# create figure.
fig=plt.figure(figsize=(8,4.5))
ax = fig.add_axes([0.05,0.05,0.9,0.85])
levels = [-12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
orig_cmap = plt.cm.coolwarm
cs = m.contourf(x,y,prmsl_abs,levels,cmap=orig_cmap)

#amundsen_low = np.max(prmsl_abs[600:660,680:1160])
#-----------------END PLOT-----------------
Пример #26
0
    def __init__( self, filename, varname, time_ndx=0, level_ndx=0 ):

        fh = nc.Dataset(filename, 'r', format='NETCDF4')

        dims = fh.dimensions

        if dims.has_key('time') :

            self.units = fh.variables[varname].units
            
            if dims.has_key('ncol') :

                if fh.variables[varname].ndim == 3 :
                    self.data = numpy.ravel(fh.variables[varname][time_ndx,level_ndx,:])
                    self.levdep = True
                else:
                    self.data = numpy.ravel(fh.variables[varname][time_ndx,:])
                    self.levdep = False

                self.lon = numpy.ravel(fh.variables["lon"][:])
                self.lat = numpy.ravel(fh.variables["lat"][:])
                self.structured = False

            if dims.has_key('lon') and dims.has_key('lat') :

                if fh.variables[varname].ndim == 4 :
                    self.data = fh.variables[varname][time_ndx,level_ndx,:,:]
                    self.levdep = True
                else:
                    self.data = fh.variables[varname][time_ndx,:,:]
                    self.levdep = False

                self.lon = fh.variables["lon"][:]
                self.lat = fh.variables["lat"][:]
                self.structured = True

                # Add longitude cyclic point
                self.data,self.lon = bm.addcyclic(self.data,self.lon)

        else :

            if dims.has_key('ncol') :
                if fh.variables[varname].ndim == 2 :
                    self.data = numpy.ravel(fh.variables[varname][level_ndx,:])
                    self.levdep = True
                else:
                    self.data = numpy.ravel(fh.variables[varname][:])
                    self.levdep = False

                self.lon = numpy.ravel(fh.variables["lon"][:])
                self.lat = numpy.ravel(fh.variables["lat"][:])
                self.structured = False

            if dims.has_key('lon') and dims.has_key('lat') :
                if fh.variables[varname].rank == 3 :
                    self.data = fh.variables[varname][level_ndx,:,:]
                    self.levdep = True
                else:
                    self.data = fh.variables[varname][:,:]
                    self.levdep = False

                self.lon = fh.variables["lon"][:]
                self.lat = fh.variables["lat"][:]
                self.structured = True

                # Add longitude cyclic point
                self.data,self.lon = bm.addcyclic(self.data,self.lon)

        fh.close
Пример #27
0
        (5./12.)*ddivdtspec[:,nold] )
        phispec += dt*( \
        (23./12.)*dphidtspec[:,nnew] - (16./12.)*dphidtspec[:,nnow]+ \
        (5./12.)*dphidtspec[:,nold] )
        # implicit hyperdiffusion for vort and div.
        vrtspec *= hyperdiff_fact
        divspec *= hyperdiff_fact
        # switch indices, do next time step.
        nsav1 = nnew; nsav2 = nnow
        nnew = nold; nnow = nsav1; nold = nsav2

    time2 = time.clock()
    print 'CPU time = ',time2-time1

    # make a orthographic plot of potential vorticity.
    m = Basemap(projection='ortho',lat_0=45,lon_0=0)
    # dimensionless PV
    pvg = (0.5*hbar*grav/omega)*(vrtg+f)/phig
    print 'max/min PV',pvg.min(), pvg.max()
    lons1d = (180./np.pi)*x.lons; lats1d = (180./np.pi)*x.lats
    pvg,lons1d = addcyclic(pvg,lons1d)
    lons, lats = np.meshgrid(lons1d,lats1d)
    x,y = m(lons,lats)
    levs = np.arange(-0.2,1.801,0.1)
    m.drawmeridians(np.arange(-180,180,60))
    m.drawparallels(np.arange(-80,81,20))
    CS=m.contourf(x,y,pvg,levs,cmap=plt.cm.spectral,extend='both')
    m.colorbar()
    plt.title('PV (T%s with hyperdiffusion, hour %6.2f)' % (ntrunc,t/3600.))
    plt.show()
Пример #28
0
# calculate the difference, absolute and percentage
gpp_dif = gpp_sitch - gpp_ctr
gpp_dif_per = gpp_dif / gpp_ctr
gpp = gpp_dif_per * 100

# Plot of global temperature on our random day
fig = plt.figure()
fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9)

# Mercator projection
m = Basemap(projection='merc', llcrnrlat=-60, urcrnrlat=60,\
            llcrnrlon=-180, urcrnrlon=180, resolution='c', lon_0=0)
m.drawcoastlines()
m.drawmapboundary()
# Make the plot continuous
gpp_cyclic, lons_cyclic = addcyclic(gpp[ :, :], lons)
# Shift the grid so lons go from -180 to 180 instead of 0 to 360.
gpp_cyclic, lons_cyclic = shiftgrid(180., gpp_cyclic, lons_cyclic, start=False)
# Create 2D lat/lon arrays for Basemap
lon2d, lat2d = np.meshgrid(lons_cyclic, lats)
# Transforms lat/lon into plotting coordinates for projection
x, y = m(lon2d, lat2d)
# Plot of gpp with 11 contour intervals
levels = [-40,-35,-30,-25,-20,-15,-10,-5,0]
#cs = m.contourf(x, y, gpp_cyclic, 11, cmap=plt.cm.Spectral_r)
cmap = plt.cm.get_cmap("hot")
cs = m.contourf(x, y, gpp_cyclic, levels, cmap=cmap)
cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5)
cbar.set_label("percentage (%)")
plt.title("GPP difference")
plt.show()
# map = Basemap(llcrnrlon=120.,llcrnrlat=-60.,urcrnrlon=180.,urcrnrlat=-30., rsphere=(6378137.00,6356752.3142), resolution='l',projection='lcc',    lat_0=-20.,lon_0=180.,lat_ts=-50.)
# # map = Basemap(llcrnrlon=90.,llcrnrlat=-60.,urcrnrlon=180.,urcrnrlat=-20., rsphere=(6378137.00,6356752.3142), resolution='l',projection='lcc',    lat_0=-20.,lon_0=180.,lat_ts=-50.)
# map.drawparallels(np.arange(-90,-10,10),labels=[0,1,0,0]) #left, right, top or bottom of the plot.
# map.drawmeridians(np.arange(-180,180,10),labels=[0,0,0,1])


map = Basemap(projection='cyl',llcrnrlon=130,llcrnrlat=-70,urcrnrlon=180,urcrnrlat=-30,resolution='l')
# plot (unwarped) rgba image.
im = map.bluemarble(scale=0.5)
map.drawcoastlines(linewidth=0.5,color='0.5')
map.drawmeridians(np.arange(-180,180,10),labels=[0,0,0,1],color='0.5')
map.drawparallels(np.arange(-90,90,10),labels=[1,0,0,0],color='0.5')


local_min, local_max = extrema(prmsl, mode='wrap', window=50)
prmsl, lons = addcyclic(prmsl, lons1)
clevs = np.arange(900,1100.,5)
lons, lats = np.meshgrid(lons, lats)
x, y = map(lons, lats)


cs = map.contour(x,y,prmsl,clevs,colors='w',linewidths=1.)
map.drawcoastlines(linewidth=1.25)
#map.fillcontinents(color='0.8')
#map.etopo()
map.bluemarble()
#map.shadedrelief()

xlows = x[local_min]; xhighs = x[local_max]
ylows = y[local_min]; yhighs = y[local_max]
lowvals = prmsl[local_min]; highvals = prmsl[local_max]
Пример #30
0
def unpack_data_object(data_object, x_variable, y_variable, x_wrap_start):
    """
    :param data_object    A cube or an UngriddedData object
    :return: A dictionary containing x, y and data as numpy arrays
    """
    from iris.cube import Cube
    import iris.plot as iplt
    import iris
    import logging
    from mpl_toolkits.basemap import addcyclic

    no_of_dims = len(data_object.shape)

    data = data_object.data  # ndarray

    x = get_coord(data_object, x_variable, data)
    if hasattr(x, 'points'):
        x = x.points
    try:
        coord = data_object.coord(name=x_variable)
        x_axis_name = guess_coord_axis(coord)
    except CoordinateNotFoundError:
        x_axis_name = None

    y = get_coord(data_object, y_variable, data)
    if hasattr(y, 'points'):
        y = y.points
    # Must use special function to check equality of array here, so NaNs are returned as equal and False is returned if
    # arrays have a different shape
    if array_equal_including_nan(y, data) or array_equal_including_nan(y, x):
        y = None

    if array_equal_including_nan(x, data):
        data = y
        y = None

    if isinstance(data_object, Cube):
        plot_defn = iplt._get_plot_defn(data_object, iris.coords.POINT_MODE, ndims=no_of_dims)
        if plot_defn.transpose:
            data = data.T
            x = x.T
            y = y.T

        # Check for auxiliary coordinates.
        aux_coords = False
        for coord in data_object[0].coords(dim_coords=False):
            aux_coords = True

        if no_of_dims == 2:
            # If we have found some auxiliary coordinates in the data and the shape of x data or y data is the same as
            # data assume we have a hybrid coordinate (which is two dimensional b nature. Perhaps need a more robust
            # method for detecting this.
            if aux_coords and (data.shape == x.shape or data.shape == y.shape):
                # Work out which set of data needs expanding to match the coordinates of the others. Note there can only
                # ever be one hybrid coordinate axis.
                if y.shape == data.shape:
                    if y[:, 0].shape == x.shape:
                        x, _y = np.meshgrid(x, y[0, :])
                    elif y[0, :].shape == x.shape:
                        x, _y = np.meshgrid(x, y[:, 0])
                elif x.shape == data.shape:
                    if x[:, 0].shape == y.shape:
                        y, _x = np.meshgrid(y, x[0, :])
                    elif x[0, :].shape == y.shape:
                        y, _x = np.meshgrid(y, x[:, 0])
            else:
                try:
                    data, x = addcyclic(data, x)
                    x, y = np.meshgrid(x, y)
                except:
                    data, y = addcyclic(data, y)
                    y, x = np.meshgrid(y, x)

    if x_axis_name == 'X' and x_wrap_start is not None:
        # x = iris.analysis.cartography.wrap_lons(x, x_wrap_start, 360)
        if isnan(x_wrap_start):
            raise InvalidCommandLineOptionError('Overall range for longitude axis must be within 0 - 360 degrees.')
        x = fix_longitude_range(x, x_wrap_start)

    logging.debug("Shape of x: " + str(x.shape))
    if y is not None:
        logging.debug("Shape of y: " + str(y.shape))
    logging.debug("Shape of data: " + str(data.shape))

    return {"data": data, "x": x, "y": y}