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)
Example #2
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)
Example #3
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")
Example #4
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
Example #5
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()
Example #6
0
def render_components(C, lats, lons, fname_tmpl = None, ndx = None):
    """
    Render the components in C [with dims comp_id x lats x lons] onto
    a world map of appropriate size.  The method assumes that the  lons x lats
    generate a rectangle.
    """
    m = Basemap(projection='mill',llcrnrlat=min(lats), urcrnrlat=max(lats), llcrnrlon=(min(lons)),
                urcrnrlon=max(lons),resolution='c')
    
    if ndx == None:
        ndx = np.arange(len(C)) + 1
        
    rmax = np.max(C)

    # lattitudes may not be sorted in ascending order, rectify this
    lat_ndx = np.argsort(lats)
    lats_s = lats[lat_ndx]

    # render each topo plot
    for ci in range(len(C)):
        
        plt.figure(figsize=(12, 8 * (max(lats) - min(lats)) / 180))
        plt.axes([0.05, 0.05, 0.9, 0.85])

        m.drawcoastlines()
        #m.fillcontinents(color='coral',lake_color='aqua', zorder = 0)
        m.etopo(scale = 0.2)

        # draw parallels and meridians.
        m.drawparallels(np.arange(-90.,91.,30.))
        m.drawmeridians(np.arange(0.,361.,60.))
        #m.drawmapboundary(fill_color='aqua')
        
        nx = int((m.xmax-m.xmin) / 20000) + 1
        ny = int((m.ymax-m.ymin) / 20000) + 1
        Ci = C[ci, lat_ndx, :]
        f = m.transform_scalar(Ci, lons, lats_s, nx, ny)
        
        # imlim seems to be equivalent to caxis() im MATLAB
        imgplt = m.imshow(f, alpha = 0.8)
        imgplt.set_clim(-rmax, rmax)
        plt.colorbar()
        
        plt.title('Component %d' % (ndx[ci]))
        
        if fname_tmpl:
            plt.savefig(fname_tmpl % (ndx[ci]))
            
    if not fname_tmpl:
        plt.show()
Example #7
0
    def map_slab1(self):
        '''
        Creates a map of the slab1.0 contours
        '''

        if self.slab1_details:
            bbox = self.slab1_details['Bounding_box']
            print(bbox)

            minlon = bbox[0]
            maxlon = bbox[1]
            minlat = bbox[2]
            maxlat = bbox[3]

            print('------------------------\nPlotting map...\n------------------------')

            figure = plt.figure(facecolor='white',figsize=(10,8))
            a = figure.add_subplot(111)
            m = Basemap(ax=a,lat_0=(minlat+((maxlat-minlat)/2.0)),lon_0=(minlon+((maxlon-minlon)/2.0)),resolution ='l',llcrnrlon=minlon,llcrnrlat=minlat,urcrnrlon=maxlon,urcrnrlat=maxlat)

            #Create grid uniformly spaced grid
            nx = int((m.xmax-m.xmin)/0.1)+1; ny = int((m.ymax-m.ymin)/0.1)+1

            slabdat = m.transform_scalar(self.slab1_details['Depth_array'],self.slab1_details['Lon_array'],self.slab1_details['Lat_array'],nx,ny)
            im = m.imshow(slabdat)

            m.drawparallels(np.arange(minlat,maxlat,((maxlat-minlat)/5)),labels=[1,1,0,0],linewidth=0.5,fontsize=10)
            m.drawmeridians(np.arange(minlon,maxlon,((maxlon-minlon)/5)),labels=[0,0,0,1],linewidth=0.5,fontsize=10)

            m.drawcoastlines()

            #Add tectonic plate boundaries - this doesn't work very well
            # self.faults = pts.read_faults('data/plates.xy')
            # for i in self.faults:
            #     faults_lons = self.faults[i][0]
            #     faults_lats = self.faults[i][1]
            #     x,y = m(faults_lons, faults_lats)
            #     m.plot(x,y,'b--',linewidth=1.0)

            #add a colorbar
            cb = m.colorbar(im,"bottom", size="5%", pad='15%')
            cb.set_label('Depth to slab surface [km]')

            #add a figure title
            a.set_title('Slab1.0 upper surface depths: %s' %self.name)

            return a,m

        else:
            print('Nothing to do: no slab1_details added!')
Example #8
0
def Mapshow(dims, data, type, para1, para2, tit, unit):

    # Prepare for drawing
    lons = np.arange(dims["minlon"], dims["maxlon"] + dims["res"] / 2, dims["res"])
    lats = np.arange(dims["minlat"], dims["maxlat"] + dims["res"] / 2, dims["res"])
    x, y = np.meshgrid(lons, lats)
    # draw Chile Basemap with lambert projection at normal x, y settings
    m = Basemap(
        llcrnrlon=dims["minlon"],
        llcrnrlat=dims["minlat"],
        urcrnrlon=dims["maxlon"],
        urcrnrlat=dims["maxlat"],
        projection="cyl",
        fix_aspect=True,
        lat_1=-10,
        lat_2=10,
        lon_0=20,
    )  # projection='lcc'
    # draw boundaries
    m.drawcoastlines()
    m.drawcountries(linewidth=2)
    m.drawstates()
    m.drawparallels(arange(-20, 30, 20), labels=[1, 0, 0, 0])  # only left ytick
    m.drawmeridians(arange(-10, 60, 20), labels=[0, 0, 0, 1])  # only bottom xtick
    # for  the classified figure
    X, Y = m(x, y)
    if type == "imshow":
        # im = m.contourf(X, Y, data, cmap=plt.cm.bwr, extend='both')
        plotdata = m.transform_scalar(data, lons, lats, dims["nlon"], dims["nlat"])
        im = m.imshow(plotdata, vmin=para2, vmax=para1, cmap=plt.cm.bwr)
    elif type == "contour":
        if para1 is not None:
            im = m.contourf(X, Y, data, para1, cmap=plt.cm.bwr, extend="both")
        else:
            im = m.contourf(X, Y, data, cmap=plt.cm.bwr, extend="both")
        cb = m.colorbar(im, pad="3%", ticks=para2)  # cb = m.colorbar(im, location='bottom', pad='16%')
        # The following method will return the zero as a small number close to zero
        # if para2 is not None:
        # 	cb.set_ticks(para2)
        # 	cb.set_ticklabels(para2)

        # map data with lon and lat position
    plt.title(tit, fontsize=20)
    plt.xlabel(unit, fontsize=18, labelpad=15)
Example #9
0
def millshow(zz,lon,lat,lonmin=-180.,lonmax=180.,latmin=-70,latmax=90, \
            theTitle=None,cmap=None,clim=None,map_type='coastline', \
            cbar='v',cbartitle=None,units=None):
    """ mill projection, imshow plot 
    """
    if cmap is None:
        cmap = plt.cm.jet
    elif cmap.startswith('GMT',0,3):
        cmap = eval('cm.' + cmap) # use cmap from Basemap module cm
    if clim is None:
        if isinstance(zz,np.ma.core.MaskedArray):
            zz1d = zz.compressed()
        else:
            zz1d = zz.ravel()
        clim = np.percentile(zz1d,1), np.percentile(zz1d,99)
    
    # base map
    lon_0 = (lon[0] + lon[-1])/2.
    m = Basemap(projection='mill', lon_0=lon_0, llcrnrlon=lonmin, \
                llcrnrlat=latmin, urcrnrlon=lonmax, urcrnrlat=latmax)
    if map_type=='coastline':
        m.drawcoastlines(linewidth=0.25)
    elif map_type=='filled':
        m.fillcontinents(color=[.33, .33, .33])
    
    # show data
    nx = len(lon); ny = len(lat)
    data = m.transform_scalar(zz,lon,lat,nx,ny)
    im = m.imshow(data,cmap)
    
    # labels        
    plt.clim(clim)
    m.drawmapboundary(fill_color='grey')
    m.drawparallels(np.arange(-90.,120.,30.),labels=[1,0,0,0])
    m.drawmeridians(np.arange(0.,420.,60.),labels=[0,0,0,1])
    if theTitle is not None:
        plt.title(theTitle)
    if cbar=='v':
        vcolorbar(im=im,cbartitle=cbartitle,units=units)
    elif cbar=='h':
        hcolorbar(im=im,cbartitle=cbartitle,units=units)
    return im    
Example #10
0
def BmPlot(filename, step, _pTotal=0, **kwargs):
    oroute = '../eps'
    try:
        _chemical = kwargs['chemical']
    except KeyError:
        _chemical = 0
    try:
        prj = kwargs['projection']
    except KeyError:
        prj = 'hammer'
    _cName = cName[_chemical]
    _column = column[_chemical]
    mfroute = oroute
    otype = 'eps'
    otype1 = 'jpg'
    if _pTotal == 1:
        outname = os.path.join(mfroute, "MF_%s_Total_%s" % (prj, _cName))
        sclField = sclMFTotal
        unit = "km"
    else:
        outname = os.path.join(mfroute, "MF_%s_%s_%d" % (prj, _cName, step))
        sclField = sclMF
        unit = "km/Myr"
    scl_ang = 180.0 / np.pi
    # read data
    data = np.genfromtxt(filename, skip_header=1)
    ilon = data[:, 1] * scl_ang
    ilat = data[:, 0] * scl_ang
    ifield = data[:, 2 + _column] * sclField
    # mesh data
    res = 1.0
    lon = np.arange(-180, 180 + res, 1.0)
    lat = np.arange(-90.0, 90.0 + res, 1.0)
    lon, lat = np.meshgrid(lon, lat)
    field = griddata((ilon, ilat), ifield, (lon, lat), method='linear')
    # initialize figure and axes
    cm = matplotlib.colors.LinearSegmentedColormap('my_colormap',
                                                   jet_adjust_dict, 1024)
    if prj == 'hammer':
        fig = plt.figure(figsize=(8, 8))
        ax_map = fig.add_axes([0.1, 0.1, 0.8, 0.8])
        ax_cbr = fig.add_axes([0.91, 0.3, 0.01, 0.4])
        # set up map
        m = Basemap(projection='hammer', lon_0=0, resolution='c', ax=ax_map)
        # plot the model
        s = m.transform_scalar(field, lon[0, :], lat[:, 0], 1000, 500)
        im = m.imshow(s, cmap=cm)
        m.drawparallels(np.arange(-90, 90, 30))
        m.drawmeridians(np.arange(-180, 180, 30))
        cb = plt.colorbar(im, cax=ax_cbr)
    elif prj == 'cart':
        fig, ax = plt.subplots()
        im = ax.pcolormesh(lon, lat, field, cmap=cm)
        cb = plt.colorbar(im, ax=ax)
    else:
        print("Wrong type of projection: %s" % prj)
        exit()
    # color bar
    cb.set_label('Melt Rate [%s]' % unit)
    fig.savefig("%s.%s" % (outname, otype))
    fig.savefig("%s.%s" % (outname, otype1))
Example #11
0
    mag = 6.25
    latmin, latmax, lonmin, lonmax = 45.4, 48.3, 5.6, 11.1
    lon, lat, pga = pgamap(mag, latmin, latmax, lonmin, lonmax, ngp, tlat, tlon)
    boxout = (45, 48.5, 5, 12, 47)
    meridians = np.arange(5, 12, 2)
    parallels = np.arange(44, 49, 2)
    llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon, lat_ts = boxout
    m = Basemap(projection='merc', llcrnrlat=llcrnrlat,
                urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon,
                urcrnrlon=urcrnrlon, lat_ts=lat_ts, resolution='i')

    xmin, ymin = m(lonmin, latmin)
    xmax, ymax = m(lonmax, latmax)
    nx = int((xmax - xmin) / 5000.) + 1
    ny = int((ymax - ymin) / 5000.) + 1
    dat, x, y = m.transform_scalar(pga / 1000., lon, lat, nx, ny,
                                   returnxy=True, masked=True)

    # m.fillcontinents(zorder=0)
    cmap = cm.get_cmap('jet')
    cf = m.contourf(x, y, dat, cmap=cmap)
    cs = m.contour(x, y, dat, colors='black',
                   levels=[0.01, 0.02, 0.04, 0.06, 0.1],
                   linestyles='solid', linewidths=3)
    plt.clabel(cs, fmt="%.2f ", fontsize=12, colors='black')

    m.drawmeridians(meridians, labels=[0, 0, 0, 1], color='lightgray',
                    linewidth=0.5, zorder=0)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], color='lightgray',
                    linewidth=0.5, zorder=0)
    m.drawcoastlines(zorder=2)
    m.drawcountries(linewidth=1.0, zorder=2)
Example #12
0
class VCDisplacementFieldPlotter(object):
    def __init__(self, min_lat, max_lat, min_lon, max_lon, map_res='i', map_proj='cyl'):
        self.look_azimuth = None
        self.look_elevation = None
        self.wavelength = 0.03
        
        self.norm = None
        
        #-----------------------------------------------------------------------
        # DisplacementmMap configuration
        #-----------------------------------------------------------------------
        # values for the fringes map are denoted by a {value}_f
        self.dmc = {
            'font':               mfont.FontProperties(family='Arial', style='normal', variant='normal', weight='normal'),
            'font_bold':          mfont.FontProperties(family='Arial', style='normal', variant='normal', weight='bold'),
            'cmap':               mplt.get_cmap('YlOrRd'),
            'cmap_f':             mplt.get_cmap('jet'),
        #water
            'water_color':          '#4eacf4',
            'water_color_f':        '#4eacf4',
        #map boundaries
            'boundary_color':       '#000000',
            'boundary_color_f':     '#ffffff',
            'boundary_width':       1.0,
            'coastline_color':      '#000000',
            'coastline_color_f':    '#ffffff',
            'coastline_width':      1.0,
            'country_color':        '#000000',
            'country_color_f':      '#ffffff',
            'country_width':        1.0,
            'state_color':          '#000000',
            'state_color_f':        '#ffffff',
            'state_width':          1.0,
        #rivers
            'river_width':          0.25,
        #faults
            'fault_color':          '#000000',
            'fault_color_f':        '#ffffff',
            'event_fault_color':    '#ff0000',
            'event_fault_color_f':  '#ffffff',
            'fault_width':          0.5,
        #lat lon grid
            'grid_color':           '#000000',
            'grid_color_f':         '#ffffff',
            'grid_width':           0.0,
            'num_grid_lines':       5,
        #map props
            'map_resolution':       map_res,
            'map_projection':       map_proj,
            'plot_resolution':      72.0,
            'map_tick_color':       '#000000',
            'map_tick_color_f':     '#000000',
            'map_frame_color':      '#000000',
            'map_frame_color_f':    '#000000',
            'map_frame_width':      1,
            'map_fontsize':         12,
            'arrow_inset':          10.0,
            'arrow_fontsize':       9.0,
            'cb_fontsize':          10.0,
            'cb_fontcolor':         '#000000',
            'cb_fontcolor_f':       '#000000',
            'cb_height':            20.0,
            'cb_margin_t':          10.0
        }
        
        #-----------------------------------------------------------------------
        # m1, fig1 is the oceans and the continents. This will lie behind the
        # masked data image.
        #-----------------------------------------------------------------------
        self.m1 = Basemap(
            llcrnrlon=min_lon,
            llcrnrlat=min_lat,
            urcrnrlon=max_lon,
            urcrnrlat=max_lat,
            lat_0=(max_lat+min_lat)/2.0,
            lon_0=(max_lon+min_lon)/2.0,
            resolution=map_res,
            projection=map_proj,
            suppress_ticks=True
        )
        #-----------------------------------------------------------------------
        # m2, fig2 is the plotted deformation data.
        #-----------------------------------------------------------------------
        self.m2 = Basemap(
            llcrnrlon=min_lon,
            llcrnrlat=min_lat,
            urcrnrlon=max_lon,
            urcrnrlat=max_lat,
            lat_0=(max_lat+min_lat)/2.0,
            lon_0=(max_lon+min_lon)/2.0,
            resolution=map_res,
            projection=map_proj,
            suppress_ticks=True
        )
        #-----------------------------------------------------------------------
        # m3, fig3 is the ocean land mask.
        #-----------------------------------------------------------------------
        self.m3 = Basemap(
            llcrnrlon=min_lon,
            llcrnrlat=min_lat,
            urcrnrlon=max_lon,
            urcrnrlat=max_lat,
            lat_0=(max_lat+min_lat)/2.0,
            lon_0=(max_lon+min_lon)/2.0,
            resolution=map_res,
            projection=map_proj,
            suppress_ticks=True
        )
            
    def set_field(self, field):
        self.lons_1d = field.lons_1d
        self.lats_1d = field.lats_1d
        self.dX = field.dX
        self.dY = field.dY
        self.dZ = field.dZ


    #---------------------------------------------------------------------------
    # Returns a PIL image of the masked displacement map using the current
    # values of the displacements. This map can then be combined into a still
    # or used as part of an animation.
    #---------------------------------------------------------------------------
    def create_field_image(self, fringes=True):
        
        #-----------------------------------------------------------------------
        # Set all of the plotting properties
        #-----------------------------------------------------------------------
    
        # properties that are fringes dependent
        if fringes:
            cmap            = self.dmc['cmap_f']
            water_color     = self.dmc['water_color_f']
            boundary_color  = self.dmc['boundary_color_f']
        else:
            cmap            = self.dmc['cmap']
            water_color     = self.dmc['water_color']
            boundary_color  = self.dmc['boundary_color']
            
        # properties that are not fringes dependent
        land_color      = cmap(0)
        plot_resolution = self.dmc['plot_resolution']
        
        #-----------------------------------------------------------------------
        # Set the map dimensions
        #-----------------------------------------------------------------------
        mw = self.lons_1d.size
        mh = self.lats_1d.size
        mwi = mw/plot_resolution
        mhi = mh/plot_resolution
        
        #print mw, mh
        
        #-----------------------------------------------------------------------
        # Fig1 is the background land and ocean.
        #-----------------------------------------------------------------------
        fig1 = mplt.figure(figsize=(mwi, mhi), dpi=plot_resolution)
        self.m1.ax = fig1.add_axes((0,0,1,1))
        self.m1.drawmapboundary(
            color=boundary_color,
            linewidth=0,
            fill_color=water_color
        )
        self.m1.fillcontinents(
            color=land_color,
            lake_color=water_color
        )
        #-----------------------------------------------------------------------
        # Fig2 is the deformations.
        #-----------------------------------------------------------------------
        fig2 = mplt.figure(figsize=(mwi, mhi), dpi=plot_resolution)
        self.m2.ax = fig2.add_axes((0,0,1,1))
        
        if self.look_azimuth is None:
            self.look_azimuth = 0.0
        if self.look_elevation is None:
            self.look_elevation = 0.0
        
        dMags = -self.dX * math.sin(self.look_azimuth) * math.cos(self.look_elevation) - self.dY * math.cos(self.look_azimuth) * math.cos(self.look_elevation) + self.dZ * math.sin(self.look_elevation)
        
        
        # make sure the values are located at the correct location on the map
        dMags_transformed = self.m2.transform_scalar(dMags, self.lons_1d, self.lats_1d, self.lons_1d.size, self.lats_1d.size)
        
        # prepare the colors for the plot and do the plot
        if fringes:
            dMags_colors = np.empty((dMags_transformed.shape[0],dMags_transformed.shape[1],4))
            r,g,b,a = cmap(0)
            dMags_colors[:,:,0].fill(r)
            dMags_colors[:,:,1].fill(g)
            dMags_colors[:,:,2].fill(b)
            dMags_colors[:,:,3].fill(a)
            non_zeros = dMags_transformed.nonzero()
            for n,i in enumerate(non_zeros[0]):
                j = non_zeros[1][n]
                r,g,b,a = cmap(math.modf(abs(dMags_transformed[i,j])/self.wavelength)[0])
                dMags_colors[i, j, 0] = r
                dMags_colors[i, j, 1] = g
                dMags_colors[i, j, 2] = b
                dMags_colors[i, j, 3] = a
            if self.norm is None:
                self.norm = mcolor.Normalize(vmin=0, vmax=self.wavelength)
            im = self.m2.imshow(dMags_colors, interpolation='spline36')
        else:
            dMags_colors = np.empty(dMags_transformed.shape)
            non_zeros = dMags_transformed.nonzero()
            #vmin = np.amin(np.fabs(dMags_transformed[non_zeros]))
            dMags_colors.fill(5e-4)
            dMags_colors[non_zeros] = np.fabs(dMags_transformed[non_zeros])
            vmax = np.amax(dMags_colors)
            if vmax <= 1:
                mod_vmax = 1
            elif vmax > 1 and vmax <= 10:
                mod_vmax = 10
            elif vmax > 10 and vmax <= 100:
                mod_vmax = 100
            elif vmax > 100 and vmax <= 1000:
                mod_vmax = 1000
            elif vmax > 1000:
                mod_vmax = 1000
            if self.norm is None:
                self.norm = mcolor.LogNorm(vmin=5e-4, vmax=mod_vmax, clip=True)
            im = self.m2.imshow(dMags_colors, cmap=cmap, norm=self.norm)
        
        #-----------------------------------------------------------------------
        # Fig3 is the land/sea mask.
        #-----------------------------------------------------------------------
        fig3 = mplt.figure(figsize=(mwi, mhi), dpi=plot_resolution)
        self.m3.ax = fig3.add_axes((0,0,1,1))
        self.m3.fillcontinents(color='#000000', lake_color='#ffffff')
        
        #-----------------------------------------------------------------------
        # Composite fig 1 - 3 together
        #-----------------------------------------------------------------------
        # FIGURE 1 draw the renderer
        fig1.canvas.draw()
        
        # FIGURE 1 Get the RGBA buffer from the figure
        w,h = fig1.canvas.get_width_height()
        buf = np.fromstring ( fig1.canvas.tostring_argb(), dtype=np.uint8 )
        buf.shape = ( w, h,4 )
     
        # FIGURE 1 canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
        buf = np.roll ( buf, 3, axis = 2 )
        im1 = Image.fromstring( "RGBA", ( w ,h ), buf.tostring( ) )
        
        # FIGURE 2 draw the renderer
        fig2.canvas.draw()
        
        # FIGURE 2 Get the RGBA buffer from the figure
        w,h = fig2.canvas.get_width_height()
        buf = np.fromstring ( fig2.canvas.tostring_argb(), dtype=np.uint8 )
        buf.shape = ( w, h,4 )
     
        # FIGURE 2 canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
        buf = np.roll ( buf, 3, axis = 2 )
        im2 = Image.fromstring( "RGBA", ( w ,h ), buf.tostring( ) )
        
        # FIGURE 3 draw the renderer
        fig3.canvas.draw()
        
        # FIGURE 3 Get the RGBA buffer from the figure
        w,h = fig3.canvas.get_width_height()
        buf = np.fromstring ( fig3.canvas.tostring_argb(), dtype=np.uint8 )
        buf.shape = ( w, h,4 )
     
        # FIGURE 3 canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
        buf = np.roll ( buf, 3, axis = 2 )
        im3 = Image.fromstring( "RGBA", ( w ,h ), buf.tostring( ) )
        
        mask = im3.convert('L')
        
        # Clear all three figures
        fig1.clf()
        fig2.clf()
        fig3.clf()
        mplt.close('all')
        gc.collect()
        
        # The final composited image.
        return  Image.composite(im1, im2, mask)

    #---------------------------------------------------------------------------
    # Calculates the look angles based on a set of elements. This will set the
    # angles to be looking along the average strike of the fault.
    #---------------------------------------------------------------------------
    def calculate_look_angles(self, element_data):
        strikes = []
        rakes = []
        
        for element in element_data:
            ele = quakelib.Element4()
            ele.set_vert(0, element['m_x_pt1'], element['m_y_pt1'], element['m_z_pt1'])
            ele.set_vert(1, element['m_x_pt2'], element['m_y_pt2'], element['m_z_pt2'])
            ele.set_vert(2, element['m_x_pt3'], element['m_y_pt3'], element['m_z_pt3'])
            ele.set_vert(3, element['m_x_pt4'], element['m_y_pt4'], element['m_z_pt4'])
            strikes.append(ele.strike())
            rakes.append(element['rake_rad'])
        
        self.look_azimuth = -sum(strikes)/len(strikes)
        
        average_rake = sum(rakes)/len(rakes)
        if average_rake >= math.pi/2.0:
            average_rake = math.pi - average_rake
        self.look_elevation = abs(average_rake)
