Beispiel #1
0
def show_ws(groups, size):
    plt.close('all')
    fig = plt.figure(figsize = (size, size))
    ax = fig.add_subplot(111)
    m = Basemap(projection = 'cyl', resolution = 'l', area_thresh = 10000, llcrnrlat = lat0, urcrnrlat = lat1, llcrnrlon = lon0, urcrnrlon = lon1)
    m.drawcoastlines()
    m.drawcountries()
    m.drawparallels(np.arange(lat0, lat1, 10), labels=[1,1,0,0])
    m.drawmeridians(np.arange(lon0, lon1, 10), labels=[0,0,0,1])

    this_mask = np.zeros((int((lat1 - lat0) / acc_res), int((lon1 - lon0) / acc_res)), dtype = 'uint8')
    for this_group in groups:
        this_rand = int(np.random.uniform(1, 255))
        for this_odr in this_group:
            mask = df_ws.loc[this_odr, 'mask']
            latlon = df_ws.loc[this_odr,  'latlon']
            y0 = int(round((lat1 - latlon[0]) / acc_res))
            y1 = y0 + mask.shape[0]
            x0 = int(round((latlon[1] - lon0) / acc_res))
            x1 = x0 + mask.shape[1]
            this_mask[y0:y1, x0:x1] = this_mask[y0:y1, x0:x1] + mask * this_rand

    this_mask = np.where(this_mask == 0, np.nan, this_mask)
    m.imshow(this_mask, origin = 'upper', interpolation = 'nearest', zorder = 10, alpha = 1)

    plt.show()
Beispiel #2
0
def plot_data(data,lon_data, lat_data, periodname, AODcatname,maptype,cmapname,minv=0,maxv=0,folder=""):
    fig = plt.figure()
    #ax = fig.add_axes([0.1,0.1,0.8,0.8])

    m = Basemap(llcrnrlon=19,llcrnrlat=34,urcrnrlon=29,urcrnrlat=42,
                resolution='h',projection='cass',lon_0=24,lat_0=38)

    nx = int((m.xmax-m.xmin)/1000.)+1
    ny = int((m.ymax-m.ymin)/1000.)+1
    topodat = m.transform_scalar(data,lon_data,lat_data,nx,ny)
    
    if minv<>0 or maxv<>0 :
        im = m.imshow(topodat,cmap=plt.get_cmap(cmapname),vmin=minv,vmax=maxv)
    else:
        im = m.imshow(topodat,cmap=plt.get_cmap(cmapname))
 

    m.drawcoastlines()
    m.drawmapboundary()
    m.drawcountries()
    m.drawparallels(np.arange(35,42.,1.), labels=[1,0,0,1])
    m.drawmeridians(np.arange(-20.,29.,1.), labels=[1,0,0,1])
    cb = m.colorbar(im,"right", size="5%", pad='2%')
    title=maptype+" AOD "+AODcatname+" "+periodname+" 2007-2014"
    plt.title(title)
    pylab.savefig(folder+maptype+"AOD"+AODcatname+"_"+periodname + ".png")
def plot_2Ddata_with_underlay(data_array, lons=None, lats=None):
    """ Plot of a 2D array on top of coast lines and country lines.
    """
    figure()

    # Create the basemap instance and draw the continents
    # Basemap kw args: llcrnrlon = lower left corner longitude, and so on
    m = Basemap(llcrnrlon=-180, llcrnrlat=-90, urcrnrlon=180, urcrnrlat=90, projection="mill")
    m.drawcoastlines(linewidth=1.25)
    m.drawcountries(linewidth=0.5)
    # m.fillcontinents(color='0.8')
    m.drawparallels(np.arange(-90, 91, 20), labels=[1, 1, 0, 0])
    m.drawmeridians(np.arange(-180, 180, 60), labels=[0, 0, 0, 1])

    # Shift the data by 180 in longitude to center the map on longitude=0
    data_array, lon_out = shiftgrid(180, data_array, lons)

    # Add the data, and place origin in upper left since the origin of the numpy
    # array corresponds tolat = 90 and long = 0
    m.imshow(data_array, origin="upper")

    # More complex version that involves interpolation on a grid of points in
    # map coordinates.
    # nx = int((m.xmax-m.xmin)/500.)+1; ny = int((m.ymax-m.ymin)/500.)+1
    # dat_array = m.transform_scalar(data_array, lons,lats,nx,ny)
    # m.imshow(dat_array, origin = 'upper')

    # figure()
    # m = Basemap(projection='ortho',lon_0=-105,lat_0=40)
    # m.drawcoastlines(linewidth=1.25)
    # m.drawcountries(linewidth=0.5)
    # dat_transformed = m.transform_scalar(data_array,

    return
Beispiel #4
0
    def __init__(self, subPlot = None, gpxData = None):
        GeoSectionViewerGpxData.__init__(self, subPlot, gpxData)

        latitudes, longitudes, elevations, timestamps = self.gpxData.getLatLongElevTs()

        latitudeMax = max(latitudes)
        latitudeMin = min(latitudes)
        longitudeMax = max(longitudes)
        longitudeMin = min(longitudes)
        elevationMax = max(elevations)
        elevationMin = min(elevations)

        scalledMax = 30
        scalledMin = 1

        scalledElevations = [((((point.elevation - elevationMin) * (scalledMax - scalledMin)) / (elevationMax - elevationMin)) + scalledMin) for i, point in enumerate(self.gpxData)]
        bbox = longitudeMin, latitudeMin, longitudeMax, latitudeMax

        mm = geotiler.Map(extent=bbox, zoom=14)
        img = geotiler.render_map(mm)
        img.save("geotiler.png")

        map = Basemap(
            llcrnrlon=bbox[0], llcrnrlat=bbox[1],
            urcrnrlon=bbox[2], urcrnrlat=bbox[3],
            projection='merc',
            resolution='i',
            ax=self.subPlot)
        map.imshow(img, aspect='auto', origin='upper')
        map.scatter(longitudes, latitudes, c='red', s=scalledElevations, marker='o', cmap=cm.hot_r, alpha=0.4, latlon=True)
        map.plot(longitudes, latitudes, 'k', c='red', latlon=True)
Beispiel #5
0
def mapper(image):

	fig = plt.figure()
	
	cmap = mpc.ListedColormap(palettable.colorbrewer.diverging.PiYG_5.mpl_colors)
	# cmap.set_bad('grey',1.)

	# ax = fig.add_subplot(1)
	plt.plot()
	plt.title("a. ((maxNDVI/mm AcuPrecip)/year)", loc= 'left')

	#set the spatial cordinates of the grid, mask the ocean and draw coastlines
	map = Basemap(llcrnrlon=112.0,llcrnrlat=-44.5,urcrnrlon=156.25,urcrnrlat=-10, resolution = 'h', epsg=4326)
	map.drawmapboundary(fill_color='grey')
	map.fillcontinents(color= 'none', lake_color='white')
	map.drawlsmask(land_color='none', )
	map.drawcoastlines()

	map.imshow(np.flipud(image), cmap=cmap, vmin=-0.006, vmax=0.009,)
	# cb = plt.colorbar()

	#Tweaking the colorbar so the the ticks allign with the grid.  
	cb = map.colorbar()#ticks= [-0.01, -0.0075, -0.0050, -0.00250, 0.0000, 0.0025, 0.0050, 0.0075, 0.010, 0.0125])
	tick_locator = ticker.MaxNLocator(nbins=5)
	cb.locator = tick_locator
	cb.update_ticks()

	#add in the grid
	map.drawparallels(np.arange(-50, -10, 10),labels=[1,0,0,0], dashes=[1,2])#color= 'none')
	map.drawmeridians(np.arange(110, 156.25, 10),labels=[0,0,0,1], dashes=[1,2])

	plt.show()
Beispiel #6
0
 def background_map(self, ax):
     llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon, lat_ts = (31, 44, -126, -113, 37.5)
     m = Basemap(projection='merc', llcrnrlat=llcrnrlat,
                 urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon,
                 lat_ts=lat_ts, resolution='i', ax=ax)
     m.drawmapboundary(fill_color='lightblue', zorder=0)
     m.fillcontinents(zorder=0)
     etopofn = '/home/behry/uni/data/etopo1_central_europe_gmt.grd'
     etopodata = Dataset(etopofn, 'r')
     z = etopodata.variables['z'][:]
     x_range = etopodata.variables['x_range'][:]
     y_range = etopodata.variables['y_range'][:]
     spc = etopodata.variables['spacing'][:]
     lats = np.arange(y_range[0], y_range[1], spc[1])
     lons = np.arange(x_range[0], x_range[1], spc[0])
     topoin = z.reshape(lats.size, lons.size, order='C')
     # transform to nx x ny regularly spaced 5km native projection grid
     nx = int((m.xmax - m.xmin) / 5000.) + 1; ny = int((m.ymax - m.ymin) / 5000.) + 1
     topodat, x, y = m.transform_scalar(np.flipud(topoin), lons, lats, nx, ny, returnxy=True)
     ls = LightSource(azdeg=300, altdeg=15, hsv_min_sat=0.2, hsv_max_sat=0.3,
                      hsv_min_val=0.2, hsv_max_val=0.3)
     # shade data, creating an rgb array.
     rgb = ls.shade(np.ma.masked_less(topodat / 1000.0, 0.0), cm.gist_gray_r)
     m.imshow(rgb)
     m.drawmeridians(np.arange(6, 12, 2), labels=[0, 0, 0, 1], color='white',
                     linewidth=0.5, zorder=0)
     m.drawparallels(np.arange(44, 50, 2), labels=[1, 0, 0, 0], color='white',
                     linewidth=0.5, zorder=0)
     m.drawcoastlines(zorder=1)
     m.drawcountries(linewidth=1.5, zorder=1)
     m.drawstates()
     m.drawrivers(color='lightblue', zorder=1)
     return m
Beispiel #7
0
def plot_world_sst():
    # Read some NetCDF data
    import netCDF4 as nc
    
    ostia = nc.Dataset('ostia.nc')
    tmp = ostia.variables['analysed_sst'][0]
    ice = ostia.variables['sea_ice_fraction'][0]
    lon = ostia.variables['lon'][:]
    lat = ostia.variables['lat'][:]

    from mpl_toolkits.basemap import Basemap

    # Set up a map
    map = Basemap(projection='cyl')
    map.drawcoastlines()
    map.drawcountries()
    map.fillcontinents(color='lightgreen', lake_color='lightblue');
    map.drawmapboundary(fill_color='lightblue')

    # Re-project the data onto the map
    image = map.transform_scalar(tmp,lon,lat,200,200)

    # Plot the data
    map.imshow(image);

    plt.show()
 def mk_regmap_contour(a2in, bnd, scm, stitle, soname, cbarname, miss_out):
   #------------------------
   # Basemap
   #------------------------
   print "Basemap"
   figmap   = plt.figure()
   axmap    = figmap.add_axes([0.1, 0.0, 0.8, 1.0])
   M        = Basemap( resolution="l", llcrnrlat=lllat, llcrnrlon=lllon, urcrnrlat=urlat, urcrnrlon=urlon, ax=axmap)
   
   #-- transform -----------
   print "transform"
   a2value_trans    = M.transform_scalar( a2in,   a1lon, a1lat, nnx, nny)
   a2value_trans    = a2value_trans.filled(miss_out)
 
   #-- to contour ----------
   a2value_trans    = dtanl_fsub.mk_a2contour_regional(a2value_trans.T, 0.0, 0.0, -9999.0).T
 
   #-- boundaries ----------
   bnd_cbar   = [-1.0e+40] + bnd + [1.0e+40]
   
   #-- color ---------------
   cminst   = matplotlib.cm.get_cmap(scm, len(bnd))
   acm      = cminst( arange( len(bnd) ) )
   lcm      = [[1,1,1,1]]+ acm.tolist()
   mycm     = matplotlib.colors.ListedColormap( lcm )
   
   #-- imshow    -----------
   im       = M.imshow(a2value_trans, origin="lower", norm=BoundaryNormSymm(bnd), cmap=mycm, interpolation="nearest")
 
   #-- shade     -----------
   a2shade_trans = ma.masked_not_equal(a2value_trans, miss_out)
   cmshade       = matplotlib.colors.ListedColormap([(0.8,0.8,0.8), (0.8,0.8,0.8)])
   im            = M.imshow(a2shade_trans, origin="lower", cmap=cmshade) 
   
   #-- coastline ---------------
   print "coastlines"
   M.drawcoastlines()
   
   #-- meridians and parallels
   M.drawmeridians(arange(0.0,360.0, meridians), labels=[0, 0, 0, 1])
   M.drawparallels(arange(-90.0,90.0, parallels), labels=[1, 0, 0, 0])
   #-- title -------------------
   axmap.set_title("%s"%(stitle))
   #-- save --------------------
   plt.savefig(soname)
   print soname 
   # for colorbar ---
   if cbarflag == "True":
     figmap   = plt.figure()
     axmap    = figmap.add_axes([0.1, 0.0, 0.8, 1.0])
     M        = Basemap( resolution="l", llcrnrlat=lllat, llcrnrlon=lllon, urcrnrlat=urlat, urcrnrlon=urlon, ax=axmap)
     a2v_trans    = M.transform_scalar( a2in,   a1lon, a1lat, nnx, nny)
     im       = M.imshow(a2value_trans, origin="lower", norm=BoundaryNormSymm(bnd), cmap=mycm)
   
     figcbar   = plt.figure(figsize=(5, 0.6))
     axcbar    = figcbar.add_axes([0, 0.4, 1.0, 0.6])
     bnd_cbar  = [-1.0e+40] + bnd + [1.0e+40]
     plt.colorbar(im, boundaries= bnd_cbar, extend="both", cax=axcbar, orientation="horizontal")
     figcbar.savefig(cbarname)
def main():

    ncols = 841
    nrows = 681
    ndays = 366

    f = open("modis_climatology_splined.bin", "r")
    data = np.fromfile(f).reshape((ndays,nrows,ncols))
    f.close()

    ncolours = 7
    vmin = 0
    vmax = 6

    cmap = sns.blend_palette(["white", "#1b7837"], ncolours, as_cmap=True)
    sns.set(style="white")

    fig = plt.figure(figsize=(10, 6))
    grid = AxesGrid(fig, [0.05,0.05,0.9,0.9], nrows_ncols=(1,1), axes_pad=0.1,
    		        cbar_mode='single', cbar_pad=0.4, cbar_size="7%",
		            cbar_location='bottom', share_all=True)
	# 111.975 + (841. * 0.05)
    # -44.025 + (681. * 0.05)
    m = Basemap(projection='cyl', llcrnrlon=111.975, llcrnrlat=-44.025, \
                urcrnrlon=154.025, urcrnrlat=-9.974999999999994, resolution='h')


    ax = grid[0]
    m.ax = ax


    shp_info = m.readshapefile('/Users/mdekauwe/research/Drought_linkage/'
                               'Bios2_SWC_1979_2013/'
                               'AUS_shape/STE11aAust',
                               'STE11aAust', drawbounds=True)


    #m.drawrivers(linewidth=0.5, color='k')

    ax.set_xlim(140.5, 154)
    ax.set_ylim(-38, -28)

    #cmap = cmap_discretize(plt.cm.YlGnBu, ncolours)

    m.imshow(data[20,:,:], cmap,
             colors.Normalize(vmin=vmin, vmax=vmax, clip=True),
             origin='upper', interpolation='nearest')


    cbar = colorbar_index(cax=grid.cbar_axes[0], ncolours=ncolours, cmap=cmap,
                          orientation='horizontal', vmin=vmin, vmax=vmax)

    fig.savefig("/Users/mdekauwe/Desktop/LAI_NSW.png", bbox_inches='tight',
                pad_inches=0.1, dpi=300)



    plt.show()
Beispiel #10
0
def radagast_test():
    lower_left, upper_right = corner_coords()
    m = Basemap(projection='geos', lon_0=0, resolution='i',
                llcrnrlon=lower_left[0], llcrnrlat=lower_left[1],
                urcrnrlon=upper_right[0], urcrnrlat=upper_right[1])
    m.drawcoastlines()
    im = Image.open('TEST-radagast.jpg')
    m.imshow(im)
    plt.show()
class CoordinateAnimation:
    def __init__(self, corners, zoom, data_pipe, figsize=(16, 9), scatter_params={}):
        self.corners = corners
        self.zoom = zoom
        self.scatter_params = scatter_params
        self.data_pipe = data_pipe
        self.plot_data = np.zeros(shape=(1, 2))
        self.fig, self.ax = plt.figure(figsize=figsize), plt.subplot(111)
        self._init_basemap()
        self.anim_scatter = animation.FuncAnimation(self.fig, self._update_scatter,
                                                    init_func=self._scatter_init)
        self.plot_scat = None
        self.plot_plot = None

    def _init_basemap(self):
        self.m = geotiler.Map(extent=self.corners, zoom=self.zoom)
        self.img = geotiler.render_map(self.m)
        self.bmap = Basemap(
            llcrnrlon=self.corners[0], llcrnrlat=self.corners[1],
            urcrnrlon=self.corners[2], urcrnrlat=self.corners[3],
            projection="merc", ax=self.ax
        )

        self.bmap.imshow(self.img, interpolation='lanczos', origin='upper')

    def _scatter_init(self):
        self.plot_scat = plt.scatter(self.plot_data[:, 0], self.plot_data[:, 1],
                                     **self.scatter_params)

        self.plot_plot = plt.plot(self.plot_data[:, 0], self.plot_data[:, 1])

    def _update_scatter(self, i):
        try:
            if not self.data_pipe.poll(3):
                return self.plot_scat,
        except KeyboardInterrupt:
            return self.plot_scat,
        try:
            gps_json = self.data_pipe.recv()
        except KeyboardInterrupt:
            return self.plot_scat,

        gga = gps_json['gga']
        try:
            parsed = pynmea2.parse(gga)
        except pynmea2.nmea.ChecksumError:
            return self.plot_scat,

        array = np.array(self.bmap(parsed.longitude, parsed.latitude))
        self.plot_data = np.vstack( (self.plot_data, array) )
        self.plot_scat.set_offsets(array)
        plt.plot(self.plot_data[1:, 0], self.plot_data[1:, 1])
        return self.plot_scat,

    def plot(self):
        plt.show()
