def map_imager_track(imager_lonlat, track_lonlat):
    """
    Plot *imager_lonlat* and *track_lonlat* on global map and return the figure.
    
    """
    from mpl_toolkits.basemap import Basemap
    
    fig = figure()
    ax = fig.add_subplot(111)
    m = Basemap(projection='cyl', llcrnrlon=-180, llcrnrlat=-90,
                urcrnrlon=180, urcrnrlat=90, resolution='l', ax=ax)
    
    m.drawcoastlines(linewidth=.5, color='grey')
    
    # Don't draw each pixel, or the machine will choke!
    npixels = imager_lonlat[0].size
    from math import sqrt
    step = int(round(sqrt(npixels / 1e5))) # Will give a total of about 1e5 pixels
    _slice_2d = (slice(None, None, step),) * 2
    m.pcolormesh(imager_lonlat[0][_slice_2d], imager_lonlat[1][_slice_2d],
                 imager_lonlat[1][_slice_2d], alpha=.5)
    m.plot(track_lonlat[0], track_lonlat[1], 'o', markersize=1, alpha=.1,
           label='track')
    
    return fig
Example #2
0
def plot_drainage_areas(path = "data/hydrosheds/test_using_splitting_amno.nc"):
    ds = Dataset(path)
    #basemap = polar_stereographic.basemap
    basemap =  Basemap()
    lons = ds.variables["lon"][:]
    lats = ds.variables["lat"][:]
    channel_slope = ds.variables["slope"][:]

    lons[lons < 0] += 360

    x, y = basemap(lons, lats)




    acc_area = ds.variables["accumulation_area"][:]
    acc_area = np.log(acc_area)
    acc_area = np.ma.masked_where(channel_slope < 0, acc_area)

    basemap.pcolormesh(x, y, acc_area)
    basemap.drawcoastlines()
    plt.colorbar()
    plt.xlim(x.min(), x.max())
    plt.ylim(y.min(), y.max())
    plt.show()
Example #3
0
    def do_subplot(field, title, lons, lats, plot_num, pole, diff=False): 
        """
        Make an individual subplot. 
        """

        if pole == 'north':
            projection = 'nplaea'
            boundinglat = 50
        else:
            projection = 'splaea'
            boundinglat = -50

        m_base = Basemap(projection=projection, boundinglat=boundinglat,
                         lon_0=0) 
        x, y = m_base(lons, lats)
        ax = fig.add_subplot(plot_num)

        max = get_max_within_area(field, lats, boundinglat, pole)
        if diff:
            cmap = plt.get_cmap('RdBu_r')
            min = -max
        else:
            cmap = plt.get_cmap()
            min = 0

        # Set the land points to be gray. 
        cmap.set_bad('0.65')
        m_base.pcolormesh(x, y, field, vmax=max, vmin=min, cmap=cmap)

        m_base.colorbar()
        m_base.drawparallels(np.arange(-80.,81.,20.))
        m_base.drawmeridians(np.arange(-180.,181.,20.))
        if title:
            plt.title(title)
Example #4
0
def diagnose_mean():
    path = "/home/huziy/skynet1_rech3/cordex/for_Samira/Africa_0.44deg_ERA40-Int1.5_E21981-2010/dailyAfrica_0.44deg_ERA40-Int1.5_E21981-2010TRAF.nc"

    ds = nc.Dataset(path)
    traf = ds.variables["TRAF"][:,0,:,:]

    traf_m = np.mean(traf, axis = 0) * 24 *60 * 60 * 365 #transform to mm/day
    lon = ds.variables["longitude"][:]
    lat = ds.variables["latitude"][:]


    lon[lon > 180] -= 360


    levels = [0,0.1,1,5,10,25, 50,100, 200, 300, 600, 1000,1500,2000,2500,3000,5000]
    cMap = get_cmap("jet", len(levels) - 1 )
    bn = BoundaryNorm(levels, cMap.N)

    ll_lon, ur_lon = np.min(lon), np.max(lon)

    ll_lat, ur_lat = np.min(lat), np.max(lat)
    traf_min = 0.1
    traf_m = np.ma.masked_where(traf_m < traf_min, traf_m)

    import matplotlib.pyplot as plt
    b = Basemap(projection="merc",llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat)
    x,y = b(lon, lat)
    plt.figure()
    b.pcolormesh(x, y, traf_m, norm = bn, cmap = cMap)
    cb = plt.colorbar()
    cb.ax.set_title("mm/year")
    b.drawcoastlines()
    plt.show()
def basemapPGAPlot(lons, lats, pga):
        
    lonmesh, latmesh = np.meshgrid(lons, lats)
    pga = np.array(pga)
    pga = pga.reshape((len(lons), len(lats)))
    
    
    plt.close()
    m = Basemap(projection='cyl', llcrnrlat=lats.min(), urcrnrlat=lats.max(), llcrnrlon=lons.min(), urcrnrlon=lons.max(), resolution='i')
    m.drawcoastlines()
    
    #m.drawmapboundary(fill_color='PaleTurquoise')
    #m.fillcontinents(color='lemonchiffon',lake_color='PaleTurquoise', zorder=0)
    m.drawmapboundary()#fill_color='lightgray')
    #m.fillcontinents(color='darkgray',lake_color='lightgray', zorder=0)
    m.drawcountries()
    
    m.drawparallels(np.arange(round(lats.min()),round(lats.max()),2), labels=[1,0,0,0])
    m.drawmeridians(np.arange(round(lons.min()),round(lons.max()),2), labels=[0,0,0,1])
    
    #m.contourf(lonmesh, latmesh, pga)
    #m.plot(simx[::], simy[::], 'm.')
    m.pcolormesh(lonmesh, latmesh, pga, vmin = 0, vmax = 20, cmap="jet")
    cb = m.colorbar()
    cb.set_label("Peak Ground Acceleration (% g)")
    m.show()
Example #6
0
def plot_on_earth(lons, lats, data, vmin=-4, vmax=12, cbar_loc='left', cbar_ticks=None):
    #import ipdb; ipdb.set_trace()
    #if ax == None:
	#ax = plt.gca()
    plot_lons, plot_data = extend_data(lons, lats, data)

    lons, lats = np.meshgrid(plot_lons, lats)

    m = Basemap(projection='cyl', resolution='c', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    x, y = m(lons, lats)

    m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax)
    #m.pcolormesh(x, y, plot_data)

    m.drawcoastlines()
    if cbar_loc == 'left':
	p_labels = [0, 1, 0, 0]
    else:
	p_labels = [1, 0, 0, 0]

    m.drawparallels(np.arange(-90.,90.1,45.), labels=p_labels, fontsize=10)
    m.drawmeridians(np.arange(-180.,180.,60.), labels=[0, 0, 0, 1], fontsize=10)

    #import ipdb; ipdb.set_trace()
    if cbar_ticks == None:
	cbar = m.colorbar(location=cbar_loc, pad='7%')
    else:
	cbar = m.colorbar(location=cbar_loc, pad='7%', ticks=cbar_ticks)

    if cbar_loc == 'left':
	cbar.ax.xaxis.get_offset_text().set_position((10,0))
def run(FILE_NAME):

    DATAFIELD_NAME = 'dHat'

    if USE_NETCDF4:
        from netCDF4 import Dataset    
        nc = Dataset(FILE_NAME)
        var = nc.variables[DATAFIELD_NAME]
        # This datafield has scale factor and add offset attributes, but no
        # fill value.  We'll turn off automatic scaling and do it ourselves.
        var.set_auto_maskandscale(False)
        data = nc.variables[DATAFIELD_NAME][:].astype(np.float64)

        # Retrieve scale/offset attributes.
        scale_factor = var.scale_factor
        add_offset = var.add_offset
    
        # Retrieve the geolocation data.
        latitude = nc.variables['geolocation'][:,:,0]
        longitude = nc.variables['geolocation'][:,:,1]
    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)
        
        ds = hdf.select(DATAFIELD_NAME)
        data = ds[:,:].astype(np.double)

        # Handle scale/osffset attributes.
        attrs = ds.attributes(full=1)
        sfa=attrs["scale_factor"]
        scale_factor = sfa[0]
        aoa=attrs["add_offset"]
        add_offset = aoa[0]

        # Retrieve the geolocation data.        
        geo = hdf.select('geolocation')
        latitude = geo[:,:,0]
        longitude = geo[:,:,1]

    data = data / scale_factor + add_offset
    
    # Draw an equidistant cylindrical projection using the high resolution
    # coastline database.
    m = Basemap(projection='cyl', resolution='h',
                llcrnrlat=30, urcrnrlat = 36,
                llcrnrlon=121, urcrnrlon = 133)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(30, 37), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(121, 133, 2), labels=[0, 0, 0, 1])
    m.pcolormesh(longitude, latitude, data, latlon=True)
    cb = m.colorbar()
    cb.set_label('Unit:mm')

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, DATAFIELD_NAME))
    fig = plt.gcf()
    # plt.show()
    
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Example #8
0
    def plot_basins(self):
        basin_values = -np.ones((self.nx, self.ny))
        for basin in self.basins:

            # @type basin Basin
            #if int(basin.name.split('_')[1]) not in [0,4,1,11,15,20,22,25]: continue

            for theCell in basin.cells:
                # @type theCell Cell
                i, j = theCell.coords()

                theValue = basin.id if theCell.next is not None else -2
                basin_values[i,j] = theValue

        basin_values = np.ma.masked_where(basin_values == -1, basin_values)
        lons, lats = self.longitudes, self.latitudes
        lons = lons.copy()
        lons[lons <= 180] += 360
        lon_min = np.min(lons)
        lon_max = np.max(lons)
        lat_min = np.min(lats)
        lat_max = np.max(lats)

        basemap = Basemap(llcrnrlon = lon_min, llcrnrlat = lat_min,
                          urcrnrlon = lon_max, urcrnrlat = lat_max,
                          resolution = 'i'
                        )
        lons, lats = basemap(lons, lats)
        colormap = plt.cm.get_cmap(name = 'prism', lut = len(self.basins))
        colormap.set_under(color = 'k')

        basemap.pcolormesh(lons, lats, basin_values, cmap = colormap, vmin = 0)

        basemap.drawcoastlines()
        plt.show()
Example #9
0
def raster_on_earth(lons, lats, data, vmin=None, vmax=None, loc='earth'):
    if loc == 'earth':
        m = Basemap(projection='cyl', resolution='c',
                    llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    elif loc in ['wa', 'west_atlantic']:
        m = Basemap(projection='cyl', resolution='c',
                    llcrnrlat=0, urcrnrlat=60, llcrnrlon=-120, urcrnrlon=-30)
    elif loc in ['nwp', 'northwest_pacific']:
        m = Basemap(projection='cyl', resolution='c',
                    llcrnrlat=0, urcrnrlat=50, llcrnrlon=100, urcrnrlon=180)

    if data is not None:
        plot_lons, plot_data = extend_data(lons, lats, data)
        lons, lats = np.meshgrid(plot_lons, lats)
        x, y = m(lons, lats)
        if vmin:
            m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax)
        else:
            m.pcolormesh(x, y, plot_data)

    m.drawcoastlines()

    p_labels = [0, 1, 0, 0]

    m.drawparallels(np.arange(-90., 90.1, 45.), labels=p_labels, fontsize=10)
    m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], fontsize=10)
Example #10
0
def plot_field_2d(lons_2d, lats_2d, field_2d, start_lon = -180, end_lon = 0, color_map = None,
                   minmax = (None, None)  ):


    plt.figure()
    m = Basemap(llcrnrlon = start_lon,llcrnrlat = np.min(lats_2d),
                urcrnrlon = end_lon,urcrnrlat = np.max(lats_2d), resolution = 'l')

    m.drawmeridians(range(start_lon,end_lon,10))
    m.drawparallels(range(-90,90,10))


 #   y, x = meshgrid(lats_2d, lons_2d)
#    lons_2d[lons_2d < start_lon] = lons_2d[lons_2d < start_lon] + 360
    x, y = m(lons_2d, lats_2d)


    x -= 360 ###########CONVERTING LONGITUDE TO -180:180
    field_2d = maskoceans(x, y, field_2d)


    m.pcolormesh(x, y, field_2d, cmap = color_map, vmin = minmax[0], vmax = minmax[1])
    m.drawcoastlines()
    #plt.imshow(np.transpose(data[:,:]), origin = 'lower') #for plotting in order to see i,j we supply j,i
    numticks = color_map.N + 1 if color_map != None else 10
    plt.colorbar(ticks = LinearLocator(numticks = numticks), format = '%.01f',
                 orientation = 'vertical', shrink = 0.6)
Example #11
0
def plot_global(cfsr_file):

	data = Dataset(cfsr_file,'r')
	lats=data.variables['lat'][:]
	lons=data.variables['lon'][:]

	array = np.squeeze(data.variables['irwin_cdr'][:,:,:])

	latn=data.geospatial_lat_min
	latx=data.geospatial_lat_max
	lonn=data.geospatial_lon_min
	lonx=data.geospatial_lon_max
	data.close()

	lons2d, lats2d=np.meshgrid(lons,lats)

	m=Basemap(projection='merc',
					llcrnrlat=latn,
					urcrnrlat=latx,
					llcrnrlon=lonn,
					urcrnrlon=lonx,
					resolution='l')

	m.drawcoastlines()
	m.pcolormesh(lons2d, lats2d, array, latlon=True, cmap='gray')
	plt.show()