Example #13
0
a2frontogen_def = dtanl_fsub.mk_a2frontogen_def(a2wb.T, a2u.T, a2v.T).T
a2frontogen_def = a2frontogen_def * 1000*100*60*60*24   # K/m/s --> K/100km/hour
#a2frontogen_def = a2frontogen_def * 1000*100   # K/m/s --> K/100km/hour

soname = sodir + "/tenkizu.%s.%04d.%02d.%02d.%02d.%04dhPa.png"%(varname, year, mon, day, hour, plev*0.01)
#------------------------
# 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"
a2frontogen_def_trans    = M.transform_scalar(a2frontogen_def,   a1lon, a1lat, nnx, nny) 
#--- 
a2psl_trans  = M.transform_scalar( a2psl, a1lon, a1lat, nnx, nny)
#

#-- boundaries ----------
bnd        = list(arange(-1.0, 1.0+0.001, 0.2))
#bnd        = list(arange(-0.1, 0.1+0.0001, 0.02))
bnd_cbar   = [-1.0e+40] + bnd + [1.0e+40]

#-- color ---------------
scm      = "coolwarm"
#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 )
Example #14
0
        #-- prep for map -----
        figname = doname[vartype, var, iclass][:-3] + ".png"
        adat    = fromfile(doname[vartype, var, iclass], float32).reshape(nwbin, ny, nx)[0]
        adat    = ma.masked_where( a2orog >= thorog, adat)
        adat    = ma.masked_equal(adat, 0.0)

        # ! convert w -> -w
        adat    = -adat
        figmap  = plt.figure()
        axmap   = figmap.add_axes([0, 0, 1.0, 1.0])

        #--------------------- 
        M       = Basemap(resolution="l", llcrnrlat=-90.0, llcrnrlon=0.0, urcrnrlat=90.0, urcrnrlon=360.0, ax=axmap)

        #-- transform --------
        adat_trans   = M.transform_scalar(adat, lons, lats, nnx, nny)
        a2mask_trans = M.transform_scalar(da3mnum_his[iclass], lons, lats, nnx, nny)

        #-- prep for colorbar ---
        cbarname= figname[:-4] + ".cbar.png"
        figcbar = plt.figure(figsize=(1,5))
        axcbar  = figcbar.add_axes([0, 0, 0.3, 1.0])

        #------------------------
        if vartype == "frac": 
          im       = M.imshow(adat, origin="lower", vmin=-1.0, vmax=1.0, interpolation="nearest")
        else: 
          #bnd      = [-0.04, -0.03, -0.02, -0.01, 0.01, 0.02, 0.03, 0.04]
          bnd      = [-0.04, -0.03, -0.02, -0.01, -0.001, 0.001, 0.01, 0.02, 0.03, 0.04]
          bnd_cbar = [-1.0e+40] + bnd + [1.0e+40]
Example #15
0
    def __init__(
        self,
        in_file,
        vg_files=[1],
        data_type=1,
        projection="cyl",
        color_map="jet",
        face_colour="white",
        time_zone=0,
        plot_contours=False,
        plot_center="t",
        plot_meridians=True,
        plot_parallels=True,
        plot_terminator=True,
        resolution="c",
        points_of_interest=[],
        save_file="",
        run_quietly=False,
        dpi=150,
        parent=None,
    ):

        self.run_quietly = run_quietly
        self.dpi = float(dpi)

        plot_parameters = VOAFile((in_file + ".voa"))
        plot_parameters.parse_file()

        if plot_parameters.get_projection() != "cyl":
            print _("Error: Only lat/lon (type 1) input files are supported")
            sys.exit(1)

        grid = plot_parameters.get_gridsize()
        self.image_defs = VOAAreaPlot.IMG_TYPE_DICT[int(data_type)]

        # TODO This needs a little more work... what if the pcenter card is not specified

        if plot_center == "p":
            plot_centre_location = plot_parameters.get_location(plot_parameters.P_CENTRE)
        else:
            plot_centre_location = plot_parameters.get_location(plot_parameters.TX_SITE)

        self.points_of_interest = [plot_centre_location]
        if len(points_of_interest) > 0:
            self.points_of_interest.extend(points_of_interest)

        imageBuf = P.zeros([grid, grid], float)

        area_rect = plot_parameters.get_area_rect()

        # The checks ought to be performed in the area_rect.
        # Do a few basic sanity checks #
        # if ( (area_rect.get_sw_lon() < -180) or (area_rect.get_ne_lon() > 180.0) or (area_rect.get_sw_lat() < -90) or (area_rect.get_ne_lat() > 90.0) ):
        #    print "Input file latitudes/longitudes are out of range"
        #    print "-180 < Latitude < 180.0, -90 < Longitude < 90"
        #    sys.exit(1)
        # if ( (area_rect.get_sw_lon() == area_rect.get_ne_lon()) or (area_rect.get_sw_lat() == area_rect.get_ne_lat()) ):
        #    print "Input file latitudes/longitudes are the same"
        #    print "-180 < Latitude < 180.0, -90 < Longitude < 90"
        #    sys.exit(1)

        points = P.zeros([grid, grid], float)
        lons = P.zeros(grid * grid, float)
        lats = P.zeros(grid * grid, float)

        lons = P.arange(
            area_rect.get_sw_lon(),
            area_rect.get_ne_lon() + 0.001,
            (area_rect.get_ne_lon() - area_rect.get_sw_lon()) / float(grid - 1),
        )
        lats = P.arange(
            area_rect.get_sw_lat(),
            area_rect.get_ne_lat() + 0.001,
            (area_rect.get_ne_lat() - area_rect.get_sw_lat()) / float(grid - 1),
        )

        colString = "P.cm." + color_map
        colMap = eval(colString)

        self.subplots = []
        self.number_of_subplots = len(vg_files)

        matplotlib.rcParams["axes.edgecolor"] = "gray"
        matplotlib.rcParams["axes.facecolor"] = "white"
        matplotlib.rcParams["figure.facecolor"] = face_colour
        # matplotlib.rcParams['figure.figsize'] = (6, 10)
        matplotlib.rcParams["figure.subplot.hspace"] = 0.45
        matplotlib.rcParams["figure.subplot.wspace"] = 0.35
        matplotlib.rcParams["figure.subplot.right"] = 0.85
        colorbar_fontsize = 12

        if self.number_of_subplots <= 1:
            self.num_rows = 1
            self.main_title_fontsize = 24
            matplotlib.rcParams["legend.fontsize"] = 12
            matplotlib.rcParams["axes.labelsize"] = 12
            matplotlib.rcParams["axes.titlesize"] = 10
            matplotlib.rcParams["xtick.labelsize"] = 10
            matplotlib.rcParams["ytick.labelsize"] = 10
            matplotlib.rcParams[
                "figure.subplot.top"
            ] = 0.8  # single figure plots have a larger title so require more space at the top.
        elif (self.number_of_subplots >= 2) and (self.number_of_subplots <= 6):
            self.num_rows = 2
            self.main_title_fontsize = 18
            matplotlib.rcParams["legend.fontsize"] = 10
            matplotlib.rcParams["axes.labelsize"] = 10
            matplotlib.rcParams["axes.titlesize"] = 11
            matplotlib.rcParams["xtick.labelsize"] = 8
            matplotlib.rcParams["ytick.labelsize"] = 8
            # self.x_axes_ticks = P.arange(0,25,4)
        else:
            self.num_rows = 3
            self.main_title_fontsize = 16
            matplotlib.rcParams["legend.fontsize"] = 8
            matplotlib.rcParams["axes.labelsize"] = 8
            matplotlib.rcParams["axes.titlesize"] = 10
            matplotlib.rcParams["xtick.labelsize"] = 6
            matplotlib.rcParams["ytick.labelsize"] = 6
            # self.x_axes_ticks = P.arange(0,25,4)

        self.num_cols = int(math.ceil(float(self.number_of_subplots) / float(self.num_rows)))
        self.fig = Figure()
        self.main_title_label = self.fig.suptitle(
            unicode(self.image_defs["title"], "utf-8"), fontsize=self.main_title_fontsize
        )

        if projection == "ortho":
            self.show_subplot_frame = False

        for plot_ctr in range(self.number_of_subplots):
            # ax = self.fig.add_subplot(plot_ctr)
            ax = self.fig.add_subplot(
                self.num_rows, self.num_cols, plot_ctr + 1, frame_on=self.show_subplot_frame, axisbg="white"
            )

            self.subplots.append(ax)

            ax.label_outer()
            # print "opening: ",(in_file+'.vg'+str(vg_files[plot_ctr]))
            vgFile = open(in_file + ".vg" + str(vg_files[plot_ctr]))
            pattern = re.compile(r"[a-z]+")

            for line in vgFile:
                match = pattern.search(line)
                if not match:
                    value = float(line[int(self.image_defs["first_char"]) : int(self.image_defs["last_char"])])
                    # TODO Does this need to be normalised here if it's also being done in the plot?
                    value = max(self.image_defs["min"], value)
                    value = min(self.image_defs["max"], value)
                    # if value < self.image_defs[2] : value = self.image_defs[2]
                    # if value > self.image_defs[3] : value = self.image_defs[3]
                    points[int(line[3:6]) - 1][int(line[0:3]) - 1] = value
            vgFile.close()

            map = Basemap(
                llcrnrlon=area_rect.get_sw_lon(),
                llcrnrlat=area_rect.get_sw_lat(),
                urcrnrlon=area_rect.get_ne_lon(),
                urcrnrlat=area_rect.get_ne_lat(),
                projection=projection,
                lat_0=plot_centre_location.get_latitude(),
                lon_0=plot_centre_location.get_longitude(),
                resolution=resolution,
                ax=ax,
            )

            map.drawcoastlines(color="black")
            map.drawcountries(color="grey")
            map.drawmapboundary(color="black", linewidth=1.0)

            warped = ma.zeros((grid, grid), float)
            warped, warped_lon, warped_lat = map.transform_scalar(
                points, lons, lats, grid, grid, returnxy=True, checkbounds=False, masked=True
            )
            warped = warped.filled(self.image_defs["min"] - 1.0)

            colMap.set_under(color="k", alpha=0.0)

            im = map.imshow(
                warped,
                cmap=colMap,
                extent=(-180, 180, -90, 90),
                origin="lower",
                norm=P.Normalize(clip=False, vmin=self.image_defs["min"], vmax=self.image_defs["max"]),
            )

            #######################
            # Plot greyline
            #######################
            if plot_terminator:
                the_sun = Sun()
                the_month = plot_parameters.get_month(vg_files[plot_ctr] - 1)
                the_day = plot_parameters.get_day(vg_files[plot_ctr] - 1)
                the_hour = plot_parameters.get_utc(vg_files[plot_ctr] - 1)
                if the_day == 0:
                    the_day = 15
                the_year = datetime.date.today().year
                num_days_since_2k = the_sun.daysSince2000Jan0(the_year, the_month, the_day)

                res = the_sun.sunRADec(num_days_since_2k)
                declination = res[1]
                if declination == 0.0:
                    declination = -0.001

                tau = the_sun.computeGHA(the_day, the_month, the_year, the_hour)

                if declination > 0:
                    terminator_end_lat = area_rect.get_sw_lat()
                else:
                    terminator_end_lat = area_rect.get_ne_lat()

                terminator_lat = [terminator_end_lat]
                terminator_lon = [area_rect.get_sw_lon()]

                for i in range(int(area_rect.get_sw_lon()), int(area_rect.get_ne_lon()), 1) + [
                    int(area_rect.get_ne_lon())
                ]:
                    longitude = i + tau
                    tan_lat = -the_sun.cosd(longitude) / the_sun.tand(declination)
                    latitude = the_sun.atand(tan_lat)
                    latitude = max(latitude, area_rect.get_sw_lat())
                    latitude = min(latitude, area_rect.get_ne_lat())
                    xpt, ypt = map(i, latitude)
                    terminator_lon.append(xpt)
                    terminator_lat.append(ypt)

                terminator_lon.append(area_rect.get_ne_lon())
                terminator_lat.append(terminator_end_lat)

                # This is a little simplistic and doesn't work for ortho plots....
                ax.plot(terminator_lon, terminator_lat, color="grey", alpha=0.75)
                ax.fill(terminator_lon, terminator_lat, facecolor="grey", alpha=0.5)

                tau = -tau
                if tau > 180.0:
                    tau = tau - 360.0
                if tau < -180.0:
                    tau = tau + 360.0

                # Plot the position of the sun (if it's in the coverage area)
                if area_rect.contains(declination, tau):
                    xpt, ypt = map(tau, declination)
                    # sbplt_ax.plot([xpt],[ypt],'yh')
                    ax.plot([xpt], [ypt], "yh")

            ##########################
            # Points of interest
            ##########################
            for location in self.points_of_interest:
                if area_rect.contains(location.get_latitude(), location.get_longitude()):
                    xpt, ypt = map(location.get_longitude(), location.get_latitude())
                    ax.plot([xpt], [ypt], "ro")
                    ax.text(xpt + 100000, ypt + 100000, location.get_name())

            if plot_meridians:
                if area_rect.get_lon_delta() <= 90.0:
                    meridians = P.arange(-180, 190.0, 10.0)
                elif area_rect.get_lon_delta() <= 180.0:
                    meridians = P.arange(-180.0, 210.0, 30.0)
                else:
                    meridians = P.arange(-180, 240.0, 60.0)
                if (projection == "ortho") or (projection == "vandg"):
                    map.drawmeridians(meridians)
                else:
                    map.drawmeridians(meridians, labels=[1, 1, 0, 1])

            if plot_parallels:
                if area_rect.get_lat_delta() <= 90.0:
                    parallels = P.arange(-90.0, 120.0, 60.0)
                else:
                    parallels = P.arange(-90.0, 120.0, 30.0)
                if (projection == "ortho") or (projection == "vandg"):
                    map.drawparallels(parallels)
                else:
                    map.drawparallels(parallels, labels=[1, 1, 0, 1])

            if plot_contours:
                map.contour(
                    warped_lon, warped_lat, warped, self.image_defs["y_labels"], linewidths=1.0, colors="k", alpha=0.5
                )

            # add a title

            title_str = plot_parameters.get_plot_description_string(
                vg_files[plot_ctr] - 1, self.image_defs["plot_type"], time_zone
            )
            if self.number_of_subplots == 1:
                title_str = plot_parameters.get_plot_description_string(
                    vg_files[plot_ctr] - 1, self.image_defs["plot_type"], time_zone
                )
                title_str = (
                    title_str + "\n" + plot_parameters.get_detailed_plot_description_string(vg_files[plot_ctr] - 1)
                )
            else:
                title_str = plot_parameters.get_minimal_plot_description_string(
                    vg_files[plot_ctr] - 1, self.image_defs["plot_type"], time_zone
                )
            self.subplot_title_label = ax.set_title(title_str)

        # Add a colorbar on the right hand side, aligned with the
        # top of the uppermost plot and the bottom of the lowest
        # plot.
        self.cb_ax = self.fig.add_axes(self.get_cb_axes())
        self.fig.colorbar(
            im,
            cax=self.cb_ax,
            orientation="vertical",
            ticks=self.image_defs["y_labels"],
            format=P.FuncFormatter(eval("self." + self.image_defs["formatter"])),
        )

        # print self.image_defs['y_labels']
        for t in self.cb_ax.get_yticklabels():
            t.set_fontsize(colorbar_fontsize)

        canvas = FigureCanvasGTK3Agg(self.fig)
        self.fig.canvas.mpl_connect("draw_event", self.on_draw)
        canvas.show()

        if save_file:
            self.save_plot(canvas, save_file)

        # todo this ought to a command line param
        if not self.run_quietly:
            dia = VOAPlotWindow("pythonProp - " + self.image_defs["title"], canvas, parent=parent)
        return