def make_map(llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat, image):
    fig, ax = plt.subplots()
    m = Basemap(llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon,
                llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,
                resolution='c', projection='merc',
                lon_0=(urcrnrlon + llcrnrlon) / 2,
                lat_0=(urcrnrlat + llcrnrlat) / 2,
                lat_ts=-23.5)
    m.ax = ax
    m.imshow(plt.imread(image), origin='upper', zorder=1)
    return fig, ax, m
Beispiel #13
0
def makeFigs():
    m = Basemap(llcrnrlon=-9.382918,llcrnrlat=39.119533,urcrnrlon= -9.376521,urcrnrlat= 39.127501,
     resolution='l',projection='merc')
    x1,y1=m(x,y)
    xarray.append(x1)
    yarray.append(y1)


    m.drawcoastlines()
    im = plt.imread("map.png")
    m.imshow(im, origin='upper')
    m.scatter(xarray,yarray,c='b',marker=".",alpha=1.0)
Beispiel #14
0
def PlotTomoMap(fname, dlon=0.5, dlat=0.5, title='', datatype='ph', outfname='', browseflag=False, saveflag=True):
    """
    Plot Tomography Map
    longitude latidute ZValue
    """
    if title=='':
        title=fname;
    if outfname=='':
        outfname=fname;
    Inarray=np.loadtxt(fname)
    LonLst=Inarray[:,0]
    LatLst=Inarray[:,1]
    ZValue=Inarray[:,2]
    llcrnrlon=LonLst.min()
    llcrnrlat=LatLst.min()
    urcrnrlon=LonLst.max()
    urcrnrlat=LatLst.max()
    Nlon=int((urcrnrlon-llcrnrlon)/dlon)+1
    Nlat=int((urcrnrlat-llcrnrlat)/dlat)+1
    fig=plt.figure(num=None, figsize=(8, 12), dpi=80, facecolor='w', edgecolor='k')
    m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, \
        rsphere=(6378137.00,6356752.3142), resolution='l', projection='merc')
    
    lon = LonLst
    lat = LatLst
    x,y = m(lon, lat)
    xi = np.linspace(x.min(), x.max(), Nlon)
    yi = np.linspace(y.min(), y.max(), Nlat)
    xi, yi = np.meshgrid(xi, yi)
    
    #-- Interpolating at the points in xi, yi
    zi = griddata(x, y, ZValue, xi, yi)
    # m.pcolormesh(xi, yi, zi, cmap='seismic_r', shading='gouraud')
    cmap=matplotlib.cm.seismic_r
    cmap.set_bad('w',1.)
    m.imshow(zi, cmap=cmap)
    m.drawcoastlines()
    m.colorbar(location='bottom',size='2%')
    # m.fillcontinents()
    # draw parallels
    m.drawparallels(np.arange(-90,90,10),labels=[1,1,0,1])
    # draw meridians
    m.drawmeridians(np.arange(-180,180,10),labels=[1,1,1,0])
    plt.suptitle(title,y=0.9, fontsize=22);
    if browseflag==True:
        plt.draw()
        plt.pause(1) # <-------
        raw_input("<Hit Enter To Close>")
        plt.close('all')
    if saveflag==True:
        fig.savefig(outfname+'.ps', format='ps')
    return 
Beispiel #15
0
def plot_file(filename):
    # Open the file using the NetCDF4 library
    nc = Dataset(filename)

    # analyze_dataset(nc)

    latlon = nc.variables['geospatial_lat_lon_extent']
    # print('geospatial_lat_lon_extent:', latlon)

    # Original example uses Brightness Temperature values, 'CMI'
    # But that's not in our dataset.
    whichvar = 'Rad'
    data = nc.variables[whichvar][:]
    prettyname = nc.variables[whichvar].long_name

    # Show it without basemap:
    # plt.imshow(data, cmap='Greys')
    # plt.show()

    # Create the basemap reference for the Satellite Projection
    bmap = Basemap(projection='geos',

                   # Extents
                   llcrnrlon=latlon.geospatial_westbound_longitude,
                   llcrnrlat=latlon.geospatial_southbound_latitude,
                   urcrnrlon=latlon.geospatial_eastbound_longitude,
                   urcrnrlat=latlon.geospatial_northbound_latitude,

                   # Should these be nadir, or center?
                   lon_0=latlon.geospatial_lon_nadir,
                   lat_0=latlon.geospatial_lat_nadir,
                   satellite_height=35786023.0, ellps='GRS80')

    # Plot GOES-16 Channel using 170 and 378 as the temperature thresholds
    bmap.imshow(data, origin='upper', cmap='Greys')

    # Draw the coastlines, countries, parallels and meridians
    bmap.drawcoastlines(linewidth=0.3, linestyle='solid', color='blue')
    bmap.drawcountries(linewidth=0.3, linestyle='solid', color='blue')

    # These don't seem to do anything
    bmap.drawparallels(np.arange(-90.0, 90.0, 10.0),
                       linewidth=0.1, color='yellow')
    bmap.drawmeridians(np.arange(0.0, 360.0, 10.0),
                       linewidth=0.1, color='yellow')

    # Insert the legend
    bmap.colorbar(location='bottom', label=prettyname)

    # Show the plot
    plt.show()
Beispiel #16
0
    def __init__(self, subPlot = None, gpxData = None, geoMarkers = None):
        GeoSectionViewerGpxData.__init__(self, subPlot, gpxData)

        latitudes, longitudes, elevations, timestamps = self.gpxData.getLatLongElevTs()

        latitudeMax = max(latitudes)
        latitudeMin = min(latitudes)
        longitudeMax = max(longitudes)
        longitudeMin = min(longitudes)
        elevationMax = max(elevations)
        elevationMin = min(elevations)

        scalledMax = 30
        scalledMin = 1

        scalledElevations = [((((point.elevation - elevationMin) * (scalledMax - scalledMin)) / (elevationMax - elevationMin)) + scalledMin) for i, point in enumerate(self.gpxData)]
        bbox = longitudeMin, latitudeMin, longitudeMax, latitudeMax

        mm = geotiler.Map(extent=bbox, zoom=14)
        self.rawMapImage = geotiler.render_map(mm)

        map = Basemap(
            llcrnrlon=bbox[0], llcrnrlat=bbox[1],
            urcrnrlon=bbox[2], urcrnrlat=bbox[3],
            projection='merc',
            resolution='i',
            ax=self.subPlot)
        map.imshow(self.rawMapImage, aspect='auto', origin='upper')
        #--draw path
        map.scatter(longitudes, latitudes, c='red', s=scalledElevations, marker='o', cmap=cm.hot_r, alpha=0.4, latlon=True)
        map.plot(longitudes, latitudes, 'k', c='red', latlon=True)
        #--draw labels
        if(geoMarkers is not None):
            for geoMarker in geoMarkers:
                xy = map(geoMarker["longitude"], geoMarker["latitude"])
        #
        #         subPlot.annotate(
        #             geoMarker["name"],
        #             xy, xytext = (-20, 20),
        #             textcoords = 'offset points', ha = 'right', va = 'bottom',
        #     #        bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
        #             bbox = dict(fc = 'yellow', alpha = 0.5),
        #             arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
        #
                subPlot.text(xy[0], xy[1], "{0}-{1} {2}".format(geoMarker["name"], geoMarker["elevation"], geoMarker["time"]),fontsize=9,
                                ha='center',va='top',color='r',
#                                bbox = dict(ec='None',fc=(1,1,1,0.5)))
                                bbox = dict(fc = 'yellow', alpha = 0.5))
Beispiel #17
0
def plot_mappa(paese):

    def GetExtent(gt,cols,rows):
        ext=[]
        xarr=[0, cols]
        yarr=[0, rows]

        for px in xarr:
            for py in yarr:
                x=gt[0]+(px*gt[1])+(py*gt[2])
                y=gt[3]+(px*gt[4])+(py*gt[5])
                ext.append([x,y])
                #print x,y
            yarr.reverse()
        return ext


    pathToRaster = "input_data/geocoded/risk_map/" + paese + ".tif"
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt
    import numpy as np
    from osgeo import gdal

    raster = gdal.Open(pathToRaster, gdal.GA_ReadOnly)
    array = raster.GetRasterBand(1).ReadAsArray()
    msk_array = np.ma.masked_equal(array, value=65535)
    # print 'Raster Projection:\n', raster.GetProjection()
    geotransform = raster.GetGeoTransform()
    cols = raster.RasterXSize
    rows = raster.RasterYSize
    ext = GetExtent(geotransform, cols, rows)
    #print ext[1][0], ext[1][1]
    #print ext[3][0], ext[3][1]

    #map = Basemap(projection='merc',llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')
    map = Basemap(projection='merc', llcrnrlat=ext[1][1], urcrnrlat=ext[3][1], llcrnrlon=ext[1][0], urcrnrlon=ext[3][0],lat_ts=20, resolution='c')

    # Add some additional info to the map
    map.drawcoastlines(linewidth=1.3, color='white')
    #map.drawrivers(linewidth=.4, color='white')
    map.drawcountries(linewidth=.75, color='white')
    #datain = np.flipud(msk_array)
    datain = np.flipud(msk_array)
    map.imshow(datain)#,origin='lower',extent=[ext[1][0], ext[3][0],ext[1][1],ext[3][1]])

    plt.show()

#plot_mappa("India")
Beispiel #18
0
    def plotField(fileName, vmin, vmax, colormap='goddard', output_folder='/', lonlatbox='-180,180,-90,90'):
        '''
        Plot any field variable
        
        :param fileName: filepath
        :param vmin: min value for colorbar
        :param vmax: max value for colorbar
        ''' 
        fig1 = plt.figure(figsize=(12,7),dpi=500)
        
        if(colormap == 'goddard'): 
            my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap',Plotter.colorDict2,256)
        else:
            my_cmap = plt.cm.RdBu_r
        
        file_values = FileHandler.openNetCDFFile(fileName)
        mVar = file_values['variable']
        lon = file_values['lon']
        lat = file_values['lat']

        if lonlatbox is None:
            if lon[0] < 0:
                lonlatbox = '-180,180,-90,90'
            else:
                lonlatbox = '0,360,-90,90'
        lonlatbox = map(int,lonlatbox.split(','))
        m = Basemap(llcrnrlon=lonlatbox[0],llcrnrlat=lonlatbox[2],urcrnrlon=lonlatbox[1],urcrnrlat=lonlatbox[3])

        def divi(x):
            return float(x)/10
        
        colorSteps = map(divi,range(int(vmin*10),int((vmax*10)+1),1))#(vmax-vmin)/2))
        
        if vmax == 0.5:
            colorSteps = [-0.5, -0.45, -0.4, -0.35, -0.3, -0.25, -0.2, -0.15, -0.1, -0.05, 0, 
                          0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]
            
        if vmax == 0. and vmin == -0.5:
            colorSteps = [-0.5, -0.475, -0.45, -0.425, -0.4, -0.375, -0.35, -0.325, -0.3, -0.275, -0.25, -0.225, 
                          -0.2, -0.175, -0.15, -0.125, -0.1, -0.075, -0.05, -0.025, 0]
            
        if vmax == 2. and vmin == 0:
            colorSteps = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9,0.95, 
                          1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
        colorTicks = colorSteps[0::2]
        my_cmap.set_bad("grey")                         #set missing value color
        #maskedArray = N.ma.masked_greater(mVar, 0.8e20) #mask missing Values
        maskedArray = N.ma.masked_outside(mVar, -0.8e20, 0.8e20)
        #discrete colormap
        norm = mpl.colors.BoundaryNorm(colorSteps, my_cmap.N)
        cs = m.imshow(maskedArray, interpolation="nearest", cmap=my_cmap, norm=norm)
        cb = m.colorbar(cs,"right", size="5%", pad='5%' , ticks=colorTicks)
        m.drawcoastlines()  
        m.drawparallels(N.arange(-90.,120.,30.),labels=[1,0,0,0]) # draw parallels
        m.drawmeridians(N.arange(0.,420.,60.),labels=[0,0,0,1]) # draw meridians
        
        plt.title(Plotter.__getTitle(fileName))
        plt.text(lonlatbox[0]+(lon[1]-lon[0])/2, lonlatbox[2]+(lat[1]-lat[0])/2, 'MurCSS')
        #print lonlatbox[0]+lon[1]-lon[0]
        return m
Beispiel #19
0
def stere(data,latitude,longitude,filename):
    """
    :param data: CO浓度数据矩阵
    :param latitude: 纬度
    :param longitude: 经度
    :param filename:
    :return:
    """
    ax = plt.gca()
    fig = plt.figure()
    m = Basemap(width=10000000,height=7500000,
            resolution='l',projection='stere',\
            lat_ts=35,lat_0=35,lon_0=107.)
    nx = int((m.xmax-m.xmin)/5000.)+1
    ny = int((m.ymax-m.ymin)/5000.)+1
    topodat = m.transform_scalar(data,longitude,latitude,nx,ny)
    im = m.imshow(topodat,cm.GMT_haxby,vmin=0,vmax=4e18)
    m.drawcoastlines()
    m.drawcountries()
    m.drawparallels(np.arange(-80.,81.,20.),labels=[1,0,0,0])
    # 画平行的纬度,前一个参数是表示起点,终点,间距的序列,后一个参数是指在哪一个方向显示纬度、经度值
    m.drawmeridians(np.arange(-180.,181.,20.),labels=[0,0,0,1])
    # 画平行的经度
    m.colorbar(im)
    plt.title("CO"+filename[12:14])
    outname = filename+'.png'
    fig.savefig(outname, dpi=fig.dpi)
Beispiel #20
0
    def do_plot(self, dataset):
        #for dataset in r533:
        points, plot_type, lons, lats, num_pts_lon, num_pts_lat, params = dataset
        plot_dt, plot_title, freq, idx = params
        #plt.figure(figsize=(12,6))
        m = Basemap(projection='cyl', resolution='l')
        m.drawcoastlines(color='black', linewidth=0.75)
        m.drawcountries(color='grey')
        m.drawmapboundary(color='black', linewidth=1.0)
        m.drawmeridians(np.arange(0,360,30))
        m.drawparallels(np.arange(-90,90,30))

        X,Y = np.meshgrid(lons, lats)

        #todo remove hard-coded values for vmin and vmax
        #im = m.pcolormesh(X, Y, points, shading='gouraud', cmap=plt.cm.jet, latlon=True, vmin=-20, vmax=40)
        #im = m.pcolormesh(X, Y, points, shading='gouraud', cmap=plt.cm.jet, latlon=True, vmin=-20, vmax=40)
        im = m.imshow(points, interpolation='bilinear', vmin=0, vmax=100)

        if self.plot_terminator:
            m.nightshade(plot_dt)

        cb = m.colorbar(im,"bottom", size="5%", pad="2%")
        plt.title(plot_title)

        plot_fn = "area_{:s}_{:s}_{:s}.png".format(plot_type, plot_dt.strftime("%H%M_%b_%Y"), "d".join(str(freq).split('.')))
        print ("Saving file ", plot_fn)
        plt.savefig(plot_fn, dpi=float(self.dpi), bbox_inches='tight')
Beispiel #21
0
def plot_ndvi(hdf_fname, fig_name,
              min_lat, min_lon, max_lat, max_lon, title='NDVI plot'):
    """Produce a plot of the NDVI data in file `hdf_fname`."""

    import matplotlib.pyplot as plt
    from matplotlib import cm
    from mpl_toolkits.basemap import Basemap

    ndvi = read_ndvi(hdf_fname, min_lat, min_lon, max_lat, max_lon)

    print 'Data obtained'
    print type(ndvi)

    fig = plt.figure()

    ax = fig.add_subplot(111)

    curr_map = Basemap(projection='cyl', llcrnrlat=min_lat, urcrnrlat=max_lat,
                       llcrnrlon=min_lon, urcrnrlon=max_lon, resolution='l')
    curr_map.drawcoastlines(linewidth=1.5)
    curr_map.drawcountries(linewidth=1.5)
    curr_map.drawparallels(np.arange(-90.,91.,2.), labels=[1, 0, 0, 0])
    curr_map.drawmeridians(np.arange(-180.,181.,2.), labels=[1, 0, 0, 1])

    im = curr_map.imshow(ndvi, cmap=cm.BrBG,
                         origin='upper', interpolation='nearest')
    cbar = fig.colorbar(im, ticks=[0, 0.4, 0.8])

    cbar.set_label('NDVI')
    cbar.ax.set_yticklabels(['< 0', '0.4', '> 0.8'])

    ax.set_title(title, fontsize=16, fontweight='bold')

    fig.savefig(fig_name)
Beispiel #22
0
def plot_hmap_ortho(h, cmap='jet', mode='log', mx=None, drng=None, 
        res=0.25, verbose=False):
    m = Basemap(projection='ortho',lat_0=90,lon_0=180,rsphere=1.)
    if verbose:
        print 'SCHEME:', h.scheme()
        print 'NSIDE:', h.nside()
    lons,lats,x,y = m.makegrid(360/res,180/res, returnxy=True)
    lons = 360 - lons
    lats *= a.img.deg2rad; lons *= a.img.deg2rad
    y,x,z = a.coord.radec2eq(n.array([lons.flatten(), lats.flatten()]))
    ax,ay,az = a.coord.latlong2xyz(n.array([0,0]))
    data = h[x,y,z]
    data.shape = lats.shape
    data /= h[0,0,1]
    #data = data**2 # only if a voltage beam
    data = data_mode(data, mode)
    m.drawmapboundary()
    m.drawmeridians(n.arange(0, 360, 30))
    m.drawparallels(n.arange(0, 90, 10))
    if mx is None: mx = data.max()
    if drng is None:
        mn = data.min()
    #    if min < (max - 10): min = max-10
    else: mn = mx - drng
    step = (mx - mn) / 10
    levels = n.arange(mn-step, mx+step, step)
    return m.imshow(data, vmax=mx, vmin=mn, cmap=cmap)