def snr(cflx, pco2):
	#~ plt.figure(figsize=(10, 10))
	curr_map = Basemap(projection='cyl', llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat, resolution='i', area_thresh=100.)
	x, y = curr_map(lon, lat)
	vmin=0
	vmax=10
	V = np.arange(0, 10)
	
	plt.subplot(211)
	im = curr_map.pcolormesh(x, y, snr_func(cflx) , vmin=vmin, vmax=vmax, cmap=cmap)
	plt.axis('tight')
	plt.colorbar()
	curr_map.drawcoastlines()
	curr_map.fillcontinents(color='grey',lake_color='aqua')	
	#~ plt.title('Cflux SNR')
	
	plt.subplot(212)
	im = curr_map.pcolormesh(x, y, snr_func(pco2), vmin=vmin, vmax=vmax, cmap=cmap)
	plt.axis('tight')
	plt.colorbar()
	curr_map.drawcoastlines()
	curr_map.fillcontinents(color='grey',lake_color='aqua')	
	#~ plt.title('Dpco2 SNR')	
	
	plt.savefig(FIGDIR + 'snrs.png')
	plt.close('all')
def plot(array,typep=None,clevel=None):

	fig,ax = plt.subplots()

	lats=array['lats']
	lons=array['lons']

	latm,lonm = np.meshgrid(lats,lons)
	latn = np.min(lats)
	latx = np.max(lats)
	lonn = np.min(lons)
	lonx = np.max(lons)

	m = Basemap(projection='merc',
	            llcrnrlat=latn,
	            urcrnrlat=latx,
	            llcrnrlon=lonn,
	            urcrnrlon=lonx,
	            resolution='l',
				ax=ax)

	if typep == 'pcolor':
		m.pcolormesh(lonm.T,latm.T,array['data'],latlon=True)
	elif typep == 'contourf':
		X,Y=m(lonm.T, latm.T)
		m.contourf(X,Y,array['data'],clevel)

	m.drawparallels(lats[1::10],labels=[1,0,0,0])
	m.drawmeridians(lons[1::20],labels=[0,0,0,1])
	m.drawcoastlines()

	plt.show(block=False)
def plot_result(field = None):
    if field is None:
        return


    basemap = Basemap(projection = 'npstere', #area_thresh = 10000,
                        lat_ts = 60, lat_0 = 60, lon_0 = -115,
                        boundinglat=10
                        )

    x = polar_stereographic.lons
    y = polar_stereographic.lats

    x, y = basemap(x, y)


    d = max(np.absolute(field.max()), np.absolute(field.min()))
    basemap.pcolormesh(x, y, field, cmap = mpl.cm.get_cmap('jet', 10),
                       vmax = d, vmin = -d)
    plt.xlim(x.min(), x.max())
    plt.ylim(y.min(), y.max())
    plt.colorbar(ticks = LinearLocator(numticks = 11), format = "%.1f")
    basemap.drawcoastlines()
    #basemap.drawrivers()
    plt.savefig("gt_aex_minus_aey.png")

    pass
Example #15
0
def _raster_on_earth(lons, lats, data, vmin=None, vmax=None, loc=None, colorbar=True, labels=True):
    if not loc:
        m = Basemap(projection='cyl', resolution='c',
                    llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    else:
        m = Basemap(projection='cyl', resolution='c', **loc)

    if data is not None:
        plot_lons, plot_data = _extend_data(lons, lats, data)
        lons, lats = np.meshgrid(plot_lons, lats)
        x, y = m(lons, lats)
        if vmin:
            m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax)
        else:
            m.pcolormesh(x, y, plot_data)

    m.drawcoastlines()

    if labels:
        p_labels = [0, 1, 0, 0]
        m.drawparallels(np.arange(-90., 90.1, 45.), labels=p_labels, fontsize=10)
        m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], fontsize=10)

    if colorbar and data is not None:
        m.colorbar(location='right', pad='7%')
    return m
def plot_cell_feature (data, cell_id_column, cell_lat_column, cell_long_column, richness_column, title=None, second_feature_data=None, second_feature_column=None):
    lats = np.asarray(np.unique(data[cell_lat_column]))
    lons = np.asarray(np.unique(data[cell_long_column]))
    lons, lats = np.meshgrid(lons,lats)
    
    richness = np.array(data[richness_column])
    richness.shape = (len(np.unique(lats)), len(np.unique(lons)))
    richness_mask = ma.masked_where(np.isnan(richness),richness)
    
    if second_feature_column:
        second_feature = np.array(second_feature_data[second_feature_column])
        second_feature.shape = (len(np.unique(lats)), len(np.unique(lons)))
        second_feature_data_mask = ma.masked_where(np.isnan(second_feature),second_feature)
        
    fig = plt.figure()
    m = Basemap(projection='merc',llcrnrlat=23.5,urcrnrlat=57, llcrnrlon=-140,urcrnrlon=-50,lat_ts=20,resolution='l')
    m.drawcoastlines(linewidth = 1.25)
    if np.nanmin(richness) < 20:
        vmin=0
    else:
        vmin=round(np.nanmin(richness)-20, -1)
    im1 = m.pcolormesh(lons,lats,richness_mask,shading='flat',cmap=plt.cm.Blues,latlon=True, vmin=vmin)
    if second_feature_column:
        im2 = m.pcolormesh(lons,lats,second_feature_data_mask,shading='flat',cmap=plt.cm.RdYlBu,latlon=True)
    cb = m.colorbar(im1,"bottom", size="5%", pad="2%")
    plt.title(title)
Example #17
0
 def plot(self,key='Re'):
     """
     Create a plot of a variable over the ORACLES study area. 
     
     Parameters
     ----------
     key : string
     See names for available datasets to plot.
     
     clf : boolean
     If True, clear off pre-existing figure. If False, plot over pre-existing figure.
     
     Modification history
     --------------------
     Written: Michael Diamond, 08/16/2016, Seattle, WA
     Modified: Michael Diamond, 08/21/2016, Seattle, WA
        -Added ORACLES routine flight plan, Walvis Bay (orange), and Ascension Island
     Modified: Michael Diamond, 09/02/2016, Swakopmund, Namibia
         -Updated flihgt track
     """
     plt.clf()
     size = 16
     font = 'Arial'
     m = Basemap(llcrnrlon=self.lon.min(),llcrnrlat=self.lat.min(),urcrnrlon=self.lon.max(),\
     urcrnrlat=self.lat.max(),projection='merc',resolution='i')
     m.drawparallels(np.arange(-180,180,5),labels=[1,0,0,0],fontsize=size,fontname=font)
     m.drawmeridians(np.arange(0,360,5),labels=[1,1,0,1],fontsize=size,fontname=font)
     m.drawmapboundary(linewidth=1.5)        
     m.drawcoastlines()
     m.drawcountries()
     if key == 'Pbot' or key == 'Ptop' or key == 'Nd' or key == 'DZ': 
         m.drawmapboundary(fill_color='steelblue')
         m.fillcontinents(color='floralwhite',lake_color='steelblue',zorder=0)
     else: m.fillcontinents('k',zorder=0)
     if key == 'Nd':
         m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\
         latlon=True,norm = LogNorm(vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1]))
     elif key == 'Zbf' or key == 'Ztf':
         levels = [0,250,500,750,1000,1250,1500,1750,2000,2500,3000,3500,4000,5000,6000,7000,8000,9000,10000]
         m.contourf(self.lon,self.lat,self.ds['%s' % key],levels=levels,\
         cmap=self.colors['%s' % key],latlon=True,extend='max')
     elif key == 'DZ':
         levels = [0,500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000]
         m.contourf(self.lon,self.lat,self.ds['%s' % key],levels=levels,\
         cmap=self.colors['%s' % key],latlon=True,extend='max')
     else:
         m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\
         latlon=True,vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1])
     cbar = m.colorbar()
     cbar.ax.tick_params(labelsize=size-2) 
     cbar.set_label('[%s]' % self.units['%s' % key],fontsize=size,fontname=font)
     if key == 'Pbot' or key == 'Ptop': cbar.ax.invert_yaxis() 
     m.scatter(14.5247,-22.9390,s=250,c='orange',marker='D',latlon=True)
     m.scatter(-14.3559,-7.9467,s=375,c='c',marker='*',latlon=True)
     m.scatter(-5.7089,-15.9650,s=375,c='chartreuse',marker='*',latlon=True)
     m.plot([14.5247,13,0],[-22.9390,-23,-10],c='w',linewidth=5,linestyle='dashed',latlon=True)
     m.plot([14.5247,13,0],[-22.9390,-23,-10],c='k',linewidth=3,linestyle='dashed',latlon=True)
     plt.title('%s from MSG SEVIRI on %s/%s/%s at %s UTC' % \
     (self.names['%s' % key],self.month,self.day,self.year,self.time),fontsize=size+4,fontname=font)
     plt.show()
Example #18
0
def doPlot2(lon,lat,aeroOptDep,title,figName,beginLatFig=-60,endLatFig=20,beginLonFig=-96,endLonFig=-13,\
beginLatReg=0,endLatReg=0,beginLonReg=0,endLonReg=0):

	m=Basemap(projection='cyl',resolution='l',llcrnrlat=beginLatFig,\
urcrnrlat=endLatFig,llcrnrlon=beginLonFig,urcrnrlon=endLonFig)
	#lon,lat=m(lon,lat)

	print figName
	parallels = np.arange(beginLatFig,endLatFig,(endLatFig-beginLatFig)/8.)
	m.drawparallels(parallels,labels=[1,0,0,1])
	meridians = np.arange(beginLonFig,endLonFig,(endLonFig-beginLonFig)/4.)
	m.drawmeridians(meridians,labels=[1,0,0,1])
        m.drawcountries(linewidth=0.5)
        m.drawcoastlines(linewidth=0.5)
        m.pcolormesh(lon,lat,aeroOptDep,vmin=0.,vmax=1)
	if beginLatReg==0 and endLatReg==0 and beginLonReg==0 and\
endLonReg==0:
		pass

	else:	
	       	drawScreen(beginLatReg,endLatReg,beginLonReg,endLonReg,m)
		#print beginLatReg,endLatReg,beginLonReg,endLonReg
        cb=m.colorbar()
        plt.title(title)
        plt.savefig(figName+'.png',format='png',dpi=150)
        plt.clf()
def run(FILE_NAME):
    
    with h5py.File(FILE_NAME, mode='r') as f:

        name = '/Grid/IRprecipitation'
        data = f[name][:]
        units = f[name].attrs['units']
        _FillValue = f[name].attrs['_FillValue']
        data[data == _FillValue] = np.nan
        data = np.ma.masked_where(np.isnan(data), data)

        
        # Get the geolocation data
        latitude = f['/Grid/lat'][:]
        longitude = f['/Grid/lon'][:]

        
    m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=-180, urcrnrlon=180)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(-90, 91, 45))
    m.drawmeridians(np.arange(-180, 180, 45), labels=[True,False,False,True])
    m.pcolormesh(longitude, latitude, data.T, latlon=True)
    cb = m.colorbar()    
    cb.set_label(units)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, name))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Example #20
0
def basemap_raster_mercator(lon, lat, grid, cmap = None):
  """
  Render a raster in mercator projection.  Locations with no values are
  rendered transparent.
  """
  # longitude/latitude extent
  lons = (np.amin(lon), np.amax(lon))
  lats = (np.amin(lat), np.amax(lat))

  if cmap is None:
    cmap = mpl.cm.jet
    cmap.set_bad('w', 1.0)

  # construct spherical mercator projection for region of interest
  m = Basemap(projection='merc',llcrnrlat=lats[0], urcrnrlat=lats[1],
              llcrnrlon=lons[0],urcrnrlon=lons[1])

  vmin,vmax = np.nanmin(grid),np.nanmax(grid)
  masked_grid = np.ma.array(grid,mask=np.isnan(grid))
  fig = plt.figure(frameon=False)
  plt.axis('off')
  m.pcolormesh(lon,lat,masked_grid,latlon=True,cmap=cmap,vmin=vmin,vmax=vmax)

  str_io = StringIO.StringIO()
  plt.savefig(str_io,bbox_inches='tight',format='png',pad_inches=0,transparent=True)
  bounds = [ (lons[0],lats[0]),(lons[1],lats[0]),(lons[1],lats[1]),(lons[0],lats[1]) ]

  return str_io.getvalue(), bounds