Example #16
0
def plot_MWAconstellations(
        outfile=None,
        obsinfo=None,
        viewgps=None,
        observing=True,
        showbeam=True,
        constellations=True,
        gleamsources=False,
        notext=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]

    obstime = Time(obsinfo['starttime'], format='gps', scale='utc')

    if viewgps is None:
        viewtime = obstime
    else:
        viewtime = Time(viewgps, format='gps', scale='utc')

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

    mapzenith = SkyCoord(ra=skydata.skymapRA,
                         dec=skydata.skymapDec,
                         equinox='J2000',
                         unit=(astropy.units.deg, astropy.units.deg))
    mapzenith.location = config.MWAPOS
    mapzenith.obstime = 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=config.MWAPOS.latitude.deg,
                   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)
    bmap.imshow(numpy.ma.log10(tform_skymap[:, ::-1]),
                cmap=CM,
                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 obstime.gps > Time.now().gps + 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, config.MWAPOS.latitude.deg)

    if constellations:
        # plot the constellations
        ConstellationStars = []
        for c in skydata.constellations.keys():
            for i in xrange(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)

    observer = ephem.Observer()
    # make sure no refraction is included
    observer.pressure = 0
    observer.long = config.MWAPOS.longitude.radian
    observer.lat = config.MWAPOS.latitude.radian
    observer.elevation = config.MWAPOS.height.value
    observer.date = viewtime.datetime.strftime('%Y/%m/%d %H:%M:%S')

    # plot the bodies
    for b in skydata.bodies.keys():
        name = skydata.bodies[b][2]
        color = skydata.bodies[b][1]
        size = skydata.bodies[b][0]
        body = b(observer)
        ra, dec = map(numpy.degrees, (body.ra, body.dec))
        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 = astropy.coordinates.Longitude(
            angle=primarybeammap.sources[source][1],
            unit=astropy.units.hour).hour
        d = astropy.coordinates.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'
        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,
                   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' %
                     (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, 'w')
                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
        for j in range(len(msk.T)):
            w2[i, j] = np.sum(ncdata2.variables[vv[number][1]][
                d1[0 + k] * 8:d1[1 + k] * 8, i, j]) / len(
                    range(d1[0 + k] * 8, d1[1 + k] * 8))  #Odyssea time range 1
            w1[i, j] = np.sum(
                nc1.variables[vv[number][0]][d1[0 + k]:d1[1 + k], i, j]) / len(
                    range(d1[0 + k], d1[1 + k]))
            #ROMS time range 1
    w = w1 - w2
    w = flipud(w)
    w = np.ma.masked_where(maska == 1, w)
    #mintemp=np.round(w.min(),-1); maxtemp=np.round(w.max(),-1);
    mintemp = temprange[number][0]
    maxtemp = temprange[number][1]
    midpt = 1 - maxtemp / (float(maxtemp) + abs(mintemp))
    v = range(mintemp, maxtemp + 10, 10)
    shifted_cmap = shiftedColorMap(cmap=mpl.cm.RdBu_r,
                                   midpoint=midpt,
                                   name='shifted')
    #norm = mpl.colors.Normalize(vmin=mintemp, vmax=maxtemp);
    nx2 = int((m1.xmax - m1.xmin) / 3000.) + 1
    ny2 = int((m1.ymax - m1.ymin) / 3000.) + 1
    tempo2 = m1.transform_scalar(w, lons, lats, nx2, ny2)
    CS3 = m1.imshow(tempo2, cmap=shifted_cmap, vmin=mintemp, vmax=maxtemp)
    plt.colorbar(CS3, cax, ticks=v, orientation='horizontal')
    m1.drawcountries()
    m1.fillcontinents(color='#ddaa66', lake_color='#9999FF')
    file_name = os.path.abspath("Time_period_%s_%s.png" %
                                (vv[number][0], str(k)))
    fig.savefig(file_name, dpi=200)
Example #18
0
                    color='0.5',
                    linewidth=0.5)
    m.drawmeridians(arange(0., 360., xlabel),
                    labels=[0, 0, 0, 1],
                    fontsize=10,
                    dashes=[2, 2],
                    color='0.5',
                    linewidth=0.5)

    # transform to map projection
    nx = int((m.xmax - m.xmin) / 2000.) + 1
    ny = int((m.ymax - m.ymin) / 2000.) + 1

    # differences in the way different machines deal with grids - weird!
    if cwd.startswith('/nas'):
        transhaz = m.transform_scalar(resampledRatio.T, lons1, lats1, nx, ny)
    else:
        transhaz = m.transform_scalar(resampledRatio.T, lons1, lats1, nx, ny)

    masked_array = ma.array(transhaz, mask=isnan(transhaz))
    #masked_array = masked_array.set_fill_value(0)

    # get colormap from cpt file
    #Optimus Prime
    cptfile = 'BrBG_10.cpt'
    cptfile = 'PuOr_10.cpt'
    cptfile = 'BlueWhiteOrangeRed.cpt'

    clim = 10.
    if clim == 4.:
        ncolours = 17
except:
    nc = NetCDFFile(
        '/nas/active/ops/community_safety/ehp/georisk_earthquake/hazard/DATA/GEBCO/au_gebco.nc'
    )

zscale = 30.  #gray
#zscale =30. #colour
data = nc.variables['elevation'][:] / zscale
lons = nc.variables['lon'][:]
lats = nc.variables['lat'][:]

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

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

print('Getting colormap...')
# get colormap
try:
    cptfile = '//Users//trev//Documents//DATA//GMT//cpt//wiki-2.0.cpt'
    cptfile = '//Users//trev//Documents//DATA//GMT//cpt//lightgrey.cpt'
    cptfile = '//Users//trev//Documents//DATA//GMT//cpt//grey_fade.cpt'
except:
    cptfile = '/nas/active/ops/community_safety/ehp/georisk_earthquake/hazard/DATA/cpt/wiki-2.0.cpt'

#cmap, zvals = cpt2colormap(cptfile, 30) # wiki
cmap, zvals = cpt2colormap(cptfile, 31)  # grey
#cmap = remove_last_cmap_colour(cmap)

#cmap = ListedColormap
Example #20
0
ds = gdal.Open("../sample_files/dem.tiff")
data = ds.ReadAsArray()

lons = np.linspace(0, 40, data.shape[1])
lats = np.linspace(0, 35, data.shape[0])

ax = fig.add_subplot(121)
ax.set_title('Without transform_scalar')

llons, llats = np.meshgrid(lons, lats)
x, y = map(llons, llats)

map.pcolormesh(x, y, data, vmin=900, vmax=950)

map.drawcoastlines()

ax = fig.add_subplot(122)
ax.set_title('Applying transform_scalar')

data_interp, x, y = map.transform_scalar(data,
                                         lons,
                                         lats,
                                         40,
                                         40,
                                         returnxy=True)

map.pcolormesh(x, y, data_interp, vmin=900, vmax=950)

map.drawcoastlines()

plt.show()
yi = np.linspace(y.min(), y.max(), 200)
X, Y = np.meshgrid(xi, yi)
pca_grid = plt.mlab.griddata(x, y, pca, xi, yi)
lat, lon = m(X, Y)
lat_1, lon_1 = m(x, y)

# Background image (see Jared's basemap_example.py)
res = 500.
dsElev = geotiff.RasterDataset(data_path + 'basemap_data/hillshade1.tif')
latElev, lonElev = dsElev.getCoordGrid1d()
latElev = np.sort(latElev)
nx = int((m.xmax - m.xmin) / res) + 1
ny = int((m.ymax - m.ymin) / res) + 1
elev = dsElev.readAsArray()
elev = np.flipud(elev)
elev = m.transform_scalar(elev, lonElev, latElev, nx, ny)

# plot map
m.drawstates(linewidth=1, zorder=7)
m.drawcountries(linewidth=1, zorder=6)
m.imshow(elev, cmap=plt.cm.gray)
p = m.contourf(lat,
               lon,
               pca_grid,
               cmap=plt.cm.rainbow,
               alpha=0.3,
               antialiased=True,
               zorder=5)