def map_vis(data,title=[],vmin=None,vmax=None,barlabel=None,cmap=None,outputdir=None):
    # print("visualizing : "+title)
    if cmap==None:
        cmap=cm.jet
    if len(data.shape)>2:
        plotdata=data[0,:,:]
    else:
        plotdata=data
    plt.clf()
    # plt.figure(figsize=(3,3),dpi=200)
    ny,nx=plotdata.shape
    geo=[35,43,-113,-101]
    if experiment=="conus":geo=[25,52.7,-124.7,-67]
    m = Basemap(projection='cyl',llcrnrlat=geo[0],urcrnrlat=geo[1],\
                llcrnrlon=geo[2],urcrnrlon=geo[3],resolution="i")
    
    mapimg=m.imshow(plotdata,vmin=vmin,vmax=vmax,cmap=cmap)
    if experiment=="conus":
        m.drawparallels(np.arange(25,55,5.),labels=[1,0,0,0],dashes=[1,4])
        m.drawmeridians(np.arange(-120,-65,10.),labels=[0,0,0,1],dashes=[1,4])
        m.drawstates(linewidth=0.5)
        m.drawcountries(linewidth=0.5)
        m.drawcoastlines(linewidth=0.5)
    else:
        m.drawparallels(np.arange(36,43,2.),labels=[1,0,0,0],dashes=[1,4])
        m.drawmeridians(np.arange(-112,-103,4.),labels=[0,0,0,1],dashes=[1,4])
        m.drawstates(linewidth=1.5)
    cbar=m.colorbar()
    if barlabel:
        cbar.set_label(barlabel)
    plt.title(" ".join(title))
    if outputdir:
        plt.savefig(outputdir+"_".join(title)+'_map.png')
    else:
        plt.savefig("_".join(title)+'_map.png')
Beispiel #24
0
    def imshow(self, data, low=0, high=255, **kwargs):
        ''' Make RGB plot over the map

        data : numpy array
            RGB or RGBA input data
        **kwargs:
            Parameters for Basemap.imshow

        Modifies
        ---------
        self.mpl : list
            append AxesImage object with imshow

        '''
        # Create X/Y axes
        self._create_xy_grids()

        # add random colormap
        if 'cmap' in kwargs and kwargs['cmap'] == 'random':
            values = np.unique(data[np.isfinite(data)])
            cmap, norm = self._create_random_colormap(values,
                                                      low=low, high=high)
            kwargs['cmap'] = cmap
            kwargs['norm'] = norm

        # Plot data using imshow
        self.mpl.append(Basemap.imshow(self, data,
                                       extent=[self.x.min(), self.x.max(),
                                               self.y.min(), self.y.max()],
                                       origin='upper', **kwargs))
        self.colorbar = len(self.mpl) - 1
Beispiel #25
0
def maping(rawimage, rawname, image, name):

	import palettable 
	import  matplotlib.colors as mpc
	
	fig = plt.figure()
	
	cmap = mpc.ListedColormap(palettable.colorbrewer.diverging.PiYG_9.mpl_colors)
	# cmap.set_bad('grey',1.)

	ax = fig.add_subplot(121)
	ax.set_title("a. (maxNDVI/year)", loc= 'left')

	#set the spatial cordinates of the grid, mask the ocean and draw coastlines
	map = Basemap(llcrnrlon=112.0,llcrnrlat=-44.5,urcrnrlon=156.25,urcrnrlat=-10, resolution = 'h', epsg=4326)
	map.drawmapboundary(fill_color='grey')
	map.fillcontinents(color= 'none', lake_color='white')
	map.drawlsmask(land_color='none', )
	map.drawcoastlines()

	map.imshow(np.flipud(rawimage), cmap=cmap, vmin=-0.01, vmax=0.0125,)
	map.colorbar()#ticks= [-0.01, -0.0075, -0.0050, -0.00250, 0.0000, 0.0025, 0.0050, 0.0075, 0.010, 0.0125])

	#add in the grid
	map.drawparallels(np.arange(-50, -10, 10),labels=[1,0,0,0], dashes=[1,2])#color= 'none')
	map.drawmeridians(np.arange(110, 156.25, 10),labels=[0,0,0,1], dashes=[1,2])
	# from palettable.colorbrewer.qualitative import Dark2_7


	ax = fig.add_subplot(122)
	ax.set_title("b. ((maxNDVI/mmrainfall)/year)", loc= 'left')
	#set the spatial cordinates of the grid, mask the ocean and draw coastlines
	map = Basemap(llcrnrlon=112.0,llcrnrlat=-44.5,urcrnrlon=156.25,urcrnrlat=-10, resolution = 'h', epsg=4326)
	map.drawmapboundary(fill_color='grey')
	map.fillcontinents(color= 'none', lake_color='white')
	map.drawlsmask(land_color='none', )
	map.drawcoastlines()

	#load the data into a figure
	map.imshow(np.flipud(image), cmap=cmap, vmin=-0.01, vmax=0.0125,)
	map.colorbar()#ticks= [-0.01, -0.0075, -0.0050, -0.00250, 0.0000, 0.0025, 0.0050, 0.0075, 0.010, 0.0125])

	#add in the grid
	map.drawparallels(np.arange(-50, -10, 10),labels=[1,0,0,0], dashes=[1,2])#color= 'none')
	map.drawmeridians(np.arange(110, 156.25, 10),labels=[0,0,0,1], dashes=[1,2])
	plt.show()
Beispiel #26
0
def cat_mapper(image, cmap, title, vmin, vmax, vmin2=False, vmax2=False, cmap2=False, norm=False, save=False):
	"""To map things by a given number of catogeries"""

	fig = plt.figure()
	

	# cmap.set_bad('grey',1.)

	# ax = fig.add_subplot(1)
	plt.plot()
	if title is True:
		plt.title(title, loc= 'left')
	else:
		pass
	#set the spatial cordinates of the grid, mask the ocean and draw coastlines
	map = Basemap(llcrnrlon=112.0,llcrnrlat=-44.5,urcrnrlon=156.25,urcrnrlat=-10, resolution = 'h', epsg=4326)
	map.drawmapboundary(fill_color='grey')
	map.fillcontinents(color= 'none', lake_color='white')
	map.drawlsmask(land_color='none', )
	map.drawcoastlines()
	map.drawstates()
	if norm == False:
		map.imshow(np.flipud(image), cmap=cmap, vmin=vmin, vmax=vmax)
	else:
		map.imshow(np.flipud(image), cmap=cmap, vmin=vmin, vmax=vmax, norm=norm)

	
	# cb = plt.colorbar()

	#Tweaking the colorbar so the the ticks allign with the grid.  
	cb = map.colorbar()#ticks= [-0.01, -0.0075, -0.0050, -0.00250, 0.0000, 0.0025, 0.0050, 0.0075, 0.010, 0.0125])
	if vmax-vmin <= 1:
		tick_locator = ticker.MaxNLocator(nbins=20)
	else:
		tick_locator = ticker.MaxNLocator(nbins=vmax-vmin)
	cb.locator = tick_locator
	cb.update_ticks()

	#add in the grid
	map.drawparallels(np.arange(-50, -10, 10),labels=[1,0,0,0], dashes=[1,2])#color= 'none')
	map.drawmeridians(np.arange(110, 156.25, 10),labels=[0,0,0,1], dashes=[1,2])

	if save is not False:
		plt.savefig("%s/CTSR/%d/R4_paperfigures/%s.png" % (path, crn, save))
	plt.show()
def satellite_plot():
	imgsrc = 'http://lance-modis.eosdis.nasa.gov/imagery/subsets/?subset=ARM_Azores.' \
		+ iter_date.strftime('%Y%j') \
		+ '.aqua.2km.jpg'

	#ENA - Graciosa Island, Azores
	#39° 5' 29.68" N, 28° 1' 32.34" W
	#Altitude: 30.48 meters

	#from shapelib import ShapeFile

	file = cStringIO.StringIO(urllib.urlopen(imgsrc).read())
	try:
		img = Image.open(file)
	except IOError:
		img = None

	#print(imgsrc)
	fig, ax = plt.subplots(figsize=(12,12))
	ax.set_title(iter_date.strftime('%A %B %d %Y'), y=1.05)
	m = Basemap(llcrnrlat=28.9951, llcrnrlon=-38.0039,
				urcrnrlat=48.9990, urcrnrlon=-18.000,
				resolution='c', ax=ax, area_thresh=0.1)

	#m.drawcoastlines()
	m.drawparallels(np.arange(-90, 90, 5), labels=[1,1,1,1])
	m.drawmeridians(np.arange(-180, 180, 5), labels=[1,1,1,1])
	if img is not None:
		m.imshow(img, origin='upper')

	m.plot(-28.02565, 39.091578, 'r*', markersize=20, latlon=True)

	m.readshapefile(os.path.join(support_directory, 'PRT_adm/PRT_adm0'),
								 'prt', drawbounds=True)

	if img is not None:
		img.close()
	figout = os.path.join(plot_directory, 'satellite/')
	if not os.path.isdir(figout):
		os.makedirs(figout)

	fig.savefig(os.path.join(figout, iter_date.strftime('%Y-%m-%d')+'.png'),
				transparent=False)
Beispiel #28
0
def map_test():
    # image edges for west africa seviri
    # (measured from the fennec browser hr panner)
    ll_lat = 2.60
    ll_lon = -30.64
    ur_lat = 46.31
    ur_lon = 44.66

    # ul_lat = 47.28
    # ul_lon = -54.00
    # lr_lat = 2.58
    # lr_lon = 27.08

    m = Basemap(projection='geos', llcrnrlon=ll_lon, llcrnrlat=ll_lat,
                urcrnrlon=ur_lon, urcrnrlat=ur_lat, resolution='h')
    image = Image.open('TEST.png')
    m.imshow(image)
    m.drawcountries()
    return m
Beispiel #29
0
def plot_hpx(hpx, mode='log', pol='x', mx=None, drng=2, interpolation=False, 
        colorbar=False, nogrid=False):
    im = a.img.Img(size=400, res=.4)
    x,y,z = im.get_top(center=n.array(im.shape)/2)
    assert(pol in 'xy')
    hpx.set_interpol(interpolation)
    if pol == 'x': d = hpx[x,y,z]
    else: d = hpx[-y,x,z]
    d.shape = x.shape
    d = n.where(x.mask, 0, d)
    if mode.startswith('phs'): d = n.angle(d)
    elif mode.startswith('lin'): d = n.absolute(d)
    elif mode.startswith('real'): d = d.real
    elif mode.startswith('imag'): d = d.imag
    elif mode.startswith('log'):
        d = n.absolute(d)
        d = n.ma.masked_less_equal(d, 0)
        d = n.ma.log10(d)
    else: raise ValueError('Unrecognized plot mode.')
    if mx is None: mx = d.max()
    if drng is None: drng = mx - d.min()
    mn = mx - drng
    if not nogrid:
        from mpl_toolkits.basemap import Basemap
        map = Basemap(projection='ortho', lon_0=180, lat_0=90,
            rsphere=1, llcrnrx=-1.25, llcrnry=-1.25, urcrnrx=1.25,urcrnry=1.25)
        map.drawmeridians(n.arange(-180,180,30))
        map.drawparallels(n.arange(0,90,15))
        map.drawmapboundary()
        map.imshow(d, vmin=mn, vmax=mx, interpolation='nearest')
    else: p.imshow(d, vmin=mn, vmax=mx, origin='lower', interpolation='nearest')

    #data.shape = az.shape
    #m.drawmapboundary()
    #m.drawmeridians(n.arange(0,360,30))
    #m.drawparallels(n.arange(0,90,10))
    #step = (max - min) / 35.
    #levels = n.arange(min-step, max+step, step)
    #m.contourf(cx, cy, data, levels)
    if colorbar: p.colorbar(shrink=.5)
Beispiel #30
0
 def map_plot(self,ax):
     xmin = self.geodict['xmin']
     xmax = self.geodict['xmax']
     ymin = self.geodict['ymin']
     ymax = self.geodict['ymax']
     clat = ymin + (ymax-ymin)/2.0
     bmap = Basemap(llcrnrlon=xmin,llcrnrlat=ymin,
               urcrnrlon=xmax,urcrnrlat=ymax,
               projection='merc',lat_ts=clat,
               resolution='h',ax=ax)
     img = bmap.imshow(flipud(self.griddata))
     bmap.drawcoastlines(color='w')
     return img 
Beispiel #31
0
lats = np.arange(-60., 60., 0.05)[::-1]
lons1, lats1 = np.meshgrid(lons, lats)

fig = plt.figure()
ax1 = plt.subplot2grid((7, 6), (0, 0), colspan=6, rowspan=3)
m1 = Basemap(llcrnrlon=-180.,llcrnrlat=-60.,urcrnrlon=180.,urcrnrlat=60.,\
    projection='mill',lon_0=0)
m1.drawcountries(linewidth=0.2)
m1.drawcoastlines(linewidth=0.3)
m1.drawparallels(np.arange(-60., 60., 30.), linewidth=0.05)
m1.drawmeridians(np.arange(-180., 180., 60.), linewidth=0.05)
cmap = LinearSegmentedColormap.from_list('mycmap', [(0 / 2., 'gray'),
                                                    (1 / 2., 'black'),
                                                    (2 / 2., 'white')])
#im1 = m1.pcolormesh(lons1, lats1, merged_map[0,:,:],shading='flat', cmap=cmap, latlon=True)
im1 = m1.imshow(np.flipud(merged_map[0, :, :]), cmap=cmap)
ax1.set_ylabel('Merged MODIS image', fontsize=10)
cb1 = m1.colorbar(im1,
                  'right',
                  pad='1%',
                  ticks=[0, 1, 2],
                  boundaries=[0, 0.1, 1.9, 2])
cb1.ax.set_yticklabels(['Ground', 'Cloud', 'Snow'], size='x-small')
title1 = ax1.set_title('Day: ' + t0.strftime('%Y-%m-%d'))
ax2 = plt.subplot2grid((7, 6), (3, 0), colspan=6, rowspan=3)
m2 = Basemap(llcrnrlon=-180.,llcrnrlat=-60.,urcrnrlon=180.,urcrnrlat=60.,\
    projection='mill',lon_0=0)
m2.drawcountries(linewidth=0.2)
m2.drawcoastlines(linewidth=0.3)
m2.drawparallels(np.arange(-60., 60., 30.), linewidth=0.05)
m2.drawmeridians(np.arange(-180., 180., 60.), linewidth=0.05)
        m = Basemap(projection='cyl',
                    llcrnrlat=rlat_0,
                    urcrnrlat=rlat_1,
                    llcrnrlon=rlon_0,
                    urcrnrlon=rlon_1,
                    resolution='c')
        m.drawcoastlines()
        m.drawparallels(
            np.arange(-10, 60, 20), labels=[1, 0, 0, 0],
            fontsize=9)  #labels=[left,right,top,bottom] #horizontal line
        m.drawmeridians(
            np.arange(80, 180, 20), labels=[0, 0, 0, 1],
            fontsize=9)  #labels=[left,right,top,bottom] #vertical line

        m.imshow(array, cmap=cmap, vmin=0, vmax=100)  #draw figure
        plt.title(fn_name, fontsize=9)

        cbar = m.colorbar(
            size="5%", pad=0.05,
            extend='max')  #pad=distance, extend='colorbar shape,,'
        cbar.ax.tick_params(labelsize=8)  #labelsize=colorbar font size
        cbar.set_label('Rainfall intensity(mm/hr)', fontsize=8,
                       ha='center')  #ha='label text position'
        #------------------