Example #21
0
def plotgrid(lon,lat,width=3000000,height=3000000) :
   import matplotlib
   import matplotlib.pyplot
   from matplotlib.figure import Figure
   from matplotlib.backends.backend_agg import FigureCanvasAgg
   from mpl_toolkits.basemap import Basemap

   #print "testlon, testlat:",lon[1,1],lat[1,1]

   #figure = Figure()
   #ax     = figure.add_subplot(111)
   #canvas = FigureCanvasAgg(figure)

   figure = matplotlib.pyplot.figure(figsize=(8,8))
   ax=figure.add_subplot(111)

   #Pick center longitude
   ix,iy=[elem/2 for elem in lon.shape]
   clon=lon[ix,iy]
   clat=lat[ix,iy]

   # Probably a way of estimating the width here...
   #print width,height
   #print clon,clat
   m = Basemap(projection='stere',lon_0=clon,lat_0=clat,resolution='l',width=width,height=height,ax=ax)
   x,y = m(lon,lat)

   # Pick a suitable set of grid lines
   nlines=10
   stepx,stepy=[elem/nlines for elem in lon.shape]
   x2=numpy.zeros((nlines+1,nlines+1))
   y2=numpy.zeros((nlines+1,nlines+1))

   #print x2.shape,x[::stepx,::stepy].shape
   x2[:-1,:-1]=x[::stepx,::stepy]
   x2[-1,:-1]=x[-1,::stepy]
   x2[:-1,-1]=x[::stepx,-1]
   x2[-1,-1]=x[-1,-1]
   y2[:-1,:-1]=y[::stepx,::stepy]
   y2[:-1,-1]=y[::stepx,-1]
   y2[-1,:-1]=y[-1,::stepy]
   y2[-1,-1]=y[-1,-1]

   m.drawcoastlines()
   m.drawmapboundary() # draw a line around the map region
   m.drawparallels(numpy.arange(-90.,120.,30.),labels=[1,0,0,0]) # draw parallels
   m.drawmeridians(numpy.arange(0.,420.,60.),labels=[0,0,0,1]) # draw meridians
   v=numpy.zeros(x.shape)
   col=".8"
   cmap=matplotlib.colors.ListedColormap([col,col])
   #m.pcolormesh(x,y,v,ax=ax,edgecolor="k",cmap=cmap)
   m.pcolormesh(x,y,v,ax=ax,edgecolor="none",cmap=cmap)
   for j in range(y2.shape[1]) :
      m.plot(x2[:,j],y2[:,j],color="b",lw=2)
   for i in range(y2.shape[0]) :
      m.plot(x2[i,:],y2[i,:],color="r",lw=2)
   ax.set_title("Every %d in x(blue) and every %d in y(red) shown"%(stepy,stepx))

   return figure
Example #22
0
def run(FILE_NAME):
    
    if USE_NETCDF4:

        from netCDF4 import Dataset

        nc = Dataset(FILE_NAME)
        grp = nc.groups['HDFEOS'].groups['GRIDS'].groups['SET1']
        data_var = grp.groups['Data Fields'].variables['E']
        data = data_var[:]

        data_longname = data_var.long_name
        data_units = data_var.units

    else:
        
        import h5py

        with h5py.File(FILE_NAME, mode='r') as f:

            dset_var = f['/HDFEOS/GRIDS/SET1/Data Fields/E']
            data = dset_var[:]

            # String attributes actually come in as the bytes type and should
            # be decoded to UTF-8 (python3).
            data_units = dset_var.attrs['units'].decode()
            data_longname = dset_var.attrs['long_name'].decode()
            fv = dset_var.attrs['_FillValue'][0]

            # We have to apply the fill value ourselves.
            data[data == fv] = np.nan
            data = np.ma.masked_array(data, np.isnan(data))

    # The projection is GEO, so we can construct the lat/lon arrays ourselves.
    scaleX = 360.0 / data.shape[1]
    scaleY = 180.0 / data.shape[0]
    longitude = np.arange(data.shape[1]) * scaleX - 180 + scaleX/2
    latitude = np.arange(data.shape[0]) * scaleY - 90 + scaleY/2

    # Draw an equidistant cylindrical projection using the low resolution
    # coastline database.
    m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat = 90,
                llcrnrlon=-180, urcrnrlon = 180)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180, 180., 45.), labels=[0, 0, 0, 1])
    m.pcolormesh(longitude, latitude, data, latlon=True)
    cb = m.colorbar()
    cb.set_label(data_units) 

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, data_longname))

    fig = plt.gcf()
    # plt.show()

    pngfile = "{0}.py.png".format(basename)    
    fig.savefig(pngfile)
def run(FILE_NAME):
    # Identify the data field.
    DATAFIELD_NAME = 'Longwave Flux (2.5R)'

    if USE_NETCDF4:
        from netCDF4 import Dataset
        nc = Dataset(FILE_NAME)
        data = nc.variables[DATAFIELD_NAME][:].astype(np.float64)
    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)
        
        # Read dataset.
        data2D = hdf.select(DATAFIELD_NAME)
        data = data2D[:,:]


    # Set fillvalue and units.
    # See "CERES Data Management System ES-4 Collection Guide" [1] and a sample
    # image by NASA [2] for details.  The fillvalue is 3.4028235E38.  Here, we
    # just use the max of the data.
    fillvalue = np.max(data)
    data[data == fillvalue] = np.nan
    datam = np.ma.masked_array(data, mask=np.isnan(data))
    
    # Set fillvalue and units.
    # See "CERES Data Management System ES-4 Collection Guide" [1] and a
    # sample image by NASA [2] for details.
    # The fillvalue is 3.4028235E38. Here, we use max value from the dataset.
    units = 'Watts/Meter^2'
    ysize, xsize = data.shape
    xinc = 360.0 / xsize
    yinc = 180.0 / ysize
    x0, x1 = (-180, 180)
    y0, y1 = (-90, 90)
    longitude = np.linspace(x0 + xinc/2, x1 - xinc/2, xsize)
    latitude = np.linspace(y0 + yinc/2, y1 - yinc/2, ysize)
    
    # Flip the latitude to run from 90 to -90
    latitude = latitude[::-1]
    
    # The data is global, so render in a global projection.
    m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=-180, urcrnrlon=180)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(-90.,90,45))
    m.drawmeridians(np.arange(-180.,180,45), labels=[True,False,False,True])
    m.pcolormesh(longitude, latitude, datam, latlon=True)
    cb = m.colorbar()

    cb.set_label(units)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, DATAFIELD_NAME))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Example #24
0
def draw_map(file, map=None, show=True, title=None, log=False, map_type=None):
    '''Use Matplotlib's basemap to generate a map of a given BIOCLIM data 
    file.
    
    You can supply a Basemap object (in any projection) as the optional 
    keyword argument "map." If none is provided, the default Miller 
    projection will be used.'''
    
    data, no_value, ul, dims, size = extract_attributes(file)
    data = get_dataset(file)
    lats = np.linspace(ul[0], ul[0]-dims[0]*size[0], size[0], endpoint=False)
    lons = np.linspace(ul[1], ul[1]+dims[1]*size[1], size[1], endpoint=False)
    if map_type == 'variance':
        x, y = np.meshgrid(lons, lats)
        raster = np.zeros(x.shape)
        values = get_spatial_variance(file, 
                                      [(lat, lon) 
                                       for lat in lats 
                                       for lon in lons])
        for a in range(data.shape[0]):
            for b in range(data.shape[1]):
                data[a,b] = values.pop()
    else:
        raster = data.ReadAsArray()

    
    # because missing data is entered as -9999, created a masked array so that 
    # these points will not be plotted
    values = np.ma.masked_where(raster==no_value, raster)
    
    # log transform data, if requested
    if log:
        if (values < 0).any():
            values -= min(values)
        values = np.log1p(values)
    
    plt.figure()
    if title is None:
        title = '%s' % file
        if file in variable_names:
            title += ': %s' % variable_names[file]
    plt.title(title)
    if map is None:
        map = Basemap(projection='mill',lon_0=0)
        map.drawcoastlines(linewidth=1)
        map.drawcountries(linewidth=1)
        map.drawstates(linewidth=0.5)
        parallels = np.arange(-90.,90,10.)
        map.drawparallels(parallels,labels=[False,True,True,False])
        meridians = np.arange(-180.,180.,20.)
        map.drawmeridians(meridians,labels=[True,False,False,True])    

    x, y = np.meshgrid(lons, lats)
            
    map.pcolormesh(x, y, data=values, latlon=True, cmap=plt.cm.Spectral_r)
    cbar = plt.colorbar()
    
    if show: plt.show()
def run(FILE_NAME):

    DATAFIELD_NAME = 'Temperature_MW_A'
    if USE_NETCDF4:
        from netCDF4 import Dataset    
        nc = Dataset(FILE_NAME)

        # The variable has a fill value, 
        # so netCDF4 converts it to a float64 masked array for us.
        data = nc.variables[DATAFIELD_NAME][11,:,:]
        latitude = nc.variables['Latitude'][:]
        longitude = nc.variables['Longitude'][:]

    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # List available SDS datasets.
        # print hdf.datasets()

        # Read dataset.
        data3D = hdf.select(DATAFIELD_NAME)
        data = data3D[11,:,:]

        # Read geolocation dataset.
        lat = hdf.select('Latitude')
        latitude = lat[:,:]
        lon = hdf.select('Longitude')
        longitude = lon[:,:]

        # Handle fill value.
        attrs = data3D.attributes(full=1)
        fillvalue=attrs["_FillValue"]

        # fillvalue[0] is the attribute value.
        fv = fillvalue[0]
        data[data == fv] = np.nan
        data = np.ma.masked_array(data, np.isnan(data))

    
    # Draw an equidistant cylindrical projection using the low resolution
    # coastline database.
    m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat = 90,
                llcrnrlon=-180, urcrnrlon = 180)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180., 181., 45.), labels=[0, 0, 0, 1])
    m.pcolormesh(longitude, latitude, data, latlon=True, alpha=0.90)
    cb = m.colorbar()
    cb.set_label('Unit:K')
    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n {1} at TempPrsLvls=11'.format(basename, DATAFIELD_NAME))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.{1}.py.png".format(basename, DATAFIELD_NAME)
    fig.savefig(pngfile)
Example #26
0
def plot_sa_diff_figure(control_dataset, data, sa_mask):
    f = plt.figure('sa_diff')
    plt.set_cmap('RdGy_r')
    graph_settings = (
	    ((-4, 4), np.arange(-4, 4.1, 2)),
	    ((-6, 6), np.arange(-6, 6.1, 3)),
	    ((-0.7, 0.7), np.arange(-0.6, 0.61, 0.3)),
	    ((-4, 4), np.arange(-4, 4.1, 2)),
	    ((-0.2, 0.2), np.arange(-0.2, 0.21, 0.1)))

    variables = ['precip', 'surf_temp', 'q', 'field1389', 'field1385']
    nice_names = {'precip': '$\Delta$Precip (mm/day)', 
		  'surf_temp': '$\Delta$Surf temp (K)', 
		  'q':'$\Delta$Humidity (g/kg)', 
		  'field1389': '$\Delta$NPP (g/m$^2$/day)', 
		  'field1385': '$\Delta$Soil moisture'}

    f.subplots_adjust(hspace=0.2, wspace=0.1)
    for i in range(len(variables)):
	variable = variables[i]
	ax = plt.subplot(2, 3, i + 1)
	ax.set_title(nice_names[variable])
	variable_diff = data['data']['1pct'][variable] - data['data']['ctrl'][variable]
	if variable == 'field1389':
	    variable_diff *= 24*60*60*1000 # per s to per day, kg to g.
	lons, lats = get_vars_from_control_dataset(control_dataset)
	vmin, vmax = graph_settings[i][0]
	#general_plot(control_dataset, variable_diff.mean(axis=0), vmin=graph_settings[i][0][0], vmax=graph_settings[i][0][1], loc='sa', sa_mask=sa_mask)
	plot_data = variable_diff.mean(axis=0)
	#plot_south_america(lons, lats, sa_mask, plot_data, vmin, vmax)

	if variable in ('surf_temp', 'precip', 'q'):
	    # unmasked.
	    data_masked = plot_data
	    plot_lons, plot_data = extend_data(lons, lats, data_masked)
	else:
	    data_masked = np.ma.array(plot_data, mask=sa_mask)
	    plot_lons, plot_data = extend_data(lons, lats, data_masked)

	lons, lats = np.meshgrid(plot_lons, lats)

	m = Basemap(projection='cyl', resolution='c', llcrnrlat=-60, urcrnrlat=15, llcrnrlon=-85, urcrnrlon=-32)
	x, y = m(lons, lats)

	m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax)

	m.drawcoastlines()
	if i == 0 or i == 3:
	    m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10)
	elif i == 2 or i == 4:
	    m.drawparallels(np.arange(-60.,15.,10.), labels=[0, 1, 0, 0], fontsize=10)
	else:
	    m.drawparallels(np.arange(-60.,15.,10.))

	m.drawmeridians(np.arange(-90.,-30.,10.), labels=[0, 0, 0, 1], fontsize=10)

	cbar = m.colorbar(location='bottom', pad='7%', ticks=graph_settings[i][1])