p = m.contourf(lat,
               lon,
               pca_grid,
Example #22
0
            jet_vals[i, j] = 1.

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()
lons = root_grp.variables['longitude'][:]
lats = root_grp.variables['latitude'][:]
nx=len(lats)
ny=len(lons)

fig=pp.figure(figsize=(16,20))
# set up orthographic map projection with
# perspective of satellite looking down at 50N, 100W.
# use low resolution coastlines.
map = Basemap(projection='ortho',lat_0=45,lon_0=20,resolution='l')
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral',lake_color='aqua')
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary(fill_color='aqua')

# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(np.arange(0,360,30))
map.drawparallels(np.arange(-90,90,30))



topodat = map.transform_scalar(temp[0],lons,lats,nx,ny)
im = map.imshow(topodat,cm.GMT_haxby,alpha=0.85)

c = pp.colorbar(im,orientation='horizontal')
pp.title('map the world')
pp.savefig('contour1.png')
pp.show()
Example #24
0
    def __init__(self,
                 in_file,
                 vg_files=[1],
                 data_type=1,
                 projection='cyl',
                 color_map='jet',
                 time_zone=0,
                 plot_contours=False,
                 plot_center='t',
                 plot_meridians=True,
                 plot_parallels=True,
                 plot_terminator=True,
                 resolution='c',
                 points_of_interest=[],
                 save_file='',
                 run_quietly=False,
                 dpi=150,
                 parent=None):

        self.run_quietly = run_quietly
        self.dpi = float(dpi)

        plot_parameters = VOAFile((in_file + '.voa'))
        plot_parameters.parse_file()

        if (plot_parameters.get_projection() != 'cyl'):
            print _("Error: Only lat/lon (type 1) input files are supported")
            sys.exit(1)

        grid = plot_parameters.get_gridsize()
        self.image_defs = VOAAreaPlot.IMG_TYPE_DICT[int(data_type)]

        # TODO This needs a little more work... what if the pcenter card is not specified

        if plot_center == 'p':
            plot_centre_location = plot_parameters.get_location(
                plot_parameters.P_CENTRE)
        else:
            plot_centre_location = plot_parameters.get_location(
                plot_parameters.TX_SITE)

        self.points_of_interest = [plot_centre_location]
        if len(points_of_interest) > 0:
            self.points_of_interest.extend(points_of_interest)

        imageBuf = P.zeros([grid, grid], float)

        area_rect = plot_parameters.get_area_rect()

        # The checks ought to be performed in the area_rect.
        # Do a few basic sanity checks #
        #if ( (area_rect.get_sw_lon() < -180) or (area_rect.get_ne_lon() > 180.0) or (area_rect.get_sw_lat() < -90) or (area_rect.get_ne_lat() > 90.0) ):
        #    print "Input file latitudes/longitudes are out of range"
        #    print "-180 < Latitude < 180.0, -90 < Longitude < 90"
        #    sys.exit(1)
        #if ( (area_rect.get_sw_lon() == area_rect.get_ne_lon()) or (area_rect.get_sw_lat() == area_rect.get_ne_lat()) ):
        #    print "Input file latitudes/longitudes are the same"
        #    print "-180 < Latitude < 180.0, -90 < Longitude < 90"
        #    sys.exit(1)

        points = P.zeros([grid, grid], float)
        lons = P.zeros(grid * grid, float)
        lats = P.zeros(grid * grid, float)

        lons = P.arange(area_rect.get_sw_lon(),
                        area_rect.get_ne_lon() + 0.001,
                        (area_rect.get_ne_lon() - area_rect.get_sw_lon()) /
                        float(grid - 1))
        lats = P.arange(area_rect.get_sw_lat(),
                        area_rect.get_ne_lat() + 0.001,
                        (area_rect.get_ne_lat() - area_rect.get_sw_lat()) /
                        float(grid - 1))

        colString = 'P.cm.' + color_map
        colMap = eval(colString)

        self.subplots = []
        self.number_of_subplots = len(vg_files)

        matplotlib.rcParams['axes.edgecolor'] = 'gray'
        matplotlib.rcParams['axes.facecolor'] = 'white'
        matplotlib.rcParams['figure.facecolor'] = 'white'
        #matplotlib.rcParams['figure.figsize'] = (6, 10)
        matplotlib.rcParams['figure.subplot.hspace'] = 0.45
        matplotlib.rcParams['figure.subplot.wspace'] = 0.35
        matplotlib.rcParams['figure.subplot.right'] = 0.85
        colorbar_fontsize = 12

        if self.number_of_subplots <= 1:
            self.num_rows = 1
            self.main_title_fontsize = 24
            matplotlib.rcParams['legend.fontsize'] = 12
            matplotlib.rcParams['axes.labelsize'] = 12
            matplotlib.rcParams['axes.titlesize'] = 10
            matplotlib.rcParams['xtick.labelsize'] = 10
            matplotlib.rcParams['ytick.labelsize'] = 10
            matplotlib.rcParams[
                'figure.subplot.top'] = 0.8  # single figure plots have a larger title so require more space at the top.
        elif ((self.number_of_subplots >= 2)
              and (self.number_of_subplots <= 6)):
            self.num_rows = 2
            self.main_title_fontsize = 18
            matplotlib.rcParams['legend.fontsize'] = 10
            matplotlib.rcParams['axes.labelsize'] = 10
            matplotlib.rcParams['axes.titlesize'] = 11
            matplotlib.rcParams['xtick.labelsize'] = 8
            matplotlib.rcParams['ytick.labelsize'] = 8
            #self.x_axes_ticks = P.arange(0,25,4)
        else:
            self.num_rows = 3
            self.main_title_fontsize = 16
            matplotlib.rcParams['legend.fontsize'] = 8
            matplotlib.rcParams['axes.labelsize'] = 8
            matplotlib.rcParams['axes.titlesize'] = 10
            matplotlib.rcParams['xtick.labelsize'] = 6
            matplotlib.rcParams['ytick.labelsize'] = 6
            #self.x_axes_ticks = P.arange(0,25,4)

        self.num_cols = int(
            math.ceil(float(self.number_of_subplots) / float(self.num_rows)))
        self.fig = Figure()
        self.main_title_label = self.fig.suptitle(
            unicode(self.image_defs['title'], 'utf-8'),
            fontsize=self.main_title_fontsize)

        if projection == 'ortho':
            self.show_subplot_frame = False

        for plot_ctr in range(self.number_of_subplots):
            #ax = self.fig.add_subplot(plot_ctr)
            ax = self.fig.add_subplot(self.num_rows,
                                      self.num_cols,
                                      plot_ctr + 1,
                                      frame_on=self.show_subplot_frame,
                                      axisbg='white')

            self.subplots.append(ax)

            ax.label_outer()
            #print "opening: ",(in_file+'.vg'+str(vg_files[plot_ctr]))
            vgFile = open(in_file + '.vg' + str(vg_files[plot_ctr]))
            pattern = re.compile(r"[a-z]+")

            for line in vgFile:
                match = pattern.search(line)
                if not match:
                    value = float(
                        line[int(self.image_defs['first_char']
                                 ):int(self.image_defs['last_char'])])
                    # TODO Does this need to be normalised here if it's also being done in the plot?
                    value = max(self.image_defs['min'], value)
                    value = min(self.image_defs['max'], value)
                    #if value < self.image_defs[2] : value = self.image_defs[2]
                    #if value > self.image_defs[3] : value = self.image_defs[3]
                    points[int(line[3:6]) - 1][int(line[0:3]) - 1] = value
            vgFile.close()

            map = Basemap(\
                llcrnrlon=area_rect.get_sw_lon(), llcrnrlat=area_rect.get_sw_lat(),\
                urcrnrlon=area_rect.get_ne_lon(), urcrnrlat=area_rect.get_ne_lat(),\
                projection=projection,\
                lat_0=plot_centre_location.get_latitude(),\
                lon_0=plot_centre_location.get_longitude(),\
                resolution=resolution,
                ax=ax)

            map.drawcoastlines(color='black')
            map.drawcountries(color='grey')
            map.drawmapboundary(color='black', linewidth=1.0)

            warped = ma.zeros((grid, grid), float)
            warped, warped_lon, warped_lat = map.transform_scalar(
                points,
                lons,
                lats,
                grid,
                grid,
                returnxy=True,
                checkbounds=False,
                masked=True)
            warped = warped.filled(self.image_defs['min'] - 1.0)

            colMap.set_under(color='k', alpha=0.0)

            im = map.imshow(warped,
                            cmap=colMap,
                            extent=(-180, 180, -90, 90),
                            origin='lower',
                            norm=P.Normalize(clip=False,
                                             vmin=self.image_defs['min'],
                                             vmax=self.image_defs['max']))

            #######################
            # Plot greyline
            #######################
            if plot_terminator:
                the_sun = Sun()
                the_month = plot_parameters.get_month(vg_files[plot_ctr] - 1)
                the_day = plot_parameters.get_day(vg_files[plot_ctr] - 1)
                the_hour = plot_parameters.get_utc(vg_files[plot_ctr] - 1)
                if (the_day == 0):
                    the_day = 15
                the_year = datetime.date.today().year
                num_days_since_2k = the_sun.daysSince2000Jan0(
                    the_year, the_month, the_day)

                res = the_sun.sunRADec(num_days_since_2k)
                declination = res[1]
                if (declination == 0.0):
                    declination = -0.001

                tau = the_sun.computeGHA(the_day, the_month, the_year,
                                         the_hour)

                if declination > 0:
                    terminator_end_lat = area_rect.get_sw_lat()
                else:
                    terminator_end_lat = area_rect.get_ne_lat()

                terminator_lat = [terminator_end_lat]
                terminator_lon = [area_rect.get_sw_lon()]

                for i in range(int(area_rect.get_sw_lon()),
                               int(area_rect.get_ne_lon()),
                               1) + [int(area_rect.get_ne_lon())]:
                    longitude = i + tau
                    tan_lat = -the_sun.cosd(longitude) / the_sun.tand(
                        declination)
                    latitude = the_sun.atand(tan_lat)
                    latitude = max(latitude, area_rect.get_sw_lat())
                    latitude = min(latitude, area_rect.get_ne_lat())
                    xpt, ypt = map(i, latitude)
                    terminator_lon.append(xpt)
                    terminator_lat.append(ypt)

                terminator_lon.append(area_rect.get_ne_lon())
                terminator_lat.append(terminator_end_lat)

                #This is a little simplistic and doesn't work for ortho plots....
                ax.plot(terminator_lon,
                        terminator_lat,
                        color='grey',
                        alpha=0.75)
                ax.fill(terminator_lon,
                        terminator_lat,
                        facecolor='grey',
                        alpha=0.5)

                tau = -tau
                if (tau > 180.0):
                    tau = tau - 360.0
                if (tau < -180.0):
                    tau = tau + 360.0

                #Plot the position of the sun (if it's in the coverage area)
                if area_rect.contains(declination, tau):
                    xpt, ypt = map(tau, declination)
                    #sbplt_ax.plot([xpt],[ypt],'yh')
                    ax.plot([xpt], [ypt], 'yh')

            ##########################
            # Points of interest
            ##########################
            for location in self.points_of_interest:
                if area_rect.contains(location.get_latitude(),
                                      location.get_longitude()):
                    xpt, ypt = map(location.get_longitude(),
                                   location.get_latitude())
                    ax.plot([xpt], [ypt], 'ro')
                    ax.text(xpt + 100000, ypt + 100000, location.get_name())

            if plot_meridians:
                if (area_rect.get_lon_delta() <= 90.0):
                    meridians = P.arange(-180, 190.0, 10.0)
                elif (area_rect.get_lon_delta() <= 180.0):
                    meridians = P.arange(-180.0, 210.0, 30.0)
                else:
                    meridians = P.arange(-180, 240.0, 60.0)
                if ((projection == 'ortho') or (projection == 'vandg')):
                    map.drawmeridians(meridians)
                else:
                    map.drawmeridians(meridians, labels=[1, 1, 0, 1])

            if plot_parallels:
                if (area_rect.get_lat_delta() <= 90.0):
                    parallels = P.arange(-90.0, 120.0, 60.0)
                else:
                    parallels = P.arange(-90.0, 120.0, 30.0)
                if ((projection == 'ortho') or (projection == 'vandg')):
                    map.drawparallels(parallels)
                else:
                    map.drawparallels(parallels, labels=[1, 1, 0, 1])

            if plot_contours:
                map.contour(warped_lon,
                            warped_lat,
                            warped,
                            self.image_defs['y_labels'],
                            linewidths=1.0,
                            colors='k',
                            alpha=0.5)

            #add a title

            title_str = plot_parameters.get_plot_description_string(
                vg_files[plot_ctr] - 1, self.image_defs['plot_type'],
                time_zone)
            if self.number_of_subplots == 1:
                title_str = plot_parameters.get_plot_description_string(
                    vg_files[plot_ctr] - 1, self.image_defs['plot_type'],
                    time_zone)
                title_str = title_str + "\n" + plot_parameters.get_detailed_plot_description_string(
                    vg_files[plot_ctr] - 1)
            else:
                title_str = plot_parameters.get_minimal_plot_description_string(
                    vg_files[plot_ctr] - 1, self.image_defs['plot_type'],
                    time_zone)
            self.subplot_title_label = ax.set_title(title_str)

        # Add a colorbar on the right hand side, aligned with the
        # top of the uppermost plot and the bottom of the lowest
        # plot.
        self.cb_ax = self.fig.add_axes(self.get_cb_axes())
        self.fig.colorbar(im,
                          cax=self.cb_ax,
                          orientation='vertical',
                          ticks=self.image_defs['y_labels'],
                          format=P.FuncFormatter(
                              eval('self.' + self.image_defs['formatter'])))

        #print self.image_defs['y_labels']
        for t in self.cb_ax.get_yticklabels():
            t.set_fontsize(colorbar_fontsize)

        canvas = FigureCanvasGTKAgg(self.fig)
        self.fig.canvas.mpl_connect('draw_event', self.on_draw)
        canvas.show()

        if save_file:
            self.save_plot(canvas, save_file)

        #todo this ought to a command line param
        if not self.run_quietly:
            dia = VOAPlotWindow('pythonProp - ' + self.image_defs['title'],
                                canvas,
                                parent=parent)
        return
Example #25
0
meridians = np.arange(-180,180,delon)
m.drawmeridians(meridians,labels=[1,1,1,1])
plt.title('Surface Winds Winds and Pressure (lat-lon grid)',y=1.075)
 
# plot vectors in map projection coordinates.

# 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()
Example #26
0
            xl = xl[::d]
            yl = yl[::d]
            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,
def plot_var(varname,ofile,title,units,data,fill_value,lon,lat):
    print('plot_var '+varname+' '+ofile)
    pl.clf()
    if plot_norm:
        title = title + ' / norm. diff ( % ) '
        units = '%'
    elif units == 'none' or units == 'None' or units == None or units == '':
            units = 'none'        
#    else:
#        title = title + ' ( ' + units + ' )'
#        units = '\n'+units
    pl.suptitle(title)
    # fix stupid scipy.io.netcdf _FillValue bug
    if use_scipy:
        data2 = np.copy( data )
        data2[data2==fill_value] = None
    else:
        data2 = data

    lon2=[ lon[0], lon[len(lon)-1] ]
    lat2=[ lat[0], lat[len(lat)-1] ] 
    lonstep=10
    latstep=10
    labelstyle=None
    fontsize=12
    if lon2 == [-179.75, 179.75] and lat2 == [89.75, -89.75]:
        lat2 = [85,-60]
        lonstep=30
        latstep=20
        #labelstyle="+/-"
        fontsize=9

    map = Basemap(llcrnrlon=min(lon2),llcrnrlat=min(lat2),urcrnrlon=max(lon2),urcrnrlat=max(lat2),projection='mill')
    map.drawcoastlines(linewidth=1.25)
    map.drawparallels(np.arange(round(min(lat2)),max(lat2),latstep),labels=[1,0,0,0],labelstyle=labelstyle,fontsize=fontsize)
    map.drawmeridians(np.arange(round(min(lon2)),max(lon2),lonstep),labels=[0,0,0,1],labelstyle=labelstyle,fontsize=fontsize)
    data3 = map.transform_scalar(np.flipud(data2), lon, np.flipud(lat), len(lon), len(lat))

    # show data
    #cs = pl.contourf(data)
    #cs = map.imshow(data3,interpolation='nearest')
    if varname in limits:
        limit = limits[varname]
        norm = None
        cmap = pl.cm.jet
        #if varname in cbar_discrete:
        if data.dtype == np.int8 or data.dtype == np.int16  or data.dtype == np.int32:
            #http://stackoverflow.com/questions/14777066/matplotlib-discrete-colorbar
            bounds = range(limit[0],limit[1]+1)
            bounds2 = [bounds[0]]
            for i in bounds[1:]:
                bounds2.append(i-0.01)
            norm = mpl.colors.BoundaryNorm(bounds2, cmap.N)
            cs = map.imshow(data3,interpolation='nearest',vmin=limit[0], vmax=limit[1], cmap=cmap, norm=norm)
            cbar = map.colorbar(cs, cmap=cmap, norm=norm, spacing='proportional', ticks=bounds[0:-1], boundaries=bounds, format='%1i')
        else:
            cs = map.imshow(data3,interpolation='nearest',vmin=limit[0], vmax=limit[1])
            cbar = map.colorbar(cs)
    else:
        cs = map.imshow(data3,interpolation='nearest')
        cbar = map.colorbar(cs)
    if units != 'none':
        cbar.ax.set_xlabel(units,ha='left')   

    pl.savefig(ofile)
Example #28
0
plt.title('Mercator',y=1.1)
print('plotting Mercator example ...')
print(m.proj4string)

# create new figure
fig=plt.figure()
# setup cassini-soldner basemap.
m = Basemap(llcrnrlon=-6,llcrnrlat=49,urcrnrlon=4,urcrnrlat=59,\
            resolution='l',area_thresh=1000.,projection='cass',\
            lat_0=54.,lon_0=-2.)
# plot image over map.
# transform to nx x ny regularly spaced native projection grid
nx = int((m.xmax-m.xmin)/20000.)+1; ny = int((m.ymax-m.ymin)/20000.)+1
# shift data so lons go from -180 to 180 instead of 20 to 380.
datamap,lonsmap = shiftgrid(180.,topodat,lons[0,:],start=False)
topomap = m.transform_scalar(datamap,lonsmap,lats[:,0],nx,ny)
# plot image over map.
im = m.imshow(topomap,cmap)
m.colorbar() # draw colorbar
m.drawcoastlines()
# draw parallels
delat = 2.
circles = np.arange(40.,70.,delat)
m.drawparallels(circles,labels=[1,0,0,1],fontsize=10)
# draw meridians
delon = 2.
meridians = np.arange(-10,10,delon)
m.drawmeridians(meridians,labels=[1,0,0,1],fontsize=10)
plt.title('Cassini-Soldner Projection')
print('plotting Cassini-Soldner example ...')
print(m.proj4string)
Example #29
0
plt.title('Mercator',y=1.1)
print('plotting Mercator example ...')
print(m.proj4string)

# create new figure
fig=plt.figure()
# setup cassini-soldner basemap.
m = Basemap(llcrnrlon=-6,llcrnrlat=49,urcrnrlon=4,urcrnrlat=59,\
            resolution='l',area_thresh=1000.,projection='cass',\
            lat_0=54.,lon_0=-2.)
# plot image over map.
# transform to nx x ny regularly spaced native projection grid
nx = int((m.xmax-m.xmin)/20000.)+1; ny = int((m.ymax-m.ymin)/20000.)+1
# shift data so lons go from -180 to 180 instead of 20 to 380.
datamap,lonsmap = shiftgrid(180.,topodat,lons[0,:],start=False)
topomap = m.transform_scalar(datamap,lonsmap,lats[:,0],nx,ny)
# plot image over map.
im = m.imshow(topomap,cmap)
m.colorbar() # draw colorbar
m.drawcoastlines()
# draw parallels
delat = 2.
circles = np.arange(40.,70.,delat)
m.drawparallels(circles,labels=[1,0,0,1],fontsize=10)
# draw meridians
delon = 2.
meridians = np.arange(-10,10,delon)
m.drawmeridians(meridians,labels=[1,0,0,1],fontsize=10)
plt.title('Cassini-Soldner Projection')
print('plotting Cassini-Soldner example ...')
print(m.proj4string)
Example #30
0
# setup basemap instance.
m = Basemap(llcrnrlon=-119,
            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, 0, 0])