'''
        n=n+1

        #---PE FILE SUBPLOT---
        plt.subplot(6,2,n) #subplot(y,x,position)
Beispiel #33
0
m = Basemap(projection='ortho', lat_0=19, lon_0=-166, resolution='i')
#m = Basemap(llcrnrlon=lonmin,llcrnrlat=latmin,urcrnrlon=lonmax,urcrnrlat=latmax#,
#                resolution='i',projection='merc',lon_0=27.,lat_0=46.7)
clip_path = m.drawmapboundary()

#m.contour(x,y,layer,cmap=RGB_light,linewidth=0,rasterized=True)

tmp = np.loadtxt(
    '/raid1/sc845/Tomographic_models/SEMUCB_WM1/UCB_a3d_dist.SEMUCB-WM1.r20151019/SEMUCB_WM1_2800km.dat'
)
lon = tmp[:, 1].reshape((181, 361))
lat = tmp[:, 2].reshape((181, 361))
dvs = tmp[:, 3].reshape((181, 361))
s = m.transform_scalar(dvs, lon[0, :], lat[:, 0], 1000, 500)
im = m.imshow(s, cmap=plt.cm.seismic_r, clip_path=clip_path, vmin=-3, vmax=0)
cb = plt.colorbar()
cb.set_label('dlnVs (%)')
cb.set_clim(-15, 15)
cb.remove()
x, y = m(lon, lat)

lon, lat, layer = LMC.get_slice(piercedepth, whattoplot='votesslow')
x, y = m(lon.ravel(), lat.ravel())
x = x.reshape(np.shape(layer))
y = y.reshape(np.shape(layer))
minval = np.min(np.min(layer))
maxval = np.max(np.max(layer)) + .1

#m.shadedrelief()
m.drawcoastlines()
Beispiel #34
0
def plot_MWAconstellations(outfile=None,
                           obsinfo=None,
                           viewgps=None,
                           observing=True,
                           showbeam=True,
                           constellations=True,
                           gleamsources=False,
                           notext=False,
                           inverse=False,
                           skydata=None,
                           background=None,
                           hidenulls=False,
                           channel=None,   # Frequency channel to use for the beam map, defaults to mean of all channels in obs.
                           xmas=XMAS,
                           plotscale=SCALE,  # A scale of 1.0 gives a 1200x1200 pixel plot
                           logger=DEFAULTLOGGER):
    if obsinfo is None:
        logger.error('Unable to find observation info')
        return None

    if skydata is None:
        skydata = SkyData()
    if not skydata.valid:
        logger.error('Unable to load star/planet data, aborting.')
        return None

    if background is None:
        background = 'transparent'

    if channel is None:
        if 0 in obsinfo['rfstreams']:
            channel = obsinfo['rfstreams'][0]['frequencies'][12]
        elif '0' in obsinfo['rfstreams']:
            channel = obsinfo['rfstreams']['0']['frequencies'][12]

    s_obstime = su.time2tai(obsinfo['starttime'])
    a_obstime = Time(obsinfo['starttime'], format='gps', scale='utc')

    if viewgps is None:
        s_viewtime = s_obstime
        a_viewtime = a_obstime
    else:
        s_viewtime = su.time2tai(viewgps)
        a_viewtime = Time(viewgps, format='gps', scale='utc')

    a_viewtime.delta_ut1_utc = 0  # We don't care about IERS tables and high precision answers
    LST_hours = a_viewtime.sidereal_time(kind='apparent', longitude=config.MWAPOS.lon)

    observer = su.S_MWAPOS.at(s_viewtime)

    mapzenith = SkyCoord(ra=skydata.skymapRA,
                         dec=skydata.skymapDec,
                         equinox='J2000',
                         unit=(astropy.units.deg, astropy.units.deg))
    mapzenith.location = config.MWAPOS
    mapzenith.obstime = a_viewtime
    altaz = mapzenith.transform_to('altaz')
    Az, Alt = altaz.az.deg, altaz.alt.deg

    fig = plt.figure(figsize=(FIGSIZE * plotscale, FIGSIZE * plotscale), dpi=DPI)
    ax1 = fig.add_subplot(1, 1, 1)

    bmap = Basemap(projection='ortho', lat_0=su.MWA_TOPO.latitude.degrees, lon_0=LST_hours.hour * 15 - 360, ax=ax1)
    nx = len(skydata.skymapra)
    ny = len(skydata.skymapdec)

    ax1.cla()

    # show the Haslam map
    tform_skymap = bmap.transform_scalar(skydata.basemap[0].data[0][:, ::-1],
                                         skydata.skymapra[::-1] * 15,
                                         skydata.skymapdec,
                                         nx, ny,
                                         masked=True)
    if inverse:
        cmap = CMI
    else:
        cmap = CM
    bmap.imshow(numpy.ma.log10(tform_skymap[:, ::-1]), cmap=cmap, vmin=math.log10(LOW), vmax=math.log10(HIGH))

    delays = []
    if showbeam:
        if not hidenulls:
            contours = [0.001, 0.1, 0.5, 0.90]
            if observing:
                beamcolor = ((0.0, 0.0, 0.0), (0.0, 0.5, 0.0), (0.0, 0.75, 0.0), (0.0, 1.0, 0.0))
            else:
                beamcolor = ((0.0, 0.0, 0.0), (0.5, 0.5, 0.5), (0.75, 0.75, 0.75), (1.0, 1.0, 1.0))
        else:
            contours = [0.1, 0.5, 0.90]
            if observing:
                beamcolor = ((0.0, 0.5, 0.0), (0.0, 0.75, 0.0), (0.0, 1.0, 0.0))
            else:
                beamcolor = ((0.5, 0.5, 0.5), (0.75, 0.75, 0.75), (1.0, 1.0, 1.0))

        # If the observation is in the future, calculate what delays will be used, instead of using the recorded actual delays
        if su.tai2gps(s_obstime) > su.tai2gps(su.time2tai()) + 10:
            if 0 in obsinfo['rfstreams']:
                delays = calc_delays(az=obsinfo['rfstreams'][0]['azimuth'], el=obsinfo['rfstreams'][0]['elevation'])
            elif '0' in obsinfo['rfstreams']:
                delays = calc_delays(az=obsinfo['rfstreams']['0']['azimuth'], el=obsinfo['rfstreams']['0']['elevation'])
            else:
                delays = [33] * 16
            logger.debug("Calculated future delays: %s" % delays)
        else:
            if 0 in obsinfo['rfstreams']:
                delays = obsinfo['rfstreams'][0]['xdelays']
            elif '0' in obsinfo['rfstreams']:
                delays = obsinfo['rfstreams']['0']['xdelays']
            logger.debug("Used actual delays: %s" % delays)

        # get the primary beam
        R = primarybeammap.return_beam(Alt,
                                       Az,
                                       delays,
                                       channel * 1.28)

        # show the beam
        X, Y = bmap(skydata.skymapRA, skydata.skymapDec)
        CS = bmap.contour(bmap.xmax - X, Y, R, contours, linewidths=plotscale, colors=beamcolor)
        ax1.clabel(CS, inline=1, fontsize=10 * plotscale)

    # Find the constellation that the beam is in
    if obsinfo['ra_phase_center'] is not None:
        ra = obsinfo['ra_phase_center']
        dec = obsinfo['dec_phase_center']
    else:
        ra = obsinfo['metadata']['ra_pointing']
        dec = obsinfo['metadata']['dec_pointing']
    if (ra is not None) and (dec is not None):
        constellation = ephem.constellation((ra * math.pi / 180.0, dec * math.pi / 180.0))
    else:
        constellation = ["N/A", "N/A"]

    X0, Y0 = bmap(LST_hours.hour * 15 - 360, su.MWA_TOPO.latitude.degrees)

    if constellations:
        # plot the constellations
        ConstellationStars = []
        for c in skydata.constellations.keys():
            for i in range(0, len(skydata.constellations[c][1]), 2):
                i1 = numpy.where(skydata.hip['HIP'] == skydata.constellations[c][1][i])[0][0]
                i2 = numpy.where(skydata.hip['HIP'] == skydata.constellations[c][1][i + 1])[0][0]
                star1 = skydata.hip[i1]
                star2 = skydata.hip[i2]
                if i1 not in ConstellationStars:
                    ConstellationStars.append(i1)
                if i2 not in ConstellationStars:
                    ConstellationStars.append(i2)
                ra1, dec1 = map(numpy.degrees, (star1['RArad'], star1['DErad']))
                ra2, dec2 = map(numpy.degrees, (star2['RArad'], star2['DErad']))
                ra = numpy.array([ra1, ra2])
                dec = numpy.array([dec1, dec2])
                newx, newy = bmap(ra, dec)
                testx, testy = bmap(newx, newy, inverse=True)
                if testx.max() < 1e30 and testy.max() < 1e30:
                    bmap.plot(2 * X0 - newx, newy, 'r-', linewidth=plotscale, latlon=False)  # This bit generates an error

        # figure out the coordinates
        # and plot the stars
        ra = numpy.degrees(skydata.hip[ConstellationStars]['RArad'])
        dec = numpy.degrees(skydata.hip[ConstellationStars]['DErad'])
        m = numpy.degrees(skydata.hip[ConstellationStars]['Hpmag'])
        newx, newy = bmap(ra, dec)
        # testx, testy = bmap(newx, newy, inverse=True)
        good = (newx > bmap.xmin) & (newx < bmap.xmax) & (newy > bmap.ymin) & (newy < bmap.ymax)
        size = 60 - 15 * m
        size[size <= 15] = 15
        size[size >= 60] = 60
        bmap.scatter(bmap.xmax - newx[good], newy[good],
                     size[good] * plotscale,
                     'r',
                     edgecolor='none',
                     alpha=0.7)

    if gleamsources:
        ra = numpy.array([x[1] for x in skydata.gleamcat])
        dec = numpy.array([x[2] for x in skydata.gleamcat])
        flux = numpy.array([x[3] for x in skydata.gleamcat])
        newx, newy = bmap(ra, dec)
        # testx, testy = bmap(newx, newy, inverse=True)
        good = (newx > bmap.xmin) & (newx < bmap.xmax) & (newy > bmap.ymin) & (newy < bmap.ymax)
        size = flux / 1.0
        size[size <= 7] = 7
        size[size >= 60] = 60
        bmap.scatter(bmap.xmax - newx[good], newy[good],
                     size[good] * plotscale,
                     'b',
                     edgecolor='none',
                     alpha=0.7)

    # plot the bodies
    for b in skydata.bodies.keys():
        name = skydata.bodies[b][2]
        color = skydata.bodies[b][1]
        if inverse:
            if name == 'Moon':
                color = 'darkgoldenrod'
            elif name == 'Jupiter':
                color = 'sienna'
            elif name == 'Saturn':
                color = 'purple'
        size = skydata.bodies[b][0]
        body_app = observer.observe(b).apparent()
        body_ra_a, body_dec_a, _ = body_app.radec()
        ra, dec = body_ra_a._degrees, body_dec_a.degrees
        newx, newy = bmap(ra, dec)
        testx, testy = bmap(newx, newy, inverse=True)
        if testx < 1e30 and testy < 1e30:
            bmap.scatter(2 * X0 - newx, newy, s=size * plotscale, c=color, alpha=1.0, latlon=False, edgecolor='none')
            ax1.text(bmap.xmax - newx + 2e5, newy,
                     name,
                     horizontalalignment='left',
                     fontsize=12 * plotscale,
                     color=color,
                     verticalalignment='center')

    # and label some sources
    for source in primarybeammap.sources.keys():
        if source == 'EOR0b':
            continue
        if source == 'CenA':
            primarybeammap.sources[source][0] = 'Cen A'
        if source == 'ForA':
            primarybeammap.sources[source][0] = 'For A'
        r = Longitude(angle=primarybeammap.sources[source][1], unit=astropy.units.hour).hour
        d = Latitude(angle=primarybeammap.sources[source][2], unit=astropy.units.deg).deg
        horizontalalignment = 'left'
        x = r
        if (len(primarybeammap.sources[source]) >= 6 and primarybeammap.sources[source][5] == 'c'):
            horizontalalignment = 'center'
            x = r
        if (len(primarybeammap.sources[source]) >= 6 and primarybeammap.sources[source][5] == 'r'):
            horizontalalignment = 'right'
            x = r
        fontsize = primarybeammap.defaultsize
        if (len(primarybeammap.sources[source]) >= 5):
            fontsize = primarybeammap.sources[source][4]
        color = primarybeammap.defaultcolor
        if (len(primarybeammap.sources[source]) >= 4):
            color = primarybeammap.sources[source][3]
        if color == 'k':
            color = 'w'

        if inverse:
            if color == 'w':
                color = 'black'

        xx, yy = bmap(x * 15 - 360, d)
        try:
            if xx < 1e30 and yy < 1e30:
                ax1.text(bmap.xmax - xx + 2e5, yy,
                         primarybeammap.sources[source][0],
                         horizontalalignment=horizontalalignment,
                         fontsize=fontsize * plotscale,
                         color=color,
                         verticalalignment='center')
        except:
            pass

    if not notext:
        if background == 'black':
            fontcolor = 'white'
        else:
            fontcolor = 'black'

        if showbeam:
            ax1.text(0, bmap.ymax - 2e5,
                     'Obs ID %d with delays %s\n at %s:\n%s at %d MHz\n in the constellation %s' % (obsinfo['starttime'],
                                                                                                    delays,
                                                                                                    a_obstime.datetime.strftime('%Y-%m-%d %H:%M UT'),
                                                                                                    obsinfo['obsname'],
                                                                                                    channel * 1.28,
                                                                                                    constellation[1]),
                     fontsize=10 * plotscale,
                     color=fontcolor)
        else:
            ax1.text(0, bmap.ymax - 2e5,
                     '%s:\nNo recent observation' % (a_obstime.datetime.strftime('%Y-%m-%d %H:%M UT')),
                     fontsize=10 * plotscale,
                     color=fontcolor)

    ax1.text(bmap.xmax, Y0, 'W', fontsize=12 * plotscale, horizontalalignment='left', verticalalignment='center')
    ax1.text(bmap.xmin, Y0, 'E', fontsize=12 * plotscale, horizontalalignment='right', verticalalignment='center')
    ax1.text(X0, bmap.ymax, 'N', fontsize=12 * plotscale, horizontalalignment='center', verticalalignment='bottom')
    ax1.text(X0, bmap.ymin, 'S', fontsize=12 * plotscale, horizontalalignment='center', verticalalignment='top')

    try:
        if type(outfile) == str:
            if not xmas:
                if background.lower() == 'transparent':
                    fig.savefig(outfile, transparent=True, facecolor='none', dpi=DPI)
                else:
                    fig.savefig(outfile, transparent=False, facecolor=background, dpi=DPI)
                return ''
            else:
                buf = io.BytesIO()
                if background.lower() == 'transparent':
                    fig.savefig(buf, format='png', transparent=True, facecolor='none', dpi=DPI)
                else:
                    fig.savefig(buf, format='png', transparent=False, facecolor=background, dpi=DPI)
                buf.seek(0)
                im = Image.open(buf)
                im.load()
                buf.close()
                r = Image.open('Treindeers.png')
                im.paste(r, box=(250, 300), mask=r)
                buf2 = io.BytesIO()
                im.save(buf2, format=outfile[outfile.find('.') + 1:].upper())
                buf2.seek(0)
                outf = open(outfile, 'wb')
                outf.write(buf2.read())
                return ''
        else:
            buf = io.BytesIO()
            if background.lower() == 'transparent':
                fig.savefig(buf, format='png', transparent=True, facecolor='none', dpi=DPI)
            else:
                fig.savefig(buf, format='png', transparent=False, facecolor=background, dpi=DPI)
            buf.seek(0)
            if not xmas:
                return buf.read()
            else:
                im = Image.open(buf)
                im.load()
                buf.close()
                r = Image.open('Treindeers.png')
                im.paste(r, box=(250, 100), mask=r)
                buf2 = io.BytesIO()
                im.save(buf2, format='PNG')
                buf2.seek(0)
                return buf2.read()
    except AssertionError:
        logger.error('Cannot save output: %s', outfile)
        return None
    finally:
        plt.close(fig)
        del ax1
        del fig
Beispiel #35
0
#with open(filename) as jfile:
#   rjsJ = json.load(jfile)
#======================================================================
df = pd.DataFrame(rjsJ, dtype=np.float32)
vplt = plt.figure(figsize=(10, 8), edgecolor=None)
#ax1 = vplt.add_axes([0.05, 0.80, 0.9, 0.15])
m = Basemap(llcrnrlon=-125.671,
            llcrnrlat=24.4769,
            urcrnrlon=-66.5202,
            urcrnrlat=49.4391,
            epsg=4326)
#http://server.arcgisonline.com/arcgis/rest/services
#try local copy first
try:
    from PIL import Image
    m.imshow(Image.open('USAStreetMap.png'), origin='upper', alpha=0.6)
except FileNotFoundError as err:
    #arcgisimage occasionally fails to download properly try,try again
    while True:
        try:
            m.arcgisimage(service='ESRI_StreetMap_World_2D',
                          xpixels=3500,
                          alpha=0.6)
        except RuntimeError as err:
            pass
        else:
            break
#---------------------------------------------------------------------
vvmin = -10  #min temp for scale
vvmax = 50  #max temp for scale
vstep = 10  #step between ticks
Beispiel #36
0
# north polar projection.
m = Basemap(lon_0=-135,boundinglat=25,round=True,
            resolution='c',area_thresh=10000.,projection='npstere')
# transform from spherical to map projection coordinates (rotation
# and interpolation).
nxv = 41; nyv = 41
nxp = 101; nyp = 101
spd = np.sqrt(u**2+v**2)
udat, vdat, xv, yv = m.transform_vector(u,v,lons1,lats1,nxv,nyv,returnxy=True)
pdat, xp, yp = m.transform_scalar(p,lons1,lats1,nxp,nyp,returnxy=True)
# create a figure, add an axes.
fig=plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# plot image over map
im = m.imshow(pdat,plt.cm.jet)
# plot wind vectors over map.
Q = m.quiver(xv,yv,udat,vdat) #or specify, e.g., width=0.003, scale=400)
qk = plt.quiverkey(Q, 0.95, 1.05, 25, '25 m/s', labelpos='W')
m.colorbar(pad='12%') # draw colorbar
m.drawcoastlines()
m.drawcountries()
# draw parallels
delat = 20.
circles = np.arange(0.,90.+delat,delat).tolist()+\
          np.arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles,labels=[1,1,1,1])
# draw meridians
delon = 45.
meridians = np.arange(-180,180,delon)
m.drawmeridians(meridians,labels=[1,1,1,1])
Beispiel #37
0
    else: min = d.min()

    #p.subplot(m2, m1, cnt+1)
    if not opts.nogrid:
        from mpl_toolkits.basemap import Basemap
        xpx,ypx = d.shape
        dx1 = -(xpx/2 + .5) * kwds['d_ra'] * a.img.deg2rad
        dx2 = (xpx/2 - .5) * kwds['d_ra'] * a.img.deg2rad
        dy1 = -(ypx/2 + .5) * kwds['d_dec'] * a.img.deg2rad
        dy2 = (ypx/2 - .5) * kwds['d_dec'] * a.img.deg2rad
        map = Basemap(projection='ortho', lon_0=180, lat_0=kwds['dec'],
            rsphere=1, llcrnrx=dx1, llcrnry=dy1, urcrnrx=dx2,urcrnry=dy2)
        map.drawmeridians(n.arange(kwds['ra']-180,kwds['ra']+180,30))
        map.drawparallels(n.arange(-90,120,30))
        map.drawmapboundary()
        map.imshow(d, vmin=min, vmax=max, cmap=cmaps[cnt%len(cmaps)], interpolation='nearest', alpha=1-.25*cnt)
    else: p.imshow(d, vmin=min, vmax=max, origin='lower', cmap=cmap, interpolation='nearest')
    p.colorbar(shrink=.5, fraction=.05)
    p.title(filename)

    if opts.batch:
        print 'Saving to', outfile
        p.savefig(outfile)
        p.clf()
        

# Add right-click functionality for finding locations/strengths in map.
cnt = 1
def click(event):
    global cnt
    if not event.button in [2,3]: return
Beispiel #38
0
    #plot the beam  contours
    if not opts.beam is None:
        bm_levels = [0.0001, 0.001, 0.01, 0.1, 0.5,
                     0.9]  #beam levels in beam units
        print "plotting beam contours: %s" % ([db(bm) for bm in bm_levels])
        lons, lats, x_bm, y_bm = map.makegrid(360 / opts.res,
                                              180 / opts.res,
                                              returnxy=True)
        map.contour(x_bm, y_bm, bm_response**2, bm_levels, colors='r', lw=10)
    if opts.skip_im: pass
    if opts.osys == 'ga':
        print data.shape
        data = n.fliplr(data)
        print data.shape
    map.imshow(data, vmax=max, vmin=min, cmap=cmap, interpolation=opts.interp)
    ax.format_coord = format_coord

    # Plot src labels and markers on top of map image
    if not opts.src is None:
        print "trying to plot sources"
        sx, sy = map(slons, slats)
        for name, xpt, ypt, flx in zip(snams, sx, sy, sflxs):
            if xpt >= 1e30 or ypt >= 1e30: continue
            #if opts.src_mark != '':
            #map.plot(sx, sy, opts.src_color+opts.src_mark,markerfacecolor=None)
            #map.scatter(sx,sy,'o',color=[(181,237,255)]*len(sx),s=n.log10(flx)*10)
            if opts.lockview and flx < 40: continue

            if flx < 60:
                s = 10
Beispiel #39
0
topodat = m.transform_scalar(data, lons, lats, nx, ny)

print 'Getting colormap...'
# get colormap
#cptfile = '//Users//tallen//Documents//DATA//GMT//cpt//mby_topo-bath_mod.cpt'
cptfile = '//Users//tallen//Documents//DATA//GMT//cpt//mby_topo-bath.cpt'
#cptfile = '//Users//tallen//Documents//DATA//GMT//cpt//gray.cpt'
cmap, zvals = cpt2colormap(cptfile, 256)
cmap = remove_last_cmap_colour(cmap)

# make shading
print 'Making map...'
ls = LightSource(azdeg=180, altdeg=45)
norm = mpl.colors.Normalize(vmin=-8000 / zscale, vmax=5000 / zscale)  #myb
rgb = ls.shade(topodat, cmap=cmap, norm=norm)
im = m.imshow(rgb)

##########################################################################################
# plt boundaries
##########################################################################################

x, y = m(walon, walat)
plt.plot(x, y, '-', c='r', lw=2.5)
labelCentroid(plt, m, 'WA', 16, walon, walat, 0)

x, y = m(ealon, ealat)
plt.plot(x, y, '-', c='r', lw=2.5)
labelCentroid(plt, m, 'EA', 16, ealon, ealat, 0)

x, y = m(salon, salat)
plt.plot(x, y, '-', c='r', lw=2.5)
Beispiel #40
0
def run_main():
    """ Main """
    print "Crawling last near real-time true-color image from MODIS... ",
    download(URL_RAPIDFIRE_SUBSET, "data.zip")

    try:
        zipf = zipfile.ZipFile('data.zip')
    except zipfile.BadZipfile:
        print "\n\n\tError: BadZipfile, maybe the data is not yet ready on MODIS site !\n"
        sys.exit(-1)

    tempdir = tempfile.mkdtemp()

    for name in zipf.namelist():
        data = zipf.read(name)
        outfile = os.path.join(tempdir, name)
        f = open(outfile, 'wb')
        f.write(data)
        f.close()

    zipf.close()

    image_path = os.path.join(tempdir, IMAGE_FILE)
    image_modis = Image.open(image_path)
    print "done !"

    print "Downloading MODIS image metadata... ",
    metadata = downloadString(URL_METADATA)
    ll_lon = parseTerm(metadata, "LL lon")
    ll_lat = parseTerm(metadata, "LL lat")
    ur_lon = parseTerm(metadata, "UR lon")
    ur_lat = parseTerm(metadata, "UR lat")
    print "done !"

    print "Downloading shape files from MODIS rapid fire... ",
    download(URL_FIRE_SHAPES, "shapes.zip")
    zipf = zipfile.ZipFile('shapes.zip')

    for name in zipf.namelist():
        data = zipf.read(name)
        outfile = os.path.join(tempdir, name)
        f = open(outfile, 'wb')
        f.write(data)
        f.close()
    zipf.close()
    print "done !"

    print "Parsing shapefile... ",

    shape_path = os.path.join(tempdir, 'Global_%s' % FIRE_LASTS)
    r = shapefile.Reader(shape_path)
    # print r.fields

    sr = r.shapeRecords()

    total = len(sr)

    xlist = []
    ylist = []
    confidence = []

    for i in xrange(total):
        sr_test = sr[i]
        xlist.append(sr_test.shape.points[0][0])  #longitude
        ylist.append(sr_test.shape.points[0][1])  #latitude
        confidence.append(sr_test.record[8])

    print "done !"
    print "Rendering... ",
    m = Basemap(projection='cyl', llcrnrlat=ur_lat, urcrnrlat=ll_lat,\
                llcrnrlon=ll_lon, urcrnrlon=ur_lon, resolution='f')
    m.drawcoastlines()
    m.drawmapboundary(fill_color='aqua')
    m.scatter(xlist,
              ylist,
              20,
              c=confidence,
              cmap=p.cm.YlOrRd,
              marker='o',
              edgecolors='none',
              zorder=10)
    m.imshow(image_modis)

    p.title(
        "The recent fire hotspots for last %s \n Pixel size: %s | Current Date: %s | Area Mapped: %s"
        % (FIRE_LASTS, RAPIDFIRE_RES, time.strftime("%d/%m/%Y"), SUBSET_NAME))
    p.show()

    os.remove("data.zip")
Beispiel #41
0
    def initialize(self):
        font = {'size': 12}
        matplotlib.rc('font', **font)
        matplotlib.style.use("dark_background")

        pixels = [1920, 1080]
        fig = Figure(figsize=(pixels[0] / 96.0, pixels[1] / 96.0),
                     edgecolor='none',
                     facecolor='k')

        i0 = 1
        i = 14
        j = 36
        s = 3

        # ----------------------------------------------------------------------
        # Eixos para os graficos
        # ----------------------------------------------------------------------
        gs1, gs2 = gridspec.GridSpec(i, j), gridspec.GridSpec(i, j)
        # ----------------------------------------------------------------------
        # Grafico de temperatura xaxis compartilhado com os demais graficos
        graf_temp = fig.add_subplot(gs1[i0 + 3 * s:i0 + 4 * s:11, 0:15])
        # Grafico de pressao
        graf_press = fig.add_subplot(gs1[i0 + 2 * s:i0 + 3 * s:11, 0:15],
                                     sharex=graf_temp)
        # Grafico umidade e precipitacao
        graf_umid = fig.add_subplot(gs1[i0 + s:i0 + 2 * s, 0:15],
                                    sharex=graf_temp)
        graf_rain = graf_umid.twinx()
        # Grafico de vento e direcao do vento
        graf_vento = fig.add_subplot(gs1[i0:i0 + s, 0:15], sharex=graf_temp)
        # ----------------------------------------------------------------------
        # Icone da pressao
        icon_pres = fig.add_subplot(gs1[i0 + 2 * s:i0 + 3 * s, 16:21],
                                    frameon=False)
        # Icone do vento
        icon_vent = fig.add_subplot(gs1[i0:i0 + s, 16:18], frameon=False)
        # Icone de umidade
        icon_umid = fig.add_subplot(gs1[i0 + s:i0 + 2 * s, 16:18],
                                    frameon=False)
        # Icone de temperatura
        icon_temp = fig.add_subplot(gs1[i0 + 3 * s:i0 + 4 * s, 16:18],
                                    frameon=False)
        # Icone direcao do vento agora
        icon_vento_dir = fig.add_subplot(gs2[i0:i0 + s, 19:22],
                                         frameon=False,
                                         projection='polar')
        # Icone de precipitacao
        icon_rain = fig.add_subplot(gs2[i0 + s:i0 + 2 * s, 18:21],
                                    frameon=False)
        # Icone de sensação térmica
        self.icon_feel = fig.add_subplot(gs2[i0 + 3 * s:i0 + 4 * s, 18:21],
                                         frameon=False)
        # Icone de rajada
        icon_gust = fig.add_subplot(gs1[i0:4, 23:27], frameon=False)
        # Icone de windrose
        icon_rose = fig.add_subplot(gs1[i0:4, 28:32],
                                    frameon=False,
                                    projection='polar')
        # ----------------------------------------------------------------------
        # Titulo Gráficos
        self.title_1 = fig.add_subplot(gs1[0, 0:12], frameon=False)
        # Titulo Icones
        self.title_2 = fig.add_subplot(gs1[0, 16:21], frameon=False)
        # Titulo Logos
        self.title_3 = fig.add_subplot(gs1[-2, 23::], frameon=False)

        map = fig.add_subplot(gs1[5:-2, 23::])

        gs1.update(wspace=0.01, hspace=0.3, left=0.04, top=1, bottom=0.000001)
        gs2.update(wspace=0.03, hspace=0.75, top=1, bottom=0.000001)

        # ----------------------------------------------------------------------
        # Plota os icones
        # ----------------------------------------------------------------------
        dir_icon = '.\images'
        zoom_f = 1.6
        kw = dict(frameon=False,
                  xycoords="data",
                  boxcoords="data",
                  xy=(0, 0),
                  box_alignment=(0.0, 0.0))
        # Desenha os icones de vento
        img_today = read_png(os.path.join(dir_icon, 'wind.png'))
        imagebox = OffsetImage(img_today, zoom=0.07 * zoom_f)
        ab = AnnotationBbox(imagebox, xybox=(0.1, 0.1), **kw)
        icon_vent.add_artist(ab)
        # ----------------------------------------------------------------------
        # Gerando eixo polar para as setas para o vento
        directions = ['N', 'NW', 'W', 'SW', 'S', 'SE', 'E', 'NE']
        icon_vento_dir.set_theta_zero_location('N')
        icon_vento_dir.set_theta_direction(1)
        icon_vento_dir.set_xticklabels(directions)
        icon_vento_dir.tick_params(axis='x', colors='w')
        icon_vento_dir.tick_params(axis='y', colors='w')
        icon_vento_dir.grid(color='w')

        # Desenha o icone de rajada
        img_today = read_png(os.path.join(dir_icon, 'rajada.png'))
        imagebox = OffsetImage(img_today, zoom=0.15 * zoom_f)
        ab = AnnotationBbox(imagebox, xybox=(0.0, 0.1), **kw)
        icon_gust.add_artist(ab)
        icon_gust.set_title(u'Rajada 2 minutos',
                            fontsize=11,
                            x=0.4,
                            y=1,
                            fontweight='bold')

        # ----------------------------------------------------------------------
        # Gerando eixo polar para plot
        icon_rose.set_theta_zero_location('N')
        icon_rose.set_theta_direction(1)
        icon_rose.set_xticklabels(directions)
        icon_rose.tick_params(axis='x', colors='w')
        icon_rose.tick_params(axis='y', colors='w')
        icon_rose.grid(color='w')

        # Desenha os icones de umidade
        img_today = read_png(os.path.join(dir_icon, 'humidity.png'))
        imagebox = OffsetImage(img_today, zoom=0.075 * zoom_f)
        ab = AnnotationBbox(imagebox, xybox=(0.325, 0.10), **kw)
        icon_umid.add_artist(ab)

        # Desenha os icones de precipitacao
        img_today = read_png(os.path.join(dir_icon, 'rain.png'))
        imagebox = OffsetImage(img_today, zoom=0.09 * zoom_f)
        ab = AnnotationBbox(imagebox, xybox=(0.275, 0.0), **kw)
        icon_rain.add_artist(ab)

        # Desenha os icones de pressao
        img_today = read_png(os.path.join(dir_icon, 'pressure.png'))
        imagebox = OffsetImage(img_today, zoom=0.125 * zoom_f)
        ab = AnnotationBbox(imagebox, xybox=(0.35, 0.0), **kw)
        icon_pres.add_artist(ab)

        # Desenha os icones de temperatura
        img_today = read_png(os.path.join(dir_icon, 'temp.png'))
        imagebox = OffsetImage(img_today, zoom=0.11 * zoom_f)
        ab = AnnotationBbox(imagebox, xybox=(0.22, 0.0), **kw)
        icon_temp.add_artist(ab)

        # Desenha o icone de sensacao termica atual
        img_today = read_png(os.path.join(dir_icon, 'realfeel.png'))
        imagebox = OffsetImage(img_today, zoom=0.10 * zoom_f)
        self.ab = AnnotationBbox(imagebox, xybox=(0.3, 0.1), **kw)
        self.icon_feel.add_artist(self.ab)
        self.icon_feel.set_title(u'Sensação\nTérmica',
                                 fontsize=11,
                                 x=0.55,
                                 y=-0.2)
        self.img = itertools.cycle(
            ['realfeel_cky.png', 'realfeel_fms.png', 'realfeel_fna.png'])

        # logo Petrobras
        img_today = read_png(os.path.join(dir_icon, 'Principal_h_cor_RGB.png'))
        imagebox = OffsetImage(img_today, zoom=0.2)
        # opcao 1: logo ao lado do credito
        ab = AnnotationBbox(imagebox, xybox=(0.0, 0.05), **kw)
        self.title_3.add_artist(ab)
        # logo Oceanop
        img_today = read_png(os.path.join(dir_icon, 'oceanop_logo.png'))
        imagebox = OffsetImage(img_today, zoom=0.4)
        # opcao 1: logo ao lado do credito
        ab = AnnotationBbox(imagebox, xybox=(0.8, 0.1), **kw)
        self.title_3.add_artist(ab)

        # ----------------------------------------------------------------------
        # Cria mapa base
        # ----------------------------------------------------------------------
        # Coordenadas da estacao meteorologica # 22 24 4.02**41 48 29.30
        Xest, Yest = -41.808138888889, -22.401116666667
        # Coordenadas da janela da imagem 2223.936_4148.723_2224.175_4148.264
        Xmin, Xmax = -41.81205, -41.8044
        Ymin, Ymax = -22.402916666667, -22.398933333333
        # Mapa base com a localizacao da estacao
        m = Basemap(ax=map,
                    epsg=4326,
                    projection='merc',
                    llcrnrlat=Ymin,
                    urcrnrlat=Ymax,
                    llcrnrlon=Xmin,
                    urcrnrlon=Xmax,
                    resolution='c')

        imgfile = os.path.join(dir_icon,
                               '2223.936_4148.723_2224.175_4148.264.jpg')
        img = plt.imread(imgfile)
        m.imshow(img, origin='upper')

        # Plota pontos de interesse
        bprops = dict(boxstyle='round', facecolor='w', alpha=0.35)
        aprops2 = dict(arrowstyle='simple',
                       connectionstyle='arc3, rad=-0.2',
                       relpos=(0., 1.),
                       facecolor='k',
                       alpha=0.6)

        map.text(-41.8066588889,
                 -22.40111,
                 'EDINC',
                 horizontalalignment='center',
                 verticalalignment='center',
                 fontweight='bold',
                 fontsize=16,
                 color='k',
                 bbox=bprops)

        pest, = map.plot(Xest, Yest, 'ro', markersize=4)

        map.annotate(u"Estação\nMeteorológica",
                     xy=(Xest, Yest),
                     xycoords='data',
                     xytext=(-41.809, -22.403),
                     size=12,
                     va='top',
                     ha='left',
                     arrowprops=aprops2,
                     bbox=bprops,
                     fontweight='bold')

        # Insere seta apontando para o norte no canto inferior direito
        imgfile = read_png(os.path.join(dir_icon, 'north_arrow.png'))
        imagebox = OffsetImage(imgfile, zoom=0.11)
        lonmin, lonmax = m.boundarylonmin, m.boundarylonmax
        latmin, latmax = min(m.boundarylats), max(m.boundarylats)
        xy = (lonmax - 0.08 * (lonmax - lonmin),
              latmax - 0.9 * (latmax - latmin))
        ab = AnnotationBbox(imagebox,
                            xy,
                            frameon=False,
                            xycoords="data",
                            boxcoords="data",
                            box_alignment=(0.0, 0.0))
        map.add_artist(ab)

        fontdict = {
            'color': 'w',
            'va': 'center',
            'ha': 'center',
            'fontsize': 13,
            'fontweight': 'bold'
        }
        self.i_vent = icon_vent.text(0.5, 0.8, 'NA', fontdict=fontdict)
        self.i_gust = icon_gust.text(0.5, 0.8, 'NA', fontdict=fontdict)
        self.i_umid = icon_umid.text(0.5, 0.75, 'NA', fontdict=fontdict)
        self.i_rain = icon_rain.text(0.5, 0.8, 'NA', fontdict=fontdict)
        self.i_pres = icon_pres.text(0.2, 0.7, 'NA', fontdict=fontdict)
        self.i_temp = icon_temp.text(0.25, 0.75, 'NA', fontdict=fontdict)
        self.i_feel = self.icon_feel.text(0.275, 0.75, 'NA', fontdict=fontdict)

        # Set icones e titulos
        axis_icon_names = [
            icon_pres, icon_vent, icon_umid, icon_rain, icon_gust, icon_pres,
            icon_temp, self.icon_feel, self.title_1, self.title_2, self.title_3
        ]
        for i in axis_icon_names:
            i.set_axis_off()

        # Set titulos nos graficos
        graf_vento.set_title(u'Vento [km/h]',
                             x=0.12,
                             y=0.75,
                             fontweight='bold',
                             fontsize=11)
        graf_press.set_title(u'Pressão Atmosférica [hPa]',
                             x=0.23,
                             y=0.75,
                             fontweight='bold',
                             fontsize=11)
        graf_umid.set_title(u'Umidade Relativa [%]',
                            x=0.19,
                            y=0.75,
                            fontweight='bold',
                            fontsize=11)
        graf_temp.set_title(u'Temperatura do Ar [\N{DEGREE SIGN}C]',
                            x=0.205,
                            y=0.75,
                            fontweight='bold',
                            fontsize=11)
        map.set_title(u'Localização da Estação Meteorólogica',
                      fontsize=15,
                      fontweight='bold',
                      loc='left',
                      y=1.05)

        self.canvasFig = fig
        #             [0]wind, [1]humi, [2]pres, [3]temp
        self.cor = ['#4CB050', '#2196F5', '#FF9702', '#F44236']
        x, y = [], []

        self.line0, = graf_vento.plot(x, y, self.cor[0])
        self.line1, = graf_umid.plot(x, y, self.cor[1])
        self.line2, = graf_rain.plot(x, y, self.cor[1], linestyle='--')
        self.line3, = graf_press.plot(x, y, self.cor[2])
        self.line4, = graf_temp.plot(x, y, self.cor[3])

        icon_vento_dir.axes.yaxis.set_ticklabels([])
        icon_rose.axes.yaxis.set_ticklabels([])

        self.canvas = FigureCanvasTkAgg(fig, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=Tkinter.TOP,
                                         fill=Tkinter.BOTH,
                                         expand=1)
        self.canvas._tkcanvas.pack(side=Tkinter.TOP,
                                   fill=Tkinter.BOTH,
                                   expand=1)

        self.after(500, self.icon_refresh, icon_vento_dir, icon_rose)
        self.update()
Beispiel #42
0
def visualize_ensemble_raster(crop, osc, raster_data, raster_mask, savepath,
                              save, cmap, colorbar_name, data_type):

    # Initialize the map figure using Basemap
    m = Basemap(
        projection='cyl',
        resolution='c',
        llcrnrlat=-60,
        urcrnrlat=90,
        llcrnrlon=-180,
        urcrnrlon=180,
    )

    fig = plt.figure()
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)

    # Create the colorscale, using RGB information and the function LinearSegmentedColormap
    if cmap == 'redblue':
        cdict = {
            'blue': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.49, 0.8, 0.9),
                     (0.51, 0.9, 1.0), (0.75, 1.0, 1.0), (1.0, 0.4, 1.0)),
            'green': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.49, 0.9, 0.9),
                      (0.51, 0.9, 0.9), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)),
            'red': ((0.0, 0.0, 0.4), (0.25, 1.0, 1.0), (0.49, 1.0, 0.9),
                    (0.51, 0.9, 0.8), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0))
        }
        clim = (-5, 5)
        cbar_label = 'Crop yield deviation (%) per unit index change'
        cmap = LinearSegmentedColormap('cmap', cdict)

    elif cmap == 'whiteblue':
        cdict = {
            'blue': ((0.0, 0.8, 0.9), (0.01, 0.9, 1.0), (0.5, 1.0, 1.0),
                     (1.0, 0.4, 1.0)),
            'green': ((0.0, 0.9, 0.9), (0.01, 0.9, 0.9), (0.5, 0.0, 0.0),
                      (1.0, 0.0, 0.0)),
            'red': ((0.0, 1.0, 0.9), (0.01, 0.9, 0.8), (0.5, 0.0, 0.0),
                    (1.0, 0.0, 0.0))
        }
        clim = (0, 100)
        cbar_label = 'Proportion of individual models that agree with the ensemble sensitivity sign'
        cmap = LinearSegmentedColormap('cmap', cdict)


# Modify settings for the raster visualization.
    raster_data = np.flipud(raster_data)
    raster_mask = np.flipud(raster_mask)
    mask_index = raster_mask * np.isnan(raster_data)
    raster_data[mask_index] = 0
    cs = m.imshow(raster_data[60:, :] * 100, clim=clim, cmap=cmap)

    m.drawcoastlines(linewidth=0.25)
    #    m.drawcountries(linewidth=0.25)
    m.fillcontinents(color='white', lake_color='white', zorder=0)

    m.drawmapboundary(fill_color='White')

    # Save the figure.
    if save == 1:
        os.chdir(savepath)
        plt.savefig(crop + '_' + osc + '_' + data_type + '.png',
                    dpi=300,
                    bbox_inches='tight')
    plt.show(m)
    # If colorbar for sensitivity doesn't exist in folder, create it.
    if colorbar_name not in os.listdir(savepath):
        # add colorbar
        plt.figure()
        cs = plt.imshow(raster_data[60:, :] * 100, clim=clim, cmap=cmap)
        plt.gca().set_visible(False)
        cbar = plt.colorbar(cs, extend='both', orientation='horizontal')
        cbar.set_label(cbar_label, fontsize=12)
        plt.savefig(colorbar_name, dpi=300, bbox_inches='tight')
Beispiel #43
0
            zl = zl[::d][:,::d]
            
            
            return xl, yl, zl
        
        lont, latt, zt = get_xyz()
        zt = zt.T
        lont, latt = np.meshgrid(lont, latt)
        
        # n = 1000
        # nx = 1 + int( (map.xmax-map.xmin)/n )
        # ny = 1 + int( (map.ymax-map.ymin)/n )
        nx = 2000; ny = 3000
        topodat = map.transform_scalar(zt, lont[0,:], latt[:,0], nx, ny)
        # im = map.imshow(topodat * 0 + 1, cmap=plt.get_cmap('Greys'), alpha = 1,interpolation = 'bilinear', rasterized=True)
        im = map.imshow(topodat, cmap=plt.get_cmap('terrain'), alpha = 1,interpolation = 'bilinear', rasterized=True)
    
    
        xt, yt = map(lont, latt)
        ls = LightSource(azdeg=315, altdeg=45)
        hs = ls.hillshade(zt, 
                    vert_exag = 2, dx=xt[0,1] - xt[0,0] , dy=yt[0,0] - yt[1,0])
        hs = map.transform_scalar(hs, lont[0,:], latt[:,0], nx, ny)
        map.imshow(hs, cmap = 'gray', alpha = .5,interpolation = 'bilinear', rasterized=True)
#%%
    
    # plt.xlim([0, width]); plt.ylim([0, height])
    # map.drawmapboundary(fill_color=None)
    # map.fillcontinents(color='lightgrey',lake_color=None)
    # map.shadedrelief()
    # map.etopo(scale = 1)
Beispiel #44
0
#y = y - ay
#z = z - az
try:
    data, indices = h[x, y, z]
except (ValueError):
    data = h[x, y, z]
data.shape = lats.shape

map.drawmapboundary()
map.drawmeridians(n.arange(0, 360, 30))
map.drawparallels(n.arange(0, 90, 10))

if opts.max is None: max = data.max()
else: max = opts.max
if opts.drng is None:
    min = data.min()
#    if min < (max - 10): min = max-10
else:
    min = max - opts.drng
step = (max - min) / 10
levels = n.arange(min - step, max + step, step)
print min, max
#data = data.clip(min, max)
#data = n.ma.array(data, mask=mask)
#min=0
map.imshow(data, vmax=max, vmin=min, cmap=cmap)
#map.contourf(cx,cy,data,levels,linewidth=0,cmap=cmap)
p.colorbar()

p.show()
Beispiel #45
0
masked_chan31 = np.ma.masked_invalid(chan31)
fig, ax = plt.subplots(1, 1, figsize=(14, 14))
basemap_args = result_dict['basemap_args']
basemap_args['ax'] = ax
basemap_args['resolution'] = 'c'
bmap = Basemap(**basemap_args)
lat_sep, lon_sep = 5, 5
parallels = np.arange(30, 60, lat_sep)
meridians = np.arange(-135, -100, lon_sep)
bmap.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10, latmax=90)
bmap.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10, latmax=90)
bmap.drawcoastlines(linewidth=1.5, linestyle='solid', color='k')

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    col = bmap.imshow(masked_chan31, origin='upper', norm=the_norm, cmap=cmap)
    cax, kw = matplotlib.colorbar.make_axes(ax,
                                            location='bottom',
                                            pad=0.05,
                                            shrink=0.7)
    out = fig.colorbar(col, cax=cax, extend='both', **kw)
    out.set_label('Chan 31 radiance (W/m^2/micron/sr)', size=20)
    ax.set_title('Chan 31 radiance vancouver', size=25)
    print(kw)

# In[8]:

wavel = 11.e-6  #chan 31 central wavelength, meters
chan31_mks = result_dict['channels'][:, :, 0] * 1.e6  #W/m^2/m/sr
Tbright = planckInvert(wavel, chan31_mks)
Tbright = Tbright - 273.15  #convert to Centigrade
Beispiel #46
0
    ##############################################################################

    print('Reading netCDF file...')
    nc = NetCDFFile(ncf)

    data = nc.variables['z'][:]
    lons = nc.variables['x'][:]
    lats = nc.variables['y'][:]

    # transform to metres
    nx = int((m.xmax - m.xmin) / 500.) + 1
    ny = int((m.ymax - m.ymin) / 500.) + 1

    hazdat = m.transform_scalar(data, lons, lats, nx, ny)

    im = m.imshow(hazdat, cmap=cmap, norm=norm, alpha=1.0)

    ##########################################################################################
    # get land & lake polygons for masking
    ##########################################################################################
    # mask non-AU polygons
    nonmask = [0, 1, 2, 3, 4, 6, 7, 11, 13, 16, 17]  # polygon number
    nonmask = [0, 9, 14, 17, 18, 19]  # polygon number
    landpolys = []
    for pidx, polygon in enumerate(m.landpolygons):
        maskPoly = True
        for nmidx in nonmask:
            if pidx == nmidx:
                maskPoly = False
        if maskPoly == True:
            poly = polygon.get_coords()
Beispiel #47
0
def main():
    global inputArgs, grib, dir_path  #Make our global vars: grib is the object that will hold our Grib Class.
    dir_path = os.path.dirname(os.path.realpath(__file__))
    comparison_days = [0, -7]
    inputArgs = handle_args(
        sys.argv)  #All input arguments if run on the command line.
    for deltaDay in comparison_days:
        # MAKE SURE TO UNCOMMENT #inputArgs.date2 when putting back into production
        if deltaDay == 0:
            date2 = None
        else:
            date2 = ((datetime.datetime.now(pytz.timezone('US/Pacific'))) +
                     datetime.timedelta(days=deltaDay)).strftime("%Y%m%d")

        ##############
        # Debugging
        inputArgs.date = (datetime.datetime.today() -
                          datetime.timedelta(days=1)).strftime("%Y%m%d")
        #inputArgs.date = time.strftime("%Y%m%d")
        #inputArgs.date = str(dayNum)
        inputArgs.date2 = date2  #Comment this out for just one date
        inputArgs.map = True  # Make the map and save png to folder.
        inputArgs.plot = False
        findValueAtPoint = False  # Find all the values at specific lat/lng points within an excel file.
        #################
        grib = Grib()  #Assign variable to the Grib Class.
        grib.model = inputArgs.model  #Our model will always be "snodas" for this program
        grib.displayunits = inputArgs.displayunits
        grib.basin = inputArgs.basin  # Basin can be "French_Meadows", "Hell_Hole", or "MFP", this gets shapefile

        # Bounding box will clip the raster to focus in on a region of interest (e.g. CA) This makes the raster MUCH smaller
        # and easier to work with. See gdal.Open -> gdal.Translate below for where this is acutally used.
        grib.bbox = [
            -125.0, 50.0, -115.0, 30.0
        ]  #[upper left lon, upper left lat, lower left lon, lower left lat]
        grib = get_snowdas(
            grib, inputArgs.date
        )  #Get the snodas file and save data into the object variable grib
        #pngFile = makePNG()
        #Any reprojections of grib.gribAll have already been done in get_snowdas.
        #The original projection of snodas is EPSG:4326 (lat/lng), so it has been changed to EPSG:3875 (x/y) in get_snodas
        projInfo = grib.gribAll.GetProjection()

        geoinformation = grib.gribAll.GetGeoTransform(
        )  #Get the geoinformation from the grib file.

        xres = geoinformation[1]
        yres = geoinformation[5]
        xmin = geoinformation[0]
        xmax = geoinformation[0] + (xres * grib.gribAll.RasterXSize)
        ymin = geoinformation[3] + (yres * grib.gribAll.RasterYSize)
        ymax = geoinformation[3]

        spatialRef = osr.SpatialReference()
        spatialRef.ImportFromWkt(projInfo)
        spatialRefProj = spatialRef.ExportToProj4()

        # create a grid of xy (or lat/lng) coordinates in the original projection
        xy_source = np.mgrid[xmin:xmax:xres, ymax:ymin:yres]
        xx, yy = xy_source

        # A numpy grid of all the x/y into lat/lng
        # This will convert your projection to lat/lng (it's this simple).
        lons, lats = Proj(spatialRefProj)(xx, yy, inverse=True)

        # Find the center point of each grid box.
        # This says move over 1/2 a grid box in the x direction and move down (since yres is -) in the
        # y direction. Also, the +yres (remember, yres is -) is saying the starting point of this array will
        # trim off the y direction by one row (since it's shifted off the grid)
        xy_source_centerPt = np.mgrid[xmin + (xres / 2):xmax:xres,
                                      ymax + (yres / 2):ymin:yres]
        xxC, yyC = xy_source_centerPt

        lons_centerPt, lats_centerPt = Proj(spatialRefProj)(xxC,
                                                            yyC,
                                                            inverse=True)

        if grib.basin != "Hell_Hole":
            mask = createMask(xxC, yyC, spatialRefProj)
            grib.basinTotal, grib.basinSWE = calculateBasin(
                mask, grib, xres, yres)

        # The shape file for the Hell Hole basin includes the SMUD domain. Therefore, if we want to extract the SMUD
        # domain, then we will create another mask on top of the Hell Hole mask. This means that any grid point
        # outside of both domains will still = 0. The SMUD domain will contain it's mask AND the Hell Hole mask.
        if grib.basin == 'Hell_Hole':
            grib.basin = 'Hell_Hole_SMUD'  #This is just to get the correct directory structure
            submask = createMask(
                xxC, yyC, spatialRefProj
            )  # All areas in array = to 1 will be in SMUD's basin
            smud_BasinArea = grib.basinArea  # Used to remove SMUD's basin area (in m^2) from Hell_Hole's basin.
            # Get SMUD's information for the SMUD submask
            grib.SMUDbasinTotal, grib.SMUDbasinSWE = calculateBasin(
                submask, grib, xres, yres)

            grib.basin = 'Hell_Hole'  # reset back
            mask = createMask(
                xxC, yyC, spatialRefProj
            )  #This will be the entire Hell Hole basin, which includes SMUD
            hhMask = mask + submask  # Hell hole basin is now anywhere where hhMask = 1 and SMUD is anywhere it = 2
            hhMask[hhMask !=
                   1] = 0  # Set anything outside of Hell Hole's mask = 0
            grib.basinArea = grib.basinArea - smud_BasinArea  # grib.basinArea currently includes smuds basin, so remove it.

            # Get HellHoles's information from the hell hole submask
            grib.basinTotal, grib.basinSWE = calculateBasin(
                hhMask, grib, xres, yres)
            print("Current Basin Total: " + str(grib.basinTotal) +
                  " SMUD Total: " + str(grib.SMUDbasinTotal))
            #grib.basinTotal = grib.basinTotal - (0.92 * smudBasinTotal[0])
            mask = hhMask  # Need to do this so we can use the correct mask in compareDates and in calculateByElevation

        # Calculate the difference between two rasters
        if inputArgs.date2 != None:
            grib.basinTotal, grib.basinSWE = compareDates(
                mask, grib, xres, yres)

        #Need to do this after Hell_Hole's data has been manipulated (to account for SMUD)
        elevation_bins = calculateByElevation(mask, grib, xres, yres)

        #Send data for writing to Excel File
        if deltaDay == 0:
            excel_output(elevation_bins)

        if inputArgs.plot == True:
            makePlot(elevation_bins, deltaDay)
        print(elevation_bins)

        print(inputArgs.date, " Basin Total: ", grib.basinTotal)

        #findValue will return a dataframe with SWE values at various lat/lng points.
        df_ptVal = None
        if findValueAtPoint == True:
            df_ptVal = findPointValue(spatialRefProj, xy_source)

        if inputArgs.map == True:
            fig = plt.figure()
            ax = fig.add_subplot(111)
            m = Basemap(llcrnrlon=-122.8,
                        llcrnrlat=37.3,
                        urcrnrlon=-119.0,
                        urcrnrlat=40.3,
                        ax=ax)

            #m.arcgisimage(service='World_Imagery', xpixels=2000, verbose=True)
            im = Image.open(
                urlopen(
                    "http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/export?bbox=-122.8,37.3,-119.0,40.3&bboxSR=4326&imageSR=4326&size=2000,1578&dpi=96&format=png32&transparent=true&f=image"
                ))
            m.imshow(im, origin='upper')

            #For inset
            # loc =>'upper right': 1,
            # 'upper left': 2,
            # 'lower left': 3,
            # 'lower right': 4,
            # 'right': 5,
            # 'center left': 6,
            # 'center right': 7,
            # 'lower center': 8,
            # 'upper center': 9,
            # 'center': 10
            axin = inset_axes(m.ax, width="40%", height="40%", loc=8)

            m2 = Basemap(llcrnrlon=-120.7,
                         llcrnrlat=38.7,
                         urcrnrlon=-120.1,
                         urcrnrlat=39.3,
                         ax=axin)

            im2 = Image.open(
                urlopen(
                    "http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/export?bbox=-120.7,38.7,-120.09999999999998,39.3&bboxSR=4326&imageSR=4326&size=2000,1999&dpi=96&format=png32&transparent=true&f=image"
                ))
            m2.imshow(im2, origin='upper')

            #m2.arcgisimage(service='World_Imagery', xpixels=2000, verbose=True)
            mark_inset(ax, axin, loc1=2, loc2=4, fc="none", ec="0.5")

            ###################################DEBUGGING AREA###############################################################
            # Debugging: Test to prove a given lat/lng pair is accessing the correct grid box:

            #*********TEST 1: Test for center points
            #grib.data[0,0] = 15 #increase the variable by some arbitrary amount so it stands out.
            #xpts, ypts = m(lons_centerPt[0,0],lats_centerPt[0,0]) #This should be in the dead center of grid[0,0]
            #m.plot(xpts,ypts, 'ro')

            #*********TEST 2: Test for first grid box
            # Test to see a if the point at [x,y] is in the upper right corner of the cell (it better be!)
            #xpts, ypts = m(lons[0, 0], lats[0, 0])  # should be in upper right corner of cell
            #m.plot(xpts, ypts, 'bo')

            # *********TEST 3: Test for first grid box
            # Test to see the location of center points of each grid in polygon
            # To make this work, uncomment the variables in def create_mask
            #debug_Xpoly_center_pts, debug_Ypoly_center_pts = m(debugCenterX, debugCenterY)
            #m.plot(debug_Xpoly_center_pts, debug_Ypoly_center_pts, 'bo')

            # *********TEST 4: Test grid box size (In lat lng coords)
            # This is for use in a Basemap projection with lat/lon (e.g. EPSG:4326)
            #testX = np.array([[-120.1, -120.1], [-120.10833, -120.10833]])
            #testY = np.array([[39.0, 39.00833], [39.0, 39.00833]])
            # testVal = np.array([[4,4],[4,4]])

            # For use in basemap projection with x/y (e.g. espg:3857. In m=basemap just include the argument projection='merc')
            # testX = np.array([[500975, 500975], [(500975 + 1172), (500975 + 1172)]])
            # testY = np.array([[502363, (502363 + 1172)], [502363, (502363 + 1172)]])
            #testVal = np.array([[18, 18], [18, 18]])
            #im1 = m.pcolormesh(testX, testY, testVal, cmap=plt.cm.jet, vmin=0.1, vmax=10, latlon=False, alpha=0.5)

            # Test to see all points
            # xtest, ytest = m(lons,lats)
            # m.plot(xtest,ytest, 'bo')
            ################################################################################################################

            hr = 0
            makeMap(lons, lats, hr, m, m2, df_ptVal, deltaDay)
    return
Beispiel #48
0
            llcrnrlat=22,
            urcrnrlon=-64,
            urcrnrlat=49,
            projection='lcc',
            lat_1=33,
            lat_2=45,
            lon_0=-95)
# create masked array, reversing data in latitude direction
# (so that data is oriented in increasing latitude, as transform_scalar requires).
topoin = ma.masked_values(array[::-1, :], -999.)
# transform DEM data to a 4 km native projection grid
nx = int((m.xmax - m.xmin) / 4000.) + 1
ny = int((m.ymax - m.ymin) / 4000.) + 1
topodat = m.transform_scalar(topoin, lons, lats, nx, ny, masked=True)
# plot DEM image on map.
im = m.imshow(topodat, cmap=cm.GMT_haxby_r)
# draw meridians and parallels.
m.drawparallels(np.arange(20, 71, 10), labels=[1, 0, 1, 0])
m.drawmeridians(np.arange(-120, -40, 10), labels=[0, 1, 0, 1])
# plot state boundaries from shapefile using ogr.
g = ogr.Open("st99_d00.shp")
L = g.GetLayer(0)  # data is in 1st layer.
for feat in L:  # iterate over features in layer
    geo = feat.GetGeometryRef()
    # iterate over geometries.
    for count in range(geo.GetGeometryCount()):
        geom = geo.GetGeometryRef(count)
        if not geom.GetGeometryCount():  # just one geometry.
            # get lon,lat points
            lons = [geom.GetX(i) for i in range(geom.GetPointCount())]
            lats = [geom.GetY(i) for i in range(geom.GetPointCount())]
topodat = m.transform_scalar(data, lons, lats, nx, ny)

print('Getting colormap...')
# get colormap
cptfile = '//Users//trev//Documents//DATA//GMT//cpt//mby_topo-bath.cpt'
#cptfile = '//Users//tallen//Documents//DATA//GMT//cpt//gray.cpt'
cmap, zvals = cpt2colormap(cptfile, 256)
cmap = remove_last_cmap_colour(cmap)

# make shading
print('Making map...')
ls = LightSource(azdeg=180, altdeg=45)
norm = mpl.colors.Normalize(vmin=-8000 / zscale, vmax=5000 / zscale)  #myb
rgb = ls.shade(topodat, cmap=cmap, norm=norm)
im = m.imshow(rgb, alpha=0.6)
'''
##########################################################################################
# add epicentres
##########################################################################################