def run(FILE_NAME):

    DATAFIELD_NAME = 'SurfaceTemperature'

    # The dataset is (6144 x 6400).  Subset it to be around than 1K x 1K
    # Otherwise, the plot will skip processing some regions.
    rows = slice(0, 6144, 6)
    cols = slice(0, 6400, 6)

    if USE_NETCDF4:    
        from netCDF4 import Dataset
        nc = Dataset(FILE_NAME)

        data = nc.variables[DATAFIELD_NAME][rows, cols]
    
        # Retrieve the geolocation data.
        latitude = nc.variables['Latitude'][rows, cols]
        longitude = nc.variables['Longitude'][rows, cols]
        
    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data2D = hdf.select(DATAFIELD_NAME)
        data = data2D[rows,cols]

        # Read geolocation dataset.
        lat = hdf.select('Latitude')
        latitude = lat[rows,cols]
        lon = hdf.select('Longitude')
        longitude = lon[rows,cols]
        

    # Apply the fill value.  The valid minimum is zero, although there's no
    # attribute.
    data[data < 0] = np.nan
    data = np.ma.masked_array(data, np.isnan(data))
    
    # Render the data in a lambert azimuthal equal area projection.
    m = Basemap(projection='nplaea', resolution='l',
                boundinglat=60, lon_0=43)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(50, 90, 10), labels=[1, 0, 0, 1])
    m.drawmeridians(np.arange(-180, 180, 30))
    x, y = m(longitude, latitude)
    m.pcolormesh(x, y, data)
    cb = m.colorbar()
    cb.set_label('Unknown')

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, DATAFIELD_NAME))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Example #28
0
def plotmap(variable, mode='multi', tstep=0, proj='merc', style='pcolormesh', clevs=20):

	latitudes = variable.coords['latitude'][:]
	longitudes = variable.coords['longitude'][:]

	lats, lons = makegrid(latitudes, longitudes, variable.shape[-2:])

	vmin, vmax = variable[:].min(), variable[:].max()

	llcrnrlat, urcrnrlat = lats.min(), lats.max()
	llcrnrlon, urcrnrlon = lons.min(), lons.max()
	lat_ts = lats.mean()
	lon_0 = lons.mean()

	fig = plt.figure(figsize=(10,14))

	cols, rows = 1, 1

	if mode == 'tstep':
		data = variable[:][tstep]
	elif mode == 'mean':
		data = variable[:].mean(axis=0)
	elif mode == 'multi':
		nplots = variable.shape[0]
		cols = int(np.floor(np.sqrt(nplots)))
		rows = int(np.ceil(np.sqrt(nplots)))

		print nplots, cols, rows

	fig, axes = plt.subplots(rows, cols, squeeze=False)

	for col in range(cols):
		for row in range(rows):
			print col, row, col+cols*row
			if proj == 'merc':
				m = Basemap(projection='merc',llcrnrlat=llcrnrlat,urcrnrlat=urcrnrlat,llcrnrlon=llcrnrlon,urcrnrlon=urcrnrlon,lat_ts=lat_ts,resolution='l', ax=axes[row][col])
			elif proj == 'lcc':
				m = Basemap(projection='lcc',llcrnrlat=llcrnrlat,urcrnrlat=urcrnrlat,llcrnrlon=llcrnrlon,urcrnrlon=urcrnrlon,lat_0=lat_ts,lon_0=lon_0,resolution='l', ax=axes[row][col])

			x, y = m(lons, lats)

			if mode == 'multi':
				data = variable[col+cols*row]

			if style == 'pcolormesh':
				m.pcolormesh(x, y, data, vmin=vmin, vmax=vmax, cmap='Blues')
			elif style == 'contour':
				m.contourf(x, y, data, clevs)
				m.contour(x, y, data, clevs, colors='black')

			m.fillcontinents(color='white',lake_color='aqua',zorder=0)
			m.drawcoastlines(linewidth=1.0)

			plt.tight_layout()

	return plt
def run(FILE_NAME):
    
    # Identify the data field.
    DATAFIELD_NAME = 'AlbedoLocal'

    hdf = SD(FILE_NAME, SDC.READ)

    # Read dataset.
    data4D = hdf.select(DATAFIELD_NAME)

    # Convert 4-D data to 2-D data by subsetting.
    SOMBlockDim = 50;
    NBandDim = 0;
    data = data4D[SOMBlockDim,:,:,NBandDim].astype(np.double)

    # Read geolocation dataset from HDF-EOS2 dumper output.
    GEO_FILE_NAME = 'lat_MISR_TC_ALBEDO_P223_F05_lvl50.output'
    GEO_FILE_NAME = os.path.join(os.environ['HDFEOS_ZOO_DIR'], 
                                 GEO_FILE_NAME)
    lat = np.genfromtxt(GEO_FILE_NAME, delimiter=',', usecols=[0])
    lat = lat.reshape(data.shape)
    
    GEO_FILE_NAME = 'lon_MISR_TC_ALBEDO_P223_F05_lvl50.output'
    GEO_FILE_NAME = os.path.join(os.environ['HDFEOS_ZOO_DIR'], 
                                 GEO_FILE_NAME)
    lon = np.genfromtxt(GEO_FILE_NAME, delimiter=',', usecols=[0])
    lon = lon.reshape(data.shape)
        
    # Read attributes.
    attrs = data4D.attributes(full=1)
    fva=attrs["_FillValue"]
    _FillValue = fva[0]

    # Apply the fill value.
    data[data == _FillValue] = np.nan
    datam = np.ma.masked_array(data, mask=np.isnan(data))


    # Set the limit for the plot.
    m = Basemap(projection='cyl', resolution='h',
                llcrnrlat=np.min(lat), urcrnrlat = np.max(lat),
                llcrnrlon=np.min(lon), urcrnrlon = np.max(lon))
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(np.floor(np.min(lat)), np.ceil(np.max(lat)), 1), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(np.floor(np.min(lon)), np.ceil(np.max(lon)), 1), labels=[0, 0, 0, 1])
    m.pcolormesh(lon, lat, datam, latlon=True)
    cb = m.colorbar()
    cb.set_label('No Unit')

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1} at SOMBlockDim=50 NBandDim=0'.format(basename, DATAFIELD_NAME))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.l50.py.png".format(basename)
    fig.savefig(pngfile)
Example #30
0
 def mapData(self, data, label=None,lon0=-179,lat0=-80,lon1=179,lat1=80):
     from mpl_toolkits.basemap import Basemap
     
     lons,lats=np.meshgrid(self.lonbounds, self.latbounds)
     m=Basemap(lon0,lat0,lon1,lat1)
     m.pcolormesh(np.transpose(lons),np.transpose(lats),np.transpose(data), latlon=True)
     m.drawcoastlines()
     cb= m.colorbar()
     if label is not None:
         cb.set_label(label)
     return m,cb
        sst = nc.variables['sst4'][:]
        lon = nc.variables['lon'][:]
        lat = nc.variables['lat'][:]
        timesst = nc.time_coverage_start

    # Interpolate the sst field onto the mooring position
    llon, llat = np.meshgrid(lon, lat)

    f = interpolate.interp2d(lon, lat, sst, kind='linear')
    sst_interp = f(lonmooring, latmooring)


    lon, lat = m(llon, llat)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    m.pcolormesh(lon, lat, sst, cmap=cmap, norm=norm)
    if sst_interp<35:
        plt.text(lonmooring2, latmooring2, '  ' + str(np.round(sst_interp[0], 2)), ha='left', va='center')
        scat = m.scatter(lonmooring2, latmooring2, s=45, c=sst_interp, cmap=cmap, norm=norm)

    m.drawcoastlines(ax=ax, linewidth=0.2)
    m.fillcontinents(color = 'gray')
    m.drawparallels(np.arange(round(coordinates[2]), coordinates[3], dlat), linewidth=0.,
                    labels=[1, 0, 0, 0], fontname='Times New Roman', fontsize=16, zorder=1)
    m.drawmeridians(np.arange(round(coordinates[0]), coordinates[1], dlon), linewidth=0.,
                    labels=[0, 0, 0, 1], fontname='Times New Roman', fontsize=16, zorder=1)
    cbar = plt.colorbar(scat, extend='both', shrink=0.7)
    cbar.set_label('$^{\circ}$C', rotation=0, horizontalalignment='left')
    cbar.set_ticks(bounds)
    plt.title(timesst[:10])
#    plt.savefig(figdir+ff)
def plot_fields(fields, break_value=None):
    """
    Plot *fields*. Each element in *fields* should be a `Field` instance.

    Plots on orthogonal projection, with lon_0, lat_0 taken from mean of lon,
    lat of first element in *fields*.

    """
    from mpl_toolkits.basemap import Basemap
    from matplotlib import pyplot as plt
    from utility_functions import broken_cmap_r

    # Comment: utility_functions is a separate package, created by J.Malm,
    # but which we can not find. If we want to run this part of the code, it
    # might be changed to something from matplotlib instead.
    # broken_cmap_r is supposed to create a colormap with a gradient on one side
    # of a threshold, and another gradient on the other side, and a unique
    # colour on the theshold it self.
    # Sara Hornquist 2015-03-12

    lon_0 = fields[0].lon.mean()
    lat_0 = fields[0].lat.mean()

    vmin, vmax, break_value = limits([f.data for f in fields], break_value)
    cmap = broken_cmap_r(vmin=vmin, vmax=vmax, break_value=break_value)

    fig = plt.figure()
    ax = None
    for ix, f in enumerate(fields):
        ax = fig.add_subplot(len(fields) % 2 + 1,
                             len(fields) // 2 + 1,
                             ix + 1,
                             sharex=ax,
                             sharey=ax)
        m = Basemap(projection='ortho',
                    lon_0=lon_0,
                    lat_0=lat_0,
                    lat_ts=0,
                    resolution='c',
                    ax=ax)
        m.drawcoastlines(linewidth=.5, color='g')

        step = (f.data.shape[1] // 256) or 1  # don't use full gigantic arrays
        _slice = (slice(None, None, step), ) * 2
        x, y = m(f.lon[_slice], f.lat[_slice])
        # Mask out pixels outside projection limb
        # on_map = (x < 1e20) | (y < 1e20)
        # data = np.ma.array(f.data[_slice], mask=~on_map)
        data = f.data[_slice]
        logger.debug("data.shape = %r" % (data.shape, ))
        # mesh = m.pcolor(x, y, data, vmin=vmin, vmax=vmax, cmap=cmap)
        # pcolormesh is much faster, but I can't get rid of off-projection drawing
        mesh = m.pcolormesh(x, y, data, vmin=vmin, vmax=vmax, cmap=cmap)
        fig.colorbar(mesh)
        ax.set_title(f.desc)

        m.drawmeridians(range(0, 360, 20), linewidth=.5)
        m.drawparallels(range(-80, 90, 10), linewidth=.5)
        # Mark 70 deg latitudes (cut off for validation)
        m.drawparallels([-70, 70], color='r', dashes=[1, 0], latmax=70)

    return fig
Example #33
0
              llcrnrlat=-65,
              urcrnrlat=90,
              llcrnrlon=-180,
              urcrnrlon=180,
              resolution='c')
x, y = map(lon2, lat2)

map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
clmhis = ma.masked_where(clmhis <= 0., clmhis)
clmhis1 = ma.masked_where(clmhis1 <= 0., clmhis1)
cc = clmhis1 - clmhis
cc = ma.masked_where(cc == 0., cc)

cs = map.pcolormesh(x, y, cc, cmap=plt.cm.bwr, vmin=-1, vmax=1)
cbar = map.colorbar(cs, location='bottom', size="4%", pad="2%")
cbar.ax.tick_params(labelsize=12)
plt.axis('off')

ax2 = fig.add_subplot(222)
ax2.set_title("ISAM yield difference 2010s (t/ha)", fontsize=18)
map = Basemap(projection='cyl',
              llcrnrlat=-65,
              urcrnrlat=90,
              llcrnrlon=-180,
              urcrnrlon=180,
              resolution='c')
map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
Example #34
0
PRMSL = grb.values
lat, lon = grb.latlons()

date = str(grb['dataDate'])
hour = str(grb['hour'])
fcsthr = str(grb[u'forecastTime'])

cycle = date.join(hour)



m = Basemap(projection='lcc',lat_1=45., lat_2=55,
           lat_0=np.median(lat),lon_0=np.median(lon),\
           rsphere=(6378137.00,6356752.3142),\
           llcrnrlon=lon.min(),urcrnrlon=lon.max(), \
           llcrnrlat=lat.min(),urcrnrlat=lat.max(), \
           area_thresh=500.)

m.drawcoastlines()
#m.drawparallels(np.arrange(lat.min(),lat.max(),20))
#m.drawmeridians(np.arrange(lon.min(),lon.max(),60))
m.drawmapboundary()

x, y = m(lon, lat)

cs = m.pcolormesh(x, y, PRMSL, shading='flat', cmap=plt.cm.jet)

plt.colorbar(cs, orientation='vertical')
plt.title('MSLP for 04E %s hr fcst from %s cycle' % (fcsthr, cycle))
plt.show()
Example #35
0
File: idw.py Project: ruoxianer/geo
base_map = Basemap(llcrnrlon=116.362,
                   urcrnrlon=121.9752,
                   llcrnrlat=30.7578,
                   urcrnrlat=35.1245,
                   lon_0=119,
                   lat_0=33,
                   ax=ax)

base_map.drawparallels(np.arange(30, 36, 1),
                       labels=[1, 0, 0, 0],
                       fontsize=12,
                       ax=ax)
base_map.drawmeridians(np.arange(116, 122, 1),
                       labels=[0, 0, 0, 1],
                       fontsize=12,
                       ax=ax)

base_map.readshapefile('shp/江苏省_行政边界',
                       'Js',
                       True,
                       default_encoding='ISO-8859-1')
cp = base_map.pcolormesh(xgrid,
                         ygrid,
                         zgrid,
                         cmap='Spectral_r',
                         shading='auto')
colorbar = base_map.colorbar(cp, label='IDW')
base_map.contour(xgrid, ygrid, zgrid, colors='w')
colorbar.outline.set_edgecolor('none')
plt.axis('off')
plt.show()
#!/usr/bin/python
'''
Module: read_and_map_mod_aerosol.py
==========================================================================================
Disclaimer: The code is for demonstration purposes only. Users are responsible to check for accuracy and revise to fit their objective.
Author: Justin Roberts-Pierel, 2015 
Organization: NASA ARSET
Purpose: To extract AOD data from a MODIS HDF4 file (or series of files) and create a map of the resulting data
See the README associated with this module for more information.
==========================================================================================
'''
#import necessary modules
from pyhdf import SD
import numpy as np
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import sys
import glob
#loops through all files listed in the text file
for FILE_NAME in ['temperature/MYD11C1.A2020022.006.2020027211827.hdf']:
    FILE_NAME = FILE_NAME.strip()
    try:
        # open the hdf file for reading
        hdf = SD.SD(FILE_NAME)
    except:
        print('Unable to open file: \n' + FILE_NAME + '\n Skipping...')
        continue
    # Get lat and lon info
    latitude = np.arange(-90, 90.05, 0.05)[::-1]
    print(latitude)