m.drawmeridians(np.arange(-120, -40, 10), labels=[0, 0, 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
Example #31
0
nnx        = int( (urlon - lllon)/dlon)
nny        = int( (urlat - lllat)/dlat)
a1lon_loc  = linspace(lllon, urlon, nnx)
a1lat_loc  = linspace(lllat, urlat, nny)
LONS, LATS = meshgrid( a1lon_loc, a1lat_loc)
#------------------------
# 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"
a2u_trans    = M.transform_scalar( a2u,   a1lon, a1lat, nnx, nny) 
a2v_trans    = M.transform_scalar( a2v,   a1lon, a1lat, nnx, nny) 
#--- 
a2psl_trans  = M.transform_scalar( a2psl, a1lon, a1lat, nnx, nny)
#

#-- boundaries ----------
#bnd        = [1,3,5,7,9,11,13,15,17]
bnd        = list(arange(0,21+1,3))
bnd_cbar   = [-1.0e+40] + bnd + [1.0e+40]

#-- color ---------------
#scm      = "rainbow"
scm      = "Spectral_r"
#scm      = "gist_rainbow"
cminst   = matplotlib.cm.get_cmap(scm, len(bnd))
Example #32
0
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_axes([0.1, 0.1, 0.7, 0.7])

# setup of basemap ('lcc' = lambert conformal conic).
# use major and minor sphere radii from WGS84 ellipsoid.
# pass axes instance to Basemap constructor so pylab won't
# be imported.
m = Basemap(llcrnrlon=-145.5,llcrnrlat=1.,urcrnrlon=-2.566,urcrnrlat=46.352,\
            rsphere=(6378137.00,6356752.3142),\
            resolution='l',area_thresh=1000.,projection='lcc',\
            lat_1=50.,lon_0=-107.,ax=ax)
# transform to nx x ny regularly spaced native projection grid
nx = int((m.xmax - m.xmin) / 40000.) + 1
ny = int((m.ymax - m.ymin) / 40000.) + 1
topodat, x, y = m.transform_scalar(topoin, lons, lats, nx, ny, returnxy=True)
# plot image over map with imshow.
im = m.imshow(topodat, cm.jet)
# setup colorbar axes instance.
pos = ax.get_position()
l, b, w, h = pos.bounds
cax = fig.add_axes([l + w + 0.075, b, 0.05, h],
                   frameon=False)  # setup colorbar axes
fig.colorbar(im, cax=cax)  # draw colorbar
# plot blue dot on boulder, colorado and label it as such.
xpt, ypt = m(-104.237, 40.125)
m.plot([xpt], [ypt], 'bo')
ax.text(xpt + 100000, ypt + 100000, 'Boulder')
# draw coastlines and political boundaries.
m.drawcoastlines()
m.drawcountries()
Example #33
0
class VCGravityFieldPlotter(object):
    def __init__(self, min_lat, max_lat, min_lon, max_lon, map_res='i', map_proj='cyl'):
        
        self.norm = None
        
        #-----------------------------------------------------------------------
        # Gravity map configuration
        #-----------------------------------------------------------------------
        self.dmc = {
            'font':               mfont.FontProperties(family='Arial', style='normal', variant='normal', weight='normal'),
            'font_bold':          mfont.FontProperties(family='Arial', style='normal', variant='normal', weight='bold'),
            'cmap':               mplt.get_cmap('seismic'),
        #water
            'water_color':          '#4eacf4',
        #map boundaries
            'boundary_color':       '#000000',
            'boundary_width':       1.0,
            'coastline_color':      '#000000',
            'coastline_width':      1.0,
            'country_color':        '#000000',
            'country_width':        1.0,
            'state_color':          '#000000',
            'state_width':          1.0,
        #rivers
            'river_width':          0.25,
        #faults
            'fault_color':          '#000000',
            'event_fault_color':    '#ff0000',
            'fault_width':          0.5,
        #lat lon grid
            'grid_color':           '#000000',
            'grid_width':           0.0,
            'num_grid_lines':       5,
        #map props
            'map_resolution':       map_res,
            'map_projection':       map_proj,
            'plot_resolution':      72.0,
            'map_tick_color':       '#000000',
            'map_frame_color':      '#000000',
            'map_frame_width':      1,
            'map_fontsize':         12,
            'arrow_inset':          10.0,
            'arrow_fontsize':       9.0,
            'cb_fontsize':          10.0,
            'cb_fontcolor':         '#000000',
            'cb_height':            20.0,
            'cb_margin_t':          10.0,
         #min/max gravity change labels for colorbar (in microgals)
            'cbar_min':             -20,
            'cbar_max':             20
        }
        
        #-----------------------------------------------------------------------
        # m1, fig1 is the oceans and the continents. This will lie behind the
        # masked data image.
        #-----------------------------------------------------------------------
        self.m1 = Basemap(
            llcrnrlon=min_lon,
            llcrnrlat=min_lat,
            urcrnrlon=max_lon,
            urcrnrlat=max_lat,
            lat_0=(max_lat+min_lat)/2.0,
            lon_0=(max_lon+min_lon)/2.0,
            resolution=map_res,
            projection=map_proj,
            suppress_ticks=True
        )
        #-----------------------------------------------------------------------
        # m2, fig2 is the plotted deformation data.
        #-----------------------------------------------------------------------
        self.m2 = Basemap(
            llcrnrlon=min_lon,
            llcrnrlat=min_lat,
            urcrnrlon=max_lon,
            urcrnrlat=max_lat,
            lat_0=(max_lat+min_lat)/2.0,
            lon_0=(max_lon+min_lon)/2.0,
            resolution=map_res,
            projection=map_proj,
            suppress_ticks=True
        )
        #-----------------------------------------------------------------------
        # m3, fig3 is the ocean land mask.
        #-----------------------------------------------------------------------
        self.m3 = Basemap(
            llcrnrlon=min_lon,
            llcrnrlat=min_lat,
            urcrnrlon=max_lon,
            urcrnrlat=max_lat,
            lat_0=(max_lat+min_lat)/2.0,
            lon_0=(max_lon+min_lon)/2.0,
            resolution=map_res,
            projection=map_proj,
            suppress_ticks=True
        )

    def set_field(self, field):
        self.lons_1d = field.lons_1d
        self.lats_1d = field.lats_1d
        self.dG = field.dG

    #---------------------------------------------------------------------------
    # Returns a PIL image of the masked displacement map using the current
    # values of the displacements. This map can then be combined into a still
    # or used as part of an animation.
    #---------------------------------------------------------------------------
    def create_field_image(self, fringes=True):
        
        #-----------------------------------------------------------------------
        # Set all of the plotting properties
        #-----------------------------------------------------------------------
    
        cmap            = self.dmc['cmap']
        water_color     = self.dmc['water_color']
        boundary_color  = self.dmc['boundary_color']
        land_color      = cmap(0.5)
        plot_resolution = self.dmc['plot_resolution']
        
        #-----------------------------------------------------------------------
        # Set the map dimensions
        #-----------------------------------------------------------------------
        mw = self.lons_1d.size
        mh = self.lats_1d.size
        mwi = mw/plot_resolution
        mhi = mh/plot_resolution
        
        #-----------------------------------------------------------------------
        # Fig1 is the background land and ocean.
        #-----------------------------------------------------------------------
        fig1 = mplt.figure(figsize=(mwi, mhi), dpi=plot_resolution)
        self.m1.ax = fig1.add_axes((0,0,1,1))
        self.m1.drawmapboundary(
            color=boundary_color,
            linewidth=0,
            fill_color=water_color
        )
        self.m1.fillcontinents(
            color=land_color,
            lake_color=water_color
        )
        #-----------------------------------------------------------------------
        # Fig2 is the deformations.
        #-----------------------------------------------------------------------
        fig2 = mplt.figure(figsize=(mwi, mhi), dpi=plot_resolution)
        self.m2.ax = fig2.add_axes((0,0,1,1))
        
        # make sure the values are located at the correct location on the map
        dG_transformed = self.m2.transform_scalar(self.dG, self.lons_1d, self.lats_1d, self.lons_1d.size, self.lats_1d.size)
        
        if self.norm is None:
            #self.norm = mcolor.Normalize(vmin=np.amin(dG_transformed), vmax=np.amax(dG_transformed))
            # Changed units to microgals (multiply MKS unit by 10^8)
            self.norm = mcolor.Normalize(vmin=self.dmc['cbar_min'], vmax=self.dmc['cbar_max'])
        
        #self.m2.imshow(dG_transformed, cmap=cmap, norm=self.norm)
        # Changed units to microgals (multiply MKS unit by 10^8)
        self.m2.imshow(dG_transformed*float(pow(10,8)), cmap=cmap, norm=self.norm)
        
        #-----------------------------------------------------------------------
        # Fig3 is the land/sea mask.
        #-----------------------------------------------------------------------
        """fig3 = mplt.figure(figsize=(mwi, mhi), dpi=plot_resolution)
        self.m3.ax = fig3.add_axes((0,0,1,1))
        #self.m3.fillcontinents(color='#000000', lake_color='#ffffff')
        dG_abs = np.fabs(dG_transformed)
        #print np.amin(dG_abs), np.amax(dG_abs), 1e6*np.amin(dG_abs), np.amax(dG_abs)*1e-1
        im = self.m3.imshow(dG_abs, cmap=mplt.get_cmap('gray_r'), norm=mcolor.Normalize(vmin=1e6*np.amin(dG_abs), vmax=np.amax(dG_abs)*1e-1, clip=True))
        
        fig3.savefig('local/test_mask.png', format='png', dpi=plot_resolution)
        """
        #-----------------------------------------------------------------------
        # Composite fig 1 - 3 together
        #-----------------------------------------------------------------------
        # FIGURE 1 draw the renderer
        fig1.canvas.draw()
        
        # FIGURE 1 Get the RGBA buffer from the figure
        w,h = fig1.canvas.get_width_height()
        buf = np.fromstring ( fig1.canvas.tostring_argb(), dtype=np.uint8 )
        buf.shape = ( w, h,4 )
     
        # FIGURE 1 canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
        buf = np.roll ( buf, 3, axis = 2 )
        im1 = Image.fromstring( "RGBA", ( w ,h ), buf.tostring( ) )
        
        # FIGURE 2 draw the renderer
        fig2.canvas.draw()
        
        # FIGURE 2 Get the RGBA buffer from the figure
        w,h = fig2.canvas.get_width_height()
        buf = np.fromstring ( fig2.canvas.tostring_argb(), dtype=np.uint8 )
        buf.shape = ( w, h,4 )
     
        # FIGURE 2 canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
        buf = np.roll ( buf, 3, axis = 2 )
        im2 = Image.fromstring( "RGBA", ( w ,h ), buf.tostring( ) )
        
        # FIGURE 3 draw the renderer
        """fig3.canvas.draw()
        
        # FIGURE 3 Get the RGBA buffer from the figure
        w,h = fig3.canvas.get_width_height()
        buf = np.fromstring ( fig3.canvas.tostring_argb(), dtype=np.uint8 )
        buf.shape = ( w, h,4 )
     
        # FIGURE 3 canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
        buf = np.roll ( buf, 3, axis = 2 )
        im3 = Image.fromstring( "RGBA", ( w ,h ), buf.tostring( ) )
        
        mask = im3.convert('L')
        """
        
        # Clear all three figures
        fig1.clf()
        fig2.clf()
        #fig3.clf()
        mplt.close('all')
        gc.collect()
        
        #mask = Image.new("L", (w,h), 'black')
        # The final composited image.
        #return  Image.composite(im1, im2, mask)
        return im2
Example #34
0
if POPDIAGPY == 'TRUE':
  outfile = os.path.join(outdir,'map_nutlim_sp.png')
else:
  outfile = os.path.join(outdir,'map_%04d-%04d_nutlim_sp.png'%(yrstart,yrend))

print('plotting %s'%(outfile))
fig = pl.figure()
ax  = fig.add_subplot(111)
map = Basemap(llcrnrlon=30,urcrnrlon=360+30,llcrnrlat=-85,urcrnrlat=85,
        resolution='l',projection='cyl',ax=ax)
map.drawcoastlines(linewidth=0.5)
map.drawrivers(linewidth=0.75,color='white')
map.drawparallels(N.arange(-90,120,30),labels=[0,0,0,0],linewidth=0.25)
map.drawmeridians(N.arange(-720,750,30),labels=[0,0,0,0],linewidth=0.25)
map.fillcontinents('white')
data, x, y = map.transform_scalar(sp_lim,tlon,tlat,nlon,nlat,returnxy=True)
IM  = map.imshow(data,norm=colors.normalize(vmin=0,vmax=6.5),cmap=cmap)
CB  = fig.colorbar(IM,ax=ax,shrink=0.5,aspect=12,drawedges=True,ticks=cbticks,
        boundaries=cblevels,values=cbticks)
CB.ax.set_yticklabels(cbticklabels)
for line in CB.ax.get_yticklines(): # remove tick lines
    line.set_markersize(0)

bottom_labels(ax,case.replace('_',' '),'',year_string,fontsize=10)
ax.set(title='Small Phyto. growth limitation factor in upper %.0f m'%(zref))
fig.savefig(outfile,dpi=150,bbox_inches='tight',pad_inches=0.2)
pl.close(fig)

# Diatom nutrient limitation plot
if POPDIAGPY == 'TRUE':
  outfile = os.path.join(outdir,'map_nutlim_diat.png')
Example #35
0
# plot topography/bathymetry as an image.

# create the figure and axes instances.
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# setup of basemap ('lcc' = lambert conformal conic).
# use major and minor sphere radii from WGS84 ellipsoid.
m = Basemap(projection='npstere',
            boundinglat=70,
            lon_0=0,
            resolution='h',
            ax=ax)
# 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 = m.transform_scalar(topoin, lons, lats, nx, ny)
# plot image over map with imshow.
im = m.imshow(topodat, cm.Blues_r, vmax=0)
# draw coastlines and political boundaries.
m.drawcoastlines()
m.fillcontinents(color='grey')
# draw parallels and meridians.
# label on left and bottom of map.
parallels = np.arange(50., 90, 5.)
m.drawparallels(parallels, labels=[1, 0, 0, 0])
meridians = np.arange(10., 360., 30.)
m.drawmeridians(meridians, labels=[0, 0, 0, 1])
#plot locations
xp, yp = m([10, 100, 215], [88, 84, 80])
m.scatter(xp, yp, color='red', s=60, edgecolors='k')
# add colorbar
Example #36
0
lons = np.linspace(20,380,num=hsize);#etopodata.variables['ETOPO05_X'][:]
lats = np.linspace(-90,90,num=vsize);#etopodata.variables['ETOPO05_Y'][:]
topoin,lons = shiftgrid(180.,topoin,lons,start=False)
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])

# ('lcc' = lambert conformal conic).
# use major and minor sphere radii from WGS84 ellipsoid.
m = Basemap(llcrnrlon=-145.5,llcrnrlat=1.,urcrnrlon=-2.566,urcrnrlat=46.352,\
            rsphere=(6378137.00,6356752.3142),\
            resolution='l',area_thresh=1000.,projection='lcc',\
            lat_1=50.,lon_0=-107.,ax=ax)

# 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 = m.transform_scalar(topoin,lons,lats,nx,ny)

# plot image over map with imshow.
im = m.imshow(topodat,cm.GMT_haxby)

# draw coastlines and boundaries.
m.drawcoastlines()
m.drawcountries()
m.drawstates()
# draw parallels and meridians.
# label on left and bottom of map.
parallels = np.arange(0.,80,20.)
m.drawparallels(parallels,labels=[1,0,0,1])
meridians = np.arange(10.,360.,30.)
m.drawmeridians(meridians,labels=[1,0,0,1])
# add colorbar
merid_values = np.arange(-100.794 - (0.0325 / 2), -100.4, 0.0325)

parallels = m.drawparallels(paral_values,
                            labels=[1, 0, 0, 0],
                            fontsize=tk_fs + 1,
                            fmt='%.2f',
                            linewidth=0.0)  #,rotation=90)
meridians = m.drawmeridians(merid_values,
                            labels=[0, 0, 0, 1],
                            fontsize=tk_fs + 1,
                            fmt='%.2f',
                            linewidth=0.0)

nx = int((m.xmax - m.xmin) / 10.) + 1
ny = int((m.ymax - m.ymin) / 10.) + 1
topodat = m.transform_scalar(topoin, e_lon, e_lat, nx, ny)

# plot image over map with imshow.
im = m.imshow(topodat, cmap='gist_earth')  #, alpha=0.8)

# for pcolormesh plotting
lon_shift = 0.5 * (lon[0, :, 1:] + lon[0, :, :-1])
lat_shift = 0.5 * (lat[0, 1:, :] + lat[0, :-1, :])
x, y = m(lon_shift[:-1, :], lat_shift[:, :-1])

CS = m.pcolormesh(x,
                  y,
                  power[0, 1:, 1:] * 0,
                  vmax=20,
                  vmin=0,
                  cmap='binary',
Example #38
0
def gen_fig_map(nivel_ref, lat_vol, lon_vol, latdelta, londelta, zona, cod, gs,
                factorlatlon, km, test_deg, op, fechas):
    ##CREACION DE MAPA
    ax2 = plt.subplot(gs[1])
    url = "C:/nc/" + str(zona) + "/" + cod + ".nc"
    etopodata = Dataset(url)
    try:
        topoin = etopodata.variables['z'][:]
        lons = etopodata.variables['x'][:]
        lats = etopodata.variables['y'][:]
    except:
        topoin = etopodata.variables['z_range'][:]
        lons = etopodata.variables['x_range'][:]
        lats = etopodata.variables['y_range'][:]
    m = Basemap(projection='merc',
                llcrnrlat=lat_vol - latdelta,
                urcrnrlat=lat_vol + latdelta,
                llcrnrlon=lon_vol - londelta,
                urcrnrlon=lon_vol + londelta,
                lat_ts=(max(lats) + min(lats)) / 2,
                resolution='i')

    #LUZ
    ls = LightSource(azdeg=180, altdeg=60)
    # transform to nx x ny regularly spaced 5km native projection grid
    nx = int((m.xmax - m.xmin) / 50.) + 1
    ny = int((m.ymax - m.ymin) / 50.) + 1
    topodat, x, y = m.transform_scalar(topoin,
                                       lons,
                                       lats,
                                       nx,
                                       ny,
                                       returnxy=True)
    cmap = plt.get_cmap('gist_earth')

    def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
        new_cmap = colors.LinearSegmentedColormap.from_list(
            'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name,
                                                a=minval,
                                                b=maxval),
            cmap(np.linspace(minval, maxval, n)))
        return new_cmap

    new_cmap = truncate_colormap(cmap, 0.1, 0.7)
    # plot image over map with imshow.
    #im = m.imshow(topodat,cmap='gist_earth')
    rgb = ls.shade(topodat, new_cmap)
    #PLOTEO DE MAPA
    im = m.imshow(rgb, alpha=0.6)
    plt.gca().add_patch(
        patches.Rectangle((0, 0), km * 1250, km * 370, facecolor="#ffffff"))
    m.drawmapscale(lon_vol - (test_deg * 0.35),
                   lat_vol - (latdelta * 0.875),
                   lon_vol,
                   lat_vol,
                   km,
                   barstyle='fancy',
                   format='%.1f')
    if op == 'reav':
        ()
    else:
        plt.text(0.02,
                 0.95,
                 str(fechas[0]) + " - " + str(fechas[1]),
                 fontsize=8,
                 color='k',
                 ha='left',
                 bbox=dict(facecolor='111111', alpha=0.85, pad=2),
                 transform=plt.gca().transAxes)
    return gs, m
Example #39
0
meridians = np.arange(-180,180,delon)
m.drawmeridians(meridians,labels=[1,1,1,1])
plt.title('Surface Winds Winds and Pressure (lat-lon grid)',y=1.075)
 
# plot vectors in map projection coordinates.

# 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.drawmapscale(llcrnrlon+lonoff, llcrnrlat+latoff, llcrnrlon+lonoff, llcrnrlat+latoff, scale_len, \
                   fontsize = 14, barstyle='fancy', zorder=100)

    ##########################################################################################
    # plot intensity grid from shakemap
    ##########################################################################################

    # set topo data
    data = nc.variables['z'][:] / zscale
    lons = nc.variables['x'][:]
    lats = nc.variables['y'][:]

    # transform topo to metres
    nx = int((m.xmax - m.xmin) / mdiv) + 1
    ny = int((m.ymax - m.ymin) / mdiv) + 1
    topodat = m.transform_scalar(data, lons, lats, nx, ny)

    print 'Resampling data...'
    N = 500j
    extent = (llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat)

    xs, ys = mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N]
    resampled = griddata(xmllons, xmllats, mmi, xs, ys, interp='linear')

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

    # nas interprets grids differently
    if cwd.startswith('/nas'):
        mmidat = m.transform_scalar(resampled.T, lons, lats, nx, ny)
print('Resampling data...')
N = 500j
extent = (minlon-mbuff_l, maxlon+mbuff_r, minlat-mbuff_r, maxlat+0)
xs,ys = mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N]
	
resampled = griddata(points, bvals, (xs, ys), method='linear')

# 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
nx = int((m.xmax-m.xmin)/3000.)+1
ny = int((m.ymax-m.ymin)/3000.)+1

transhaz = m.transform_scalar(resampled.T,lons,lats,nx,ny)

masked_array = ma.array(transhaz, mask=isnan(transhaz))

m.imshow(masked_array, cmap=cmap, extent=extent, norm=norm, zorder=0)

##########################################################################################
# get land & lake polygons for masking
##########################################################################################
# mask non-AU polygons
nonmask = [0, 5, 8, 10, 13, 14, 15, 16, 17, 20, 21] #, 2, 3, 4, 6, 7, 11, 13, 16, 17] # polygon number
landpolys = []
for pidx, polygon in enumerate(m.landpolygons):
    maskPoly = True
    for nmidx in nonmask:
        if pidx == nmidx:
Example #42
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
Example #43
0
xres = 360.0 / nx
lats = linspace(-90.0, 90.0, ny)
lons = linspace(0.0, 360.0 - 360.0/nx, nx)
lllat  = 20.0
lllon  = 120.0
urlat  = 50.0
urlon  = 160.0

nnx    = int( (urlon - lllon)/ xres)
nny    = int( (urlat - lllat)/ yres)
#-----------------------
dir_his = "/media/disk2/out/CMIP5/day/NorESM1-M/historical/r1i1p1/tracks/dura24/wfpr/mp"
shis   = dir_his + "/mp.p00.00.c01.04.r1000.nw17_DJF_day_NorESM1-M_historical_r1i1p1.bn"
adatin = fromfile(shis, float32).reshape(17,96,144)[0]
#
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)
#--

adat   = M.transform_scalar(adatin, lons, lats, nnx, nny)