ncols = 18

# get year range
minyear = 10*floor(cat.data['year'][0]/10.)
maxyear = cat.data['year'][-1]
yearrng = float(round(maxyear - minyear))
#cmap = plt.cm.get_cmap('Spectral', ncols)

cptfile = '/Users/trev/Documents/DATA/GMT/cpt/temperature.cpt'
#cptfile = '/Users/trev/Documents/DATA/GMT/cpt/grayscale08.cpt'
Beispiel #50
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 13 15:54:40 2019

@author: Administrator
"""

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from osgeo import gdal

map = Basemap(projection='cyl',
              lat_0=0,
              lon_0=0,
              llcrnrlon=85,
              llcrnrlat=25,
              urcrnrlon=90,
              urcrnrlat=30)

#读取tiff
ds = gdal.Open("sample_files/dem/srtm_54_07.img")
data = ds.ReadAsArray()

map.imshow(data, cmap=plt.get_cmap('terrain'), alpha=0.5)

plt.show()
Beispiel #51
0
class CoordinateHelper(object):
    def __init__(self, x=None,y=None, zone=None, zone_number=None,  zone_letter=None, mm=None, bbox_expand=0.05, projection='merc', **kwargs):
        self.expand = bbox_expand
        if zone and not (zone_number and zone_letter):
            self._zone_number = int(zone[0:2])
            self._zone_letter = zone[2:3]
        else:
            self._zone_number=zone_number
            self._zone_letter = zone_letter
        self.zone_numbers = None
        self.zone_letters = None
        self.set_xy(x,y)
        if not x is None:
            if not mm:
                self.mm = self.get_basemap(projection=projection, **kwargs)
            elif isinstance(mm, Basemap):
                self.mm = mm
            else:
                raise ValueError('bmap must be a mpl_toolkits.basemap.Basemap but is a {type(mm)}')
        
        
    def set_xy(self,x,y, ctype=None):
        self.x = np.array(x)
        self.y = np.array(y)
        if self.x.shape != self.y.shape:
            raise ValueError(f'x and y must have same shape! ({self.x.shape} != {self.y.shape})')
        if ctype in ['latlon', 'img', 'utm']:
            self.type = ctype
        else:
            self._detect_type()
#        try:

        if not self._zone_number is None:
            self.zone_numbers = np.tile(self._zone_number, self.x.shape)
            if not self._zone_letter is None:
                self.zone_letters = np.tile(self._zone_letter, self.x.shape)
                return

        self.zone_numbers, self.zone_letters = self._get_zones()
#        self.zone_numbers = zone_numbers
#        print(zone_numbers, zone_letters )
#                self.zone_letter = zone_letter
#                and not self.zone_letter is None:
#            if (self.zone_number, self.zone_letter) != (zone_number, zone_letter):
#                Warning('The zone for the new data ((zone_number, zone_letter)} does not correspond to the zone already initialized ({self.zone_number, self.zone_letter}).')
#        except Exception as ex:
#            print(ex)
        
            
    def _detect_type(self):
#        print(self.y, type(self.y))
        if all([np.all((-180<=c) & (c<=180)) for c in (self.x,self.y)]):
            self.type = 'latlon'
            y = self.y
            self.y = self.x
            self.x = y
        elif all([np.all((0<c) & (c<1e5)) for c in (self.x,self.y)]):
            self.type = 'img'
        elif all([np.all((0<c) & (c<1e7)) for c in (self.x,self.y)]):
            self.type = 'utm'
        else:
            raise ValueError('Could not detect coord type (latlon/utm/img) based on data ranges')
        print(f'{self.type} detected')

    def get_bbox_latlon(self, format='latlon'):
        lat,lon = self.to_latlon()
        lonm = lon.min()
        lonM = lon.max()
        latm = lat.min()
        latM = lat.max()
        lonex = (lonM-lonm)*self.expand/2
        latex = (latM-latm)*self.expand/2
        if format=='basemap':
            return {
                'llcrnrlon':lonm - lonex,
                'llcrnrlat':latm - latex,
                'urcrnrlon':lonM + lonex,
                'urcrnrlat':latM + latex
            }
        elif format[0:6]=='lonlat':
            bbox = (
                lonm - lonex,
                latm - latex,
                lonM + lonex,
                latM + latex
            )
        else:
            bbox = (
                latm - latex,
                lonm - lonex,
                latM + latex,
                lonM + lonex
            )
        if format[-1]==',':
            return (bbox[0:2], bbox[2:4])
        else:
            return bbox
    
    def get_bbox_utm(self):
        bbox = self.get_bbox_latlon(format='latlon')
        return tuple([utm.from_latlon(lat, lon)[0:2] for lat,lon in  zip(bbox[::2], bbox[1::2])])

    def get_basemap(self, **kwargs):
        self.mm = Basemap(**self.get_bbox_latlon(format='basemap'), **kwargs)
        return self.mm

    def get_osm_zoom_level(self, bbox):
        m0 = 156412
        bbox = self.get_bbox_latlon(format='latlon,')
        dlat = bbox[1][0]-bbox[0][0]
        dlon = bbox[1][1] - bbox[0][1]
        level_diff =np.abs(np.array([360/2**x for x in range(20)])-max(dlat, dlon))
        level = level_diff.argmin()+2
        print(f'OSM level {level} selected to display minimum {max(dlat, dlon)} degrees')
        return level
        
    def get_osm(self, *args, provider='osm', **kwargs):
        #geotiler cannot handle the bbox to be of type numpy, so convert to native floats:
        bbox = [x.item() for x in self.get_bbox_latlon(format='lonlat')]
        gm = geotiler.Map(extent=bbox, zoom=self.get_osm_zoom_level(bbox), provider=provider)
        self.img = geotiler.render_map(gm)
        return self.mm.imshow(self.img, *args, interpolation='lanczos', origin='upper', **kwargs)

    def to_img(self):
        if self.type=='img':
            return (self.x, self.y)
        else:
            if isinstance(self.mm, Basemap):
                if self.type=='latlon':
                    return self.mm(self.x,self.y, latlon=True)
                elif self.type=='utm':
                    f = np.vectorize(utm.to_latlon)
                    return self.mm(f(self.x,self.y, zone_number=self.zone_numbers, zone_letter=self.zone_letters), latlon=True)
            else:
                raise AttributeError('Cannot convert image coordinates to latlon as no basemap is defined!')

    def to_utm(self):
        f = np.vectorize(utm.from_latlon)
        if self.type=='latlon':
            return f(self.x,self.y)[0:2]
        elif self.type=='utm':
            return (self.x, self.y)
        elif self.type=='img':
            if isinstance(self.mm, Basemap):
                return f(self.mm(self.x, self.y))[0:2]
            else:
                raise AttributeError('Cannot convert image coordinates to UTM as no basemap is defined!')

    def to_lonlat(self):
        lat, lon = self.to_latlon()
        return (lon, lat)

    def to_latlon(self):
        if self.type=='latlon':
            return (self.x, self.y)
        elif self.type=='utm':
            f = np.vectorize(utm.to_latlon)
            return f(self.x,self.y, zone_number=self.zone_numbers, zone_letter=self.zone_letters)
        elif self.type=='img':
            if isinstance(self.mm, Basemap):
                return self.mm(self.x, self.y)
            else:
                raise AttributeError('Cannot convert image coordinates to latlon as no basemap is defined!')

    def _get_zones(self):
        f_letter = np.vectorize(utm.latitude_to_zone_letter)
        f_number = np.vectorize(utm.latlon_to_zone_number)
        lat, lon = self.to_latlon()
        zone_numbers = f_number(lat,lon)
        zone_letters = f_letter(lat)
        if len(set(zip(zone_numbers.ravel(), zone_letters.ravel()))) !=1:
            print(f'Coordinates are spread across several UTM zones {[str(n) + l for n,l in set(zip(zone_numbers.ravel(), zone_letters.ravel()))]}')
        return zone_numbers, zone_letters
Beispiel #52
0
except:
    # Draw some map elements on the map
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.drawrivers(color='blue')
    print ("Normal map")
#m.drawcoastlines( linewidth=0.1, color='k' )
# m.fillcontinents(color=land,lake_color=water,zorder=99)  
# ax.set_extent([lllon,urlon,lllat,urlat],crs=ccrs.PlateCarree())
# ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor=land),zorder=100)
# #
m.drawparallels([lllat,urlat], labels = [1,0,0,0], fontsize=10,linewidth=0,zorder=102)
m.drawmeridians([lllon,urlon], labels = [0,0,0,1], fontsize=10,linewidth=0,zorder=102)
data = ma.masked_less_equal(visual[npix:spix,wpix:epix],2)
im=m.imshow(data,interpolation="nearest",origin="upper",cmap=cmapL,norm=norml,zorder=110) # interpolation="nearest",origin="upper",
# print (lon,lat)
# m.scatter(lon,lat,s=0.5,marker="o",zorder=110,edgecolors="g", facecolors="g")#,transform=ccrs.PlateCarree()) #, 
ax0.plot(lon ,lat ,color="g",marker="o",label="intitial",markersize=7,zorder=111) #fillstyle="none",
#================
kx1= kx1lt[point]
ky1= ky1lt[point]
lat1 = south + 10.0 - res/2.0 - ky1*res  
lon1 = west + res/2.0 + kx1*res
ax0.plot(lon1 ,lat1 ,color="r",marker="o",label="best-loc",markersize=7,zorder=112) #fillstyle="none",
#================
kx2= kx2lt[point]
ky2= ky2lt[point]
if kx2 != -9999 and ky2 != -9999:
    lat2 = south + 10.0 - res/2.0 - ky2*res  
    lon2 = west + res/2.0 + kx2*res
Beispiel #53
0
bwr_cmap = plt.get_cmap('bwr')
cdict_new = bwr_cmap._segmentdata.copy()
cdict_new['alpha'] = ((0.0, 1.0, 1.0),
                #   (0.25,1.0, 1.0),
                   (0.6, 0.4, 0.0),
                #   (0.75,1.0, 1.0),
                   (1.0, 1.0, 1.0))
blue_red1 = LinearSegmentedColormap('BlueRed1', cdict_new)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

## Instantiate the Basemap - all subsequent images will be applied directly to the map. 
m = Basemap(llcrnrlon=lon0, llcrnrlat=lat0, urcrnrlon=lon1, urcrnrlat=lat1, resolution='l', lat_0=lat0, lon_0=lon0)
# grab the openstreetmaps image
osm_image = misc.imread('map.png')
#plot it onto the map
m.imshow(osm_image, extent=[lon0, lat0, lon1, lat1], origin='upper', aspect='auto')
##

## READ THE DATA: 
# read in the undocking data
undocking_dataframe = pd.read_csv('2013-07-CitiBikeTripData.csv', usecols=[1,5,6], index_col=0, parse_dates=True)
#read in the docking datax
docking_dataframe_unsorted = pd.read_csv('2013-07-CitiBikeTripData.csv', usecols=[2,9,10], index_col=0, parse_dates=True)
docking_dataframe = docking_dataframe_unsorted.sort_index()

# find the first timestamp
initial_start_date_undocking = undocking_dataframe.index[0]

# ims will hold the series of images that make up the animation
ims = []
# determine the number of frames in the animation
Beispiel #54
0
z_02 = griddata(xy1_igrid, z_igrid_02, (xi, yi), method='cubic')
z_03 = griddata(xy1_igrid, z_igrid_03, (xi, yi), method='cubic')

rgb_projected = np.zeros((1000, 1000, 3))
for i in np.arange(1000):
    for j in np.arange(1000):
        rgb_projected[i, j, 0] = z_01[i, j]
        rgb_projected[i, j, 1] = z_02[i, j]
        rgb_projected[i, j, 2] = z_03[i, j]

#rgb_projected[ z > 1 ] = 1.0
#rgb_projected[ z < 0 ] = 0.0
whereAreNaNs = np.isnan(rgb_projected)
rgb_projected[whereAreNaNs] = 0.75

img = m.imshow(np.rot90(np.fliplr(rgb_projected)), origin='lower')

m.drawcoastlines()

m.drawparallels(np.arange(-90., 120., 5.),
                color='k',
                labels=[True, False, False, False])
m.drawmeridians(np.arange(0., 420., 5.),
                color='k',
                labels=[False, False, False, True])

ax.set_xlabel("", fontsize=10)
ax.set_ylabel("", fontsize=10)

#boundingbox = [60.0, 29.0, 52.5, 45.0]
lats = [52.5, 52.5, 60., 60.]
Beispiel #55
0
 basemap_kws = dict(resolution='c', ax=the_ax)
 basemap_kws.update(project_channels['basemap_args'])
 bmap = Basemap(**basemap_kws)
 if index == 3:
     channel = project_channels['channels'][:, :, 0] - project_channels[
         'channels'][:, :, 1]
     chan_list.append('1-4')
     cmap = cmap_div
     cbar_label = 'reflectivity difference'
 elif index == 2:
     channel = project_channels['channels'][:, :, index]
     cbar_label = 'radiance W/m^2/sr/um'
 else:
     cbar_label = 'reflectance'
     channel = project_channels['channels'][:, :, index]
 col = bmap.imshow(channel, origin='upper', cmap=cmap, **limits[index])
 bmap.drawparallels(parallels,
                    labels=[1, 0, 0, 0],
                    fontsize=10,
                    latmax=90)
 bmap.drawmeridians(meridians,
                    labels=[0, 0, 0, 1],
                    fontsize=10,
                    latmax=90)
 bmap.drawcoastlines()
 _ = the_ax.set(title='vancouver chan {}'.format(chan_list[index]))
 colorbar = fig.colorbar(col,
                         shrink=0.5,
                         pad=0.05,
                         extend='both',
                         ax=the_ax)
Beispiel #56
0
chl_mat.mask = chl_mat == -999

m = Basemap(llcrnrlat=min(lat0),urcrnrlat=max(lat0),\
     llcrnrlon=min(lon0),urcrnrlon=max(lon0), resolution='l')
x, y = np.meshgrid(lon0, lat0)
m.drawparallels(parallel_steps,
                labels=[1, 0, 0, 1],
                color='grey',
                linewidth=0.1)
m.drawmeridians(meridian_steps,
                labels=[1, 0, 0, 1],
                color='grey',
                linewidth=0.1)
m.drawcoastlines(linewidth=0.1)
m.imshow(chl_mat,origin='upper', extent=[min(lon0), max(lon0), min(lat0), max(lat0)],\
                                           norm=LogNorm(),cmap='rainbow',interpolation='nearest')

clb = plt.colorbar(fraction=0.046, pad=0.05, orientation='horizontal')
#    clb.ax.set_xlabel('Absolute Density (counts)')

# wtm
ax = plt.subplot(2, 2, 2)
ax.set_title('wtm(0 =< p1/(p1+p2) =< 1')
current_cmap = plt.cm.get_cmap()
current_cmap.set_bad(color='white')

class_mask.mask = class_mask == -999

m = Basemap(llcrnrlat=min(lat0),urcrnrlat=max(lat0),\
     llcrnrlon=min(lon0),urcrnrlon=max(lon0), resolution='l')
x, y = np.meshgrid(lon0, lat0)
Beispiel #57
0
def map_haz(fig, plt, haz_map_file, sitelon, sitelat, **kwargs):
    '''
    kwargs:
        shpfile: path to area source - is a list of files
        resolution: c (crude), l (low), i (intermediate), h (high), f (full)
        mbuffer: map buffer in degrees
    '''

    from openquake.nrmllib.hazard.parsers import GMFScenarioParser
    from mpl_toolkits.basemap import Basemap
    from numpy import arange, array, log10, mean, mgrid, percentile
    from matplotlib.mlab import griddata
    from matplotlib import colors, colorbar, cm
    from os import path
    from mapping_tools import drawshapepoly, labelpolygon
    import shapefile

    # set kwargs
    drawshape = False
    res = 'c'
    mbuff = -0.3
    keys = ['shapefile', 'resolution', 'mbuffer']
    for key in keys:
        if key in kwargs:
            if key == 'shapefile':
                shpfile = kwargs[key]
                drawshape = True

            if key == 'resolution':
                res = kwargs[key]

            if key == 'mbuffer':
                mbuff = kwargs[key]

    gmfsp = GMFScenarioParser(haz_map_file).parse()
    metadata, values = parse_nrml_hazard_map(haz_map_file)

    hazvals = []
    latlist = []
    lonlist = []
    for val in values:
        lonlist.append(val[0])
        latlist.append(val[1])
        hazvals.append(val[2])

    # get map bounds
    llcrnrlat = min(latlist) - mbuff / 2.
    urcrnrlat = max(latlist) + mbuff / 2.
    llcrnrlon = min(lonlist) - mbuff
    urcrnrlon = max(lonlist) + mbuff
    lon_0 = mean([llcrnrlon, urcrnrlon])
    lat_1 = percentile([llcrnrlat, urcrnrlat], 25)
    lat_2 = percentile([llcrnrlat, urcrnrlat], 75)

    m = Basemap(llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat, \
                urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat,
                projection='lcc',lat_1=lat_1,lat_2=lat_2,lon_0=lon_0,
                resolution=res,area_thresh=1000.)

    m.drawcoastlines(linewidth=0.5, color='k')
    m.drawcountries()

    # draw parallels and meridians.
    m.drawparallels(arange(-90., 90., 1.),
                    labels=[1, 0, 0, 0],
                    fontsize=10,
                    dashes=[2, 2],
                    color='0.5',
                    linewidth=0.5)
    m.drawmeridians(arange(0., 360., 1.),
                    labels=[0, 0, 0, 1],
                    fontsize=10,
                    dashes=[2, 2],
                    color='0.5',
                    linewidth=0.5)

    # make regular grid
    N = 150j
    extent = (min(lonlist), max(lonlist), min(latlist), max(latlist))
    xs, ys = mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N]
    resampled = griddata(array(lonlist), array(latlist), log10(array(hazvals)),
                         xs, ys)

    #############################################################################
    # transform grid to basemap

    # get 1D lats and lons for map transform
    lons = ogrid[extent[0]:extent[1]:N]
    lats = ogrid[extent[2]:extent[3]:N]

    # transform to map projection
    if max(lonlist) - min(lonlist) < 1:
        transspace = 500
    elif max(lonlist) - min(lonlist) < 5:
        transspace = 1000
    elif max(lonlist) - min(lonlist) < 10:
        transspace = 2000
    else:
        transspace = 5000

    nx = int((m.xmax - m.xmin) / transspace) + 1
    ny = int((m.ymax - m.ymin) / transspace) + 1
    transhaz = m.transform_scalar(resampled.T, lons, lats, nx, ny)

    m.imshow(transhaz,
             cmap='Spectral_r',
             extent=extent,
             vmin=-2,
             vmax=log10(2.),
             zorder=0)

    # plot site
    xx, yy = m(sitelon, sitelat)
    plt.plot(xx, yy, '*', ms=20, mec='k', mew=2.0, mfc="None")

    # superimpose area source shapefile
    if drawshape == True:
        for shp in shpfile:
            sf = shapefile.Reader(shp)
            drawshapepoly(m, plt, sf, col='k', lw=1.5, polyline=True)
            labelpolygon(m, plt, sf, 'CODE', fsize=14)

    # set colourbar
    # set cb for final fig
    plt.gcf().subplots_adjust(bottom=0.1)
    cax = fig.add_axes([0.6, 0.05, 0.25, 0.02])  # setup colorbar axes.
    norm = colors.Normalize(vmin=-2, vmax=log10(2.))
    cb = colorbar.ColorbarBase(cax,
                               cmap=cm.Spectral_r,
                               norm=norm,
                               orientation='horizontal')

    # set cb labels
    #linticks = array([0.01, 0.03, 0.1, 0.3 ])
    logticks = arange(-2, log10(2.), 0.25)
    cb.set_ticks(logticks)
    labels = [str('%0.2f' % 10**x) for x in logticks]
    cb.set_ticklabels(labels)

    # get map probabiltiy from filename
    mprob = path.split(haz_map_file)[-1].split('_')[-1].split('-')[0]
    probstr = str(int(float(mprob) * 100))

    # set colourbar title
    if metadata['statistics'] == 'mean':
        titlestr = ''.join((metadata['imt'], ' ', metadata['sa_period'], ' s ', \
                            probstr,'% in ',metadata['investigation_time'][0:-2], \
                            ' Year Mean Hazard (g)'))
        #cb.set_ticklabels(labels)
        cb.set_label(titlestr, fontsize=12)

    return plt
import util
import sys, os
import d4PDF

srcdir = '/home/utsumi/mnt/lab_tank/utsumi/bams2020/XX-HPB_NAT-100/6hr/pgrad/2010/01'
idtime = datetime(2010,1,1,0)
edtime = datetime(2010,1,31,18)
ldtime = util.ret_lDTime(idtime, edtime, timedelta(hours=6))
ny,nx = 320,640

a1lat = d4PDF.Lat()
a1lon = d4PDF.Lon()
[[lllat,lllon],[urlat,urlon]] = [[-90,0],[90,360]]

a2out = np.zeros([ny,nx], 'int32')
a2zero= np.zeros([ny,nx], 'int32')
for dtime in ldtime:
    year,mon,day,hour = dtime.timetuple()[:4]
    srcpath = srcdir + '/pgrad.2010012806.320x640'
    srcpath = srcdir + '/pgrad.%04d%02d%02d%02d.320x640'%(year,mon,day,hour)
    a2in = np.fromfile(srcpath,'float32').reshape(ny,nx) 
    a2out = a2out + ma.masked_where(a2in>0, a2zero).filled(1).astype('int32')


figmap   = plt.figure()
axmap    = figmap.add_axes([0.1, 0.1, 0.8, 0.8])
M        = Basemap( resolution="l", llcrnrlat=lllat, llcrnrlon=lllon, urcrnrlat=urlat, urcrnrlon=urlon, ax=axmap)
im = M.imshow(ma.masked_equal(a2out,0), origin='lower',vmax=5)
plt.colorbar(im)
M.drawcoastlines()
plt.savefig('/home/utsumi/temp/bams2020/temp.centers.png')
        fi.write(str(anchor_positions_procrustes.tolist()) + "\n")
        fi.write(str(anchor_gt_positions.tolist()) + "\n")
        fi.write(str(pos_selfloc.tolist()) + "\n")
        fi.write(str(pos_selfloc_procrustes.tolist()) + "\n")
        # fi.write(str(tform.keys()) + "\n")
        # tform["rotation"] = tform["rotation"].tolist()
        # tform["translation"] = tform["translation"].tolist()
        # fi.write(str(tform.values()) + "\n")
        fi.write(str(stress) + "\n")
        fi.close()
        print "selfloc test results written to: \n" + results_file_selfloc

    if options.map:
        figure_map.canvas.set_window_title(
            args[0].split("/")[-1].split(".")[0] + "_map")
        basemap.imshow(img, interpolation='lanczos', origin='upper')
        i = 1
        if options.crop_ict:
            ax.axis([85, 230, 48, 140])
            basemap.drawmapscale(lon=6.06201,
                                 lat=50.77870,
                                 lon0=6.06201,
                                 lat0=50.77870,
                                 length=20,
                                 units='m',
                                 barstyle='fancy',
                                 fontsize=24,
                                 yoffset=1.2)
        else:
            basemap.drawmapscale(lon=bbox[0] - 0.1 * (bbox[0] - bbox[2]),
                                 lat=bbox[1] - 0.07 * (bbox[1] - bbox[3]),
Beispiel #60
0
def processing(path):
    """
    Generates images from NetCDF files
    pathDir: root direcotry with "Data", "Output" and "Scripts" folders
    pathFile: path to NetCDF file to be manipulated
    outFolder: path to directory where the generated images should be saved
    Output: .png image file
    """

    # Getting information from the file name ============================================================
    # Search for the GOES-16 channel in the file name
    INPE_Band_ID = (path[path.find("S10635") + 6:path.find("_")])
    # print(INPE_Band_ID)
    # Get the band number subtracting the value by 332
    Band = int(INPE_Band_ID) - 332

    # Create a GOES-16 Bands string array
    Wavelenghts = [
        '[]', '[0.47 μm]', '[0.64 μm]', '[0.865 μm]', '[1.378 μm]',
        '[1.61 μm]', '[2.25 μm]', '[3.90 μm]', '[6.19 μm]', '[6.95 μm]',
        '[7.34 μm]', '[8.50 μm]', '[9.61 μm]', '[10.35 μm]', '[11.20 μm]',
        '[12.30 μm]', '[13.30 μm]'
    ]
    Band_Wavelenght = Wavelenghts[int(Band)]
    # Search for the Scan start in the file name
    Start = (path[path.find(INPE_Band_ID + "_") + 4:path.find(".nc")])
    # Getting the date from the file name
    year = Start[0:4]
    month = Start[4:6]
    day = Start[6:8]
    date = day + "-" + month + "-" + year
    time = Start[8:10] + ":" + Start[
        10:12] + " UTC"  # Time of the Start of the Scan

    # Get the unit based on the channel. If channels 1 trough 6 is Albedo. If channels 7 to 16 is BT.
    Unit = "Albedo (%)"
    # Choose a title for the plot
    Title = " GOES-16 ABI CMI Band " + str(
        Band) + " " + Band_Wavelenght + " " + Unit + " " + date + " " + time
    # Insert the institution name
    Institution = "CEPAGRI - UNICAMP"
    # Required libraries ================================================================================

    # Open the file using the NetCDF4 library
    nc = Dataset(path)

    # Choose the visualization extent (min lon, min lat, max lon, max lat)
    extent = [-115.98, -55.98, -25.01, 34.98]
    min_lon = extent[0]
    max_lon = extent[2]
    min_lat = extent[1]
    max_lat = extent[3]

    # Get the latitudes
    lats = nc.variables['lat'][:]
    # Get the longitudes
    lons = nc.variables['lon'][:]

    # print (lats)
    # print (lons)

    # latitude lower and upper index
    latli = np.argmin(np.abs(lats - extent[1]))
    latui = np.argmin(np.abs(lats - extent[3]))

    # longitude lower and upper index
    lonli = np.argmin(np.abs(lons - extent[0]))
    lonui = np.argmin(np.abs(lons - extent[2]))

    # Extract the Brightness Temperature / Reflectance values from the NetCDF
    data = nc.variables['Band1'][latli:latui, lonli:lonui]

    # Flip the y axis, divede by 100
    data = (np.flipud(data) / 100)

    # Define the size of the saved picture ==============================================================
    DPI = 150
    ax = plt.figure(figsize=(2000 / float(DPI), 2000 / float(DPI)),
                    frameon=True,
                    dpi=DPI)
    #====================================================================================================

    # Plot the Data =====================================================================================
    # Create the basemap reference for the Rectangular Projection
    bmap = Basemap(llcrnrlon=extent[0],
                   llcrnrlat=extent[1],
                   urcrnrlon=extent[2],
                   urcrnrlat=extent[3],
                   epsg=4326)

    # Draw the countries and Brazilian states shapefiles
    bmap.readshapefile('/Scripts/GEONETCast/Shapefiles/BRA_adm1',
                       'BRA_adm1',
                       linewidth=0.50,
                       color='cyan')
    bmap.readshapefile(
        '/Scripts/GEONETCast/Shapefiles/ne_10m_admin_0_countries',
        'ne_10m_admin_0_countries',
        linewidth=0.50,
        color='cyan')

    # Draw parallels and meridians
    bmap.drawparallels(np.arange(-90.0, 90.0, 5.0),
                       linewidth=0.3,
                       dashes=[4, 4],
                       color='white',
                       labels=[False, False, False, False],
                       fmt='%g',
                       labelstyle="+/-",
                       xoffset=-0.80,
                       yoffset=-1.00,
                       size=7)
    bmap.drawmeridians(np.arange(0.0, 360.0, 5.0),
                       linewidth=0.3,
                       dashes=[4, 4],
                       color='white',
                       labels=[False, False, False, False],
                       fmt='%g',
                       labelstyle="+/-",
                       xoffset=-0.80,
                       yoffset=-1.00,
                       size=7)

    # Converts a CPT file to be used in Python
    cpt = loadCPT(
        '/Scripts/GEONETCast/Colortables/Square Root Visible Enhancement.cpt')
    # Makes a linear interpolation
    cpt_convert = LinearSegmentedColormap('cpt', cpt)
    # Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference)
    bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=0, vmax=100)

    # Insert the colorbar at the bottom
    cb = bmap.colorbar(location='bottom',
                       size='2%',
                       pad='-3.5%',
                       ticks=[20, 40, 60, 80])
    cb.ax.set_xticklabels(['20', '40', '60', '80'])
    cb.outline.set_visible(False)  # Remove the colorbar outline
    cb.ax.tick_params(width=0)  # Remove the colorbar ticks
    cb.ax.xaxis.set_tick_params(
        pad=-14.5)  # Put the colobar labels inside the colorbar
    cb.ax.tick_params(
        axis='x', colors='black',
        labelsize=8)  # Change the color and size of the colorbar labels

    # Add a black rectangle in the bottom to insert the image description
    lon_difference = (extent[2] - extent[0])  # Max Lon - Min Lon
    currentAxis = plt.gca()
    currentAxis.add_patch(
        Rectangle((extent[0], extent[1]),
                  lon_difference,
                  lon_difference * 0.015,
                  alpha=1,
                  zorder=3,
                  facecolor='black'))

    # Add the image description inside the black rectangle
    lat_difference = (extent[3] - extent[1])  # Max lat - Min lat
    plt.text(extent[0],
             extent[1] + lat_difference * 0.003,
             Title,
             horizontalalignment='left',
             color='white',
             size=10)
    plt.text(extent[2],
             extent[1] + lat_difference * 0.003,
             Institution,
             horizontalalignment='right',
             color='yellow',
             size=10)

    # Add logos / images to the plot
    logo_GNC = plt.imread('/Scripts/GEONETCast/Logos/GNC_Logo.png')
    logo_INPE = plt.imread('/Scripts/GEONETCast/Logos/INPE_Logo.png')
    logo_NOAA = plt.imread('/Scripts/GEONETCast/Logos/NOAA_Logo.png')
    logo_GOES = plt.imread('/Scripts/GEONETCast/Logos/GOES_Logo.png')
    logo_cepagri = plt.imread('/Scripts/GEONETCast/Logos/Logo_CEPAGRI.png')

    ax.figimage(logo_GNC, 20, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_INPE, 90, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_NOAA, 165, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_GOES, 228, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_cepagri, 326, 70, zorder=3, alpha=1, origin='upper')

    # Save the result
    # print('/Scripts/GEONETCast/Output/' + path[12:18] + '/INPE_G16_CH' + str(Band) + '_' + Start + '.png')
    plt.savefig('/Scripts/GEONETCast/Output/' + path[12:18] + '/INPE_G16_CH' +
                str(Band) + '_' + Start + '.png',
                dpi=DPI,
                bbox_inches='tight',
                pad_inches=0)