Example #37
0
plt.figure()
grib = 'multi_1.at_10m.t00z.f000.grib2'
grbs = pygrib.open(grib)

# In this example we will extract the same significant wave height field we used in the
# first example. Remember that indexing in Python starts at zero.
grb = grbs.select(name='Significant height of wind waves')[0]
data = grb.values
lat, lon = grb.latlons()

# From this point on the code is almost identical to the previous example.
# Plot the field using Basemap. Start with setting the map projection using the limits of the lat/lon data itself:

m=Basemap(projection='mill',lat_ts=10,llcrnrlon=lon.min(), \
  urcrnrlon=lon.max(),llcrnrlat=lat.min(),urcrnrlat=lat.max(), \
  resolution='c')
# Convert the lat/lon values to x/y projections.
x, y = m(lon, lat)

# Next, plot the field using the fast pcolormesh routine and set the colormap to jet.
cs = m.pcolormesh(x, y, data, shading='flat', cmap=plt.cm.jet)
# Add a coastline and axis values.
m.drawcoastlines()
m.fillcontinents()
m.drawmapboundary()
m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1])
# Add a colorbar and title, and then show the plot.
plt.colorbar(cs, orientation='vertical')
plt.title('Example 2: NWW3 Significant Wave Height from GRiB')
plt.show()
Example #38
0
lat,lon = grb.latlons() # Set the names of the latitude and longitude variables in your input GRIB file
print(len(lat))
print(len(lon))
 

# BIG 
        # "area": "70/-15/30/30",
# m=Basemap(projection='mill', llcrnrlon=-15,urcrnrlon=30,llcrnrlat=30,urcrnrlat=70,resolution='h')

# 64x64
        # "area": "58.8/8.1/40/27",
# m=Basemap(projection='mill', llcrnrlon=8.1,urcrnrlon=27,llcrnrlat=40,urcrnrlat=58.8,resolution='h')
# 32x32
        # "area": "54.3/13/45/22",
m=Basemap(projection='mill', llcrnrlon=13,urcrnrlon=22,llcrnrlat=45,urcrnrlat=54.3,resolution='h')

x, y = m(lon,lat)

# cs = m.pcolormesh(x,y,data-273.15,cmap=plt.cm.hot)
cs = m.pcolormesh(x,y,data-273.15)

my_coast = m.drawcoastlines()
my_states = m.drawcountries()
# my_p = m.drawparallels(np.arange(40,60,2),labels=[1,1,0,0])
# my_m = m.drawmeridians(np.arange(10,28,2),labels=[0,0,0,1])
 
plt.colorbar(pad=0.10, label='Teplota')
plt.title('Teplota') # Set the name of the variable to plot
plt.savefig('temp_32_title.png') # Set the output file name
plt.show()
             resolution='f',
             ax=axes[0])
m1.drawcoastlines(linewidth=0.3)
m1.drawcountries()
m1.drawmapscale(-121, 58.7, lons_d01.mean(), lats_d01.mean(), 100)
m1.drawparallels(np.arange(-50, 70, 5),
                 linewidth=0.5,
                 labels=[True, False, False, False],
                 fontsize=20)
m1.drawmeridians(np.arange(-130, -100, 5),
                 linewidth=0.5,
                 labels=[False, False, False, False],
                 fontsize=20)
map1 = m1.pcolormesh(lons_d01,
                     lats_d01,
                     avg_daily_obs_d01,
                     latlon=True,
                     cmap=newcmp)
axes[0].set_title('G4ICE - 9 km\n', fontsize=30)
mstats = 'm = %.4f, s = %.4f' % (np.nanmean(avg_daily_obs_d01),
                                 np.nanstd(avg_daily_obs_d01))
plt.text(1.0,
         1.0,
         mstats,
         horizontalalignment='right',
         verticalalignment='bottom',
         transform=axes[0].transAxes,
         fontsize=my_fontsize)
map1.set_clim(0, 0.05)

m1 = Basemap(projection='lcc',
Example #40
0
def run(FILE_NAME):

    DATAFIELD_NAME = 'Water_Vapor'

    if USE_NETCDF4:

        from netCDF4 import Dataset
        nc = Dataset(FILE_NAME)

        # The netCDF4 module will correctly apply fill value and
        # scaling equation.
        data = nc.variables[DATAFIELD_NAME][:]

        latitude = nc.variables['Latitude'][:]
        longitude = nc.variables['Longitude'][:]

        # Retrieve attributes.
        units = nc.variables[DATAFIELD_NAME].units
        long_name = nc.variables[DATAFIELD_NAME].long_name

    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data2D = hdf.select(DATAFIELD_NAME)
        data = data2D[:, :].astype(np.double)

        # Read geolocation dataset.
        lat = hdf.select('Latitude')
        latitude = lat[:, :]
        lon = hdf.select('Longitude')
        longitude = lon[:, :]

        # Retrieve attributes.
        attrs = data2D.attributes(full=1)
        lna = attrs["long_name"]
        long_name = lna[0]
        aoa = attrs["add_offset"]
        add_offset = aoa[0]
        fva = attrs["_FillValue"]
        _FillValue = fva[0]
        sfa = attrs["scale_factor"]
        scale_factor = sfa[0]
        ua = attrs["units"]
        units = ua[0]
        vra = attrs["valid_range"]
        valid_min = vra[0][0]
        valid_max = vra[0][1]

        # Apply _FillValue, scale and offset.
        invalid = np.logical_or(data > valid_max, data < valid_min)
        invalid = np.logical_or(invalid, data == _FillValue)
        data[invalid] = np.nan
        data = data * scale_factor + add_offset
        data = np.ma.masked_array(data, np.isnan(data))

    # The data is local to Alaska, so no need for a global or hemispherical
    # projection.
    m = Basemap(projection='laea',
                resolution='l',
                lat_ts=65,
                lat_0=65,
                lon_0=-150,
                width=4800000,
                height=3500000)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(40, 81, 10), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-210, -89., 30), labels=[0, 0, 0, 1])
    m.pcolormesh(longitude, latitude, data, latlon=True)
    cb = m.colorbar()
    cb.set_label(units)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, long_name))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Example #41
0
def main():

    ## Problem parameters
    
    # The intended flight
    #source = Point_l(14.7,100.6)
    #target = Point_l(-3.6,105.3)
    source = Point_l( -5.083052, 119.606448 ) # Our start
    target = Point_l( 13.610979, 100.753909 ) # Our end
    
    # The problem domain and resolution
    '''
    lat_min = -10.0
    lat_max = 20.0
    lon_min = 90.0
    lon_max = 120.0
    lat_res = 150 
    lon_res = 150
    '''

    # Rectangle
    '''
    lat_min = 20
    lat_max = 40
    lon_min = 140
    lon_max = 160
    lat_res = 200 
    lon_res = 200
    '''
    
    # Case study
    lat_min = -10
    lat_max = 20
    lon_min = 90
    lon_max = 130
    lat_res = 300
    lon_res = 300

    dim = Dimension_l(lat_min, lat_max, lat_res, lon_min, lon_max, lon_res)
    
    # create Basemap instance.
    m = Basemap(projection='mill',\
                llcrnrlat=lat_min,urcrnrlat=lat_max,\
                llcrnrlon=lon_min,urcrnrlon=lon_max,\
                resolution='l')

    # Convert the problem domain to meters
    x_min, y_min = m(lon_min, lat_min)
    x_max, y_max = m(lon_max, lat_max)
    dim_m = Dimension_m(y_min, y_max, lat_res, x_min, x_max, lon_res)
    source_m = Point_m(m(source.lon,source.lat)[0], m(source.lon, source.lat)[1])
    target_m = Point_m(m(target.lon,target.lat)[0], m(target.lon, target.lat)[1])

    print("X resolution (km) is: " + str((dim_m.x_max - dim_m.x_min) / (dim_m.x_res - 1) / 1000.0 ))
    print("Y resolution (km) is: " + str((dim_m.y_max - dim_m.y_min) / (dim_m.y_res - 1) / 1000.0 ))

    # Airport locations
    airports = get_airports(dim)
    airports_m = [Point_m(m(apt.lon,apt.lat)[0], m(apt.lon, apt.lat)[1]) for apt in airports]

    # Get current data
    U_m, V_m = get_currents(dim_m, dim, m)

    # Get depth data
    depth_m = get_depths(dim, dim_m, m)

    ## Run calculations to evaluate the problem
    print("\n=== Evaluating problem\n")

    # Calculate costs
    costs_sp = calc_costs_sp(dim_m, airports_m)
    costs_sb = calc_costs_sb(dim_m)

    init_vals = calc_init_values(dim_m, source_m, target_m, airports_m, m)
    sink_crash = p_intact * init_vals
    surface_crash = (1 - p_intact) * init_vals
    
    # Useful things for later plotting
    (xSource, ySource) = m(source.lon, source.lat)
    (xTarget, yTarget) = m(target.lon, target.lat)
    
    aptCoords = [(p.lon, p.lat) for p in airports]
    aptCoords = np.array(aptCoords)
    xA, yA = m(aptCoords[:,0], aptCoords[:,1])

    # Calculate the likelihood that a search plane finds a crash at
    # each location
    sp_find_prob = search_plane_probabilities(dim_m, surface_crash, sink_crash, depth_m)
    sb_find_prob = search_vessel_probabilities(dim_m, surface_crash, sink_crash)
        
    # Calculate the price to search each area
    price_per_prob_sp = costs_sp / sp_find_prob
    price_per_prob_sb = costs_sb / sp_find_prob

    sp_mean = price_per_prob_sp[np.where(np.logical_not(np.isinf(price_per_prob_sp)))].mean()
    sb_mean = price_per_prob_sb[np.where(np.logical_not(np.isinf(price_per_prob_sb)))].mean()
    print(sp_mean)  
    print(sb_mean)  
 
    price_per_prob_sp[np.where(np.isinf(price_per_prob_sp))] = sp_mean
    price_per_prob_sb[np.where(np.isinf(price_per_prob_sb))] = sb_mean
    
    ## Plot
    # Set up the figure
    fig = plt.figure(figsize=(8,8))
    ax = fig.add_axes([0.1,0.1,0.8,0.8])    
    
    m.fillcontinents(zorder=1)
    m.drawcoastlines()
    m.drawcountries()
    parallels = np.arange(0.,90,10.)
    #m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)

    # Draw the line representing the flight
    m.plot([xSource, xTarget], [ySource, yTarget], lw=4, c='black', zorder=4)

    # Draw dots on airports
    m.scatter(xA, yA, s=80, marker='^', color='purple', zorder=5)


    # Draw a contour map of costs
    lons, lats = m.makegrid(lat_res, lon_res)
    x, y = m(lons, lats)
    #cs = m.contourf(x, y, depth_m, 50, cmap='Blues_r')
    #pc = m.pcolormesh(x, y, depth_m)
    print(price_per_prob_sp.max())
    print(price_per_prob_sp.min())
    pc = m.pcolormesh(x, y, price_per_prob_sb, cmap='YlOrRd_r',vmax=5e6)
    #cbar = m.colorbar(pc,location='bottom',pad="5%", ticks = [0, init_vals.max()])
    cbar = m.colorbar(pc,location='bottom',pad="5%")
    #plt.title("Distribution of undirected crashes")
    plt.show()
    return

    # Draw a contour map of probabilities
    p_x = np.linspace(dim_m.x_min, dim_m.x_max, dim_m.x_res)
    p_y = np.linspace(dim_m.y_min, dim_m.y_max, dim_m.y_res)
    x, y = np.meshgrid(p_x, p_y)
    '''
    cs = m.contourf(x, y, u_m, cmap="blues")
    cbar = m.colorbar(cs,location='bottom',pad="5%")
    '''

    # Allow the probabilities to flow in the current
    current_mapping = generate_current_mapping(dim_m, U_m, V_m, 1.0/10)
    curr_probs = init_vals.copy()
    maxInitProb = init_vals.max() * 1.2

    for iDay in range(100):

        curr_probs = sink_crash + surface_crash

        # Calculate the likelihood that a search plane finds a crash at
        # each location
        sp_find_prob = search_plane_probabilities(dim_m, surface_crash, sink_crash, depth_m)
        sb_find_prob = search_vessel_probabilities(dim_m, surface_crash, sink_crash)

        # Calculate the price to search each area
        price_per_prob_sp = costs_sp / sp_find_prob
        price_per_prob_sb = costs_sb / sp_find_prob

        #price_per_prob_sp = mask_vals(dim_m, price_per_prob_sp, m, fill=10000)
        #print(price_per_prob_sp.min())
        #price_per_prob_sp[np.where(np.isinf(price_per_prob_sp))] = float('NaN')
        #print(price_per_prob_sp.max())

        # Plotting stuff
        if(iDay % 5 == 0):
            fig = plt.figure(figsize=(8,8))
            
            ax = fig.add_axes([0.1,0.1,0.8,0.8])    
            m.plot([xSource, xTarget], [ySource, yTarget], lw=4, c='black', zorder=4)
            m.scatter(xA, yA, s=80, marker='^', color='purple', zorder=5)
            
            m.fillcontinents(zorder=1)
            m.drawcoastlines()
            m.drawcountries()
            parallels = np.arange(0.,90,10.)
            m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
            
            #cs = m.contourf(x, y, curr_probs, 50, cmap="YlOrRd", vmin=0, vmax=maxInitProb)
            #cs = m.pcolormesh(x, y, curr_probs, cmap="YlOrRd", vmin = 0, vmax=maxInitProb)
            cs = m.pcolormesh(x, y, curr_probs, cmap="YlOrRd", vmax = maxInitProb)
            #cs = m.pcolormesh(x, y, depth_m, cmap="bone")
            cbar = m.colorbar(cs,location='bottom',pad="5%")
            #Q = m.quiver(x, y, U_m, V_m)
            plt.show() 
        
        # Update the probabilities
        surface_crash = apply_current_mapping(dim_m, surface_crash, current_mapping, m)