#--
im     = M.imshow(adat, origin="lower", cmap="RdBu", interpolation="nearest")
M.drawcoastlines()
#
plt.savefig("a2.png")
plt.show()
Example #44
0
def modelMap(grids, shakefile=None, suptitle=None, inventory_shapefile=None,
             plotorder=None, maskthreshes=None, colormaps=None, boundaries=None,
             zthresh=0, scaletype='continuous', lims=None, logscale=False,
             ALPHA=0.7, maproads=True, mapcities=True, isScenario=False,
             roadfolder=None, topofile=None, cityfile=None, oceanfile=None,
             roadcolor='#6E6E6E', watercolor='#B8EEFF', countrycolor='#177F10',
             outputdir=None, savepdf=True, savepng=True, showplots=False,
             roadref='unknown', cityref='unknown', oceanref='unknown',
             printparam=False, ds=True, dstype='mean', upsample=False):
    """
    This function creates maps of mapio grid layers (e.g. liquefaction or
    landslide models with their input layers)
    All grids must use the same bounds
    TO DO change so that all input layers do not have to have the same bounds,
    test plotting multiple probability layers, and add option so that if PDF and
    PNG aren't output, opens plot on screen using plt.show()

    :param grids: Dictionary of N layers and metadata formatted like:
        maplayers['layer name']={
        'grid': mapio grid2D object,
        'label': 'label for colorbar and top line of subtitle',
        'type': 'output or input to model',
        'description': 'detailed description of layer for subtitle'}.
      Layer names must be unique.
    :type name: Dictionary or Ordered dictionary - import collections;
      grids = collections.OrderedDict()
    :param shakefile: optional ShakeMap file (url or full file path) to extract information for labels and folder names
    :type shakefile: Shakemap Event Dictionary
    :param suptitle: This will be displayed at the top of the plots and in the
      figure names
    :type suptitle: string
    :param plotorder: List of keys describing the order to plot the grids, if
      None and grids is an ordered dictionary, it will use the order of the
      dictionary, otherwise it will choose order which may be somewhat random
      but it will always put a probability grid first
    :type plotorder: list
    :param maskthreshes: N x 1 array or list of lower thresholds for masking
      corresponding to order in plotorder or order of OrderedDict if plotorder
      is None. If grids is not an ordered dict and plotorder is not specified,
      this will not work right. If None (default), nothing will be masked
    :param colormaps: List of strings of matplotlib colormaps (e.g. cm.autumn_r)
      corresponding to plotorder or order of dictionary if plotorder is None.
      The list can contain both strings and None e.g. colormaps = ['cm.autumn',
      None, None, 'cm.jet'] and None's will default to default colormap
    :param boundaries: None to show entire study area, 'zoom' to zoom in on the
      area of action (only works if there is a probability layer) using zthresh
      as a threshold, or a dictionary defining lats and lons in the form of
      boundaries.xmin = minlon, boundaries.xmax = maxlon, boundaries.ymin =
      min lat, boundaries.ymax = max lat
    :param zthresh: threshold for computing zooming bounds, only used if
      boundaries = 'zoom'
    :type zthresh: float
    :param scaletype: Type of scale for plotting, 'continuous' or 'binned' -
      will be reflected in colorbar
    :type scaletype: string
    :param lims: None or Nx1 list of tuples or numpy arrays corresponding to
      plotorder defining the limits for saturating the colorbar (vmin, vmax) if
      scaletype is continuous or the bins to use (clev) if scaletype if binned.
      The list can contain tuples, arrays, and Nones, e.g. lims = [(0., 10.),
      None, (0.1, 1.5), np.linspace(0., 1.5, 15)]. When None is specified, the
      program will estimate the limits, when an array is specified but the scale
      type is continuous, vmin will be set to min(array) and vmax will be set
      to max(array)
    :param lims: None or Nx1 list of Trues and Falses corresponding to
      plotorder defining whether to use a linear or log scale (log10) for
      plotting the layer. This will be reflected in the labels
    :param ALPHA: Transparency for mapping, if there is a hillshade that will
      plot below each layer, it is recommended to set this to at least 0.7
    :type ALPHA: float
    :param maproads: Whether to show roads or not, default True, but requires
      that roadfile is specified and valid to work
    :type maproads: boolean
    :param mapcities: Whether to show cities or not, default True, but requires
      that cityfile is specified and valid to work
    :type mapcities: boolean
    :param isScenario: Whether this is a scenario (True) or a real event (False)
      (default False)
    :type isScenario: boolean
    :param roadfolder: Full file path to folder containing road shapefiles
    :type roadfolder: string
    :param topofile: Full file path to topography grid (GDAL compatible) - this
      is only needed to make a hillshade if a premade hillshade is not specified
    :type topofile: string
    :param cityfile: Full file path to Pager file containing city & population
      information
    :type cityfile: string
    :param roadcolor: Color to use for roads, if plotted, default #6E6E6E
    :type roadcolor: Hex color or other matplotlib compatible way of defining
      color
    :param watercolor: Color to use for oceans, lakes, and rivers, default
      #B8EEFF
    :type watercolor: Hex color or other matplotlib compatible way of defining
      color
    :param countrycolor: Color for country borders, default #177F10
    :type countrycolor: Hex color or other matplotlib compatible way of defining
      color
    :param outputdir: File path for outputting figures, if edict is defined, a
      subfolder based on the event id will be created in this folder. If None,
      will use current directory
    :param savepdf: True to save pdf figure, False to not
    :param savepng: True to save png figure, False to not
    :param ds: True to allow downsampling for display (necessary when arrays
      are quite large, False to not allow)
    :param dstype: What function to use in downsampling, options are 'min',
      'max', 'median', or 'mean'
    :param upsample: True to upsample the layer to the DEM resolution for better
      looking hillshades

    :returns:
        * PDF and/or PNG of map
        * Downsampled and trimmed version of input grids. If no
        modification was needed for plotting, this will be identical to grids but
        without the metadata

    """

    if suptitle is None:
        suptitle = ' '

    plt.ioff()

    defaultcolormap = cm.jet

    if shakefile is not None:
        edict = ShakeGrid.load(shakefile, adjust='res').getEventDict()
        temp = ShakeGrid.load(shakefile, adjust='res').getShakeDict()
        edict['eventid'] = temp['shakemap_id']
        edict['version'] = temp['shakemap_version']
    else:
        edict = None

    # Get output file location
    if outputdir is None:
        print('No output location given, using current directory for outputs\n')
        outputdir = os.getcwd()
    if edict is not None:
        outfolder = os.path.join(outputdir, edict['event_id'])
    else:
        outfolder = outputdir
    if not os.path.isdir(outfolder):
        os.makedirs(outfolder)

    # Get plotting order, if not specified
    if plotorder is None:
        plotorder = list(grids.keys())

    # Get boundaries to use for all plots
    cut = True
    if boundaries is None:
        cut = False
        keytemp = list(grids.keys())
        boundaries = grids[keytemp[0]]['grid'].getGeoDict()
    elif boundaries == 'zoom':
        # Find probability layer (will just take the maximum bounds if there is
        # more than one)
        keytemp = list(grids.keys())
        key1 = [key for key in keytemp if 'model' in key.lower()]
        if len(key1) == 0:
            print('Could not find model layer to use for zoom, using default boundaries')
            keytemp = list(grids.keys())
            boundaries = grids[keytemp[0]]['grid'].getGeoDict()
        else:
            lonmax = -1.e10
            lonmin = 1.e10
            latmax = -1.e10
            latmin = 1.e10
            for key in key1:
                # get lat lons of areas affected and add, if no areas affected,
                # switch to shakemap boundaries
                temp = grids[key]['grid']
                xmin, xmax, ymin, ymax = temp.getBounds()
                lons = np.linspace(xmin, xmax, temp.getGeoDict().nx)
                lats = np.linspace(ymax, ymin, temp.getGeoDict().ny)  # backwards so it plots right
                row, col = np.where(temp.getData() > float(zthresh))
                lonmin = lons[col].min()
                lonmax = lons[col].max()
                latmin = lats[row].min()
                latmax = lats[row].max()
                # llons, llats = np.meshgrid(lons, lats)  # make meshgrid
                # llons1 = llons[temp.getData() > float(zthresh)]
                # llats1 = llats[temp.getData() > float(zthresh)]
                # if llons1.min() < lonmin:
                #     lonmin = llons1.min()
                # if llons1.max() > lonmax:
                #     lonmax = llons1.max()
                # if llats1.min() < latmin:
                #     latmin = llats1.min()
                # if llats1.max() > latmax:
                #     latmax = llats1.max()
            boundaries1 = {'dx': 100, 'dy': 100., 'nx': 100., 'ny': 100}  # dummy fillers, only really care about bounds
            if xmin < lonmin-0.15*(lonmax-lonmin):
                boundaries1['xmin'] = lonmin-0.1*(lonmax-lonmin)
            else:
                boundaries1['xmin'] = xmin
            if xmax > lonmax+0.15*(lonmax-lonmin):
                boundaries1['xmax'] = lonmax+0.1*(lonmax-lonmin)
            else:
                boundaries1['xmax'] = xmax
            if ymin < latmin-0.15*(latmax-latmin):
                boundaries1['ymin'] = latmin-0.1*(latmax-latmin)
            else:
                boundaries1['ymin'] = ymin
            if ymax > latmax+0.15*(latmax-latmin):
                boundaries1['ymax'] = latmax+0.1*(latmax-latmin)
            else:
                boundaries1['ymax'] = ymax
            boundaries = GeoDict(boundaries1, adjust='res')
    else:
        # SEE IF BOUNDARIES ARE SAME AS BOUNDARIES OF LAYERS
        keytemp = list(grids.keys())
        tempgdict = grids[keytemp[0]]['grid'].getGeoDict()
        if np.abs(tempgdict.xmin-boundaries['xmin']) < 0.05 and \
           np.abs(tempgdict.ymin-boundaries['ymin']) < 0.05 and \
           np.abs(tempgdict.xmax-boundaries['xmax']) < 0.05 and \
           np.abs(tempgdict.ymax - boundaries['ymax']) < 0.05:
            print('Input boundaries are almost the same as specified boundaries, no cutting needed')
            boundaries = tempgdict
            cut = False
        else:
            try:
                if boundaries['xmin'] > boundaries['xmax'] or \
                   boundaries['ymin'] > boundaries['ymax']:
                    print('Input boundaries are not usable, using default boundaries')
                    keytemp = list(grids.keys())
                    boundaries = grids[keytemp[0]]['grid'].getGeoDict()
                    cut = False
                else:
                    # Build dummy GeoDict
                    boundaries = GeoDict({'xmin': boundaries['xmin'],
                                          'xmax': boundaries['xmax'],
                                          'ymin': boundaries['ymin'],
                                          'ymax': boundaries['ymax'],
                                          'dx': 100.,
                                          'dy': 100.,
                                          'ny': 100.,
                                          'nx': 100.},
                                         adjust='res')
            except:
                print('Input boundaries are not usable, using default boundaries')
                keytemp = list(grids.keys())
                boundaries = grids[keytemp[0]]['grid'].getGeoDict()
                cut = False

    # Pull out bounds for various uses
    bxmin, bxmax, bymin, bymax = boundaries.xmin, boundaries.xmax, boundaries.ymin, boundaries.ymax

    # Determine if need a single panel or multi-panel plot and if multi-panel,
    # how many and how it will be arranged
    fig = plt.figure()
    numpanels = len(grids)
    if numpanels == 1:
        rowpan = 1
        colpan = 1
        # create the figure and axes instances.
        fig.set_figwidth(5)
    elif numpanels == 2 or numpanels == 4:
        rowpan = np.ceil(numpanels/2.)
        colpan = 2
        fig.set_figwidth(13)
    else:
        rowpan = np.ceil(numpanels/3.)
        colpan = 3
        fig.set_figwidth(15)
    if rowpan == 1:
        fig.set_figheight(rowpan*6.0)
    else:
        fig.set_figheight(rowpan*5.3)

    # Need to update naming to reflect the shakemap version once can get
    # getHeaderData to work, add edict['version'] back into title, maybe
    # shakemap id also?
    fontsizemain = 14.
    fontsizesub = 12.
    fontsizesmallest = 10.
    if rowpan == 1.:
        fontsizemain = 12.
        fontsizesub = 10.
        fontsizesmallest = 8.
    if edict is not None:
        if isScenario:
            title = edict['event_description']
        else:
            timestr = edict['event_timestamp'].strftime('%b %d %Y')
            title = 'M%.1f %s v%i - %s' % (edict['magnitude'], timestr, edict['version'], edict['event_description'])
        plt.suptitle(title+'\n'+suptitle, fontsize=fontsizemain)
    else:
        plt.suptitle(suptitle, fontsize=fontsizemain)

    clear_color = [0, 0, 0, 0.0]

    # Cut all of them and release extra memory

    xbuff = (bxmax-bxmin)/10.
    ybuff = (bymax-bymin)/10.
    cutxmin = bxmin-xbuff
    cutymin = bymin-ybuff
    cutxmax = bxmax+xbuff
    cutymax = bymax+ybuff
    if cut is True:
        newgrids = collections.OrderedDict()
        for k, layer in enumerate(plotorder):
            templayer = grids[layer]['grid']
            try:
                newgrids[layer] = {'grid': templayer.cut(cutxmin, cutxmax, cutymin, cutymax, align=True)}
            except Exception as e:
                print(('Cutting failed, %s, continuing with full layers' % e))
                newgrids = grids
                continue
        del templayer
        gc.collect()
    else:
        newgrids = grids
    tempgdict = newgrids[list(grids.keys())[0]]['grid'].getGeoDict()

    # Upsample layers to same as topofile if desired for better looking hillshades
    if upsample is True and topofile is not None:
        try:
            topodict = GDALGrid.getFileGeoDict(topofile)
            if topodict.dx >= tempgdict.dx or topodict.dy >= tempgdict.dy:
                print('Upsampling not possible, resolution of results already smaller than DEM')
                pass
            else:
                tempgdict1 = GeoDict({'xmin': tempgdict.xmin-xbuff,
                                      'ymin': tempgdict.ymin-ybuff,
                                      'xmax': tempgdict.xmax+xbuff,
                                      'ymax': tempgdict.ymax+ybuff,
                                      'dx': topodict.dx,
                                      'dy': topodict.dy,
                                      'nx': topodict.nx,
                                      'ny': topodict.ny},
                                     adjust='res')
                tempgdict2 = tempgdict1.getBoundsWithin(tempgdict)
                for k, layer in enumerate(plotorder):
                    newgrids[layer]['grid'] = newgrids[layer]['grid'].subdivide(tempgdict2)
        except:
            print('Upsampling failed, continuing')

    # Downsample all of them for plotting, if needed, and replace them in
    # grids (to save memory)
    tempgrid = newgrids[list(grids.keys())[0]]['grid']
    xsize = tempgrid.getGeoDict().nx
    ysize = tempgrid.getGeoDict().ny
    inchesx, inchesy = fig.get_size_inches()
    divx = int(np.round(xsize/(500.*inchesx)))
    divy = int(np.round(ysize/(500.*inchesy)))
    xmin, xmax, ymin, ymax = tempgrid.getBounds()
    gdict = tempgrid.getGeoDict()  # Will be replaced if downsampled
    del tempgrid
    gc.collect()

    if divx <= 1:
        divx = 1
    if divy <= 1:
        divy = 1
    if (divx > 1. or divy > 1.) and ds:
        if dstype == 'max':
            func = np.nanmax
        elif dstype == 'min':
            func = np.nanmin
        elif dstype == 'med':
            func = np.nanmedian
        else:
            func = np.nanmean
        for k, layer in enumerate(plotorder):
            layergrid = newgrids[layer]['grid']
            dat = block_reduce(layergrid.getData().copy(),
                               block_size=(divy, divx),
                               cval=float('nan'),
                               func=func)
            if k == 0:
                lons = block_reduce(np.linspace(xmin, xmax, layergrid.getGeoDict().nx),
                                    block_size=(divx,),
                                    func=np.mean,
                                    cval=float('nan'))
                if math.isnan(lons[-1]):
                    lons[-1] = lons[-2] + (lons[1]-lons[0])
                lats = block_reduce(np.linspace(ymax, ymin, layergrid.getGeoDict().ny),
                                    block_size=(divy,),
                                    func=np.mean,
                                    cval=float('nan'))
                if math.isnan(lats[-1]):
                    lats[-1] = lats[-2] + (lats[1]-lats[0])
                gdict = GeoDict({'xmin': lons.min(),
                                 'xmax': lons.max(),
                                 'ymin': lats.min(),
                                 'ymax': lats.max(),
                                 'dx': np.abs(lons[1]-lons[0]),
                                 'dy': np.abs(lats[1]-lats[0]),
                                 'nx': len(lons),
                                 'ny': len(lats)},
                                adjust='res')
            newgrids[layer]['grid'] = Grid2D(dat, gdict)
        del layergrid, dat
    else:
        lons = np.linspace(xmin, xmax, xsize)
        lats = np.linspace(ymax, ymin, ysize)  # backwards so it plots right side up

    #make meshgrid
    llons1, llats1 = np.meshgrid(lons, lats)

    # See if there is an oceanfile for masking
    bbox = PolygonSH(((cutxmin, cutymin), (cutxmin, cutymax), (cutxmax, cutymax), (cutxmax, cutymin)))
    if oceanfile is not None:
        try:
            f = fiona.open(oceanfile)
            oc = next(f)
            f.close
            shapes = shape(oc['geometry'])
            # make boundaries into a shape
            ocean = shapes.intersection(bbox)
        except:
            print('Not able to read specified ocean file, will use default ocean masking')
            oceanfile = None
    if inventory_shapefile is not None:
        try:
            f = fiona.open(inventory_shapefile)
            invshp = list(f.items(bbox=(bxmin, bymin, bxmax, bymax)))
            f.close()
            inventory = [shape(inv[1]['geometry']) for inv in invshp]
        except:
            print('unable to read inventory shapefile specified, will not plot inventory')
            inventory_shapefile = None

    # # Find cities that will be plotted
    if mapcities is True and cityfile is not None:
        try:
            mycity = BasemapCities.loadFromGeoNames(cityfile=cityfile)
            bcities = mycity.limitByBounds((bxmin, bxmax, bymin, bymax))
            #bcities = bcities.limitByPopulation(40000)
            bcities = bcities.limitByGrid(nx=4, ny=4, cities_per_grid=2)
        except:
            print('Could not read in cityfile, not plotting cities')
            mapcities = False
            cityfile = None

    # Load in topofile
    if topofile is not None:
        try:
            topomap = GDALGrid.load(topofile, resample=True, method='linear', samplegeodict=gdict)
        except:
            topomap = GMTGrid.load(topofile, resample=True, method='linear', samplegeodict=gdict)
        topodata = topomap.getData().copy()
        # mask oceans if don't have ocean shapefile
        if oceanfile is None:
            topodata = maskoceans(llons1, llats1, topodata, resolution='h', grid=1.25, inlands=True)
    else:
        print('no hillshade is possible\n')
        topomap = None
        topodata = None

    # Load in roads, if needed
    if maproads is True and roadfolder is not None:
        try:
            roadslist = []
            for folder in os.listdir(roadfolder):
                road1 = os.path.join(roadfolder, folder)
                shpfiles = glob.glob(os.path.join(road1, '*.shp'))
                if len(shpfiles):
                    shpfile = shpfiles[0]
                    f = fiona.open(shpfile)
                    shapes = list(f.items(bbox=(bxmin, bymin, bxmax, bymax)))
                    for shapeid, shapedict in shapes:
                        roadslist.append(shapedict)
                    f.close()
        except:
            print('Not able to plot roads')
            roadslist = None

    val = 1
    for k, layer in enumerate(plotorder):
        layergrid = newgrids[layer]['grid']
        if 'label' in list(grids[layer].keys()):
            label1 = grids[layer]['label']
        else:
            label1 = layer
        try:
            sref = grids[layer]['description']['name']
        except:
            sref = None
        ax = fig.add_subplot(rowpan, colpan, val)
        val += 1
        clat = bymin + (bymax-bymin)/2.0
        clon = bxmin + (bxmax-bxmin)/2.0
        # setup of basemap ('lcc' = lambert conformal conic).
        # use major and minor sphere radii from WGS84 ellipsoid.
        m = Basemap(llcrnrlon=bxmin, llcrnrlat=bymin, urcrnrlon=bxmax, urcrnrlat=bymax,
                    rsphere=(6378137.00, 6356752.3142),
                    resolution='l', area_thresh=1000., projection='lcc',
                    lat_1=clat, lon_0=clon, ax=ax)

        x1, y1 = m(llons1, llats1)  # get projection coordinates
        axsize = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
        if k == 0:
            wid, ht = axsize.width, axsize.height
        if colormaps is not None and \
           len(colormaps) == len(newgrids) and \
           colormaps[k] is not None:
            palette = colormaps[k]
        else:  # Find preferred default color map for each type of layer
            if 'prob' in layer.lower() or 'pga' in layer.lower() or \
               'pgv' in layer.lower() or 'cohesion' in layer.lower() or \
               'friction' in layer.lower() or 'fs' in layer.lower():
                palette = cm.jet
            elif 'slope' in layer.lower():
                palette = cm.gnuplot2
            elif 'precip' in layer.lower():
                palette = cm2.s3pcpn
            else:
                palette = defaultcolormap

        if topodata is not None:
            if k == 0:
                ptopo = m.transform_scalar(
                    np.flipud(topodata), lons+0.5*gdict.dx,
                    lats[::-1]-0.5*gdict.dy, np.round(300.*wid),
                    np.round(300.*ht), returnxy=False, checkbounds=False,
                    order=1, masked=False)
                #use lightsource class to make our shaded topography
                ls = LightSource(azdeg=135, altdeg=45)
                ls1 = LightSource(azdeg=120, altdeg=45)
                ls2 = LightSource(azdeg=225, altdeg=45)
                intensity1 = ls1.hillshade(ptopo, fraction=0.25, vert_exag=1.)
                intensity2 = ls2.hillshade(ptopo, fraction=0.25, vert_exag=1.)
                intensity = intensity1*0.5 + intensity2*0.5
                #hillshm_im = m.transform_scalar(np.flipud(hillshm), lons, lats[::-1], np.round(300.*wid), np.round(300.*ht), returnxy=False, checkbounds=False, order=0, masked=False)
            #m.imshow(hillshm_im, cmap='Greys', vmin=0., vmax=3., zorder=1, interpolation='none')  # vmax = 3 to soften colors to light gray
            #m.pcolormesh(x1, y1, hillshm, cmap='Greys', linewidth=0., rasterized=True, vmin=0., vmax=3., edgecolors='none', zorder=1);
            # plt.draw()

        # Get the data
        dat = layergrid.getData().copy()

        # mask out anything below any specified thresholds
        # Might need to move this up to before downsampling...might give illusion of no hazard in places where there is some that just got averaged out
        if maskthreshes is not None and len(maskthreshes) == len(newgrids):
            if maskthreshes[k] is not None:
                dat[dat <= maskthreshes[k]] = float('NaN')
                dat = np.ma.array(dat, mask=np.isnan(dat))

        if logscale is not False and len(logscale) == len(newgrids):
            if logscale[k] is True:
                dat = np.log10(dat)
                label1 = r'$log_{10}$(' + label1 + ')'

        if scaletype.lower() == 'binned':
            # Find order of range to know how to scale
            order = np.round(np.log(np.nanmax(dat) - np.nanmin(dat)))
            if order < 1.:
                scal = 10**-order
            else:
                scal = 1.
            if lims is None or len(lims) != len(newgrids):
                clev = (np.linspace(np.floor(scal*np.nanmin(dat)), np.ceil(scal*np.nanmax(dat)), 10))/scal
            else:
                if lims[k] is None:
                    clev = (np.linspace(np.floor(scal*np.nanmin(dat)), np.ceil(scal*np.nanmax(dat)), 10))/scal
                else:
                    clev = lims[k]
            # Adjust to colorbar levels
            dat[dat < clev[0]] = clev[0]
            for j, level in enumerate(clev[:-1]):
                dat[(dat >= clev[j]) & (dat < clev[j+1])] = clev[j]
            # So colorbar saturates at top
            dat[dat > clev[-1]] = clev[-1]
            #panelhandle = m.contourf(x1, y1, datm, clev, cmap=palette, linewidth=0., alpha=ALPHA, rasterized=True)
            vmin = clev[0]
            vmax = clev[-1]
        else:
            if lims is not None and len(lims) == len(newgrids):
                if lims[k] is None:
                    vmin = np.nanmin(dat)
                    vmax = np.nanmax(dat)
                else:
                    vmin = lims[k][0]
                    vmax = lims[k][-1]
            else:
                vmin = np.nanmin(dat)
                vmax = np.nanmax(dat)

        # Mask out cells overlying oceans or block with a shapefile if available
        if oceanfile is None:
            dat = maskoceans(llons1, llats1, dat, resolution='h', grid=1.25, inlands=True)
        else:
            #patches = []
            if type(ocean) is PolygonSH:
                ocean = [ocean]
            for oc in ocean:
                patch = getProjectedPatch(oc, m, edgecolor="#006280", facecolor=watercolor, lw=0.5, zorder=4.)
                #x, y = m(oc.exterior.xy[0], oc.exterior.xy[1])
                #xy = zip(x, y)
                #patch = Polygon(xy, facecolor=watercolor, edgecolor="#006280", lw=0.5, zorder=4.)
                ##patches.append(Polygon(xy, facecolor=watercolor, edgecolor=watercolor, zorder=500.))
                ax.add_patch(patch)
            ##ax.add_collection(PatchCollection(patches))

        if inventory_shapefile is not None:
            for in1 in inventory:
                if 'point' in str(type(in1)):
                    x, y = in1.xy
                    x = x[0]
                    y = y[0]
                    m.scatter(x, y, c='m', s=50, latlon=True, marker='^',
                              zorder=100001)
                else:
                    x, y = m(in1.exterior.xy[0], in1.exterior.xy[1])
                    xy = list(zip(x, y))
                    patch = Polygon(xy, facecolor='none', edgecolor='k', lw=0.5, zorder=10.)
                    #patches.append(Polygon(xy, facecolor=watercolor, edgecolor=watercolor, zorder=500.))
                    ax.add_patch(patch)
        palette.set_bad(clear_color, alpha=0.0)
        # Plot it up
        dat_im = m.transform_scalar(
            np.flipud(dat), lons+0.5*gdict.dx, lats[::-1]-0.5*gdict.dy,
            np.round(300.*wid), np.round(300.*ht), returnxy=False,
            checkbounds=False, order=0, masked=True)
        if topodata is not None:  # Drape over hillshade
            #turn data into an RGBA image
            cmap = palette
            #adjust data so scaled between vmin and vmax and between 0 and 1
            dat1 = dat_im.copy()
            dat1[dat1 < vmin] = vmin
            dat1[dat1 > vmax] = vmax
            dat1 = (dat1 - vmin)/(vmax-vmin)
            rgba_img = cmap(dat1)
            maskvals = np.dstack((dat1.mask, dat1.mask, dat1.mask))
            rgb = np.squeeze(rgba_img[:, :, 0:3])
            rgb[maskvals] = 1.
            draped_hsv = ls.blend_hsv(rgb, np.expand_dims(intensity, 2))
            m.imshow(draped_hsv, zorder=3., interpolation='none')
            # This is just a dummy layer that will be deleted to make the
            # colorbar look right
            panelhandle = m.imshow(dat_im, cmap=palette, zorder=0.,
                                   vmin=vmin, vmax=vmax)
        else:
            panelhandle = m.imshow(dat_im, cmap=palette, zorder=3.,
                                   vmin=vmin, vmax=vmax, interpolation='none')
        #panelhandle = m.pcolormesh(x1, y1, dat, linewidth=0., cmap=palette, vmin=vmin, vmax=vmax, alpha=ALPHA, rasterized=True, zorder=2.);
        #panelhandle.set_edgecolors('face')
        # add colorbar
        cbfmt = '%1.1f'
        if vmax is not None and vmin is not None:
            if (vmax - vmin) < 1.:
                cbfmt = '%1.2f'
            elif vmax > 5.:  # (vmax - vmin) > len(clev):
                cbfmt = '%1.0f'

        #norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
        if scaletype.lower() == 'binned':
            cbar = fig.colorbar(panelhandle, spacing='proportional',
                                ticks=clev, boundaries=clev, fraction=0.036,
                                pad=0.04, format=cbfmt, extend='both')
            #cbar1 = ColorbarBase(cbar.ax, cmap=palette, norm=norm, spacing='proportional', ticks=clev, boundaries=clev, fraction=0.036, pad=0.04, format=cbfmt, extend='both', extendfrac='auto')

        else:
            cbar = fig.colorbar(panelhandle, fraction=0.036, pad=0.04,
                                extend='both', format=cbfmt)
            #cbar1 = ColorbarBase(cbar.ax, cmap=palette, norm=norm, fraction=0.036, pad=0.04, extend='both', extendfrac='auto', format=cbfmt)

        if topodata is not None:
            panelhandle.remove()

        cbar.set_label(label1, fontsize=10)
        cbar.ax.tick_params(labelsize=8)

        parallels = m.drawparallels(getMapLines(bymin, bymax, 3),
                                    labels=[1, 0, 0, 0], linewidth=0.5,
                                    labelstyle='+/-', fontsize=9, xoffset=-0.8,
                                    color='gray', zorder=100.)
        m.drawmeridians(getMapLines(bxmin, bxmax, 3), labels=[0, 0, 0, 1],
                        linewidth=0.5, labelstyle='+/-', fontsize=9,
                        color='gray', zorder=100.)
        for par in parallels:
            try:
                parallels[par][1][0].set_rotation(90)
            except:
                pass

        #draw roads on the map, if they were provided to us
        if maproads is True and roadslist is not None:
            try:
                for road in roadslist:
                    try:
                        xy = list(road['geometry']['coordinates'])
                        roadx, roady = list(zip(*xy))
                        mapx, mapy = m(roadx, roady)
                        m.plot(mapx, mapy, roadcolor, lw=0.5, zorder=9)
                    except:
                        continue
            except Exception as e:
                print(('Failed to plot roads, %s' % e))

        #add city names to map
        if mapcities is True and cityfile is not None:
            try:
                fontname = 'Arial'
                fontsize = 8
                if k == 0:  # Only need to choose cities first time and then apply to rest
                    fcities = bcities.limitByMapCollision(
                        m, fontname=fontname, fontsize=fontsize)
                    ctlats, ctlons, names = fcities.getCities()
                    cxis, cyis = m(ctlons, ctlats)
                for ctlat, ctlon, cxi, cyi, name in zip(ctlats, ctlons, cxis, cyis, names):
                    m.scatter(ctlon, ctlat, c='k', latlon=True, marker='.',
                              zorder=100000)
                    ax.text(cxi, cyi, name, fontname=fontname,
                            fontsize=fontsize, zorder=100000)
            except Exception as e:
                print('Failed to plot cities, %s' % e)

        #draw star at epicenter
        plt.sca(ax)
        if edict is not None:
            elat, elon = edict['lat'], edict['lon']
            ex, ey = m(elon, elat)
            plt.plot(ex, ey, '*', markeredgecolor='k', mfc='None', mew=1.0,
                     ms=15, zorder=10000.)

        m.drawmapboundary(fill_color=watercolor)

        m.fillcontinents(color=clear_color, lake_color=watercolor)
        m.drawrivers(color=watercolor)
        ##m.drawcoastlines()

        #draw country boundaries
        m.drawcountries(color=countrycolor, linewidth=1.0)

        #add map scale
        m.drawmapscale((bxmax+bxmin)/2., (bymin+(bymax-bymin)/9.), clon, clat, np.round((((bxmax-bxmin)*111)/5)/10.)*10, barstyle='fancy', zorder=10)

        # Add border
        autoAxis = ax.axis()
        rec = Rectangle((autoAxis[0]-0.7, autoAxis[2]-0.2), (autoAxis[1]-autoAxis[0])+1, (autoAxis[3]-autoAxis[2])+0.4, fill=False, lw=1, zorder=1e8)
        rec = ax.add_patch(rec)
        rec.set_clip_on(False)

        plt.draw()

        if sref is not None:
            label2 = '%s\nsource: %s' % (label1, sref)  # '%s\n' % label1 + r'{\fontsize{10pt}{3em}\selectfont{}%s}' % sref  #
        else:
            label2 = label1
        plt.title(label2, axes=ax, fontsize=fontsizesub)

        #draw scenario watermark, if scenario
        if isScenario:
            plt.sca(ax)
            cx, cy = m(clon, clat)
            plt.text(cx, cy, 'SCENARIO', rotation=45, alpha=0.10, size=72, ha='center', va='center', color='red')

        #if ds: # Could add this to print "downsampled" on map
        #    plt.text()

        if k == 1 and rowpan == 1:
            # adjust single level plot
            axsize = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
            ht2 = axsize.height
            fig.set_figheight(ht2*1.6)
        else:
            plt.tight_layout()

        # Make room for suptitle - tight layout doesn't account for it
        plt.subplots_adjust(top=0.92)

    if printparam is True:
        try:
            fig = plt.gcf()
            dictionary = grids['model']['description']['parameters']
            paramstring = 'Model parameters: '
            halfway = np.ceil(len(dictionary)/2.)
            for i, key in enumerate(dictionary):
                if i == halfway and colpan == 1:
                    paramstring += '\n'
                paramstring += ('%s = %s; ' % (key, dictionary[key]))
            print(paramstring)
            fig.text(0.01, 0.015, paramstring, fontsize=fontsizesmallest)
            plt.draw()
        except:
            print('Could not display model parameters')

    if edict is not None:
        eventid = edict['eventid']
    else:
        eventid = ''

    time1 = datetime.datetime.utcnow().strftime('%d%b%Y_%H%M')
    outfile = os.path.join(outfolder, '%s_%s_%s.pdf' % (eventid, suptitle, time1))
    pngfile = os.path.join(outfolder, '%s_%s_%s.png' % (eventid, suptitle, time1))

    if savepdf is True:
        print('Saving map output to %s' % outfile)
        plt.savefig(outfile, dpi=300)
    if savepng is True:
        print('Saving map output to %s' % pngfile)
        plt.savefig(pngfile)
    if showplots is True:
        plt.show()
    else:
        plt.close(fig)

    return newgrids
Example #45
0
    def __init__(self, in_file,
                    vg_files = [1],
                    data_type = 1, 
                    projection = 'cyl',                
                    color_map = 'jet',
                    time_zone = 0,
                    plot_contours = False,
                    plot_center = 't',
                    plot_meridians = True,
                    plot_parallels = True, 
                    plot_terminator = True,
                    resolution = 'c',
                    points_of_interest = [],
                    save_file = '',
                    run_quietly = False,
                    dpi = 150,
                    parent = None):

        self.run_quietly = run_quietly
        self.dpi=float(dpi)

        plot_parameters = VOAFile((in_file+'.voa'))
        plot_parameters.parse_file()
    
        if (plot_parameters.get_projection() != 'cyl'):
            print _("Error: Only lat/lon (type 1) input files are supported")
            sys.exit(1)

        grid = plot_parameters.get_gridsize()
        self.image_defs = VOAAreaPlot.IMG_TYPE_DICT[int(data_type)]

        # TODO This needs a little more work... what if the pcenter card is not specified
    
        if plot_center == 'p':
            plot_centre_location = plot_parameters.get_location(plot_parameters.P_CENTRE)
        else:        
            plot_centre_location = plot_parameters.get_location(plot_parameters.TX_SITE)
    
        self.points_of_interest = [plot_centre_location]        
        if len(points_of_interest) > 0:
            self.points_of_interest.extend(points_of_interest)

        imageBuf = P.zeros([grid, grid], float)

        area_rect = plot_parameters.get_area_rect()
        points = P.zeros([grid,grid], float)
        lons = P.zeros(grid*grid, float) 
        lats = P.zeros(grid*grid, float)
    
        lons = P.arange(area_rect.get_sw_lon(), area_rect.get_ne_lon()+0.001,(area_rect.get_ne_lon()-area_rect.get_sw_lon())/float(grid-1))
        lats = P.arange(area_rect.get_sw_lat(), area_rect.get_ne_lat()+0.001,(area_rect.get_ne_lat()-area_rect.get_sw_lat())/float(grid-1))
    
        colString = 'P.cm.'+color_map
        colMap = eval(colString)
    
        self.subplots = []        
        
        matplotlib.rcParams['axes.edgecolor'] = 'gray'
        matplotlib.rcParams['axes.facecolor'] = 'white'
        matplotlib.rcParams['figure.facecolor'] = 'white'
        #matplotlib.rcParams['figure.figsize'] = (6, 10)
#        matplotlib.rcParams['figure.subplot.hspace'] = 0.45
#        matplotlib.rcParams['figure.subplot.wspace'] = 0.35
#        matplotlib.rcParams['figure.subplot.right'] = 0.85
        colorbar_fontsize = 8
                        
        self.num_rows = 1
        self.main_title_fontsize = 18
        matplotlib.rcParams['legend.fontsize'] = 12
        matplotlib.rcParams['axes.labelsize'] = 10
        matplotlib.rcParams['axes.titlesize'] = 10
        matplotlib.rcParams['xtick.labelsize'] = 8 
        matplotlib.rcParams['ytick.labelsize'] = 8 
#        matplotlib.rcParams['figure.subplot.top'] = 0.8 # single figure plots have a larger title so require more space at the top.
        
        self.fig=Figure(figsize=(9,5))      
#        self.main_title_label = self.fig.suptitle(unicode(self.image_defs['title'],'utf-8'), fontsize=self.main_title_fontsize)
        
        ax = self.fig.add_subplot(111,axisbg = 'white')            
        self.subplots.append(ax)
                    
        ax.label_outer()
        #print "opening: ",(in_file+'.vg'+str(vg_files[plot_ctr]))
        plot_ctr = 0