Example #42
0
ax.format_coord = format_coord

m.drawcoastlines()
m.drawcountries()
m.drawparallels(np.linspace(m.llcrnrlat, m.urcrnrlat, parallelres),
                labels=[True, False, False, False])
m.drawmeridians(np.linspace(m.llcrnrlon, m.urcrnrlon, meridianres),
                labels=[False, False, False, True])
m.drawstates()
x = np.linspace(0, m.urcrnrx, dim[1])
y = np.linspace(0, m.urcrnry, dim[2])
xx, yy = np.meshgrid(x, y)

quad = m.pcolormesh(xx,
                    yy,
                    np.transpose(np.squeeze(ftledata[timestep, :, :])),
                    shading='gouraud',
                    cmap='viridis')
#quad = m.contourf(xx,yy, np.transpose(np.squeeze(ftledata[timestep,:,:])),shading='gouraud',cmap='viridis')
cbar = fig.colorbar(quad, ax=ax, pad=0.01)
ax.set_title('Time Step {0}'.format(timestep))
ridges = m.contour(xx,
                   yy,
                   np.transpose(np.squeeze(ftledata[timestep, :, :])),
                   levels=[-1])

canvas = FigureCanvasTkAgg(fig, root)
canvas.show()
canvas.get_tk_widget().grid(row=1, column=3, rowspan=40)

toolbar_frame = tk.Frame(root)
Example #43
0
class Figure():
    """
	Figure is an object containing data to plot and map options.
	It enables to easily draw a map with data on it.
	"""
    def __init__(self, figure: plt.Figure, ax: plt.Axes, dataset: nc.Dataset,
                 map_options: dict, presets: dict):
        self.figure = figure
        self.ax = ax
        self.presets = presets
        self.map_options = map_options
        self.map_settings = self._get_map_settings()

        self.map = Basemap(ax=self.ax, **self.map_settings)
        self.map.drawmapboundary(fill_color='aqua')
        self.map.drawcoastlines()
        if self.map_options['countries']:
            self.map.drawcountries()
        if self.map_options['rivers']:
            self.map.drawrivers()

        # Extract longitude and latitude arrays (try 2 different name formats)
        try:
            self.lons = np.ma.getdata(dataset['lon'][:])
            self.lats = np.ma.getdata(dataset['lat'][:])
        except:
            self.lons = np.ma.getdata(dataset['longitude'][:])
            self.lats = np.ma.getdata(dataset['latitude'][:])

        self.data = self._retrieve_data_from_dataset(dataset)

        self.transform_data()

    def _get_map_settings(self):
        """
		Return the basemap kwargs from global map options.
		"""
        settings = self.presets[self.map_options['preset']]['args'].copy()
        settings['resolution'] = self.map_options['resolution']
        return settings

    def _retrieve_data_from_dataset(self, dataset: nc.Dataset):
        """
		Extract data from the dataset and process it.
		"""
        if self.map_options['pl_index'] is not None:
            data = dataset[self.map_options['variable']][
                self.map_options['time_index'],
                self.map_options['pl_index'], :, :]
        else:
            data = dataset[self.map_options['variable']][
                self.map_options['time_index'], :, :]
        data = data * self.map_options['coef'] + self.map_options['offset']
        return data

    def transform_data(self):
        """
		Transform the data.
		"""
        lon_offset = self.map_options['lon_offset']
        self.lons = self.lons + lon_offset
        temp = self.data[:, 0:720].copy()
        self.data[:, 0:720] = self.data[:, 720:1440].copy()
        self.data[:, 720:1440] = temp

    def adapt_coordinates(self):
        """
		Adapt coordinates to the chosen projection.
		"""
        x, y = np.meshgrid(self.lons, self.lats)
        xx, yy = self.map(x, y)
        xx[~np.isfinite(xx)] = -180
        yy[~np.isfinite(yy)] = 0
        return xx, yy

    def plot_data(self):
        """
		Plot data on the map.
		"""
        lon, lat = self.adapt_coordinates()

        if self.map_settings['projection'] == "ortho":
            self.data[lon > 1e20] = np.nan
            self.data[lat > 1e20] = np.nan
            self.data[lon < -1e20] = np.nan
            self.data[lat < -1e20] = np.nan

        if self.map_options['norm']:
            norm = display_tools.MidpointNormalize(
                vmin=self.map_options['c_min'],
                vmax=self.map_options['c_max'],
                midpoint=self.map_options['midpoint'])
        else:
            norm = None

        mesh = self.map.pcolormesh(lon,
                                   lat,
                                   self.data,
                                   cmap=self.map_options['cmap'],
                                   norm=norm)

        if self.map_options['colorbar']:
            divider = make_axes_locatable(self.ax)
            cax = divider.append_axes("right", size='3%', pad=0.1)
            plt.colorbar(mappable=mesh,
                         ax=self.ax,
                         cax=cax,
                         orientation='vertical',
                         extend='both')
Example #44
0
    for k in range(0, 699):
        for d in range(0, 600):
            temp_c[j,k,d] = t2[j,k,d] - 273.15
            temp_c90[j, k, d] = t290[j, k, d] - 273.15
            diff[j,k,d] = temp_c90[j,k,d] - temp_c[j,k,d]
datevar = num2date(time[:], units='hours since 1970-01-01 00:00:00', calendar='standard')
# print(datevar[:])
map = Basemap(projection='merc', llcrnrlon=lons[0], llcrnrlat=lats[0], urcrnrlon=lons[599], urcrnrlat=lats[698],
              resolution='i')
# map.drawcoastlines()
# map.drawstates()
# map.drawcountries()
# map.drawlsmask(land_color='Linen', ocean_color='#CCFFFF')
lon2, lat2 = np.meshgrid(lons, lats)
x, y = map(lon2, lat2)

plt.figure(figsize=(601/100, 700/100))
plt.gca().set_axis_off()
plt.subplots_adjust(top=1, bottom=0, right=1, left=0,
                    hspace=0, wspace=0)
plt.margins(0, 0)
#plt.colorbar(label="Temperature (Celsius)")
for b in range(0, 24):
    map.pcolormesh(x, y, diff[b, :, :], cmap='bwr', vmin=-6, vmax=6)
    #plt.title('2m Temperature on %s' % datevar[b])
    plt.savefig("E:/elise/Documents/UVA-Climate-Lab-/diurnal/ta2m_diurnal_mean_diff_2090-2099_%s.png" % b, transparent='True',
                bbox_inches='tight', pad_inches=0)
    print('saved %s' % b)
plt.colorbar(label="Difference in Temperature (Celsius)")
plt.savefig("E:/elise/Documents/UVA-Climate-Lab-/diurnal/ta2m_diurnal_mean_diff_2090-2099_KEY_%s.png" % b, transparent='True',
            bbox_inches='tight', pad_inches=0)
# Handle scale offset
attrs = data.attributes(full=1)
scale = attrs['slope']
offset = attrs['intercept']
dataf = dataf*scale[0] + offset[0]

# Draw an equidistant cylindrical projection using the low resolution
# coastline database.
m = Basemap(projection='cyl', resolution='l',
            llcrnrlat=-90, urcrnrlat = 90,
            llcrnrlon=-180, urcrnrlon = 180)
m.drawcoastlines(linewidth=0.5)
m.drawparallels(np.arange(-90, 91, 45))
m.drawmeridians(np.arange(-180, 180, 45), labels=[True,False,False,True])
m.pcolormesh(longitude, latitude, dataf, latlon=True)


# Draw color bar.
cb = m.colorbar()
ua = attrs['units']
units = ua[0]
# Remove garbage character at the end.
cb.set_label('Unit: '+units[:-1])

# Draw title.
lna=attrs["long_name"]
long_name = lna[0]
# Remove garbage character at the end.
plt.title('{0}\n {1}'.format(FILE_NAME, long_name[:-1]))
fig = plt.gcf()
Example #46
0
            data = np.ma.masked_invalid(data)

            # Get the lat/lon data
            lon, lat = response[0].getLatLonCoords()
            lon, lat = m(lon, lat)

            # Initialize figure size (48,27) for 4K and (24,15) for 1080p
            #plt.figure(num=None, figsize=(24,15), dpi=80)
            fig = plt.figure(num=None, figsize=(8, 5), dpi=80)

            # Add radar data
            cmap = radarColors
            m.pcolormesh(lon,
                         lat,
                         data,
                         cmap=cmap,
                         vmin=-30,
                         vmax=85,
                         alpha=0.5,
                         zorder=3)
            # Add date/time stamp
            timestamp = time.strftime(
                '%a %x %I:%M %p %Z',
                time.localtime(
                    calendar.timegm(
                        time.strptime(str(times[x].validPeriod.end),
                                      "%Y-%m-%d %H:%M:%S"))))

            plt.annotate(timestamp,
                         xy=(0.01, 0.01),
                         xycoords='axes fraction',
                         fontsize=10,
Example #47
0
              llcrnrlat=-65,
              urcrnrlat=90,
              llcrnrlon=-180,
              urcrnrlon=180,
              resolution='c')
#map.drawcoastlines()
x, y = map(lon2, lat2)

map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
#print iyield2
cs = map.pcolormesh(x,
                    y,
                    iyield1,
                    cmap=plt.cm.jet,
                    norm=colors.PowerNorm(gamma=1. / 2.),
                    vmin=0,
                    vmax=16)

#cbar = map.colorbar(cs,location='bottom',size="5%",pad="2%")
#cbar.ax.tick_params(labelsize=15)
plt.axis('off')
cmap = plt.cm.bwr
bounds = [-30, -25, -20, -15, -10, -5, 0, 20, 40, 60, 80, 100, 120]
norm = colors.BoundaryNorm(bounds, cmap.N)
#norm = colors.Normalize(vmin=-150, vmax=150)
#norm=colors.SymLogNorm(linthresh=2, linscale=1,vmin=-200,vmax=200)

ax2 = fig.add_subplot(422)
#ax2.set_title("CESM-ISAM Maize Yield (t/ha)",fontsize=20)
Example #48
0
def mapDraw(flnm,
            titlTxt=None,
            barTxt=None,
            fignm=None,
            projMap='cea',
            scale=1.0,
            log=False,
            maskNum=None,
            vMin=None,
            vMax=None,
            cmNm='terrain_r',
            lut=None,
            split=None):
    from mpl_toolkits.basemap import Basemap
    from numpy import ma
    from matplotlib.colors import LogNorm

    inproj = osr.SpatialReference()
    if type(flnm) is str:  #GDAL recongnized GIS data
        print 'Input data: GIS dataset.'
        if fignm is None:
            fignm = flnm + '.png'
        if titlTxt is None:
            titlTxt = flnm
        print 'Plotting map from', flnm, 'to', fignm
        # Read the data and metadata
        ds = gdal.Open(flnm)
        data = GIS.read(flnm) * scale
        gt = ds.GetGeoTransform()
        proj = ds.GetProjection()
        xres = gt[1]
        yres = gt[5]
        # get the edge coordinates and add half the resolution
        # to go to center coordinates
        xmin = gt[0] + xres * 0.5
        xmax = gt[0] + (xres * ds.RasterXSize) - xres * 0.5
        ymin = gt[3] + (yres * ds.RasterYSize) + yres * 0.5
        ymax = gt[3] - yres * 0.5
        ds = None
        # create a grid of xy coordinates in the original projection
        inproj.ImportFromWkt(proj)
    elif type(flnm) is np.ndarray:
        print 'Input data: CLM dataset.'
        xmin, xres, xmax = [-180 + 1.25 / 2, 1.25, 180 - 1.25 / 2]
        ymin, yres, ymax = [
            -90 + 180.0 / (193 * 2), -180.0 / 193, 90 - 180.0 / (193 * 2)
        ]
        ##### CLM: 0~360 =====> -180~180
        inproj.ImportFromEPSG(4326)
        data = np.hstack([flnm[:, 288 / 2:], flnm[:, :288 / 2]])
        del flnm
    else:
        print 'Input data type', type(flnm), 'not recongised.'
        return False

    import matplotlib.pyplot as plt
    fig = plt.figure()

    m = Basemap(projection=projMap,
                llcrnrlat=ymin,
                urcrnrlat=min(ymax, 90),
                llcrnrlon=xmin,
                urcrnrlon=xmax,
                resolution='c')  #extent
    m.drawcountries(linewidth=.1)
    m.drawcoastlines(linewidth=.2)
    m.drawparallels(np.arange(-60, 60, 30),
                    labels=[1, 0, 0, 0],
                    linewidth=.3,
                    color='grey')
    m.drawmeridians(np.arange(-180, 180, 30),
                    labels=[0, 0, 1, 0],
                    linewidth=.3,
                    color='grey')

    xy_source = np.mgrid[xmin:xmax + xres:xres, ymax + yres:ymin:yres]
    outproj = osr.SpatialReference()
    outproj.ImportFromProj4(m.proj4string)
    xx, yy = GIS.cordConv(xy_source, inproj, outproj)

    # plot the data (first layer)
    if split is not None:
        lut = len(split) - 1
        dump = np.zeros(data.shape) * np.NaN
        for j in range(len(split)):
            dump[data >= split[j]] = j
        data = dump
    colmap = plt.cm.get_cmap(cmNm, lut)
    colmap.set_bad('w')
    if maskNum is not None:
        data[data == maskNum] = np.nan

    if log is True:
        if vMin is None:
            vMin = np.max([np.nanmin(data), 0.01])
        if vMax is None:
            vMax = 10**np.ceil(np.log10(np.nanmax(data)))
        im = m.pcolormesh(xx,
                          yy,
                          ma.array(data.T, mask=np.isnan(data.T)),
                          cmap=colmap,
                          norm=LogNorm(vmin=vMin, vmax=vMax))
    else:
        if vMin is None:
            vMin = np.min(data[np.isfinite(data)])
        if vMax is None:
            vMax = np.max(data[np.isfinite(data)])
        im = m.pcolormesh(xx,
                          yy,
                          ma.array(data.T, mask=np.isnan(data.T)),
                          cmap=colmap,
                          vmin=vMin,
                          vmax=vMax)

    ax = plt.gca()
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size="5%", pad=0.05)
    cbar = plt.colorbar(im, cax=cax)
    if split is not None:
        tick_temp = np.arange(len(split) + 1)
        cbar.set_ticks(tick_temp)
        string = []
        for l in range(len(split)):
            string.append(str(split[l]))
        cbar.set_ticklabels(string)

    if barTxt is not None:
        cbar.set_label(barTxt)
    #cbar.update_ticks()
    plt.savefig(fignm, dpi=500)
    plt.close()