#        dir_name = os.path.dirname(in_file)
#        if not os.path.exists(dir_name):
#            os.makedirs(dir_name)

        vgFile = open(in_file+'.vg'+str(vg_files[plot_ctr]))
        pattern = re.compile(r"[a-z]+")

        for line in vgFile:
            match = pattern.search( line )
            if not match:
                value = float(line[int(self.image_defs['first_char']):int(self.image_defs['last_char'])]) 
                # TODO Does this need to be normalised here if it's also being done in the plot?
                value = max(self.image_defs['min'], value)
                value = min(self.image_defs['max'], value)
                #if value < self.image_defs[2] : value = self.image_defs[2] 
                #if value > self.image_defs[3] : value = self.image_defs[3] 
                points[int(line[3:6])-1][int(line[0:3])-1] = value
        vgFile.close()

        map = Basemap(\
            llcrnrlon=area_rect.get_sw_lon(), llcrnrlat=area_rect.get_sw_lat(),\
            urcrnrlon=area_rect.get_ne_lon(), urcrnrlat=area_rect.get_ne_lat(),\
            projection=projection,\
            lat_0=plot_centre_location.get_latitude(),\
            lon_0=plot_centre_location.get_longitude(),\
            resolution=resolution,
            ax=ax)
            
        map.drawcoastlines(color='black')
        map.drawcountries(color='grey')
        map.drawmapboundary(color='black', linewidth=1.0)

        warped = ma.zeros((grid, grid),float)
        warped, warped_lon, warped_lat = map.transform_scalar(points,lons,lats,grid,grid, returnxy=True, checkbounds=False, masked=True)
        warped = warped.filled(self.image_defs['min']-1.0)
        
        colMap.set_under(color ='k', alpha=0.0)
    
        im = map.imshow(warped,
            cmap=colMap,
            extent = (-180, 180, -90, 90),
            origin = 'lower',
            norm = P.Normalize(clip = False,
            vmin=self.image_defs['min'],
            vmax=self.image_defs['max']))


        #######################
        # Plot greyline
        #######################
        if plot_terminator:
            the_sun = Sun()
            the_month = plot_parameters.get_month(vg_files[plot_ctr]-1)
            the_day = plot_parameters.get_day(vg_files[plot_ctr]-1)
            the_hour = plot_parameters.get_utc(vg_files[plot_ctr]-1)
            if (the_day == 0):
                the_day = 15
            the_year = datetime.date.today().year
            num_days_since_2k = the_sun.daysSince2000Jan0(the_year, the_month, the_day)

            res =  the_sun.sunRADec(num_days_since_2k)
            declination = res[1]
            if(declination==0.0):
                declination=-0.001

            tau = the_sun.computeGHA(the_day, the_month, the_year, the_hour);

            if declination > 0:
                terminator_end_lat = area_rect.get_sw_lat()
            else:
                terminator_end_lat = area_rect.get_ne_lat()              
              
            terminator_lat = [terminator_end_lat]
            terminator_lon = [area_rect.get_sw_lon()]
            
            for i in range(int(area_rect.get_sw_lon()),int(area_rect.get_ne_lon()),1)+[int(area_rect.get_ne_lon())]:
                longitude=i+tau;
                tan_lat = - the_sun.cosd(longitude) / the_sun.tand(declination)
                latitude = the_sun.atand(tan_lat)
                latitude = max(latitude, area_rect.get_sw_lat())
                latitude = min(latitude, area_rect.get_ne_lat())
                xpt, ypt = map(i, latitude)
                terminator_lon.append(xpt)
                terminator_lat.append(ypt)

            terminator_lon.append(area_rect.get_ne_lon())
            terminator_lat.append(terminator_end_lat)
            
            #This is a little simplistic and doesn't work for ortho plots....
            ax.plot(terminator_lon, terminator_lat, color='grey', alpha=0.75)
            ax.fill(terminator_lon, terminator_lat, facecolor='grey', alpha = 0.5)

            tau = -tau 
            if (tau > 180.0):
                tau = tau-360.0
            if (tau < -180.0):
                tau = tau+360.0

            #Plot the position of the sun (if it's in the coverage area)
            if area_rect.contains(declination, tau):
                xpt,ypt = map(tau,declination) 
                #sbplt_ax.plot([xpt],[ypt],'yh') 
                ax.plot([xpt],[ypt],'yh') 

        ##########################   
        # Points of interest
        ##########################
        for location in self.points_of_interest: 
            if area_rect.contains(location.get_latitude(), location.get_longitude()):
                xpt,ypt = map(location.get_longitude(),location.get_latitude()) 
                ax.plot([xpt],[ypt],'ro') 
                ax.text(xpt+100000,ypt+100000,location.get_name())

        if plot_meridians:
            if (area_rect.get_lon_delta() <= 90.0):
                meridians = P.arange(-180, 190.0, 10.0)
            elif (area_rect.get_lon_delta() <= 180.0):
                meridians = P.arange(-180.0, 210.0, 30.0)
            else:
                meridians = P.arange(-180, 240.0, 60.0)
            if ((projection == 'ortho')    or (projection == 'vandg')):
                map.drawmeridians(meridians)
            else:    
                map.drawmeridians(meridians,labels=[1,1,0,1])

        if plot_parallels:
            if (area_rect.get_lat_delta() <= 90.0):
                parallels = P.arange(-90.0, 120.0, 60.0)
            else:
                parallels = P.arange(-90.0, 120.0, 30.0)
            if ((projection == 'ortho')    or (projection == 'vandg')):
                map.drawparallels(parallels)
            else:    
                map.drawparallels(parallels,labels=[1,0,0,1])

        if plot_contours:
            map.contour(warped_lon, warped_lat, warped, self.image_defs['y_labels'], linewidths=1.0, colors='k', alpha=0.5)

        #add a title
        title_str = plot_parameters.get_plot_description_string(vg_files[plot_ctr]-1, self.image_defs['plot_type'], time_zone)
        title_str = title_str + "\n" + plot_parameters.get_detailed_plot_description_string(vg_files[plot_ctr]-1)
        self.subplot_title_label = ax.set_title(title_str)

        # Add a colorbar on the right hand side, aligned with the 
        # top of the uppermost plot and the bottom of the lowest
        # plot.
        pos = [0.91,0.19,0.02,0.62]
        self.cb_ax = self.fig.add_axes(pos)
        cb = self.fig.colorbar(im, cax=self.cb_ax, 
                    orientation='vertical',
                    ticks=self.image_defs['y_labels'],
                    format = P.FuncFormatter(eval('self.'+self.image_defs['formatter'])))
        cb.set_label(unicode(self.image_defs['title'],'utf-8'))
        
        #print self.image_defs['y_labels']
        for t in self.cb_ax.get_yticklabels():
            t.set_fontsize(colorbar_fontsize)
        
        canvas = FigureCanvasAgg(self.fig)
        
        if save_file :
            self.save_plot(canvas, save_file)
Example #46
0
# longitudes go from 20 to 380.
topoin = np.loadtxt('etopo20data.gz')
lons = np.loadtxt('etopo20lons.gz')
lats = np.loadtxt('etopo20lats.gz')
# shift data so lons go from -180 to 180 instead of 20 to 380.
topoin,lons = shiftgrid(180.,topoin,lons,start=False)

# setup of basemap ('lcc' = lambert conformal conic).
# use major and minor sphere radii from WGS84 ellipsoid.
m = Basemap(llcrnrlon=-145.5,llcrnrlat=1.,urcrnrlon=-2.566,urcrnrlat=46.352,\
            rsphere=(6378137.00,6356752.3142),\
            resolution='l',area_thresh=1000.,projection='lcc',\
            lat_1=50.,lon_0=-107.)
# transform to nx x ny regularly spaced native projection grid
nx = int((m.xmax-m.xmin)/40000.)+1; ny = int((m.ymax-m.ymin)/40000.)+1
topodat,x,y = m.transform_scalar(topoin,lons,lats,nx,ny,returnxy=True)
# create the figure.
fig=plt.figure(figsize=(8,8))
# add an axes, leaving room for colorbar on the right.
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# associate this axes with the Basemap instance.
m.ax = ax
# plot image over map with imshow.
im = m.imshow(topodat,plt.cm.jet)
# setup colorbar axes instance.
pos = ax.get_position()
l, b, w, h = pos.bounds
cax = plt.axes([l+w+0.075, b, 0.05, h])
plt.colorbar(im,cax=cax) # draw colorbar
# plot blue dot on boulder, colorado and label it as such.
xpt,ypt = m(-104.237,40.125) 
Example #47
0
  ##
  
  
  #----------------------
  # dmp
  #----------------------
  iname     = ddifname[class_lb, "dmp", 0]
  stitle    = "%s up%02d"%("dmp", class_lb)
  a2mask    = da3mnum_his[0][0]
  a         = fromfile(iname, float32) * 60.0 * 60.0 * 24.0
  a         = a.reshape(nwbin, ny, nx)
  a         = a[0]
  pngname   = iname[:-3] + ".png"
  
  # transform the data  ---
  a_trans   = M.transform_scalar( a, lons, lats, nnx, nny)
  #------------------------
  scale     = "dmp"
  dcm[scale] = ret_colormap(scale) 
  bnd       = [-3.0, -2.0, -1.0, -0.5,  0.5 , 1.0, 2.0 , 3.0]
  im        = M.imshow(a_trans, origin="lower", norm=BoundaryNormSymm(bnd), cmap=dcm[scale], interpolation="nearest")
  M.drawcoastlines()
  plt.title(stitle)
  savefig(pngname)
  plt.clf()
  print pngname

  cbarname  = iname[:-3] + ".cbar.png"
  bnd_cbar  = [-1.0e+40] + bnd + [1.0e+40]
  figcbar   = plt.figure(figsize=(1,5))
  #axcbar    = figcbar.add_axes([0,0,0.9,1])
Example #48
0
fire = mpl.colors.ListedColormap(np.loadtxt('cmaps/fire.txt')/255)
fireflipsqrt = mpl.colors.ListedColormap(np.sqrt(np.flipud(np.loadtxt('cmaps/fire.txt')))/np.sqrt(255))
fire2 = mpl.colors.ListedColormap(np.power(np.loadtxt('cmaps/fire.txt'),1.5)/np.power(255,1.5))

#INSIDE LOOP...

for ll in xrange(-180,180):
  # Set up the map
  # lat_ts is the latitude of true scale.
  # resolution = 'c' means use crude resolution coastlines.
  # m = Basemap(projection='merc',llcrnrlat=-65,urcrnrlat=80,\
  #            llcrnrlon=0,urcrnrlon=360,lat_ts=0,resolution='c')

  m = Basemap(projection='ortho', lon_0=ll, lat_0=20, resolution='c')
  m.shadedrelief(scale=0.1)
  m.drawcoastlines(color='0.4')
  m.drawcountries(color='0.4')
  #m.fillcontinents(color='white',lake_color='gray')
  m.drawparallels(np.arange(-90.,91.,30.))
  m.drawmeridians(np.arange(0., 360., 60.))
  m.drawmapboundary(fill_color='0.8')

  nx = int((m.xmax-m.xmin)/50000.)+1; ny = int((m.ymax-m.ymin)/50000.)+1
  Tarray = m.transform_scalar(array, np.arange(-180,180), np.arange(-90,90), nx,ny)
  #m.contourf(x, y, array, np.arange(-1.0, 1.05, 0.1), cmap=cm.jet_r)
  m.imshow(Tarray,interpolation='nearest',vmin=0.0,vmax=4.0, cmap=fire2)
  cbar = m.colorbar()
  cbar.set_ticks([0,1,2,3,4])
  plt.title("Coverage Deficit: Surface Runoff (hrs)")
  plt.savefig("figures/globeframes_covdef/frame{0}".format(str(ll+180).rjust(3, "0")))
  plt.clf()
      tick_labels[i] = '%.2f' %tick_labels[i]
    return ticks, tick_labels
  
  
# imshow
maps = [WBdiff]
colormaps = [cm.GMT_polar_r, cm.GMT_polar, cm.GMT_polar]
map_titles = ['P$-$ET (21 ka) $-$ P$-$ET (0 ka)']
units = ['Precip. minus Evapotransp. difference [mm yr$^{-1}$]']
#fig, axes = plt.subplots(1, 3, figsize=(24,6))
fig = plt.figure(figsize=(8,6))
for i in range(len(maps)):
  ax = fig.add_subplot(len(maps), 1, i+1)
  lons = np.linspace(-180+.125, 180-.125, 1440)
  lats = np.linspace(-90+.125, 90-.125, 720)
  transformed = m.transform_scalar(maps[i],lons,lats,nx,ny)
  maxvalue = np.max(transformed)
  minvalue = np.min(transformed)
  mn = myNorm(0, minvalue, maxvalue)
  transformed_scaled = mn(transformed)
  ticks, labels = mn.makeTickLabels(11)
  labels = np.round(np.array(labels).astype(float)).astype(int)
  #ax = axes[i]
  im = m.imshow(transformed_scaled, colormaps[i], interpolation='nearest')#, vmin=-1*absmaxvalue, vmax=absmaxvalue)
  m.drawcoastlines(color='k')
  m.drawcountries(color='k')
  m.drawstates(color='k')
  cbar = m.colorbar(im, ticks=ticks)
  cbar.ax.set_yticklabels(labels)
  cbar.set_label(units[i], fontsize=16)
  ax.set_title(map_titles[i], fontsize=24)
    ilon = int(lon[i] - 0.5)
    array[ilat,ilon] = five[i]*100
    
array[array == 0] = np.NaN
array,lons = shiftgrid(180., array, np.arange(0,360), start=False)

#INSIDE LOOP...

for ll in xrange(-180,180):
  # Set up the map
  # lat_ts is the latitude of true scale.
  # resolution = 'c' means use crude resolution coastlines.
  # m = Basemap(projection='merc',llcrnrlat=-65,urcrnrlat=80,\
  #            llcrnrlon=0,urcrnrlon=360,lat_ts=0,resolution='c')

  m = Basemap(projection='ortho', lon_0=ll, lat_0=20, resolution='c')
  m.shadedrelief(scale=0.1)
  m.drawcoastlines(color='0.4')
  m.drawcountries(color='0.4')
  #m.fillcontinents(color='white',lake_color='gray')
  m.drawparallels(np.arange(-90.,91.,30.))
  m.drawmeridians(np.arange(0., 360., 60.))
  m.drawmapboundary(fill_color='0.8')

  nx = int((m.xmax-m.xmin)/50000.)+1; ny = int((m.ymax-m.ymin)/50000.)+1
  Tarray = m.transform_scalar(array, np.arange(-180,180), np.arange(-90,90), nx,ny)
  #m.contourf(x, y, array, np.arange(-1.0, 1.05, 0.1), cmap=cm.jet_r)
  m.imshow(Tarray,interpolation='nearest',vmin=0.0,vmax=5.0, cmap=cm.jet_r)
  m.colorbar()
  plt.savefig("figures/globeframes/frame{0}".format(str(ll+180).rjust(3, "0")))
  plt.clf()
Example #51
0
nlons = array.shape[1]; nlats = array.shape[0]
delon = coords[1]
delat = coords[5]
lons = coords[0] + delon*np.arange(nlons)
lats = coords[3] + delat*np.arange(nlats)[::-1] # reverse lats
# setup figure.
fig = plt.figure(figsize=(11,6))
# setup basemap instance.
m = Basemap(llcrnrlon=-119,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,0,0])
m.drawmeridians(np.arange(-120,-40,10),labels=[0,0,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
Example #52
0
def plot_field(
    latlons,
    field,
    plot_type='scatter',
    show_lats=True,
    show_lons=True,
    ax=None,
    clevs=None,
    topofile = '/home/roberto/data/topography/ETOPO1_Ice_g_gdal.grd',
    **kwargs):
    '''
    Plot the locations considered in the grid search.

    :param latlons: Tuples contain the lat/lon pairs.
    :type latlons: Two column numpy array.
    :param field: The field to plot. Must have the dimensions commensurate to *latlons*.
    :type field: Two dimensional numpy array.
    :param str plot_type: Either "scatter" (for points) or "contour" (for contours).
    :param bool show_lats: Should latitudes be shown on the y-axis.
    :param bool show_lons: Should longitudes be shown on the x-axis.
    :param ax: Axes for figure to add the plot to.
    :type ax: None or :py:class:`matplotlib.Axes`.
    :param list clevs: The levels for the contour plot. Ignored if *plot_type* is "scatter".
    :param str topfile: Path to file to load 'etopo' topography from.
    '''

    from mpl_toolkits.basemap import Basemap

    if not ax:
        fig = plt.figure()
        ax = fig.add_subplot(111)
    else:
        fig = ax.figure

    cpool_sea,cpool_land = get_topography_cpool()
    cdict = topography_colormap(cpool_sea,cpool_land)
    relief = mcols.LinearSegmentedColormap('my_colormap', cdict, 256)
    # loading topographic data

    lats, lons =  latlons.T
    boundaries = get_boundaries(lats,lons,xpnd = 0.7)
    lllon,lllat,urlon,urlat = boundaries
    #Obtaning nice boundaries for the map
    m = Basemap(*boundaries,projection='merc',resolution='l',ax=ax)
    m.drawcoastlines(linewidth=1.5)
    m.drawcountries()
    if urlon - lllon < 5.:
        dlon = 1.0
    else:
        dlon = 2.0
    if urlat - lllat < 5.:
        dlat = 1.0
    else:
        dlat = 2.0
    if show_lats:
        lats_labs = [1,0,0,1]
    else:
        lats_labs = [0,0,0,0]

    if show_lons:
        lons_labs = [1,0,0,1]
    else:
        lons_labs = [0,0,0,0]
    parallels = np.arange(-90.,90,dlat)
    m.drawparallels(parallels,labels=lats_labs)
    meridians = np.arange(-180,180,dlon)
    m.drawmeridians(meridians,labels=lons_labs)
    #Ploting elevation
    if topofile:
        nxx = int((m.xmax-m.xmin)/500.)+1
        nyy = int((m.ymax-m.ymin)/500.)+1
        tlats,tlons,telev = get_topography_slice(lllon,lllat,urlon,urlat)
        topodat = m.transform_scalar(telev,tlons,tlats,nxx,nyy)
        im = m.imshow(topodat/1000.,relief,vmax=6.5,vmin=-6.5)
    else:
        m.fillcontinents(color='#FF9900',lake_color='#FF9900')
        m.drawmapboundary(fill_color='aqua')
    #Plotting field
    if plot_type == 'scatter':
        field_plot = m.scatter(lons, lats, latlon=True, **kwargs)
    elif plot_type == 'contour':
        grid_lats = np.sort(lats)
        grid_lons = np.sort(lons)
        grid_lats, grid_lons = np.meshgrid(grid_lats, grid_lons)
        grid_inter= griddata((lats,lons),field,(grid_lats,grid_lons),method = 'linear')
        #~ xpts, ypts = m(grid_lons,grid_lats)
        #~ m.contour(xpts,ypts,grid_slip, clevs,
                    #~ linewidths=1.5,colors='k',animated=True
        #~ print clevs
        if not np.any(clevs):
            clevs = np.linspace(field.min(),field.max(),8)
        field_plot = m.contour(grid_lons, grid_lats, grid_inter,clevs,latlon=True, **kwargs)
    output_dic = {'fig' : fig, 'ax': ax, 'field' : field_plot,
                  'limits' : boundaries, 'map' : m }
    if topofile:
        output_dic['topography'] = im
    return output_dic