Example #49
0
map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()



lone,late = N.meshgrid(lonnc,latnc) #Returns coordinate matrices from coordinate vectors
x,y = map(lone,late)
ncvar_maizef=maskoceans(x,y,ncvar_maizef)
ncvar_maizef=ma.filled(ncvar_maizef, fill_value=0.)
ncvar_maizef = ma.masked_where(ncvar_maizef<=0,ncvar_maizef)
ncvar_maizef = ma.masked_where(mask_clm<=0,ncvar_maizef)

#print maskus_new
m3y=ncvar_maizef
cs = map.pcolormesh(x,y,m3y,cmap=plt.cm.YlGn,vmin=0,vmax=16)
cbar = map.colorbar(cs,location='bottom',size="5%",pad="2%")
cbar.ax.tick_params(labelsize=15) 
plt.axis('off')
plt.savefig('maiirrm3.jpg',dpi=300,bbox_inches='tight')


fig = plt.figure(figsize=(20,15))

ax2 = fig.add_subplot(321)
ax2.set_title("ISAM-CESM Maize Yield (t/ha)",fontsize=20)
map = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')
#map = Basemap(projection='robin',lon_0=0,resolution='c')
map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
Example #50
0
lons = np.linspace(float(grb['longitudeOfFirstGridPointInDegrees']), 
		float(grb['longitudeOfLastGridPointInDegrees']), int(grb['Ni']) )	#generate x coordinates normalized to the range of data
lats = np.linspace(float(grb['latitudeOfFirstGridPointInDegrees']), 
		float(grb['latitudeOfLastGridPointInDegrees']), int(grb['Nj']) )	#generate y coordinates normalized to the range of data

# need to shift data grid longitudes from (0..360) to (-180..180)? (do not use for LIS, do not use for GFS)
# data, lons = shiftgrid(180., data, lons, start=False)  # use this to bump data from 0..360 on the lons to -180..180
grid_lon, grid_lat = np.meshgrid(lons, lats) #regularly spaced 2D grid

print("Adj Lon Range: " + str(grid_lon[0,0]) + " --> " + str(grid_lon[0,-1]))
#print("Data test: " , data[-102.210999:43.824593,40:50].T)

plt.figure(figsize=(12,8))
m = Basemap( projection='lcc', resolution='c', rsphere=(6378137.00,6356752.3142), 
			llcrnrlon=-108.0, urcrnrlon=-92.50, llcrnrlat=38.0, 
			urcrnrlat=50., lat_1=33., lat_2=45, lat_0=39, lon_0=-96.)

x, y = m(grid_lon, grid_lat)

cs = m.pcolormesh(x,y,data,shading='flat',cmap=plt.cm.gist_stern_r)

#m.readshapefile('/mnt/d/Libraries/Documents/Scripts/LIS_Plot/Test_Data/Aux_files/States_21basic/states', 'states')
#m.readshapefile('/mnt/d/Libraries/Documents/Scripts/LIS_Plot/Test_Data/Aux_files/Canada/Canada', 'Canada')
m.drawcoastlines()
m.drawmapboundary()
m.drawparallels(np.arange(-90.,120.,30.),labels=[1,0,0,0])
m.drawmeridians(np.arange(-180.,180.,30.),labels=[0,0,0,1])

plt.colorbar(cs,orientation='vertical', shrink=0.5)
plt.title('SPoRT LIS: RSM 0-10cm') # Set the name of the variable to plot
plt.savefig(grib +'.png') # Set the output file name
Example #51
0
# longitudes go from 20 to 380.
topodat = np.loadtxt('etopo20data.gz')
lons = np.loadtxt('etopo20lons.gz')
lats = np.loadtxt('etopo20lats.gz')
lons, lats = np.meshgrid(lons, lats)

print('min/max etopo20 data:')
print(topodat.min(),topodat.max())

# create new figure
fig=plt.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')
# plot image over map.
im = m.pcolormesh(lons,lats,topodat,cmap=cmap,latlon=True)
m.colorbar() # draw colorbar
m.drawcoastlines()
# draw parallels
m.drawparallels(np.arange(-90,90,30),labels=[1,0,0,1])
# draw meridians
m.drawmeridians(np.arange(0,360,60),labels=[1,0,0,1])
plt.title('Cylindrical Equidistant')
print('plotting Cylindrical Equidistant example ...')
print(m.proj4string)

# create new figure
fig=plt.figure()
# setup miller cylindrical map projection.
m = Basemap(llcrnrlon=-180.,llcrnrlat=-90,urcrnrlon=180.,urcrnrlat=90.,\
            resolution='c',area_thresh=10000.,projection='mill')
Example #52
0
            u = vars['eastward_vel'][time, :, :]
            v = vars['northward_vel'][time, :, :]

        lon = vars['lon'][:]
        lat = vars['lat'][:]

        downsamp = 25
        ref_lat = lat.mean()
        ref_lon = lon.mean()
        lon, lat = np.meshgrid(lon, lat)
        x, y = lonlat2m(lon=lon, lat=lat, ref_lon=ref_lon, ref_lat=ref_lat)

        im = m.pcolormesh(lon,
                          lat,
                          species,
                          vmin=c_min,
                          vmax=c_max,
                          latlon=True,
                          cmap='Greys',
                          shading='gouraud')

        flow_y = r_r[k]
        flow_x = r_r[k + 3]
        for p in range(len(flow_x)):
            x = flow_x[p]
            y = flow_y[p]
            if len(x) > 6:
                m.plot(x, y, 'r-')  #, latlon=True)

        flow_y = a_r[k]
        flow_x = a_r[k + 3]
        for p in range(len(flow_x)):
inproj = osr.SpatialReference()
inproj.ImportFromWkt(proj)
outproj = osr.SpatialReference()
outproj.ImportFromProj4(m.proj4string)

mycmap = matplotlib.colors.LinearSegmentedColormap.from_list(
    "", ["darkblue", "yellow", "darkred"])

xx, yy = convertXY(xy_source, inproj, outproj)

colors = ["darkblue", "yellow", "darkred"]

im1 = m.pcolormesh(xx,
                   yy,
                   z.T,
                   cmap=matplotlib.colors.ListedColormap(colors),
                   vmin=1,
                   vmax=3,
                   zorder=3)

arrnames = np.array(["Low", "Low", "Medium", "High"])
formatter = plt.FuncFormatter(lambda val, loc: arrnames[val])
cbar = m.colorbar(im1,
                  location='bottom',
                  pad="5%",
                  size="5%",
                  ticks=[0, 1, 2, 3],
                  format=formatter)
cbar.set_label('Exposure', size="28", labelpad=20)

plt.show()
Example #54
0
#v = np.linspace( -0.8, 0.8, 17, endpoint=True)
#norm = colors.BoundaryNorm(boundaries=v, ncolors=256)

#strd
ax = plt.subplot2grid((4,6), (1,0))
m = Basemap(projection='cyl', llcrnrlat=-45.0, llcrnrlon=110.0, urcrnrlat=-5.0, urcrnrlon=160.0)
m.drawcoastlines()
m.drawparallels(np.array([-45, -35, -25, -15, -5]), labels=[1,0,0,0], fontsize=7)
m.drawmeridians(np.array([110, 120, 130, 140, 150, 160]), labels=[0,0,0,1], fontsize=7)
lon, lat = np.meshgrid(lon,lat)
xi,yi = m(lon,lat)
mn_strd_nino = np.ma.masked_invalid(mn_strd_nino)
ss_strd_nino = np.ma.masked_invalid(ss_strd_nino)
v = np.linspace( -26, 26, 27, endpoint=True)
norm = colors.BoundaryNorm(boundaries=v, ncolors=256)
mymap= m.pcolormesh(xi, yi, mn_strd_nino, norm=norm, cmap='bwr')
ss = m.pcolor(xi, yi, ss_strd_nino, hatch='...', norm=norm, cmap='bwr')
cb = m.colorbar(mymap,"right", size="5%", pad="2%", ticks=v)
cb.ax.tick_params(labelsize=6)
for label in cb.ax.yaxis.get_ticklabels()[1::2]:
    label.set_visible(False)
cb.set_label('$W/m^2$', fontsize=8)
plt.title('Longwave downwards', fontsize=10)
ax.set_ylabel('El Nino', labelpad=20)

ax = plt.subplot2grid((4,6), (2,0))
m = Basemap(projection='cyl', llcrnrlat=-45.0, llcrnrlon=110.0, urcrnrlat=-5.0, urcrnrlon=160.0)
m.drawcoastlines()
m.drawparallels(np.array([-45, -35, -25, -15, -5]), labels=[1,0,0,0], fontsize=7)
m.drawmeridians(np.array([110, 120, 130, 140, 150, 160]), labels=[0,0,0,1], fontsize=7)
mn_strd_nina = np.ma.masked_invalid(mn_strd_nina)
Example #55
0
for i in xrange(dimy):
	for j in xrange(dimx):
		if finalmatrix[i][j] == 2:
			cb[i][j] = 1
		else:
			cb[i][j] = 0
#this is necessary!!!
#cb = np.flipud(cb)

#print np.sum(cb)

################
#plotting time!#
################

#make our lon and lat 2D
lon1, lat1 = np.meshgrid(lon, lat)

m = Basemap(resolution='l', projection='merc', \
llcrnrlon=90, llcrnrlat=-20, urcrnrlon=150, urcrnrlat=20) #for mercator

#draw map coastline, etc
m.drawcoastlines(linewidth=0.25)
m.drawcountries(linewidth=0.25)

#finishing
plt.title('Pendeteksi Awan CB ver 1.0')
cs = m.pcolormesh(lon1, lat1, np.squeeze(cb), cmap='Set3', latlon=True)
#cbar = m.colorbar(cs, location='bottom', pad="10%") #add color bar
plt.show()
Example #56
0
def plot_field(path, image_outpath, unitlabel, product_name):
    """
    :return:

    """
    """
    creates single frame (from one flepart output file)
    time step is given by the file
    spatial domain is given by lon0, lon1, lat0, lat1, z0, z1

            |-----------------lon1, lat1
            |                     |
            |                     |
        lon0, lat0 ---------------|

    z0 is lower vertica level, z1 is the upper


    Developer note..:

        For most map projections, the map projection region can either be specified by setting these keywords:

        Keyword    Description
        llcrnrlon    longitude of lower left hand corner of the desired map domain (degrees).
        llcrnrlat    latitude of lower left hand corner of the desired map domain (degrees).
        urcrnrlon    longitude of upper right hand corner of the desired map domain (degrees).
        urcrnrlat    latitude of upper right hand corner of the desired map domain (degrees).
        or these

        Keyword    Description
        width    width of desired map domain in projection coordinates (meters).
        height    height of desired map domain in projection coordinates (meters).
        lon_0    center of desired map domain (in degrees).
        lat_0    center of desired map domain (in degrees).


        resolution:  c (crude), l (low), i (intermediate), h (high), f (full)
        more at http://matplotlib.org/basemap/api/basemap_api.html
    """

    d = scipy.io.loadmat(path)

    numxgrid = d["numxgrid"][0, 0]
    numygrid = d["numygrid"][0, 0]
    dxout = d["dxout"][0, 0]
    dyout = d["dyout"][0, 0]
    outlon0 = d["outlon0"][0, 0]
    outlat0 = d["outlat0"][0, 0]
    outlon1 = d["outlon1"][0, 0]
    outlat1 = d["outlat1"][0, 0]
    levels = d["levels"]
    time_step = d["time_step_length"][0, 0]
    data0 = d["data"]

    logging.debug("domain: %6.2f-%6.2f %6.2f %6.2f" %
                  (outlon0, outlon1, outlat0, outlat1))

    #this is better I think than the originla script
    lons0 = numpy.linspace(outlon0, outlon1, numxgrid)
    lats0 = numpy.linspace(outlat0, outlat1, numygrid)
    lons, lats = numpy.meshgrid(lons0, lats0)

    #"canvas" ready, now let's plot something
    steps = data0.shape[0]

    nuclide = path.split(os.sep)[-1].split(".")[0]

    if pcf.MAX_D != -999:
        max_d = pcf.MAX_D
    else:
        if len(data0.shape) == 4:
            max_d = data0[:, :, :, 0].max()
        elif len(data0.shape) == 3:
            max_d = data0[:, :, :].max()

    print INFO + "Processing: %s" % (nuclide)

    fig = plt.figure(figsize=(pcf.FIG_X, pcf.FIG_Y))

    if pcf.DO_OVERLAY:
        #fig = plt.figure(figsize=(15,15), dpi=400)
        ax = fig.add_axes([0., 0., 1., 1.])
        #ax = axes([0,0,1,1], frameon=False)
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.set_frame_on(False)

        map = Basemap(projection=pcf.PROJECTION,
                      llcrnrlon=outlon0,
                      llcrnrlat=outlat0,
                      urcrnrlon=outlon1,
                      urcrnrlat=outlat1,
                      resolution=pcf.BASEMAP_RESOLUTION,
                      area_thresh=pcf.BASEMAP_AREA_THR,
                      ax=ax)
    else:
        map = Basemap(projection=pcf.PROJECTION,
                      llcrnrlon=outlon0,
                      llcrnrlat=outlat0,
                      urcrnrlon=outlon1,
                      urcrnrlat=outlat1,
                      resolution=pcf.BASEMAP_RESOLUTION,
                      area_thresh=pcf.BASEMAP_AREA_THR)

    #now we create a mesh for plotting data
    x, y = map(lons, lats)

    release_start_str = rcf.SOURCE_TERM["release_start"]
    release_start = dt.strptime(release_start_str, rcf.DATE_FORMAT)
    delta_step = datetime.timedelta(seconds=rcf.SOURCE_TERM["time_step"])

    c1 = False

    for t in range(steps):
        #clear the previous image, we use the same figure and Basemap instance
        if not pcf.DO_OVERLAY:
            plt.clf()

        if len(data0.shape) == 4:
            data = data0[t, :, :, 0].transpose()
        elif len(data0.shape) == 3:
            data = data0[t, :, :].transpose()

        if max_d > 0:

            log_max = math.ceil(math.log10(max_d))

            levels = numpy.logspace(log_max - pcf.NUMBER_OF_ORDERS, log_max,
                                    4 * pcf.NUMBER_OF_ORDERS + 1)

            #if c1: # remove old plot in OVERLAY mode
            #    c1.remove()
            if data.max() > 0.:
                if pcf.DO_OVERLAY:
                    ax.clear()

                if pcf.PLOT_METHOD == "pcolormesh":
                    # huuuuge SVGs :(
                    c1 = map.pcolormesh(
                        x,
                        y,
                        data,
                        #shading='gouraud',
                        norm=LogNorm(vmin=levels[0], vmax=levels[-1]),
                        cmap=pcf.C_MAP,
                        alpha=pcf.ALPHA)

                elif pcf.PLOT_METHOD == "contourf":

                    c1 = map.contourf(
                        x,
                        y,
                        data,
                        #shading='gouraud',
                        levels=levels,
                        norm=LogNorm(vmin=levels[0], vmax=levels[-1]),
                        cmap=pcf.C_MAP,
                        alpha=pcf.ALPHA)
                    """
                    c1 = map.contour(x, y, data,
                                      #shading='gouraud',
                                      levels = levels,
                                      norm=LogNorm(vmin=levels[0], vmax=levels[-1]),
                                      cmap=pcf.C_MAP,
                                      alpha=1.0)
                    """
                elif pcf.PLOT_METHOD == "imshow":
                    if pcf.PROJECTION != "cyl":
                        raise (
                            "Cannot be used with mercator projection, uniform grid does not fit"
                        )
                    else:
                        outlon0m, outlat0m = map(outlon0, outlat0)
                        outlon1m, outlat1m = map(outlon1, outlat1)

                        c1 = map.imshow(data,
                                        interpolation='nearest',
                                        extent=(outlon0m, outlon1m, outlat0m,
                                                outlat1m),
                                        origin='lower',
                                        norm=LogNorm(vmin=levels[0],
                                                     vmax=levels[-1]),
                                        cmap=pcf.C_MAP,
                                        alpha=pcf.ALPHA)

                if not pcf.DO_OVERLAY:
                    cbar = map.colorbar(c1, location="bottom", pad="7%")
                    cbar.set_label(unitlabel)

        par_step = pcf.NESTED_PAR_STEP
        mer_step = pcf.NESTED_MER_STEP

        if not pcf.DO_OVERLAY:

            parallels = numpy.arange(-90., 90., par_step)
            map.drawparallels(parallels,
                              labels=[True, False, False, True],
                              fontsize=10)

            # draw meridians
            meridians = numpy.arange(-180.0, 180.0, mer_step)
            map.drawmeridians(meridians,
                              labels=[True, False, False, True],
                              fontsize=10)

            map.drawcoastlines()
            map.drawcountries()

        out_fname = nuclide + "_t=%3.3d" % t

        date = release_start + t * delta_step

        if not pcf.DO_OVERLAY:
            plt.title(product_name + " of " + nuclide + " " +
                      date.strftime("(%Y-%m-%d %H:%M)"))

        if pcf.PDFS_FLAG:  #pdfs will be also saved
            out_fname += ".pdf"
        if pcf.JPGS_FLAG:  #produce JPGs?
            out_fname += ".jpeg"
        if pcf.PNGS_FLAG:  #produce PNGs?
            out_fname += ".png"
        if pcf.SVGS_FLAG:  #produce PNGs?
            out_fname += ".svg"

        print "Saving to ", image_outpath + os.sep + out_fname

        if pcf.TIGHT_LAYOUT or pcf.DO_OVERLAY:
            plt.savefig(image_outpath + os.sep + out_fname,
                        bbox_inches='tight',
                        pad_inches=0,
                        transparent=True)
        else:
            plt.savefig(image_outpath + os.sep + out_fname, transparent=True)

    if pcf.DO_OVERLAY:
        create_colorbar(c1, nuclide, image_outpath, unitlabel)

    plt.close(fig)
Example #57
0
							 ticks=np.arange(-0,7,1))
	#cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,
	#						norm=mpl.colors.Normalize(vmin = -0.5, vmax = 6.5),
	#						 ticks=np.arange(-0,7,1))
	cb.ax.set_yticklabels(['land','ocean',' ','top','lake','sink','bottom'])
	#print(new_mask.shape,lat_0,lon_0)
	m = Basemap(projection='lcc',
			resolution='l',
			rsphere=(6378137.00,6356752.3142),
			width=new_mask.shape[1]*1000,
			height=new_mask.shape[0]*1000,
			lat_1=30,lat_2=60,
			lat_0=lat_0, lon_0=lon_0,ax=ax1
			)
	
	m.drawcoastlines()
	m.drawcountries()
	m.drawstates()
	
	x = np.linspace(0, m.urcrnrx, new_mask.shape[1])
	y = np.linspace(0, m.urcrnry, new_mask.shape[0])
	
	xx, yy = np.meshgrid(x, y)
	
	m.pcolormesh(xx, yy, np.ma.masked_where(new_mask[::-1,:]==0,new_mask[::-1,:]),
				cmap=cmap,vmin = 0-.5, vmax = 6+.5)
	#plt.show()
	
	plt.savefig(out_pfsol.replace('.pfsol','_mask.png'),dpi=300)

Example #58
0
def run(FILE_NAME):

    # Identify the data field.
    DATAFIELD_NAME = 'Range_1'

    if USE_GDAL:
        import gdal
        GRID_NAME = 'MODIS_Grid_1km_2D'
        gname = 'HDF4_EOS:EOS_GRID:"{0}":{1}:{2}'.format(
            FILE_NAME, GRID_NAME, DATAFIELD_NAME)
        gdset = gdal.Open(gname)
        data = gdset.ReadAsArray().astype(np.float64)

        # Construct the grid.
        x0, xinc, _, y0, _, yinc = gdset.GetGeoTransform()
        nx, ny = (gdset.RasterXSize, gdset.RasterYSize)
        x = np.linspace(x0, x0 + xinc * nx, nx)
        y = np.linspace(y0, y0 + yinc * ny, ny)
        xv, yv = np.meshgrid(x, y)

        # In basemap, the sinusoidal projection is global, so we won't use it.
        # Instead we'll convert the grid back to lat/lons.
        sinu = pyproj.Proj("+proj=sinu +R=6371007.181 +nadgrids=@null +wktext")
        wgs84 = pyproj.Proj("+init=EPSG:4326")
        lon, lat = pyproj.transform(sinu, wgs84, xv, yv)

        # Read the attributes.
        meta = gdset.GetMetadata()
        long_name = meta['long_name']
        units = meta['units']
        _FillValue = np.float(meta['_FillValue'])
        scale_factor = np.float(meta['scale_factor'])
        valid_range = [np.float(x) for x in meta['valid_range'].split(', ')]

        del gdset
    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data2D = hdf.select(DATAFIELD_NAME)
        data = data2D[:, :].astype(np.double)

        # Read geolocation dataset from HDF-EOS2 dumper output.
        GEO_FILE_NAME = 'lat_MOD09GA.A2007268.h10v08.005.2007272184810_MODIS_Grid_1km_2D.output'
        GEO_FILE_NAME = os.path.join(os.environ['HDFEOS_ZOO_DIR'],
                                     GEO_FILE_NAME)
        lat = np.genfromtxt(GEO_FILE_NAME, delimiter=',', usecols=[0])
        lat = lat.reshape(data.shape)

        GEO_FILE_NAME = 'lon_MOD09GA.A2007268.h10v08.005.2007272184810_MODIS_Grid_1km_2D.output'
        GEO_FILE_NAME = os.path.join(os.environ['HDFEOS_ZOO_DIR'],
                                     GEO_FILE_NAME)
        lon = np.genfromtxt(GEO_FILE_NAME, delimiter=',', usecols=[0])
        lon = lon.reshape(data.shape)

        # Read attributes.
        attrs = data2D.attributes(full=1)
        lna = attrs["long_name"]
        long_name = lna[0]
        vra = attrs["valid_range"]
        valid_range = vra[0]
        fva = attrs["_FillValue"]
        _FillValue = fva[0]
        sfa = attrs["scale_factor"]
        scale_factor = sfa[0]
        ua = attrs["units"]
        units = ua[0]

    invalid = np.logical_or(data > valid_range[1], data < valid_range[0])
    invalid = np.logical_or(invalid, data == _FillValue)
    data[invalid] = np.nan
    data = data / scale_factor
    data = np.ma.masked_array(data, np.isnan(data))

    m = Basemap(projection='cyl',
                resolution='h',
                llcrnrlat=-2.5,
                urcrnrlat=12.5,
                llcrnrlon=-82.5,
                urcrnrlon=-67.5)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(0, 15, 5), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-80, -65, 5), labels=[0, 0, 0, 1])
    m.pcolormesh(lon, lat, data, latlon=True)
    cb = m.colorbar()
    cb.set_label(units)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, long_name))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Example #59
0
#plt.figure(3)

m.drawcoastlines()
m.drawparallels(parallels, labels=[1, 1, 0, 0], fontsize=10)
m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)

lon1d = np.arange(-180, 181, 10)
lat1d = np.arange(-30, 31, 10)
print(lon1d)
LG, LT = np.meshgrid(lon1d, lat1d)
cx, cy = m(LG, LT)
#CS = m.pcolormesh(cx,cy,np.nanmean(cld_array,axis=0),cmap = ('RdYlBu_r'),shading='gouraud')

print(cx[1, :], cy[:, 1])
print(np.nanmean(cld_array, axis=0)[1, :])
m.pcolormesh(cx, cy, np.nanmean(cld_array, axis=0), cmap=plt.cm.jet)
plt.colorbar()

plt.figure(5)
m.drawcoastlines()
m.drawparallels(parallels, labels=[1, 1, 0, 0], fontsize=10)
m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)

m.pcolormesh(cx, cy, np.nanmean(ciwv_array, axis=0), cmap=plt.cm.jet)
plt.colorbar()

plt.figure(2)
#plt.plot(np.nanmean(np.nanmean(cld_array,axis=1),axis=1))

C = cld_array[:, 0, 9]
V = ciwv_array[:, 0, 9]
Example #60
0
 mapa = Basemap(projection = 'cyl', resolution='i',
             llcrnrlat = lat_i, urcrnrlat = lat_f,
             llcrnrlon = long_i, urcrnrlon = long_f)
 # desenha linhas dos continentes
 mapa.drawcoastlines(linewidth = 1.2, zorder = 2)
 # desenha linhas dos paises
 mapa.drawcountries(linewidth = 1.2, zorder = 2)
 # desenha linhas dos estados
 mapa.drawstates(linewidth = 0.5, zorder = 2)
 # cor dos continentes
 mapa.fillcontinents(color = '#c0f772', zorder = 1)
 # cor do oceano
 mapa.drawmapboundary(fill_color = '#49c4d1', zorder = 0)
 
 # plota os dados como cores
 mapa.pcolormesh(xx, yy, dados_degree, cmap = 'OrRd', latlon=True,
                 zorder = 2, alpha = 0.5)
 # escabala de cores
 cbar = plt.colorbar(orientation='horizontal', shrink=0.625, aspect=20, fraction=0.2,pad=0.02)
 cbar.set_label('Degree', size = 12)
 
 # titulo do mapa
 plt.title(mes + r'/' + ano, size = 15)
 
 # salva imagem
 plt.savefig(rd + '/Mapas/degree/' + ano + '/' + 
             'mapa' + str(numMapa % 12 + 1) + '_' + mes, bbox_inches='tight')
 plt.close()
 del dados_degree
 
 # plota betweenness