Exemplo n.º 1
0
other_land_geos = []
for record in ShapeReader(shapefile).records():
    if record.attributes['ADMIN'] in ['China', 'Taiwan']:
        country_geos.append(record.geometry)
    else:
        other_land_geos.append(record.geometry)

# Define map projection to allow Cartopy to transform ``lat`` and ``lon`` values accurately into points on the
# matplotlib plot canvas.
projection = PlateCarree()

# Define a Cartopy Feature for the country borders and the land mask (i.e.,
# all other land) from the shapefile geometries, so they can be easily plotted
countries = ShapelyFeature(country_geos,
                           crs=projection,
                           facecolor='none',
                           edgecolor='black',
                           lw=1.5)
land_mask = ShapelyFeature(other_land_geos,
                           crs=projection,
                           facecolor='white',
                           edgecolor='none')

# Download the Natural Earth shapefile for the states/provinces at 10m resolution
shapefile = natural_earth(category='cultural',
                          resolution='10m',
                          name='admin_1_states_provinces')

# Extract the Chinese province borders
province_geos = [record.geometry for record in ShapeReader(shapefile).records()
                 if record.attributes['admin'] == 'China']
                        np.isnan(sites_ammonium_son_c))
correlate_son = stats.pearsonr(gc_data_ammonium_son[~nas_son],
                               sites_ammonium_son_c[~nas_son])

nas_djf = np.logical_or(np.isnan(gc_data_ammonium_djf),
                        np.isnan(sites_ammonium_djf_c))
correlate_djf = stats.pearsonr(gc_data_ammonium_djf[~nas_djf],
                               sites_ammonium_djf_c[~nas_djf])

print('Correlation = ', correlate_Annual)

# plotting spatial map model and DEFRA network
os.chdir('/home/a/ap744/scratch_alok/shapefiles/GBP_shapefile')
Europe_shape = r'GBR_adm1.shp'
Europe_map = ShapelyFeature(Reader(Europe_shape).geometries(),
                            ccrs.PlateCarree(),
                            edgecolor='black',
                            facecolor='none')
print('Shapefile_read')
title_list = 'DEFRA and GEOS-Chem Particulate ammonium'
title_list1 = 'Spatial Map DEFRA and GEOS-Chem Particulate ammonium'

#fig,ax = plt.subplots(2,1, figsize=(11,11))
fig1 = plt.figure(facecolor='White', figsize=[11, 11])
pad = 1.1
# plt.suptitle(title_list, fontsize = 35, y=0.96)

ax = plt.subplot(231)
#plt.title(title_list1, fontsize = 30, y=1)
ax = plt.axes(projection=ccrs.PlateCarree())
ax.add_feature(Europe_map)
ax.set_extent([-9, 3, 49, 61], crs=ccrs.PlateCarree())  # [lonW,lonE,latS,latN]
Exemplo n.º 3
0
demands = pd.read_csv('../Summary_info/demands.csv', index_col=0)
structures = pd.read_csv('../Structures_files/modeled_diversions.csv',
                         index_col=0)

for index, row in structures.iterrows():
    structures.at[str(index),
                  'Mean demand'] = np.mean(demands.loc[str(index)].values)

extent = [-109.069, -105.6, 38.85, 40.50]
extent_large = [-111.0, -101.0, 36.5, 41.5]
#rivers_10m = cpf.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '10m')
tiles = cimgt.StamenTerrain(style='terrain')
shape_feature = ShapelyFeature(
    Reader('../Structures_files/Shapefiles/Water_Districts.shp').geometries(),
    ccrs.PlateCarree(),
    edgecolor='black',
    facecolor='None')
flow_feature = ShapelyFeature(
    Reader('../Structures_files/Shapefiles/UCRBstreams.shp').geometries(),
    ccrs.PlateCarree(),
    edgecolor='royalblue',
    facecolor='None')

fig = plt.figure(figsize=(18, 9))
ax = plt.axes(projection=tiles.crs)
#ax.add_feature(rivers_10m, facecolor='None', edgecolor='royalblue', linewidth=2, zorder=4)
ax.add_image(tiles, 9, interpolation='none', alpha=0.8)
ax.set_extent(extent)
ax.add_feature(shape_feature, facecolor='#a1a384', alpha=0.6)
ax.add_feature(flow_feature, alpha=0.6, linewidth=1.5, zorder=4)
Exemplo n.º 4
0
def main(fname, plot_dir, start_year, end_year):

    ds = xr.open_dataset(fname)
    lat = ds.y.values
    lon = ds.x.values
    bottom, top = lat[0], lat[-1]
    left, right = lon[0], lon[-1]

    nmonths, nrows, ncols = ds.Rainf.shape
    nyears = (end_year - start_year) + 1
    yr_count = 0
    aet = np.zeros((nyears, nrows, ncols))
    ppt = np.zeros((nyears, nrows, ncols))
    sec_2_day = 86400.0
    count = 0
    yr_count = 0
    mth_count = 1

    for year in np.arange(start_year, end_year + 1):
        for month in np.arange(1, 13):

            days_in_month = monthrange(year, month)[1]
            conv = sec_2_day * days_in_month

            yr_val = str(ds.time[count].values).split("-")[0]
            print(yr_val)

            aet[yr_count, :, :] += ds.Evap[count, :, :] * conv
            ppt[yr_count, :, :] += ds.Rainf[count, :, :] * conv
            mth_count += 1

            if mth_count == 13:
                mth_count = 1
                yr_count += 1

            count += 1

    ppt = np.nanmean(ppt, axis=0)
    aet = np.nanmean(aet, axis=0)
    cmi = np.where(~np.isnan(aet), ppt - aet, np.nan)

    fig = plt.figure(figsize=(9, 6))
    plt.rcParams['font.family'] = "sans-serif"
    plt.rcParams['font.size'] = "14"
    plt.rcParams['font.sans-serif'] = "Helvetica"

    cmap = plt.cm.get_cmap('BrBG', 10)  # discrete colour map

    projection = ccrs.PlateCarree()
    axes_class = (GeoAxes, dict(map_projection=projection))
    rows = 1
    cols = 1

    axgr = AxesGrid(fig,
                    111,
                    axes_class=axes_class,
                    nrows_ncols=(rows, cols),
                    axes_pad=0.2,
                    cbar_location='right',
                    cbar_mode='single',
                    cbar_pad=0.5,
                    cbar_size='5%',
                    label_mode='')  # note the empty label_mode

    for i, ax in enumerate(axgr):
        # add a subplot into the array of plots
        plims = plot_map(ax, cmi, cmap, i, top, bottom, left, right)
        """
        import cartopy.feature as cfeature
        states = cfeature.NaturalEarthFeature(category='cultural',
                                              name='.in_1_states_provinces_lines',
                                              scale='10m',facecolor='none')

        # plot state border
        SOURCE = 'Natural Earth'
        LICENSE = 'public domain'
        ax.add_feature(states, edgecolor='black', lw=0.5)
        """
        from cartopy.feature import ShapelyFeature
        from cartopy.io.shapereader import Reader
        #fname = '/Users/mdekauwe/research/Drought_linkage/Bios2_SWC_1979_2013/AUS_shape/STE11aAust.shp'
        fname = "/Users/mdekauwe/Dropbox/ne_10m_admin_1_states_provinces_lines/ne_10m_admin_1_states_provinces_lines.shp"
        shape_feature = ShapelyFeature(Reader(fname).geometries(),
                                       ccrs.PlateCarree(),
                                       edgecolor='black')
        ax.add_feature(shape_feature,
                       facecolor='none',
                       edgecolor='black',
                       lw=0.5)

    cbar = axgr.cbar_axes[0].colorbar(plims)
    cbar.ax.set_title("P-AET\n(mm yr$^{-1}$)", fontsize=16, pad=10)
    cbar.ax.set_yticklabels(
        [' ', '$\minus$40', '$\minus$20', '0', '20', '40-1200'])

    props = dict(boxstyle='round', facecolor='white', alpha=0.0, ec="white")
    ax.text(0.95,
            0.05,
            "(c)",
            transform=ax.transAxes,
            fontsize=12,
            verticalalignment='top',
            bbox=props)

    ofname = os.path.join(plot_dir, "cmi.png")
    fig.savefig(ofname, dpi=300, bbox_inches='tight', pad_inches=0.1)
def plot_AcrossASF_woWinds(acASF,
                           dfmg,
                           wd=190 / 25.4,
                           ht=230 / 25.4,
                           savefig=False,
                           savename="untitled.png",
                           levels=[],
                           xlat=False,
                           show=True,
                           MEOPDIR="/media/sda7",
                           p2pdist=True,
                           fontsize=8,
                           region='Whole',
                           bathy=None,
                           plotBathy=True,
                           llcrnrlon=-180,
                           llcrnrlat=-90,
                           urcrnrlon=+180,
                           urcrnrlat=+90):
    matplotlib.rcParams.update({'font.size': fontsize})
    plt.close(1)
    fig = plt.figure(1, figsize=(wd, ht))
    gs = gridspec.GridSpec(3,
                           2,
                           height_ratios=[1, 0.25, 0.5],
                           width_ratios=[1, 0.02],
                           hspace=0.,
                           wspace=0.05)
    contour_ax = plt.subplot(gs[0, 0])

    if (region == "CDP"):
        llcrnrlon, llcrnrlat = 60, -68
        urcrnrlon, urcrnrlat = 71, -65.5
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "WPB"):
        llcrnrlon, llcrnrlat = 69, -70
        urcrnrlon, urcrnrlat = 80, -66
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "EPB"):
        llcrnrlon, llcrnrlat = 69, -70
        urcrnrlon, urcrnrlat = 83, -64.5
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "LAC"):
        llcrnrlon, llcrnrlat = 80, -68
        urcrnrlon, urcrnrlat = 89, -64.5
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "KC"):
        llcrnrlon, llcrnrlat = 99, -68
        urcrnrlon, urcrnrlat = 112, -63
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "AC"):
        llcrnrlon, llcrnrlat = 133, -68
        urcrnrlon, urcrnrlat = 147, -64
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "RS"):
        llcrnrlon, llcrnrlat = 160, -79
        urcrnrlon, urcrnrlat = 180, -71
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "AS"):
        llcrnrlon, llcrnrlat = -122, -75.5
        urcrnrlon, urcrnrlat = -98, -70
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "BS"):
        llcrnrlon, llcrnrlat = -102, -71.5
        urcrnrlon, urcrnrlat = -58, -60
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "WS"):
        llcrnrlon, llcrnrlat = -50, -82
        urcrnrlon, urcrnrlat = -20, -72
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "PMC"):
        llcrnrlon, llcrnrlat = -19, -74
        urcrnrlon, urcrnrlat = 0, -65
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    if (region == "PHC"):
        llcrnrlon, llcrnrlat = 28, -71
        urcrnrlon, urcrnrlat = 38, -65
        map_proj = ccrs.PlateCarree()  #ccrs.Orthographic(65, -90)
    else:
        map_proj = ccrs.PlateCarree()

    mapax = plt.subplot(gs[2, 0], projection=map_proj)
    mapax.set_extent([llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat],
                     crs=ccrs.PlateCarree())
    colorbar_ax1 = plt.subplot(gs[0, 1])
    colorbar_ax2 = plt.subplot(gs[2, 1])

    profs = acASF.PROFILE_NUMBERS
    profs = [int(x) for x in profs.split(',')]
    year = dfmg.loc[dfmg.PROFILE_NUMBER.isin([profs[0]]),
                    "JULD"].dt.year.values[0]
    month = dfmg.loc[dfmg.PROFILE_NUMBER.isin([profs[0]]),
                     "JULD"].dt.month.values[0]
    region = acASF.REGION

    ctemps = []
    latlons = []
    depth = []
    gamman = []
    echodepth = []
    dist_gline = []
    zonal = []
    merid = []
    stress_curl = []
    wek = []

    no_of_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    for i in range(len(profs)):
        dfSelect = dfmg.PROFILE_NUMBER.isin([profs[i]])
        ctemps = np.concatenate((ctemps, dfmg.loc[dfSelect, "CTEMP"].values))
        latlons.append([
            dfmg.loc[dfSelect, 'LATITUDE'].values[0],
            dfmg.loc[dfSelect, 'LONGITUDE'].values[0]
        ])
        depth = np.concatenate((depth, dfmg.loc[dfSelect, "DEPTH"].values))
        gamman = np.concatenate((gamman, dfmg.loc[dfSelect, "gamman"].values))
        echodepth = np.concatenate(
            (echodepth, [dfmg.loc[dfSelect].ECHODEPTH.values[0]]))

        if xlat:
            dist_gline = np.concatenate(
                (dist_gline, dfmg.loc[dfSelect, "LATITUDE"].values))
        elif p2pdist:
            if (i == 0):
                dist_gline = np.concatenate(
                    (dist_gline, np.zeros(len(dfmg[dfSelect]))))
            else:
                dist = dist_gline[-1] + haversine(latlons[i - 1], latlons[i])
                dist_gline = np.concatenate(
                    (dist_gline,
                     np.zeros(len(dfmg[dfSelect]), dtype=float) + dist))
        else:
            dist_gline = np.concatenate(
                (dist_gline, dfmg.loc[dfSelect, "DIST_GLINE"].values))
    latlons = np.array(latlons)

    dist_echo = np.unique(dist_gline)
    print(gamman.shape)
    if xlat:
        ndist = int(np.max(dist_gline) / 0.1)
    else:
        ndist = int(np.max(dist_gline) / 2.)

    dist_grid = np.linspace(np.min(dist_gline), np.max(dist_gline), ndist)
    ndepth = int(-np.min(depth) / 10.)
    depth_grid = np.linspace(np.min(depth), 0, ndepth)

    dist_grid, depth_grid = np.meshgrid(dist_grid, depth_grid)
    gamman_interpolated = griddata(np.array([dist_gline, depth]).T,
                                   gamman, (dist_grid, depth_grid),
                                   method='cubic')

    cs = contour_ax.scatter(dist_gline,
                            depth,
                            c=ctemps,
                            vmin=-2.0,
                            vmax=0.5,
                            s=10)

    slope_labels = np.zeros(len(echodepth), dtype=int)
    slope_labels[echodepth > -1000] = 0
    slope_labels[(echodepth < -1000) & (echodepth > -1500)] = 1
    slope_labels[(echodepth < -1500) & (echodepth > -2000)] = 2
    slope_labels[(echodepth < -2000) & (echodepth > -3000)] = 3
    slope_labels[(echodepth < -3000)] = 4

    contour_ax_twinx = contour_ax.twiny()
    contour_ax_twinx.set_xticks(dist_echo)
    contour_ax_twinx.set_xticklabels(slope_labels)

    contour_ax.set_ylabel("Depth (m)")
    if xlat:
        contour_ax.set_xlabel("Latitude")
    elif p2pdist:
        contour_ax.set_xlabel("Chainage (km)")
    else:
        contour_ax.set_xlabel("Distance from GL (km)")
    xaxislength = np.max(dist_gline) - np.min(dist_gline)
    contour_ax.set_xlim(
        np.min(dist_gline) - xaxislength * 0.02,
        np.max(dist_gline) + xaxislength * 0.02)
    contour_ax_twinx.set_xlim(
        np.min(dist_gline) - xaxislength * 0.02,
        np.max(dist_gline) + xaxislength * 0.02)

    if levels:
        cs_gamman = contour_ax.contour(dist_grid,
                                       depth_grid,
                                       gamman_interpolated,
                                       levels=levels,
                                       colors='0.5')
    else:
        try:
            levels = np.array(str.split(acASF.LEVELS, ","), dtype=float)
            cs_gamman = contour_ax.contour(dist_grid,
                                           depth_grid,
                                           gamman_interpolated,
                                           levels=levels,
                                           colors='0.5')
        except:
            levels = None
            cs_gamman = contour_ax.contour(dist_grid,
                                           depth_grid,
                                           gamman_interpolated,
                                           colors='0.5')

    contour_ax.clabel(cs_gamman, colors='k', fontsize=8, fmt='%3.2f')

    #mapax.plot(latlons.LONGITUDE.values, latlons.LATITUDE.values, marker="x", markersize=20, transform=ccrs.PlateCarree() )
    mapax.scatter(latlons[:, 1],
                  latlons[:, 0],
                  marker="x",
                  s=20,
                  transform=ccrs.PlateCarree())
    #mapax.coastlines()
    parallels = np.arange(-80, -50 + 1, 5.)
    #m.drawparallels(parallels,labels=[1,0,0,0], linewidth=0.2, ax=mapax) # labels: left,right,top,bottom
    meridians = np.arange(-180, 180, 20.)
    #m.drawmeridians(meridians,labels=[0,1,1,1], linewidth=0.2, ax=mapax)

    cbar1 = Colorbar(ax=colorbar_ax1,
                     mappable=cs,
                     orientation='vertical',
                     extend='both',
                     label="CT$^\circ$C")
    if (plotBathy == True):
        try:
            if bathy.variables:
                pass
        except:
            bathy = xr.open_dataset(MEOPDIR +
                                    '/Datasets/Bathymetry/GEBCO_2014_2D.nc')
        lonlen = len(bathy.lon)
        lonindices = np.arange(0, lonlen + 1, 30)
        lonindices[-1] = lonindices[-1] - 1
        bathyS = bathy.isel(lon=lonindices, lat=np.arange(0, 3600, 5))
        clevs = np.array([-1000, -1500, -2000, -3000])[::-1]

        longrid, latgrid = np.meshgrid(bathyS.lon.values, bathyS.lat.values)
        cs2 = mapax.contour(
            longrid,
            latgrid,
            bathyS.elevation.where(bathyS.elevation <= 0).values,
            levels=clevs,
            linewidths=0.8,
            transform=ccrs.PlateCarree(
            ))  #, , cmap='rainbow'   , levels=clevs,
        ## plt.figure(2)
        ## cf = plt.contourf(longrid, latgrid,bathyS.elevation.where(bathyS.elevation <= 0).values, levels=clevs, extend='min') #, , cmap='rainbow'   , levels=clevs,
        ## plt.figure(1)
        cbar1 = Colorbar(ax=colorbar_ax2, mappable=cs2, orientation='vertical')
        cbar1.ax.get_children()[0].set_linewidths(5)
        cbar1.set_label('Depth (m)')
    shpfile = MEOPDIR + "/Datasets/Shapefiles/AntarcticGroundingLine/GSHHS_f_L6.shp"
    with fiona.open(shpfile) as records:
        geometries = [sgeom.shape(shp['geometry']) for shp in records]
    mapax.add_geometries(geometries,
                         ccrs.PlateCarree(),
                         edgecolor='k',
                         facecolor='none')

    ISedgefname = MEOPDIR + "/Datasets/Shapefiles/AntIceShelfEdge/ne_10m_antarctic_ice_shelves_lines.shp"
    ISe_feature = ShapelyFeature(Reader(ISedgefname).geometries(),
                                 ccrs.PlateCarree(),
                                 facecolor='none',
                                 edgecolor="gray")
    mapax.add_feature(ISe_feature, zorder=3)

    mapax.set_extent([llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat])
    gl = mapax.gridlines(crs=ccrs.PlateCarree(),
                         draw_labels=True,
                         linewidth=1,
                         color='gray',
                         alpha=0.5,
                         linestyle='--')
    gl.ylabels_right = False
    gl.xlabels_top = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    gl.xlabel_style = {'size': 8, 'color': 'k'}
    gl.ylabel_style = {'size': 8, 'color': 'k'}

    gl = contour_ax.grid(linewidth=1, color='gray', alpha=0.5, linestyle='--')

    contour_ax.set_title(region + ", " + str(year) + "/ " + str(month))

    if savefig:
        plt.savefig(savename, dpi=300, bbox_inches="tight")
    if show:
        plt.show()
Exemplo n.º 6
0
def proc(fname, oname, title=None, workdir=None):
    #if 'dat' in locals():
    if True:

        #dat = cpr.calpost_reader('../calpost_3d/tseries/tseries_ch4_1min_conc_pilot_min_emis_3_xto_recp_1_13lvl_fmt_1_dsp_3_tur_3_byweek_20190224_20190303.dat', z=zlvl)
        #dat = cpr.calpost_reader('../calpost_3d/tseries/tseries_ch4_1min_conc_pilot_min_emis_3_xto_recp_1_13lvl_fmt_1_dsp_3_tur_3_prf_1_byday_20190224.dat' , z=zlvl)
        dat = cpr.calpost_reader(fname, z=zlvl)

    # grab necessary info
    # [60:] to drop first 60min of data (spin-up)
    print(dat['v'].shape)
    if dat['v'].shape[0] > 200:
        maybe_hourly = False
        arr = dat['v'][60:]
        tstamps = dat['ts'][60:]
    else:
        maybe_hourly = True
        arr = dat['v']
        tstamps = dat['ts']
    grid = dat['grid']


    # get horizontal extent 
    extent = [
        grid['x0'], grid['x0'] + grid['nx'] * grid['dx'],
        grid['y0'], grid['y0'] + grid['ny'] * grid['dy'],
    ]

    # distance in calpost is in km
    extent = [_ * 1000 for _ in extent]
    x = dat['x'] * 1000
    y = dat['y'] * 1000

    z = dat['z']


    arr = arr[:, 0:14, ...]
    #zlvl = zlvl[:14]
    z = zlvl[:14]

    # convert unit of array from g/m3 tp ppb
    # mwt g/mol
    # molar volume m3/mol
    arr = arr / 16.043 * 0.024465403697038 * 1e9

    # array has nan, so mask them
    arr = np.ma.masked_invalid(arr)


    title = title

    # Mrinali/Gary's surfer color scale
    cmap = colors.ListedColormap([
        '#D6FAFE', '#02FEFF', '#C4FFC4', '#01FE02',
        '#FFEE02', '#FAB979', '#EF6601', '#FC0100', ])
    cmap.set_under('#FFFFFF')
    cmap.set_over('#000000')
    # Define a normalization from values -> colors
    bndry = [1, 10, 50, 100, 200, 500, 1000, 2000]
    norm = colors.BoundaryNorm(bndry, len(bndry))


    # receptor box defined by Shanon
    df_corners = pd.read_csv(StringIO(
    '''
    box,lon,lat
    receptor,-102.14119642699995,31.902587319000077
    receptor,-102.06890715999998,31.928683642000067
    receptor,-102.03957186099996,31.873156213000073
    receptor,-102.11577420099997,31.85033867900006
    receptor,-102.14119642699995,31.902587319000077
    emitter,-102.1346819997111,31.80019199958484
    emitter,-102.0045175208385,31.83711037948465
    emitter,-102.046423081171,31.94509160994673
    emitter,-102.1790300003915,31.90254999960113
    emitter,-102.1346819997111,31.80019199958484
    '''.strip()))
    receptor_corners = df_corners.loc[df_corners['box'] == 'receptor', ['lon','lat']].values

    shp_soft = shpreader.Reader('data/SoftLaunch_alt.shp')

    figure_options = {
    #    'suptitle': title,
        #'colorbar_options': {
        #    'label': r'$CH_4$ (ppbV)',
        #},
        'footnote_options': {'text': "{tstamp}", 'y':.01},
#        'tight_layout': True,
    }

    # make all the fonts smaller, since tight_layout doesnt work for irregular set of panels
#    mpl.rc('font', **{'size': mpl.rcParams['font.size']*.9})
    if title is not None:
        figure_options['suptitle'] = {'s': title, 'y': .98}
    plotter_options = {
    #    'background_manager': BackgroundManager(
    #        add_image_options=[cimgt.GoogleTiles(style='satellite'), 13],
    #        ),
    #    'title': title,
        'contour_options': {
            'levels': bndry,
            'cmap': cmap,
            'norm': norm,
            'alpha': .5,
            'extend': 'max',
        },
        'colorbar_options': None,
        'footnote': '',
        'customize_once': [
    #        # add recetptor box
    #        lambda p: p.ax.add_geometries(
    #            [Polygon([_ for _ in receptor_corners])],  # four corners into polygon
    #            crs = ccrs.PlateCarree(),  # projection is unprojected ("PlateCarre")
    #            facecolor='none', edgecolor='black', lw=.6,  # plot styles
    #            ),
            # add softlaunch box
            # ridiculously complicated...
    #        lambda p: p.ax.add_feature(
    #            ShapelyFeature(
    #                shp_soft.geometries(),
    #                crs=ccrs.PlateCarree(),
    #            facecolor='none', 
    #            #edgecolor='black', 
    #            edgecolor='#BDEDFC',
    #            lw=.6,  # plot styles
    #            )),

        ],
    }
    downwind_options = {
    'origin' : (-436491, -727712),
    'distance' : (50, 150, 300),
    'distance_for_direction' : 150, 
    #'half_angle': 30,
    'half_angle': 45,
    'half_arclen': 150,
    'kind' : 'cross',
    }


    figure_options.update({'nrow':2, 'ncol': 3})
    plotter_options_multi = [plotter_options.copy() for _ in range(5) ]
    plotter_options_multi[1]['downwind_options'] = (downwind_options | {'kind': 'planview'}) 
    plotter_options_multi[0]['downwind_options'] = (downwind_options | {'kind': 'along', })
    plotter_options_multi[2]['downwind_options'] = (downwind_options | {'kind': 'cross', 'distance':  50})
    plotter_options_multi[3]['downwind_options'] = (downwind_options | {'kind': 'cross', 'distance': 150})
    plotter_options_multi[4]['downwind_options'] = (downwind_options | {'kind': 'cross', 'distance': 300})

    plotter_options_multi[1].update(
    {
        'background_manager': BackgroundManager(
            #add_image_options=[cimgt.GoogleTiles(style='satellite'), 13],
            add_image_options=[cimgt.GoogleTiles(style='satellite'), 20],
            ),
        'colorbar_options': {
            'label': r'$CH_4$ (ppbV)',
            },
        'customize_once': [
    #        # add recetptor box
    #        lambda p: p.ax.add_geometries(
    #            [Polygon([_ for _ in receptor_corners])],  # four corners into polygon
    #            crs = ccrs.PlateCarree(),  # projection is unprojected ("PlateCarre")
    #            facecolor='none', edgecolor='black', lw=.6,  # plot styles
    #            ),
            # add softlaunch box
            # ridiculously complicated...
            lambda p: p.ax.add_feature(
                ShapelyFeature(
                    shp_soft.geometries(),
                    crs=ccrs.PlateCarree(),
                facecolor='none', 
                #edgecolor='black', 
                edgecolor='#BDEDFC',
                lw=.6,  # plot styles
                )),

        ],
    }
    )

    plotter_options_multi[0].update({
    'customize_once': [
            lambda q: q.ax.text(.05, .95, f'along wind',
                                ha='left', va='top',
                                transform=q.ax.transAxes),
            lambda q: q.ax.set_ylabel('height (m AGL)'), 
            lambda q: q.ax.set_xlabel('from source (m)'),#, fontsize='small'),
            lambda q: q.ax.xaxis.set_tick_params(labelsize='small'),
            lambda q: q.ax.axvline(x= 50, color='gray', alpha=.5, lw=.6),
            lambda q: q.ax.axvline(x=150, color='gray', alpha=.5, lw=.6),
            lambda q: q.ax.axvline(x=300, color='gray', alpha=.5, lw=.6),
    ],
    'pos': (2, 2, 1),

    })
    plotter_options_multi[1].update({
    'pos': (2, 2, 2),
    })


    plotter_options_multi[2].update({
    'customize_once': [
            lambda q: q.ax.text(.05, .95, f'cross wind @ 50m',
                                ha='left', va='top',
                                transform=q.ax.transAxes),
            lambda q: q.ax.set_ylabel('height (m AGL)'), 
            lambda q: q.ax.set_xlabel('from plume center (m)'),
#            lambda q: q.ax.set_xlim(left=-300, right=300), 
            lambda q: q.ax.set_xlim(left=-150, right=150), 
            lambda q: q.ax.xaxis.set_tick_params(labelsize='small'),
            lambda q: q.ax.axvline(x=0, color='gray', alpha=.5, lw=.6),

    ],
    'pos': (2, 3, 4),
    })

    plotter_options_multi[3].update({
    'customize_once': [
            lambda q: q.ax.text(.05, .95, f'cross wind @ 150m',
                                ha='left', va='top',
                                transform=q.ax.transAxes),
            lambda q: q.ax.set_ylabel('height (m AGL)'), 
            lambda q: q.ax.set_xlabel('from plume center (m)'),
#            lambda q: q.ax.set_xlim(left=-300, right=300), 
            lambda q: q.ax.set_xlim(left=-150, right=150), 
            lambda q: q.ax.xaxis.set_tick_params(labelsize='small'),
            lambda q: q.ax.axvline(x=0, color='gray', alpha=.5, lw=.6),

    ],
    'pos': (2, 3, 5),
    })

    plotter_options_multi[4].update({
    'customize_once': [
            lambda q: q.ax.text(.05, .95, f'cross wind @ 300m',
                                ha='left', va='top',
                                transform=q.ax.transAxes),
            lambda q: q.ax.set_ylabel('height (m AGL)'), 
            lambda q: q.ax.set_xlabel('from plume center (m)'),
#            lambda q: q.ax.set_xlim(left=-300, right=300), 
            lambda q: q.ax.set_xlim(left=-150, right=150), 
            lambda q: q.ax.xaxis.set_tick_params(labelsize='small'),
            lambda q: q.ax.axvline(x=0, color='gray', alpha=.5, lw=.6),
    ],
    'pos': (2, 3, 6),
    })

    # since tignt layout doesnt work i change each of texts' font here
    for po in plotter_options_multi:
        po['customize_once'].extend(
                [ 
                    lambda q: q.ax.xaxis.set_tick_params(labelsize='xx-small'),
                    lambda q: q.ax.yaxis.set_tick_params(labelsize='xx-small'),
                    lambda q: q.ax.set_xlabel(q.ax.get_xlabel(), fontsize='small', labelpad=1),
                    lambda q: q.ax.set_ylabel(q.ax.get_ylabel() if q.ax.get_subplotspec().get_rows_columns()[4]==0 else None, fontsize='small', labelpad=1),
                    ]
                )
            



    arrays = [arr]*5
#    arrays[1] = None

#    plotter_options_multi.insert(0, {'footnote':''})
#    arrays.insert(0, None)


    #print(plotter_options_multi)
    #for po in plotter_options_multi:
    #    print(po['downwind_options'])
    #raise

#    my_po = plotter_options.copy()
#    my_po['downwind_options'] = {
#    'origin' : (-436491, -727712),
##    'distance' : (50, 150, 300),
#    'distance_for_direction' : 150, 
#    'distance' : 50,
##    'half_angle': 30,
#    'half_arclen': 150,
##    'kind' : 'planview',
#    'kind' : 'cross',
##    'kind' : 'along',
#    }
#    p = plotter_solo.Plotter(array = arr, tstamps=tstamps,
#            x=x, y=y, z=z, projection=LambertConformalHRRR(),
#            plotter_options=my_po)
#    p.savefig('xxx.png', tidx=0)


    # make a plot template
    p = plotter_multi.Plotter(arrays=arrays, tstamps=tstamps, 
                             x=x, y=y, z=z, projection=LambertConformalHRRR(),
                             plotter_options=plotter_options_multi,
                            figure_options = figure_options)

    #p.savefig('dwprof_all.png', tidx=60)
    if maybe_hourly:
        ti = 0
    else:
        ti = 60
    p.savefig(oname.with_suffix('.png'), tidx=ti)

    nthreads = 24
    p.savemp4(oname, wdir=workdir, nthreads=nthreads)
# From Lei Duan

import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature
from matplotlib import pyplot as plt


#from matplotlib.colors import ListedColormap, LinearSegmentedColormap
ax = plt.subplot(111, projection = ccrs.PlateCarree())
ax.set_global()
ax.add_feature(cfeature.COASTLINE)

# Plot western interconnect
fname = 'data/US_Interconnects/WesternInterconnect.shp'
shape_feature = ShapelyFeature(Reader(fname).geometries(),
                                ccrs.PlateCarree(), edgecolor='black')
ax.add_feature(shape_feature, facecolor='blue')

#ax.pcolormesh( lon, lat, test1, transform=ccrs.PlateCarree() )
#ax.set_extent([-150,-50, 10, 80])
plt.show()
Exemplo n.º 8
0
# lon1 = -118.4
# lon2 = -116.5
# lat1 = 47
# lat2 = 48.4
# =============================================================================

# AIRPACT extents
lon1 = -127
lon2 = -109
lat1 = 50.5
lat2 = 39

#AIRPACT
shape_feature = ShapelyFeature(Reader(fname_airpact).geometries(),
                               useproj,
                               edgecolor='black',
                               alpha=0.1,
                               facecolor='none')

ax.add_feature(shape_feature)

# Urbanova
shape_feature = ShapelyFeature(Reader(fname).geometries(),
                               useproj,
                               edgecolor='red',
                               alpha=0.1,
                               facecolor='none')

ax.add_feature(shape_feature)

# Annotate
Exemplo n.º 9
0
             draw_labels=True,
             linestyle='--',
             linewidth=1,
             color='gray',
             alpha=0.5)
gl.xlabels_top=False
gl.ylabels_right=False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER


# Add the Stamen data at zoom level 10.
ax.add_image(stamen_terrain, 10)
#######  plotagem shape do rio de janeiro
mapa_amsul = ShapelyFeature(Reader('/media/ladsin/IGOR06/MESTRADO/PPGM/PROJETO_PETROBRAS/CURSO_PYTHON_RONALDO/shapefiles/rj_unidades_da_federacao/33UFE250GC_SIR.shp').geometries(),
                            ccrs.PlateCarree(),
                            edgecolor='black',
                            facecolor='None')
ax.add_feature(mapa_amsul)

#######  plotagem shape dos dutos do rio de janeiro 
mapa_duto = ShapelyFeature(Reader('/media/ladsin/IGOR06/MESTRADO/PPGM/PROJETO_PETROBRAS/CURSO_PYTHON_RONALDO/shapefiles/RJ25_tra_trecho_duto_l/RJ25_tra_trecho_duto_l.shp').geometries(),
                            ccrs.PlateCarree(),
                            edgecolor='red',
                            facecolor='None')
ax.add_feature(mapa_duto)

#######  plotagem shape dos municipios do rio de janeiro
mapa_limites = ShapelyFeature(Reader('/media/ladsin/IGOR06/MESTRADO/PPGM/PROJETO_PETROBRAS/CURSO_PYTHON_RONALDO/shapefiles/T_LM_MUNICIPIOS_2010/T_LM_MUNICIPIOS_2010Polygon.shp').geometries(),
                            ccrs.PlateCarree(),
                            edgecolor='black',
                            facecolor='None')
Exemplo n.º 10
0
def draw_contour(shakegrid,
                 popgrid,
                 oceanfile,
                 oceangridfile,
                 cityfile,
                 basename,
                 borderfile=None,
                 is_scenario=False):
    """Create a contour map showing MMI contours over greyscale population.

    :param shakegrid:
      ShakeGrid object.
    :param popgrid:
      Grid2D object containing population data.
    :param oceanfile:
      String path to file containing ocean vector data in a format compatible
      with fiona.
    :param oceangridfile:
      String path to file containing ocean grid data .
    :param cityfile:
      String path to file containing GeoNames cities data.
    :param basename:
      String path containing desired output PDF base name, i.e.,
      /home/pager/exposure.  ".pdf" and ".png" files will
      be made.
    :param make_png:
      Boolean indicating whether a PNG version of the file should also be
      created in the same output folder as the PDF.
    :returns:
      Tuple containing:
        - Name of PNG file created, or None if PNG output not specified.
        - Cities object containing the cities that were rendered on the
          contour map.
    """
    gd = shakegrid.getGeoDict()

    # Retrieve the epicenter - this will get used on the map
    center_lat = shakegrid.getEventDict()['lat']
    center_lon = shakegrid.getEventDict()['lon']

    # load the ocean grid file (has 1s in ocean, 0s over land)
    # having this file saves us almost 30 seconds!
    oceangrid = read(oceangridfile,
                     samplegeodict=gd,
                     resample=True,
                     doPadding=True)

    # load the cities data, limit to cities within shakemap bounds
    allcities = Cities.fromDefault()
    cities = allcities.limitByBounds((gd.xmin, gd.xmax, gd.ymin, gd.ymax))

    # define the map
    # first cope with stupid 180 meridian
    height = (gd.ymax - gd.ymin) * DEG2KM
    if gd.xmin < gd.xmax:
        width = (gd.xmax - gd.xmin) * np.cos(np.radians(center_lat)) * DEG2KM
        xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax)
    else:
        xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax)
        xmax += 360
        width = ((gd.xmax + 360) - gd.xmin) * \
            np.cos(np.radians(center_lat)) * DEG2KM

    aspect = width / height

    # if the aspect is not 1, then trim bounds in x or y direction
    # as appropriate
    if width > height:
        dw = (width - height) / 2.0  # this is width in km
        xmin = xmin + dw / (np.cos(np.radians(center_lat)) * DEG2KM)
        xmax = xmax - dw / (np.cos(np.radians(center_lat)) * DEG2KM)
        width = (xmax - xmin) * np.cos(np.radians(center_lat)) * DEG2KM
    if height > width:
        dh = (height - width) / 2.0  # this is width in km
        ymin = ymin + dh / DEG2KM
        ymax = ymax - dh / DEG2KM
        height = (ymax - ymin) * DEG2KM

    aspect = width / height
    figheight = FIGWIDTH / aspect
    bbox = (xmin, ymin, xmax, ymax)
    bounds = (xmin, xmax, ymin, ymax)
    figsize = (FIGWIDTH, figheight)

    # Create the MercatorMap object, which holds a separate but identical
    # axes object used to determine collisions between city labels.
    mmap = MercatorMap(bounds, figsize, cities, padding=0.5)
    fig = mmap.figure
    ax = mmap.axes
    # this needs to be done here so that city label collision
    # detection will work
    fig.canvas.draw()

    geoproj = mmap.geoproj
    proj = mmap.proj

    # project our population grid to the map projection
    projstr = proj.proj4_init
    popgrid_proj = popgrid.project(projstr)
    popdata = popgrid_proj.getData()
    newgd = popgrid_proj.getGeoDict()

    # Use our GMT-inspired palette class to create population and MMI colormaps
    popmap = ColorPalette.fromPreset('pop')
    mmimap = ColorPalette.fromPreset('mmi')

    # set the image extent to that of the data
    img_extent = (newgd.xmin, newgd.xmax, newgd.ymin, newgd.ymax)
    plt.imshow(popdata,
               origin='upper',
               extent=img_extent,
               cmap=popmap.cmap,
               vmin=popmap.vmin,
               vmax=popmap.vmax,
               zorder=POP_ZORDER,
               interpolation='nearest')

    # draw 10m res coastlines
    ax.coastlines(resolution="10m", zorder=COAST_ZORDER)

    states_provinces = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_1_states_provinces_lines',
        scale='50m',
        facecolor='none')

    ax.add_feature(states_provinces, edgecolor='black', zorder=COAST_ZORDER)

    # draw country borders using natural earth data set
    if borderfile is not None:
        borders = ShapelyFeature(
            Reader(borderfile).geometries(), ccrs.PlateCarree())
        ax.add_feature(borders,
                       zorder=COAST_ZORDER,
                       edgecolor='black',
                       linewidth=2,
                       facecolor='none')

    # clip the ocean data to the shakemap
    bbox = (gd.xmin, gd.ymin, gd.xmax, gd.ymax)
    oceanshapes = _clip_bounds(bbox, oceanfile)

    ax.add_feature(ShapelyFeature(oceanshapes, crs=geoproj),
                   facecolor=WATERCOLOR,
                   zorder=OCEAN_ZORDER)

    # So here we're going to project the MMI data to
    # our mercator map, then smooth and contour that
    # projected grid.

    # smooth the MMI data for contouring, themn project
    mmi = shakegrid.getLayer('mmi').getData()
    smoothed_mmi = gaussian_filter(mmi, FILTER_SMOOTH)
    newgd = shakegrid.getGeoDict().copy()
    smooth_grid = Grid2D(data=smoothed_mmi, geodict=newgd)
    smooth_grid_merc = smooth_grid.project(projstr)
    newgd2 = smooth_grid_merc.getGeoDict()

    # project the ocean grid
    oceangrid_merc = oceangrid.project(projstr)

    # create masked arrays using the ocean grid
    data_xmin, data_xmax = newgd2.xmin, newgd2.xmax
    data_ymin, data_ymax = newgd2.ymin, newgd2.ymax
    smooth_data = smooth_grid_merc.getData()
    landmask = np.ma.masked_where(oceangrid_merc._data == 0.0, smooth_data)
    oceanmask = np.ma.masked_where(oceangrid_merc._data == 1.0, smooth_data)

    # contour the data
    contourx = np.linspace(data_xmin, data_xmax, newgd2.nx)
    contoury = np.linspace(data_ymin, data_ymax, newgd2.ny)
    ax.contour(
        contourx,
        contoury,
        np.flipud(oceanmask),
        linewidths=3.0,
        linestyles='solid',
        zorder=1000,
        cmap=mmimap.cmap,
        vmin=mmimap.vmin,
        vmax=mmimap.vmax,
        levels=np.arange(0.5, 10.5, 1.0),
    )

    ax.contour(
        contourx,
        contoury,
        np.flipud(landmask),
        linewidths=2.0,
        linestyles='dashed',
        zorder=OCEANC_ZORDER,
        cmap=mmimap.cmap,
        vmin=mmimap.vmin,
        vmax=mmimap.vmax,
        levels=np.arange(0.5, 10.5, 1.0),
    )

    # the idea here is to plot invisible MMI contours at integer levels
    # and then label them. clabel method won't allow text to appear,
    # which is this case is kind of ok, because it allows us an
    # easy way to draw MMI labels as roman numerals.
    cs_land = plt.contour(
        contourx,
        contoury,
        np.flipud(oceanmask),
        linewidths=0.0,
        levels=np.arange(0, 11),
        alpha=0.0,
        zorder=CLABEL_ZORDER,
    )

    roman_format_dict = {
        1: 'I',
        2: 'II',
        3: 'III',
        4: 'IV',
        5: 'V',
        6: 'VI',
        7: 'VII',
        8: 'VIII',
        9: 'IX',
        10: 'X',
    }
    clabel_text_land = ax.clabel(cs_land,
                                 cs_land.cvalues,
                                 colors='k',
                                 fmt=roman_format_dict,
                                 fontsize=16,
                                 zorder=CLABEL_ZORDER)
    # this sometimes works to draw a shadow effect, but other times
    # results in a duplicate offset roman numeral all in white.
    # TODO: Figure this out!+
    # for clabel in clabel_text_land:
    #     clabel.set_path_effects([path_effects.Stroke(linewidth=2.0,
    #                                                  foreground='white'),
    #                              path_effects.Normal()])

    cs_ocean = plt.contour(
        contourx,
        contoury,
        np.flipud(landmask),
        linewidths=0.0,
        levels=np.arange(0, 11),
        zorder=CLABEL_ZORDER,
    )

    clabel_text_ocean = ax.clabel(cs_ocean,
                                  cs_ocean.cvalues,
                                  colors='k',
                                  fmt=roman_format_dict,
                                  fontsize=16,
                                  zorder=CLABEL_ZORDER)
    # this sometimes works to draw a shadow effect, but other times
    # results in a duplicate offset roman numeral all in white.
    # TODO: Figure this out!
    # for clabel in clabel_text:
    #     clabel.set_path_effects([path_effects.Stroke(linewidth=2.0,
    #                                                  foreground='white'),
    #                              path_effects.Normal()])

    # draw meridians and parallels using Cartopy's functions for that
    gl = ax.gridlines(draw_labels=True,
                      linewidth=2,
                      color=(0.9, 0.9, 0.9),
                      alpha=0.5,
                      linestyle='-',
                      zorder=GRID_ZORDER)
    gl.xlabels_top = False
    gl.xlabels_bottom = False
    gl.ylabels_left = False
    gl.ylabels_right = False
    gl.xlines = True

    # let's floor/ceil the edges to nearest half a degree
    gxmin = np.floor(xmin * 2) / 2
    gxmax = np.ceil(xmax * 2) / 2
    gymin = np.floor(ymin * 2) / 2
    gymax = np.ceil(ymax * 2) / 2

    xlocs = np.linspace(gxmin, gxmax + 0.5, num=5)
    ylocs = np.linspace(gymin, gymax + 0.5, num=5)

    gl.xlocator = mticker.FixedLocator(xlocs)
    gl.ylocator = mticker.FixedLocator(ylocs)
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    gl.xlabel_style = {'size': 15, 'color': 'black'}
    gl.ylabel_style = {'size': 15, 'color': 'black'}

    # TODO - figure out x/y axes data coordinates
    # corresponding to 10% from left and 10% from top
    # use geoproj and proj
    dleft = 0.01
    dtop = 0.97
    proj_str = proj.proj4_init
    merc_to_dd = pyproj.Proj(proj_str)

    # use built-in transforms to get from axes units to data units
    display_to_data = ax.transData.inverted()
    axes_to_display = ax.transAxes

    # these are x,y coordinates in projected space
    yleft, t1 = display_to_data.transform(
        axes_to_display.transform((dleft, 0.5)))
    t2, xtop = display_to_data.transform(axes_to_display.transform(
        (0.5, dtop)))

    # these are coordinates in lon,lat space
    yleft_dd, t1_dd = merc_to_dd(yleft, t1, inverse=True)
    t2_dd, xtop_dd = merc_to_dd(t2, xtop, inverse=True)

    # drawing our own tick labels INSIDE the plot, as
    # Cartopy doesn't seem to support this.
    yrange = ymax - ymin
    xrange = xmax - xmin
    ddlabelsize = 12
    for xloc in gl.xlocator.locs:
        outside = xloc < xmin or xloc > xmax
        # don't draw labels when we're too close to either edge
        near_edge = (xloc - xmin) < (xrange * 0.1) or (xmax - xloc) < (xrange *
                                                                       0.1)
        if outside or near_edge:
            continue
        direction = 'W'
        if xloc >= 0:
            direction = 'E'
        xtext = r'$%.1f^\circ$%s' % (abs(xloc), direction)
        ax.text(xloc,
                xtop_dd,
                xtext,
                fontsize=ddlabelsize,
                zorder=GRID_ZORDER,
                ha='center',
                fontname=DEFAULT_FONT,
                transform=ccrs.Geodetic())

    for yloc in gl.ylocator.locs:
        outside = yloc < gd.ymin or yloc > gd.ymax
        # don't draw labels when we're too close to either edge
        near_edge = (yloc - gd.ymin) < (yrange * 0.1) or (gd.ymax - yloc) < (
            yrange * 0.1)
        if outside or near_edge:
            continue
        if yloc < 0:
            ytext = r'$%.1f^\circ$S' % (abs(yloc))
        else:
            ytext = r'$%.1f^\circ$N' % (abs(yloc))
        ax.text(yleft_dd,
                yloc,
                ytext,
                fontsize=ddlabelsize,
                zorder=GRID_ZORDER,
                va='center',
                fontname=DEFAULT_FONT,
                transform=ccrs.Geodetic())

    # draw cities
    mapcities = mmap.drawCities(shadow=True, zorder=CITIES_ZORDER)

    # draw the figure border thickly
    # TODO - figure out how to draw map border
    # bwidth = 3
    # ax.spines['top'].set_visible(True)
    # ax.spines['left'].set_visible(True)
    # ax.spines['bottom'].set_visible(True)
    # ax.spines['right'].set_visible(True)
    # ax.spines['top'].set_linewidth(bwidth)
    # ax.spines['right'].set_linewidth(bwidth)
    # ax.spines['bottom'].set_linewidth(bwidth)
    # ax.spines['left'].set_linewidth(bwidth)

    # Get the corner of the map with the lowest population
    corner_rect, filled_corner = _get_open_corner(popgrid, ax)
    clat2 = round_to_nearest(center_lat, 1.0)
    clon2 = round_to_nearest(center_lon, 1.0)

    # draw a little globe in the corner showing in small-scale
    # where the earthquake is located.
    proj = ccrs.Orthographic(central_latitude=clat2, central_longitude=clon2)
    ax2 = fig.add_axes(corner_rect, projection=proj)
    ax2.add_feature(cfeature.OCEAN,
                    zorder=0,
                    facecolor=WATERCOLOR,
                    edgecolor=WATERCOLOR)
    ax2.add_feature(cfeature.LAND, zorder=0, edgecolor='black')
    ax2.plot([clon2], [clat2],
             'w*',
             linewidth=1,
             markersize=16,
             markeredgecolor='k',
             markerfacecolor='r')
    ax2.gridlines()
    ax2.set_global()
    ax2.outline_patch.set_edgecolor('black')
    ax2.outline_patch.set_linewidth(2)

    # Draw the map scale in the unoccupied lower corner.
    corner = 'lr'
    if filled_corner == 'lr':
        corner = 'll'
    draw_scale(ax, corner, pady=0.05, padx=0.05)

    # Draw the epicenter as a black star
    plt.sca(ax)
    plt.plot(center_lon,
             center_lat,
             'k*',
             markersize=16,
             zorder=EPICENTER_ZORDER,
             transform=geoproj)

    if is_scenario:
        plt.text(center_lon,
                 center_lat,
                 'SCENARIO',
                 fontsize=64,
                 zorder=WATERMARK_ZORDER,
                 transform=geoproj,
                 alpha=0.2,
                 color='red',
                 horizontalalignment='center')

    # create pdf and png output file names
    pdf_file = basename + '.pdf'
    png_file = basename + '.png'

    # save to pdf
    plt.savefig(pdf_file)
    plt.savefig(png_file)

    return (pdf_file, png_file, mapcities)
Exemplo n.º 11
0
def radar_subplots(mom,fig,display,klat,klon,klat1,klon1,klat2,klon2,rhib1,rhie1,rhib2,rhie2,head1,head2,radar,swp_id,currentscantime,p_var,e_test):
    if print_long== True: print('made it into radar_subplots')
    
    ## SET UP PLOTTING CONTROLS
    NSSLmm, NEBmm, UASd = True, False, False #which other platforms do you wish to plot 
    rhi_ring= True #do you want the rhi spokes
    country_roads, hwys, county_lines, state_lines = False, True, False, False #background plot features
    legend_elements=[]
    ###########################

    ## SET UP VARS FOR EACH RADAR MOMENTS
    if mom == 'refl':
        pos, field=221, 'refl_fix'
        c_scale, c_label='pyart_HomeyerRainbow','Radar Reflectivity [dbz]'
        vminb, vmaxb= -30.,30.
        p_title, leg ='Reflectivity', True
    elif mom == 'vel':
        pos, field=222, 'vel_fix'
        c_scale, c_label='pyart_balance','Velocity [m/s]'
        vminb, vmaxb= -40.,40.
        p_title, leg ='Radial Velocity', False
    
    ## Bounding box, x km away from the radar in all directions 
    xmin, xmax = getLocation(klat,klon,270,21)[1], getLocation(klat,klon,90,21)[1]
    ymin, ymax = getLocation(klat,klon,180,21)[0], getLocation(klat,klon,0,21)[0]
    
    ## SET UP SUBPLOTS   
    ax_n=fig.add_subplot(pos,projection=display.grid_projection)
    ax_n.plot(klon,klat,transform=display.grid_projection)
    display.plot_ppi_map(field, swp_id,title_flag=False, cmap=c_scale, ax=ax_n, vmin=vminb, vmax=vmaxb, colorbar_label= c_label, min_lon=xmin, max_lon=xmax, min_lat=ymin, max_lat=ymax, embelish=False) 
    ax_n.text(.5,-.065,p_title,transform=ax_n.transAxes,horizontalalignment='center',fontsize=40) #the radar subplot titles
        
    ## PLOT RHI SPOKES
    if rhi_ring == True:
        try:
            rhi_spokes_rings(rhib1,rhie1,head1,klat1,klon1,radar,display,ymin,ymax,xmin,xmax) #plot the spokes for radar1
        except: error_printing(e_test)
        try:
            rhi_spokes_rings(rhib2,rhie2,head2,klat2,klon2,radar,display,ymin,ymax,xmin,xmax) #plot the spokes for radar2
        except: error_printing(e_test)

    ## PLOT RADAR MARKERS
    try:
        if np.logical_and(klat2>ymin,np.logical_and(klat2<ymax,np.logical_and(klon2>xmin,klon2<xmax))):
            m_style,m_color,l_color,leg_str,legend_elements=platform_attr('Ka2',legend_elements,radar_m=True, r_s=True)
            ax_n.plot(klon2,klat2,marker=m_style, transform=ccrs.PlateCarree(),color=m_color,markersize=18,markeredgewidth=5,path_effects=[PathEffects.withStroke(linewidth=15,foreground='k')],
                    zorder=10)
            #d2=ax_n.text(klon2+0.006, klat2-0.011,'Ka2',transform=ccrs.PlateCarree(), zorder=10, path_effects=[PathEffects.withStroke(linewidth=4,foreground='xkcd:pale blue')]) #textlabel on plot 
    except: error_printing(e_test)
    try:
        if np.logical_and(klat1>ymin,np.logical_and(klat1<ymax,np.logical_and(klon1>xmin,klon1<xmax))):
            m_style,m_color,l_color,leg_str,legend_elements=platform_attr('Ka1',legend_elements,radar_m=True, r_s=True)
            ax_n.plot(klon1,klat1,marker=m_style, transform=ccrs.PlateCarree(),color=m_color,markersize=18,markeredgewidth=5,path_effects=[PathEffects.withStroke(linewidth=15,foreground='k')],
                    zorder=10)
            #d1=ax_n.text(klon1+0.006, klat1+0.005, 'Ka1',transform=ccrs.PlateCarree(), zorder=10, path_effects=[PathEffects.withStroke(linewidth=4,foreground='xkcd:pale blue')])
    except: error_printing(e_test)
    
    ## PLOT OTHER PLATFORMS             
    if NSSLmm == True:
        for NSSLMM in NSSLMM_df:
            if print_long== True: print(NSSLMM.name)
            m_style,m_color,l_color,leg_str,legend_elements=platform_attr(NSSLMM,legend_elements,r_s=True)
            platform_plot(NSSLMM,currentscantime,ax_n,'xkcd:light grey',m_color,p_var,e_test, labelbias=(0,0))
    if NEBmm == True:
        print('To be filled in')
    if UASd == True:
        for UAS in UAS_files:
            m_style,m_color,l_color,leg_str,legend_elements=platform_attr(UAS,legend_elements,r_s=True)
            platform_plot(UAS,currentscantime,ax_n,'xkcd:very pale green',p_var,labelbias=(0,0.01))
 
    
    ## SET UP LEGENDS
    l_list=legend_elements.tolist()
    if leg == True: #add legend for platform markers
        l=ax_n.legend(handles=l_list,loc='lower left', bbox_transform=ax_n.transAxes, bbox_to_anchor=(-0.45,0), handlelength=.1,title="Platforms",shadow=True,fancybox=True,ncol=1,edgecolor='black')
        l.get_title().set_fontweight('bold')
    else: #Set up an invisible legend in a jankey method to force the plots to be where I want them (#goodenoughforgovwork)
        ax_n.legend([],[],loc='lower left', bbox_transform=ax_n.transAxes, bbox_to_anchor=(1.3,1.017), handlelength=.25,frameon=False)
    
    ## PLOT BACKGROUND FEATURES
    if country_roads == True:
        ox.config(log_file=True, log_console=True, use_cache=True)
        G = ox.graph_from_bbox(ymax,ymin,xmax,xmin)
        ox.save_load.save_graph_shapefile(G, filename='tmp'+str(0), folder=filesys+'Radar_Processing/TORUS19/roads/', encoding='utf-8')
        fname = filesys+'Radar_Processing/TORUS19/roads/tmp'+str(0)+'/edges/edges.shp'
        shape_feature = ShapelyFeature(Reader(fname).geometries(),ccrs.PlateCarree(), edgecolor='gray', linewidth=0.5)
        ax_n.add_feature(shape_feature, facecolor='none')
        shutil.rmtree(filesys+'Radar_Processing/TORUS19/roads/tmp'+str(0)+'/')
    if hwys == True:
        fname = filesys+'Radar_Processing/TORUS19/roads/GPhighways.shp'
        shape_feature = ShapelyFeature(Reader(fname).geometries(),ccrs.PlateCarree(), edgecolor='grey')#edgecolor='black')
        ax_n.add_feature(shape_feature, facecolor='none')
    if county_lines == True:
        fname = filesys+'Radar_Processing/TORUS19/roads/cb_2017_us_county_5m.shp'
        shape_feature = ShapelyFeature(Reader(fname).geometries(),ccrs.PlateCarree(), edgecolor='gray')
        ax_n.add_feature(shape_feature, facecolor='none', linewidth=1.5, linestyle="--")
    if state_lines == True:
        states_provinces = cartopy.feature.NaturalEarthFeature(category='cultural',name='admin_1_states_provinces_lines',scale='10m',facecolor='none')
        ax_n.add_feature(states_provinces, edgecolor='black', linewidth=2)
     
    if print_long== True: print('Made it through radar_subplots')
    
    return
ax = fig.add_subplot(111, projection=ccrs.Miller())
ax.set_extent([235.5, 246, 33, 45], crs=ccrs.Miller())
plot = ax.contourf(veg.x,
                   veg.y,
                   veg,
                   transform=ccrs.PlateCarree(),
                   levels=[0, 1, 2],
                   cmap='YlGn')  #PiYG
states = cartopy.feature.NaturalEarthFeature(
    category='cultural',
    name='admin_1_states_provinces_lakes_shp',
    scale='110m',
    facecolor='none')
ax.add_feature(states, edgecolor='0.2')
ecoregions = ShapelyFeature(
    Reader(root + "epa_ecoregions3/level3_cali.shp").geometries(),
    ccrs.PlateCarree())
ax.add_feature(ecoregions, edgecolor='0.3', facecolor='none', linewidth=0.2)
ax.set_title('Dominant vegetation type', fontsize=18)
cbar = plt.colorbar(plot,
                    orientation='horizontal',
                    shrink=0.65,
                    pad=0.05,
                    ticks=[0.5, 1.5])
cbar.ax.set_xticklabels(['Shrub/grass', 'Forest'], fontsize=18)
ax.text(-124.2, 33.5, '(a)', fontsize=18, fontweight='bold')
#cbar.ax.set_xticklabels(['Forest loss','Forest gain'], fontsize=20) #hack - just needed this for a PiYG colorbar in final figure
ax.set_xticks([-124, -122, -120, -118, -116, -114], crs=ccrs.PlateCarree())
ax.set_yticks([32, 34, 36, 38, 40, 42], crs=ccrs.PlateCarree())
ax.set_xticklabels([-124, -122, -120, -118, -116, ''])
ax.set_yticklabels([32, 34, 36, 38, 40, 42])
Exemplo n.º 13
0
                  color='gray',
                  alpha=0.3,
                  linestyle='-')
gl.xlabels_top = False
gl.ylabels_right = False
ax.set_aspect('auto')
ax.coastlines('10m')
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '10m',\
                                         edgecolor='face', facecolor='#555570'))
# #ax.add_feature(cfeature.NaturalEarthFeature('cultural', 'admin_0_pacific_groupings', '10m',edgecolor='black',facecolor = 'none'))
# ax.add_feature(cfeature.NaturalEarthFeature('cultural', 'admin_0_boundary_lines_land', '10m',edgecolor='black',facecolor = 'none',alpha = 0.1))

EEZ = ShapelyFeature(Reader(
    "C:\\Data\\Layers\\Intersect_EEZ_IHO_v4_2020\\Intersect_EEZ_IHO_v4_2020.shp"
).geometries(),
                     the_proj,
                     edgecolor='blue',
                     facecolor='none',
                     linewidth=3.0,
                     alpha=0.3)
ax.add_feature(EEZ)

#pick_up_area = mp.patches.Ellipse(pick_up_center, pickup_width, pickup_height,\
#                                  color = "#55aa55", alpha = 0.3)
#
if (plot_set == 'GotlandDeep' or plot_set == 'GotlandDeep2021'):
    pick_up_area = mp.patches.Rectangle((19.6,57),20.5-19.6,57.5-57.0,\
                                      color = "#55aa00", alpha = 0.3)
if (plot_set == 'NorthernProper'):
    pick_up_area = mp.patches.Rectangle(pickup_corner1,pickup_w,pickup_h,\
                                      color = "#ff0000", alpha = 0.3)
Exemplo n.º 14
0
ax.quiver(
    x=lonHorizontalCenterCells,
    y=latHorizontalCenterCells,
    u=UpropArray,
    v=VpropArray,
    units='xy',
    angles='xy',
    scale_units='xy',
    scale=arrowsScale,
    regrid_shape=arrowsRegridShape,
    pivot='middle',
    transform=ccrs.Mercator())

# adds shapefile
land_feature = ShapelyFeature(
    Reader(landShapefile).geometries(),
    crs=ccrs.Mercator(),
    facecolor=facecolor)

ax.add_feature(
    land_feature,
    edgecolor=edgecolor)

# adds longitude and latitude ticks
xticks, yticks, xticklabels, yticklabels = ticks_definer(
    MHDF5Reader.getLonHorizontalGrid(),
    MHDF5Reader.getLatHorizontalGrid(),
    tickInterval)
ax.set_xticks(xticks, crs=ccrs.Mercator())
ax.set_yticks(yticks, crs=ccrs.Mercator())
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
def day4_8Plots():  #plots day 4-8 severe weather risk
    day4_8 = day4_8files()  #list of files
    SPCimagefiles = []  #list of image files
    risklevel = []  #for day 4-8
    Day4_8Risk = False  #for if there's warnings in day 4-8 (set to no warnings as of now)
    for i in range(len(day4_8)):
        shpfile = day4_8[i]
        dn = Reader(shpfile).records()
        for j in dn:
            risklevel.append(j.attributes['DN'])  #pulls out the risk number

    for i in range(len(day4_8)):
        if risklevel[i] != 0:
            Day4_8Risk = True  # there is a warning on day 4-8, want to plot them all individually
            print 'Day4-8 Risk is True'
            break

    if Day4_8Risk == False:  #if there's no risk for day 4-8
        plt.figure()
        xmin = -120
        xmax = -70
        ymin = 20
        ymax = 55
        start = str(datetime.utcnow() +
                    dat.timedelta(days=3))  #for the valid/expire time
        validyear = start[0:4]
        validmonth = start[5:7]
        validday = start[8:10]
        validhour = str(1200)

        end = str(datetime.utcnow() + dat.timedelta(days=8))
        expireyear = end[0:4]
        expiremonth = end[5:7]
        expireday = end[8:10]
        expirehour = str(1200)

        ax = plt.axes(projection=crs.LambertConformal())
        ax.add_feature(cfeature.OCEAN, edgecolor='gray', linewidth=1.5)
        ax.add_feature(cfeature.LAKES)
        ax.add_feature(
            ShapelyFeature(Reader(
                "ne_50m_admin_1_states_provinces_lakes.shp").geometries(),
                           crs.PlateCarree(),
                           facecolor='w',
                           edgecolor='gray',
                           linewidth=1.5))
        ax.set_extent([xmin, xmax, ymin, ymax])
        plt.title(
            'SPC Convective Outlook Day 4-8: Low Probability/Predictability')
        filename = 'SPCDay4-8.png'
        text = 'Valid: ' + validmonth + '/' + validday + '/' + validyear + ' ' + validhour + 'Z - ' + expiremonth + '/' + expireday + '/' + expireyear + ' ' + expirehour + 'Z\nPredictability or potential for severe weather too low\nData from NWS/NOAA Storm Prediction Center (www.spc.noaa.gov)\nFind discussions about these categories on the SPC website.'
        ax.text(0.01,
                0.01,
                text,
                verticalalignment='bottom',
                horizontalalignment='left',
                transform=ax.transAxes,
                fontsize='8',
                bbox=dict(facecolor='white', alpha=0.75))

        ax.yaxis.set_visible(False)
        ax.xaxis.set_visible(False)

        plt.savefig(filename, bbox_inches='tight')
        plt.close()
        SPCimagefiles.append(filename)
    else:  #if there is any risk on any of days 4-8
        valid = []  #outlook valid time
        expire = []  #outlook expire time
        for i in range(len(day4_8)):
            plt.figure()
            xmin = -120
            xmax = -70
            ymin = 20
            ymax = 55
            ax = plt.axes(projection=crs.LambertConformal())
            ax.add_feature(cfeature.OCEAN, edgecolor='gray', linewidth=1.5)
            ax.add_feature(cfeature.LAKES)
            ax.add_feature(
                ShapelyFeature(Reader(
                    "ne_50m_admin_1_states_provinces_lakes.shp").geometries(),
                               crs.PlateCarree(),
                               facecolor='w',
                               edgecolor='gray',
                               linewidth=1.5))
            ax.set_extent([xmin, xmax, ymin, ymax])

            shpfile = day4_8[i]
            dn = Reader(shpfile).records()

            for j in dn:
                if j.attributes['VALID'] not in valid:
                    valid.append(j.attributes['VALID'])
                if j.attributes['EXPIRE'] not in expire:
                    expire.append(j.attributes['EXPIRE'])
                if j.attributes['DN'] == 15:
                    ax.add_geometries(j.geometry,
                                      crs.LambertConformal(
                                          central_longitude=0.0,
                                          central_latitude=0.0),
                                      facecolor='yellow',
                                      alpha=.75)
                elif j.attributes['DN'] == 30:
                    ax.add_geometries(j.geometry,
                                      crs.LambertConformal(
                                          central_longitude=0.0,
                                          central_latitude=0.0),
                                      facecolor='orange',
                                      alpha=.75)
            plt.title('SPC Convective Outlook: Day ' + str(i + 4))
            filename = 'SPCDay' + str(i + 4) + '.png'
            #for blurb at bottom, with valid/expiration times

            start = valid[i]
            validyear = start[0:4]
            validmonth = start[4:6]
            validday = start[6:8]
            validhour = start[8:12]

            end = expire[i]
            expireyear = end[0:4]
            expiremonth = end[4:6]
            expireday = end[6:8]
            expirehour = end[8:12]

            ax.yaxis.set_visible(False)
            ax.xaxis.set_visible(False)
            text = 'Valid: ' + validmonth + '/' + validday + '/' + validyear + ' ' + validhour + 'Z - ' + expiremonth + '/' + expireday + '/' + expireyear + ' ' + expirehour + 'Z\nData from NWS/NOAA Storm Prediction Center (www.spc.noaa.gov)\nFind discussions about these categories on the SPC website.'
            ax.text(0.01,
                    0.01,
                    text,
                    verticalalignment='bottom',
                    horizontalalignment='left',
                    transform=ax.transAxes,
                    fontsize='8',
                    bbox=dict(facecolor='white', alpha=0.75))
            #for the legend on the right
            fifteen = mpatches.Patch(color='yellow', label='15%')
            thirty = mpatches.Patch(color='orange', label='30%')
            plt.legend(handles=[thirty, fifteen],
                       loc='lower right',
                       fontsize='8')
            plt.savefig(filename, bbox_inches='tight')
            plt.close()
            SPCimagefiles.append(filename)

    print "Successfully made the following maps: "
    print SPCimagefiles
Exemplo n.º 16
0
    def plot(self, xar, **kwargs):
        """Wraps xr.DataArray.plot.pcolormesh and formats the plot as configured
        in the call to Map().

        title is xar.long_name
        cbar_label is xar.units

        Parameters
        ----------
        xar : xr.DataArray
            two-dimensional data array
        kwargs : dict
            are passed on to xr.DataArray.plot.pcolormesh()

        Returns
        ----------
        fig : matplotlib.pyplot.figure
        ax : matplotlib.pyplot.axis
        """
        for dim in ['longitude', 'latitude']:
            if dim not in xar.coords:
                raise KeyError(dim + ' not found in coordinates!')

        plt.close()
        fig = plt.figure(**self.fig_kws)

        if not self.proj:
            self.proj = choose_proj_from_xar(xar)
        ax = plt.axes(projection=self.proj)

        countries = cfeature.NaturalEarthFeature(
            category='cultural',
            name='admin_0_boundary_lines_land',
            scale='50m',
            facecolor='none')
        rivers = cfeature.NaturalEarthFeature(scale='50m',
                                              category='physical',
                                              name='rivers_lake_centerlines',
                                              edgecolor='blue',
                                              facecolor='none')

        ax.add_feature(countries, edgecolor='grey')
        ax.coastlines('50m')
        ax.add_feature(rivers, edgecolor='blue')
        gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True)
        gl.xlabels_top = False

        if self.drainage_baisins:
            sf = Reader(
                "../data/drainage_basins/Major_Basins_of_the_World.shp")
            shape_feature = ShapelyFeature(sf.geometries(),
                                           self.transform,
                                           edgecolor='black')
            ax.add_feature(shape_feature, facecolor='none', edgecolor='green')

        # cbar_kwargs = kwargs.pop('cbar_kwargs', dict())
        subplot_kws = kwargs.pop('subplot_kws', dict())
        subplot_kws['projection'] = self.proj

        # choose which colormap to use: pos and neg values => RdYlGn, else inferno
        if ((xar.max() - xar.min()) > xar.max()):
            cmap = 'RdYlGn'
        else:
            cmap = 'spring_r'

        # colorbar preset to match height of plot
        # if 'fraction' not in cbar_kwargs: cbar_kwargs['fraction'] = 0.015
        xar.plot.pcolormesh(ax=ax,
                            transform=self.transform,
                            subplot_kws=subplot_kws,
                            cmap=cmap,
                            **kwargs)
        return fig, ax
def windhailPlot(files, name):  #plots day 1 wind & hail probability
    SPCimagefiles = []
    valid = []
    expire = []

    plt.figure()
    xmin = -120
    xmax = -70
    ymin = 20
    ymax = 55

    ax = plt.axes(projection=crs.LambertConformal())
    ax.add_feature(cfeature.OCEAN, edgecolor='gray', linewidth=1.5)
    ax.add_feature(cfeature.LAKES)
    ax.add_feature(
        ShapelyFeature(
            Reader("ne_50m_admin_1_states_provinces_lakes.shp").geometries(),
            crs.PlateCarree(),
            facecolor='w',
            edgecolor='gray',
            linewidth=1.5))
    ax.set_extent([xmin, xmax, ymin, ymax])
    plt.title('SPC Day 1: ' + name + ' Outlook')
    filename = 'SPCDay1' + name + '.png'
    ax.yaxis.set_visible(False)
    ax.xaxis.set_visible(False)

    five = mpatches.Patch(color='brown', label='5%')
    fifteen = mpatches.Patch(color='yellow', label='15%')
    thirty = mpatches.Patch(color='red', label='30%')
    fourtyfive = mpatches.Patch(color='fuchsia', label='45%')
    sixty = mpatches.Patch(color='purple', label='60%')
    sig = mpatches.Patch(color='k', label='Sig')
    plt.legend(handles=[five, fifteen, thirty, fourtyfive, sixty, sig],
               loc='lower right',
               fontsize='8')

    for i in range(len(files)):
        shpfile = files[i]
        dn = Reader(shpfile).records()
        for j in dn:
            if j.attributes['VALID'] not in valid:
                valid.append(j.attributes['VALID'])
            if j.attributes['EXPIRE'] not in expire:
                expire.append(j.attributes['EXPIRE'])

            if j.attributes['DN'] == 5:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='brown',
                                  alpha=.75)
            elif j.attributes['DN'] == 15:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='yellow',
                                  alpha=.75)
            elif j.attributes['DN'] == 30:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='red',
                                  alpha=.75)
            elif j.attributes['DN'] == 45:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='fuchsia',
                                  alpha=.75)
            elif j.attributes['DN'] == 60:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='purple',
                                  alpha=.75)
            elif j.attributes['DN'] == 10:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='none',
                                  hatch='/////',
                                  alpha=.75)

    #start of text for blurb at bottom
    start = valid[0]
    validyear = start[0:4]
    validmonth = start[4:6]
    validday = start[6:8]
    validhour = start[8:12]

    end = expire[0]
    expireyear = end[0:4]
    expiremonth = end[4:6]
    expireday = end[6:8]
    expirehour = end[8:12]

    text = 'Valid: ' + validmonth + '/' + validday + '/' + validyear + ' ' + validhour + 'Z - ' + expiremonth + '/' + expireday + '/' + expireyear + ' ' + expirehour + 'Z\nData from NWS/NOAA Storm Prediction Center (www.spc.noaa.gov)\nFind discussions about these categories on the SPC website.'
    ax.text(0.01,
            0.01,
            text,
            verticalalignment='bottom',
            horizontalalignment='left',
            transform=ax.transAxes,
            fontsize='8',
            bbox=dict(facecolor='white', alpha=0.75))

    plt.savefig(filename, bbox_inches='tight', fontsize='8')
    SPCimagefiles.append(filename)
    print "Successfully made the following maps: "
    print SPCimagefiles
    plt.close()
Exemplo n.º 18
0
#pcm3    = mp.contourf(lons, lats, dem,   transform=ccrs.PlateCarree(), 
#                      levels=breaks, cmap=cmap, norm=norm, alpha=0.5)#, antialiased=True)

#plt.show()
#stop
# catchments
for icat in range(len(catchlist)): 
    # federal countries, bundeslaender
    if   (icat==5 or icat==2):
        color='r'
    elif (icat==0 or icat==4):
        color='g'
    else:
        color='b'
    reader    = shpreader.Reader(inpath + 'basin_' + catchlist[icat] + '.shp')
    fed_count = ShapelyFeature(reader.geometries(), ccrs.PlateCarree())
    mp.add_feature(fed_count, facecolor=color, alpha=0.10, lw=0.5, edgecolor='0') #, alpha=0.75)
    # catchment labels
    mp.annotate(label_cat[icat],(lon_cat[icat], lat_cat[icat]), xycoords=transform,
                va='center', ha='left', color=color)


# eddy stations
mp.plot(lon_ec, lat_ec, ls='None',marker='s',mfc='None', mec='k',mew=1.2, ms=3,transform=ccrs.PlateCarree())
for i in range(len(lon_ec)):
    if ( label_ec[i] == 'E1'):
        xp=lon_ec[i]+0.03; yp=lat_ec[i]#-0.15
        va='top'; ha='left'
    elif ( label_ec[i] == 'E2'):
        xp=lon_ec[i]; yp=lat_ec[i]#-0.15
        va='top'; ha='center'
ax = plt.axes(projection=ccrs.Robinson())
ax.add_geometries(y[0:1], ccrs.PlateCarree(), facecolor='white', hatch='xxxx')
plt.show()

# In[3]:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature

fname = 'D:\Data\ChinaShapefile//PilotAreas.shp'

ax = plt.axes(projection=ccrs.Robinson())
shape_feature = ShapelyFeature(Reader(fname).geometries(),
                               ccrs.PlateCarree(),
                               facecolor='none')
ax.add_feature(shape_feature)
plt.show()

# In[4]:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER
import matplotlib.ticker as mticker
import cartopy.feature as cfeature

#plt.figure(figsize=(41.53683777162, 18))
plt.figure(figsize=(13.84561259054, 6))
ax = plt.axes(projection=ccrs.InterruptedGoodeHomolosine())
Exemplo n.º 20
0
def mapICARUS_ZOOM(proj, delimiter='; ', threshold=thresh, cmap=c_map):
    """Produces a map of ICARUS outputs"""

    roads = 'input_data/GIS_data/tokyo_roads/tokyo_roads_esri.shp'
    roads_feature = ShapelyFeature(
        Reader(roads).geometries(), ccrs.PlateCarree())

    for value in threshold:

        lat_arr = []
        lon_arr = []
        color_arr = []

        outputs = os.listdir("input_data/icarus_output")
        n = 0

        for file in outputs:
            with open("input_data/icarus_output/" + file) as infile:

                while True:
                    try:
                        # filter out lat/lon values, append to arrays for later plotting
                        line = infile.readline().split(delimiter)

                        predictions = eval(line[5])
                        pred_arr = []

                        d = 0
                        for prediction in predictions:
                            prediction = predictions[d]['confidence']

                            if prediction > value:
                                pred_arr.append(prediction)
                                d += 1
                                n += 1

                            else:
                                d += 1

                        if len(pred_arr) > 0:
                            lat = line[0]
                            lon = line[1]

                            lat_arr.append(float(lat))
                            lon_arr.append(float(lon))
                            color_arr.append(round(float(max(pred_arr)), 2))

                        else:
                            pass

                    except IndexError:
                        break

        # set up map, aspect ratio is 2:1
        fig_height = 20
        fig = plt.figure(figsize=(fig_height, fig_height / 2))
        ax = fig.add_axes([0.05, 0.05, 1, 0.9], projection=proj)
        # set extent ([x0,x1,y0,y1]) for Japan [128.19, 155.9, 29.52, 49.7], Tokyo [139.6, 139.8, 35.46, 35.57]
        extents = {
            "Japan": [128.19, 155.9, 29.52, 49.7],
            "DT_Tokyo": [139.6, 139.8, 35.46, 35.57],
            "Tokyo": [139.685, 139.919, 35.624, 35.720],
            "NYC_Manhattan": [-74.026, -73.927, 40.702, 40.801],
            "NYC": [-74.150636, -73.8121, 40.64457, 40.8569]
        }

        set_ext = "Tokyo"

        ax.set_extent(extents[set_ext])

        # add features to the map (leave facecolor and change ONLY edgecolor!)
        ax.add_feature(roads_feature,
                       edgecolor=colors['black'],
                       facecolor='none',
                       alpha=0.8,
                       linewidth=0.5,
                       label="Roads")
        ax.coastlines()
        ax.add_feature(cfeature.OCEAN, color=colors["black"], alpha=1)
        ax.add_feature(cfeature.LAND, color=colors["grey"], alpha=1)
        ax.add_feature(cfeature.BORDERS, linewidth=0.7)

        # add gridlines
        gl = ax.gridlines(
            xlocs=range(-180, 181, 1),
            ylocs=range(-90, 100, 1),
            draw_labels=True,
            color=colors["grey"],
            linewidth=0.2,
        )
        gl.xlabel_style = {"color": colors["grey"]}
        gl.ylabel_style = {"color": colors["grey"]}
        gl.xlabels_top = False
        gl.ylabels_left = False

        # add points to map (s= sets size of each point, c= sets colour of each point according to a third array, in combination with cmap, which then gives the actual colormap, alpha= sets opacity (between 0 and 1))
        map = plt.scatter(lat_arr,
                          lon_arr,
                          s=0,
                          marker="s",
                          alpha=1,
                          transform=proj,
                          c=color_arr,
                          cmap=cmap,
                          vmin=0.5,
                          vmax=1)
        plt.scatter(lat_arr,
                    lon_arr,
                    s=10,
                    marker="s",
                    alpha=0.65,
                    transform=proj,
                    c=color_arr,
                    cmap=cmap,
                    vmin=0.5,
                    vmax=1)
        plt.scatter(-200000,
                    2000000,
                    s=30,
                    marker="s",
                    edgecolor='black',
                    linewidth=0.5,
                    alpha=1,
                    transform=proj,
                    c=colors["cmap_max"],
                    label="Predictions")
        plt.scatter(-200000,
                    2000000,
                    s=30,
                    marker="_",
                    edgecolor='black',
                    linewidth=2,
                    alpha=1,
                    transform=proj,
                    c=colors["black"],
                    label="Road Network")

        # add colorbar and legend
        bar = plt.colorbar(map, shrink=0.75, pad=0.03)
        bar.set_label("Prediction Confidence", labelpad=20, fontsize=12)
        leg = plt.legend(loc="lower center", fontsize=12)

        for t in leg.get_texts():
            t.set_va('center')

        # add titles and stuff
        # plt.suptitle("ALL SEASON ROADS DETECTED USING ICARUS ON TWEETS WITH APPENDED MEDIA")
        plt.title(
            "ALL SEASON ROADS DETECTED USING ICARUS ON TWEETS WITH APPENDED MEDIA AND GEOTAG\nMAY 12 - JUNE 12 2019, TOKYO (JPN), PREDICTION THRESHOLD {}"
            .format(value),
            color=colors["grey"],
            pad=20,
            fontsize=20,
            fontweight='bold')

        print("Legend Location: ", extents[set_ext][0], extents[set_ext][2])
        # add additional information
        addCredits(ax,
                   x=extents[set_ext][0] + 0.028,
                   y=extents[set_ext][2] + 0.003,
                   info=infostring_DTT,
                   zoom=set_ext)

        # save the figure and show on screen
        plt.savefig("Saved_Maps/map_ICARUS_{}_thresh{}".format(
            set_ext, int(value * 100)))
        print("Threshold: {} -- ICARUS Output Mapped\n".format((value)))
Exemplo n.º 21
0
from matplotlib.lines import Line2D
legend_elements = [
    Line2D([0], [0], color='b', lw=2, label='PAN-AMAZONIA'),
]

#    Line2D([0], [0], marker='o', color='w', label='Scatter',
#           markerfacecolor='g', markersize=15),
#    Patch(facecolor='orange', edgecolor='r',
#          label='Color Patch')]

var = ['avail_p', 'total_p', 'org_p', 'inorg_p', 'occ_p', 'mineral_p', 'tot_p']

raisg_mask = "/home/jdarela/Desktop/data_src/soil_map/tidy_data/predictor_data_raster/mask.shp"

mask = ShapelyFeature(Reader(raisg_mask).geometries(), ccrs.PlateCarree())

#mask = ShapelyFeature(raisg_mask, crs=ccrs.PlateCarree())


def open_dataset(vname, mean=True, tp=False):
    if not tp:
        fname = "predicted_" + vname + ".nc4"
    else:
        fname = "predictedTP_" + vname + ".nc4"
    fh = Dataset(fname)

    var = np.fliplr(fh.variables[vname][:])

    if mean:
        return var.mean(axis=0, )
ax2 = fig.add_axes([0.0025, 0.475, 0.995, 0.52],
                   projection=ccrs.UTM(7),
                   label='Zoom_1')

fn_ib_diss = '/home/atom/ongoing/work_worldwide/figures/fig3/fig3_icebridge_300m_diss.shp'
fn_ic_diss = '/home/atom/ongoing/work_worldwide/figures/fig3/fig3_icesat_800m_diss.shp'

ext = [290000, 685000, 6550000 - 25000, 6845000]

ax2.set_extent(ext, ccrs.UTM(7))

shape_feature = ShapelyFeature(Reader(fn_land_poly).geometries(),
                               ccrs.UTM(7),
                               edgecolor='None',
                               alpha=1,
                               facecolor=plt.cm.RdYlBu(0.5),
                               linewidth=1,
                               zorder=1)
ax2.add_feature(shape_feature)
ax2.outline_patch.set_edgecolor('black')

ds = gdal.Open(fn_dh)
hs = ds.ReadAsArray()
# hs[water_notglacier] = np.nan
gt = ds.GetGeoTransform()  # Defining bounds
ext = (gt[0], gt[0] + ds.RasterXSize * gt[1], gt[3] + ds.RasterYSize * gt[5],
       gt[3])
hs_tmp = hs.astype(float)
hs_tmp[hs_tmp <= -9999] = np.nan
Exemplo n.º 23
0
    def drawHazusMap(self, shakegrid, filename, model_config):
        gd = shakegrid.getGeoDict()

        # Retrieve the epicenter - this will get used on the map (??)
        center_lat = shakegrid.getEventDict()['lat']
        center_lon = shakegrid.getEventDict()['lon']

        # define the map
        # first cope with stupid 180 meridian
        height = (gd.ymax - gd.ymin) * 111.191
        if gd.xmin < gd.xmax:
            width = (gd.xmax - gd.xmin) * \
                np.cos(np.radians(center_lat)) * 111.191
            xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax)
        else:
            xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax)
            xmax += 360
            width = ((gd.xmax + 360) - gd.xmin) * \
                np.cos(np.radians(center_lat)) * 111.191

        aspect = width / height

        # if the aspect is not 1, then trim bounds in
        # x or y direction as appropriate
        if width > height:
            dw = (width - height) / 2.0  # this is width in km
            xmin = xmin + dw / (np.cos(np.radians(center_lat)) * 111.191)
            xmax = xmax - dw / (np.cos(np.radians(center_lat)) * 111.191)
            width = (xmax - xmin) * np.cos(np.radians(center_lat)) * 111.191
        if height > width:
            dh = (height - width) / 2.0  # this is width in km
            ymin = ymin + dh / 111.191
            ymax = ymax - dh / 111.191
            height = (ymax - ymin) * 111.191

        aspect = width / height
        figheight = FIGWIDTH / aspect
        bounds = (xmin, xmax, ymin, ymax)
        figsize = (FIGWIDTH, figheight)

        # load the counties here so we can grab the county names to
        # draw on the map
        counties_file = model_config['counties']
        counties_shapes = fiona.open(counties_file, 'r')
        counties = counties_shapes.items(bbox=(xmin, ymin, xmax, ymax))
        county_shapes = []

        county_columns = {
            'name': [],
            'lat': [],
            'lon': [],
            'pop': [],
        }

        for cid, county in counties:
            # county is a dictionary
            county_shape = sShape(county['geometry'])
            state_fips = county['properties']['STATEFP10']
            county_fips = county['properties']['COUNTYFP10']
            fips = int(state_fips + county_fips)
            df = self._dataframe
            weight = 1
            if (df['CountyFips'] == fips).any():
                loss_row = df[df['CountyFips'] == fips].iloc[0]
                weight = loss_row['EconLoss']
            center_point = county_shape.centroid
            county_name = county['properties']['NAMELSAD10'].replace(
                'County', '').strip()
            # feature = ShapelyFeature([county_shape], ccrs.PlateCarree(),
            #                          zorder=COUNTY_ZORDER)
            county_shapes.append(county_shape)
            county_columns['name'].append(county_name)
            county_columns['pop'].append(county_shape.area * weight)
            county_columns['lat'].append(center_point.y)
            county_columns['lon'].append(center_point.x)
            # ax.add_feature(feature, facecolor=GREY,
            #                edgecolor='grey', linewidth=0.5)
            # tx, ty = mmap.proj.transform_point(
            #     center_point.x, center_point.y, ccrs.PlateCarree())
            # plt.text(tx, ty, county_name,
            #          zorder=NAME_ZORDER,
            #          horizontalalignment='center',
            #          verticalalignment='center')

        # Create the MercatorMap object, which holds a separate but identical
        # axes object used to determine collisions between city labels.
        # here we're pretending that county names are city names.
        county_df = pd.DataFrame(county_columns)
        cities = Cities(county_df)
        mmap = MercatorMap(bounds, figsize, cities, padding=0.5)
        fig = mmap.figure
        ax = mmap.axes
        geoproj = mmap.geoproj
        proj = mmap.proj

        # this is a workaround to an occasional problem where some vector layers
        # are not rendered. See
        # https://github.com/SciTools/cartopy/issues/1155#issuecomment-432941088
        proj._threshold /= 6

        # this needs to be done here so that city label collision
        # detection will work
        fig.canvas.draw()

        # draw county names
        mmap.drawCities(zorder=NAME_ZORDER)

        # now draw the counties in grey
        for county_shape in county_shapes:
            feature = ShapelyFeature([county_shape],
                                     ccrs.PlateCarree(),
                                     zorder=COUNTY_ZORDER)
            ax.add_feature(feature,
                           facecolor=GREY,
                           edgecolor='grey',
                           linewidth=0.5,
                           zorder=COUNTY_ZORDER)

        # now draw the county boundaries only so that we can see
        # them on top of the colored tracts.
        for county_shape in county_shapes:
            feature = ShapelyFeature([county_shape],
                                     ccrs.PlateCarree(),
                                     zorder=COUNTY_ZORDER)
            ax.add_feature(feature,
                           facecolor=(0, 0, 0, 0),
                           edgecolor='grey',
                           linewidth=0.5,
                           zorder=NAME_ZORDER)

        # define bounding box we'll use to clip vector data
        bbox = (xmin, ymin, xmax, ymax)

        # load and clip ocean vectors to match map boundaries
        oceanfile = model_config['ocean_vectors']
        oceanshapes = _clip_bounds(bbox, oceanfile)
        ax.add_feature(ShapelyFeature(oceanshapes, crs=geoproj),
                       facecolor=WATERCOLOR,
                       zorder=OCEAN_ZORDER)

        # draw states with black border - TODO: Look into
        states_file = model_config['states']
        transparent = '#00000000'
        states = _clip_bounds(bbox, states_file)
        ax.add_feature(ShapelyFeature(states, crs=geoproj),
                       facecolor=transparent,
                       edgecolor='k',
                       zorder=STATE_ZORDER)

        # draw census tracts, colored by loss level
        tracts_file = model_config['tracts']
        tract_shapes = fiona.open(tracts_file, 'r')
        tracts = tract_shapes.items(bbox=(xmin, ymin, xmax, ymax))
        ntracts = 0
        for tid, tract in tracts:
            # tract is a dictionary
            ntracts += 1
            tract_shape = sShape(tract['geometry'])
            state_fips = str(int(tract['properties']['STATEFP10']))
            county_fips = state_fips + tract['properties']['COUNTYFP10']
            fips_column = self._dataframe['CountyFips']
            if not fips_column.isin([county_fips]).any():
                continue
            tract_fips = int(county_fips + tract['properties']['TRACTCE10'])
            econloss = 0.0
            if tract_fips in self._tract_loss:
                econloss = self._tract_loss[tract_fips]
                # print('Tract %i: Economic loss: %.3f' % (tract_fips, econloss))
            else:
                x = 1

            if econloss < 1e3:
                color = GREEN
            elif econloss >= 1e3 and econloss < 1e5:
                color = YELLOW
            elif econloss >= 1e5 and econloss < 1e6:
                color = ORANGE
            else:
                color = RED
            feature = ShapelyFeature([tract_shape],
                                     ccrs.PlateCarree(),
                                     zorder=TRACT_ZORDER)
            ax.add_feature(feature, facecolor=color)

        # # Draw the epicenter as a black star
        # plt.plot(center_lon, center_lat, 'k*', markersize=16,
        #          zorder=EPICENTER_ZORDER, transform=geoproj)

        # save our map out to a file
        logging.info('Saving to %s' % filename)
        t0 = time.time()
        plt.savefig(filename, dpi=300)
        t1 = time.time()
        logging.info('Done saving map - %.2f seconds' % (t1 - t0))
Exemplo n.º 24
0
                       figsize=(10, 5))
divnorm = colors.TwoSlopeNorm(0, vmin=-1.3, vmax=0.2)

CS = plt.contourf(LON,
                  LAT,
                  diff,
                  15,
                  cmap=plt.cm.hsv_r,
                  norm=divnorm,
                  transform=ccrs.PlateCarree())

coastname = './Shapefiles/Costa.shp'
coastlines_10m = cfeature.NaturalEarthFeature('physical', 'coastline', '10m')
coastlines_10m = ShapelyFeature(Reader(coastname).geometries(),
                                ccrs.epsg(25831),
                                linewidth=1,
                                facecolor='None',
                                edgecolor='black')
ax.add_feature(coastlines_10m, facecolor='None', edgecolor='black')
filename = './Shapefiles/AMB31N.shp'
AMB_feature = ShapelyFeature(Reader(filename).geometries(),
                             ccrs.epsg(25831),
                             linewidth=1,
                             facecolor='None',
                             edgecolor='black')
ax.add_feature(AMB_feature)

cbar = fig.colorbar(CS)
cbar.ax.set_ylabel('2m Temperature ($^\circ$C)', size=12)

plt.savefig(directory + name)
Exemplo n.º 25
0
def feature():
    unit_circle = sgeom.Point(0, 0).buffer(0.5)
    unit_square = unit_circle.envelope
    geoms = [unit_circle, unit_square]
    feature = ShapelyFeature(geoms, ccrs.PlateCarree())
    return feature
Exemplo n.º 26
0
    def execute(self):
        """
        Raises:
            NotADirectoryError: When the event data directory does not exist.
            FileNotFoundError: When the the shake_result HDF file does not
                exist.
        """
        install_path, data_path = get_config_paths()
        datadir = os.path.join(data_path, self._eventid, 'current', 'products')
        if not os.path.isdir(datadir):
            raise NotADirectoryError('%s is not a valid directory.' % datadir)
        datafile = os.path.join(datadir, 'shake_result.hdf')
        if not os.path.isfile(datafile):
            raise FileNotFoundError('%s does not exist.' % datafile)

        # Open the ShakeMapOutputContainer and extract the data
        container = ShakeMapOutputContainer.load(datafile)
        if container.getDataType() != 'grid':
            raise NotImplementedError('uncertaintymaps module can only '
                                      'operate on gridded data, not sets of '
                                      'points')

        # get the path to the products.conf file, load the config
        config_file = os.path.join(install_path, 'config', 'products.conf')
        spec_file = get_configspec('products')
        validator = get_custom_validator()
        config = ConfigObj(config_file, configspec=spec_file)
        results = config.validate(validator)
        check_extra_values(config, self.logger)
        if not isinstance(results, bool) or not results:
            config_error(config, results)

        # create contour files
        self.logger.debug('Uncertainty mapping...')

        # get the operator setting from config
        operator = config['products']['mapping']['operator']

        # get all of the pieces needed for the uncertainty mapping functions
        layers = config['products']['mapping']['layers']
        if 'countries' in layers and layers['countries'] != '':
            countries_file = layers['countries']
        else:
            countries_file = None
        if 'states_provs' in layers and layers['states_provs'] != '':
            states_provs_file = layers['states_provs']
        else:
            states_provs_file = None
        if 'oceans' in layers and layers['oceans'] != '':
            oceans_file = layers['oceans']
        else:
            oceans_file = None
        if 'lakes' in layers and layers['lakes'] != '':
            lakes_file = layers['lakes']
        else:
            lakes_file = None

        # Get the number of parallel workers
        max_workers = config['products']['mapping']['max_workers']

        # Reading HDF5 files currently takes a long time, due to poor
        # programming in MapIO.  To save us some time until that issue is
        # resolved, we'll coarsely subset the topo grid once here and pass
        # it into both mapping functions
        # get the bounds of the map
        info = container.getMetadata()
        xmin = info['output']['map_information']['min']['longitude']
        xmax = info['output']['map_information']['max']['longitude']
        ymin = info['output']['map_information']['min']['latitude']
        ymax = info['output']['map_information']['max']['latitude']
        dy = float(
            info['output']['map_information']['grid_spacing']['latitude'])
        dx = float(
            info['output']['map_information']['grid_spacing']['longitude'])
        padx = 5 * dx
        pady = 5 * dy
        sxmin = float(xmin) - padx
        sxmax = float(xmax) + padx
        symin = float(ymin) - pady
        symax = float(ymax) + pady

        sampledict = GeoDict.createDictFromBox(sxmin, sxmax, symin, symax, dx,
                                               dy)
        tdata = np.full([sampledict.ny, sampledict.nx], 0.0)
        topogrid = Grid2D(data=tdata, geodict=sampledict)

        model_config = container.getConfig()

        imtlist = container.getIMTs()

        textfile = os.path.join(
            get_data_path(), 'mapping',
            'map_strings.' + config['products']['mapping']['language'])
        text_dict = get_text_strings(textfile)
        if config['products']['mapping']['fontfamily'] != '':
            matplotlib.rcParams['font.family'] = \
                config['products']['mapping']['fontfamily']
            matplotlib.rcParams['axes.unicode_minus'] = False

        allcities = Cities.fromDefault()
        states_provs = None
        countries = None
        oceans = None
        lakes = None
        faults = None
        roads = None
        if states_provs_file is not None:
            states_provs = ShapelyFeature(
                Reader(states_provs_file).geometries(),
                ccrs.PlateCarree(),
                facecolor='none')
        elif 'CALLED_FROM_PYTEST' not in os.environ:
            states_provs = cfeature.NaturalEarthFeature(
                category='cultural',
                name='admin_1_states_provinces_lines',
                scale='10m',
                facecolor='none')
            # The feature constructor doesn't necessarily download the
            # data, but we want it to so that multiple threads don't
            # try to do it at once when they actually access the data.
            # So below we just call the geometries() method to trigger
            # the download if necessary.
            _ = states_provs.geometries()

        if countries_file is not None:
            countries = ShapelyFeature(Reader(countries_file).geometries(),
                                       ccrs.PlateCarree(),
                                       facecolor='none')
        elif 'CALLED_FROM_PYTEST' not in os.environ:
            countries = cfeature.NaturalEarthFeature(category='cultural',
                                                     name='admin_0_countries',
                                                     scale='10m',
                                                     facecolor='none')
            _ = countries.geometries()

        if oceans_file is not None:
            oceans = ShapelyFeature(Reader(oceans_file).geometries(),
                                    ccrs.PlateCarree(),
                                    facecolor=WATERCOLOR)
        elif 'CALLED_FROM_PYTEST' not in os.environ:
            oceans = cfeature.NaturalEarthFeature(category='physical',
                                                  name='ocean',
                                                  scale='10m',
                                                  facecolor=WATERCOLOR)
            _ = oceans.geometries()

        if lakes_file is not None:
            lakes = ShapelyFeature(Reader(lakes_file).geometries(),
                                   ccrs.PlateCarree(),
                                   facecolor=WATERCOLOR)
        elif 'CALLED_FROM_PYTEST' not in os.environ:
            lakes = cfeature.NaturalEarthFeature(category='physical',
                                                 name='lakes',
                                                 scale='10m',
                                                 facecolor=WATERCOLOR)
            _ = lakes.geometries()

        alist = []
        llogo = config['products']['mapping'].get('license_logo') or None
        ltext = config['products']['mapping'].get('license_text') or None
        for imtype in imtlist:
            component, imtype = imtype.split('/')
            comp = container.getComponents(imtype)[0]
            d = {
                'imtype': imtype,
                'topogrid': topogrid,
                'allcities': allcities,
                'states_provinces': states_provs,
                'countries': countries,
                'oceans': oceans,
                'lakes': lakes,
                'roads': roads,
                'roadcolor': layers['roadcolor'],
                'roadwidth': layers['roadwidth'],
                'faults': faults,
                'faultcolor': layers['faultcolor'],
                'faultwidth': layers['faultwidth'],
                'datadir': datadir,
                'operator': operator,
                'filter_size': 0,
                'info': info,
                'component': comp,
                'imtdict': container.getIMTGrids(imtype, comp),
                'ruptdict': copy.deepcopy(container.getRuptureDict()),
                'stationdict': container.getStationDict(),
                'config': model_config,
                'tdict': text_dict,
                'display_magnitude': self.display_magnitude,
                'pdf_dpi': config['products']['mapping']['pdf_dpi'],
                'img_dpi': config['products']['mapping']['img_dpi'],
                'license_logo': llogo,
                'license_text': ltext,
            }
            alist.append(d)

            #
            # Populate the contents.xml
            #
            for key in ('std', 'phi', 'tau'):
                if key not in d['imtdict'] or d['imtdict'][key] is None:
                    continue

                if key == 'std':
                    ext = '_sigma'
                    utype = ' Total'
                elif key == 'phi':
                    ext = '_phi'
                    utype = ' Within-event'
                else:
                    ext = '_tau'
                    utype = ' Between-event'

                if imtype == 'MMI':
                    fileimt = 'intensity'
                else:
                    fileimt = oq_to_file(imtype)

                self.contents.addFile(
                    fileimt + ext + 'UncertaintyMap',
                    fileimt.upper() + utype + ' Uncertainty Map',
                    'Map of ' + imtype + utype + ' uncertainty.',
                    fileimt + ext + '.jpg', 'image/jpeg')
                self.contents.addFile(
                    fileimt + ext + 'UncertaintyMap',
                    fileimt.upper() + utype + ' Uncertainty Map',
                    'Map of ' + imtype + utype + ' uncertainty.',
                    fileimt + ext + '.pdf', 'application/pdf')

        if max_workers > 0:
            with cf.ProcessPoolExecutor(max_workers=max_workers) as ex:
                results = ex.map(make_map, alist)
                list(results)
        else:
            for adict in alist:
                make_map(adict)

        container.close()
Exemplo n.º 27
0
        'label': r'$CH_4$ (ppbV)',
    },
    'customize_once': [
#        # add recetptor box
#        lambda p: p.ax.add_geometries(
#            [Polygon([_ for _ in receptor_corners])],  # four corners into polygon
#            crs = ccrs.PlateCarree(),  # projection is unprojected ("PlateCarre")
#            facecolor='none', edgecolor='black', lw=.6,  # plot styles
#            ),
        # add softlaunch box
        # ridiculously complicated...
        lambda p: p.ax.add_feature(
            ShapelyFeature(
                shp_soft.geometries(),
                crs=ccrs.PlateCarree(),
            facecolor='none', 
            #edgecolor='black', 
            edgecolor='#BDEDFC',
            lw=.6,  # plot styles
            )),

    ]}

# make a plot template
p = plotter_solo.Plotter(array=arr, tstamps=tstamps, 
                         x=x, y=y, z=z, projection=LambertConformalHRRR(),
                         plotter_options=plotter_options)

# want to load the extra stuff, incl background
# dont know why ipdate dowsnt work....

p.savefig('wish_me_luck.png', tidx=60)
def makeCatPlots():  #makes day 1-3 convective outlooks
    cat = catfiles()  #list of files
    SPCimagefiles = []  #list of image files
    valid = []  #valid time
    expire = []  #expire time

    for i in range(len(cat)):
        plt.figure()
        xmin = -120
        xmax = -70
        ymin = 20
        ymax = 55
        ax = plt.axes(projection=crs.LambertConformal())
        ax.add_feature(cfeature.OCEAN, edgecolor='gray', linewidth=1.5)
        ax.add_feature(cfeature.LAKES)
        ax.add_feature(
            ShapelyFeature(Reader(
                "ne_50m_admin_1_states_provinces_lakes.shp").geometries(),
                           crs.PlateCarree(),
                           facecolor='w',
                           edgecolor='gray',
                           linewidth=1.5))
        ax.set_extent([xmin, xmax, ymin, ymax])

        shpfile = cat[i]  #plotted shapefile
        dn = Reader(shpfile).records()

        for j in dn:
            if j.attributes['VALID'] not in valid:
                valid.append(j.attributes['VALID'])
            if j.attributes['EXPIRE'] not in expire:
                expire.append(j.attributes['EXPIRE'])
            #plots each category
            if j.attributes['DN'] == 2:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='lightgreen',
                                  alpha=.75)
            elif j.attributes['DN'] == 3:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='green',
                                  alpha=.75)
            elif j.attributes['DN'] == 4:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='yellow',
                                  alpha=.75)
            elif j.attributes['DN'] == 5:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='orange',
                                  alpha=.75)
            elif j.attributes['DN'] == 6:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='red',
                                  alpha=.75)
            elif j.attributes['DN'] == 7:
                ax.add_geometries(j.geometry,
                                  crs.LambertConformal(central_longitude=0.0,
                                                       central_latitude=0.0),
                                  facecolor='fuchsia',
                                  alpha=.75)
        #start of text for blurb at bottom
        start = valid[i]
        validyear = start[0:4]
        validmonth = start[4:6]
        validday = start[6:8]
        validhour = start[8:12]

        end = expire[i]
        expireyear = end[0:4]
        expiremonth = end[4:6]
        expireday = end[6:8]
        expirehour = end[8:12]

        plt.title('SPC Convective Outlook: Day ' + str(i + 1))
        filename = 'SPCDay' + str(i + 1) + '.png'
        ax.yaxis.set_visible(False)
        ax.xaxis.set_visible(False)
        #makes key
        tstm = mpatches.Patch(color='lightgreen', label='TSTM')
        mrgl = mpatches.Patch(color='green', label='MRGL')
        slgt = mpatches.Patch(color='yellow', label='SLGT')
        enh = mpatches.Patch(color='orange', label='ENH')
        mdt = mpatches.Patch(color='red', label='MDT')
        high = mpatches.Patch(color='fuchsia', label='HIGH')

        plt.legend(handles=[tstm, mrgl, slgt, enh, mdt, high],
                   loc='lower right',
                   fontsize='8')
        text = 'Valid: ' + validmonth + '/' + validday + '/' + validyear + ' ' + validhour + 'Z - ' + expiremonth + '/' + expireday + '/' + expireyear + ' ' + expirehour + 'Z\nData from NWS/NOAA Storm Prediction Center (www.spc.noaa.gov)\nFind discussions about these categories on the SPC website.'
        ax.text(0.01,
                0.01,
                text,
                verticalalignment='bottom',
                horizontalalignment='left',
                transform=ax.transAxes,
                fontsize='8',
                bbox=dict(facecolor='white', alpha=0.75))
        plt.savefig(filename, bbox_inches='tight')
        SPCimagefiles.append(filename)
        plt.close()
        ### end of categorical convective outlooks
    print "Successfully made the following maps: "
    print SPCimagefiles
Exemplo n.º 29
0
    def execute(self):
        """
        Raises:
            NotADirectoryError: When the event data directory does not exist.
            FileNotFoundError: When the the shake_result HDF file does not
                exist.
        """
        install_path, data_path = get_config_paths()
        datadir = os.path.join(data_path, self._eventid, 'current', 'products')
        if not os.path.isdir(datadir):
            raise NotADirectoryError('%s is not a valid directory.' % datadir)
        datafile = os.path.join(datadir, 'shake_result.hdf')
        if not os.path.isfile(datafile):
            raise FileNotFoundError('%s does not exist.' % datafile)

        # Open the ShakeMapOutputContainer and extract the data
        container = ShakeMapOutputContainer.load(datafile)
        if container.getDataType() != 'grid':
            raise NotImplementedError('mapping module can only operate on '
                                      'gridded data, not sets of points')

        # get the path to the products.conf file, load the config
        config_file = os.path.join(install_path, 'config', 'products.conf')
        spec_file = get_configspec('products')
        validator = get_custom_validator()
        config = ConfigObj(config_file, configspec=spec_file)
        results = config.validate(validator)
        check_extra_values(config, self.logger)
        if not isinstance(results, bool) or not results:
            config_error(config, results)

        # create contour files
        self.logger.debug('Mapping...')

        # get the filter size from the products.conf
        filter_size = config['products']['contour']['filter_size']

        # get the operator setting from config
        operator = config['products']['mapping']['operator']

        # get all of the pieces needed for the mapping functions
        layers = config['products']['mapping']['layers']
        if 'topography' in layers and layers['topography'] != '':
            topofile = layers['topography']
        else:
            topofile = None
        if 'roads' in layers and layers['roads'] != '':
            roadfile = layers['roads']
        else:
            roadfile = None
        if 'faults' in layers and layers['faults'] != '':
            faultfile = layers['faults']
        else:
            faultfile = None

        # Get the number of parallel workers
        max_workers = config['products']['mapping']['max_workers']

        # Reading HDF5 files currently takes a long time, due to poor
        # programming in MapIO.  To save us some time until that issue is
        # resolved, we'll coarsely subset the topo grid once here and pass
        # it into both mapping functions
        # get the bounds of the map
        info = container.getMetadata()
        xmin = info['output']['map_information']['min']['longitude']
        xmax = info['output']['map_information']['max']['longitude']
        ymin = info['output']['map_information']['min']['latitude']
        ymax = info['output']['map_information']['max']['latitude']
        dy = float(info['output']['map_information']
                   ['grid_spacing']['latitude'])
        dx = float(info['output']['map_information']
                   ['grid_spacing']['longitude'])
        padx = 5 * dx
        pady = 5 * dy
        sxmin = float(xmin) - padx
        sxmax = float(xmax) + padx
        symin = float(ymin) - pady
        symax = float(ymax) + pady

        sampledict = GeoDict.createDictFromBox(sxmin, sxmax,
                                               symin, symax,
                                               dx, dy)
        if topofile:
            topogrid = read(topofile,
                            samplegeodict=sampledict,
                            resample=False)
        else:
            tdata = np.full([sampledict.ny, sampledict.nx], 0.0)
            topogrid = Grid2D(data=tdata, geodict=sampledict)

        model_config = container.getConfig()

        imtlist = container.getIMTs()

        textfile = os.path.join(get_data_path(), 'mapping',
                                'map_strings.' +
                                config['products']['mapping']['language'])
        text_dict = get_text_strings(textfile)
        if config['products']['mapping']['fontfamily'] != '':
            matplotlib.rcParams['font.family'] = \
                config['products']['mapping']['fontfamily']
            matplotlib.rcParams['axes.unicode_minus'] = False

        allcities = Cities.fromDefault()
        states_provs = None
        countries = None
        oceans = None
        lakes = None
        extent = (float(xmin), float(ymin), float(xmax), float(ymax))
        if 'CALLED_FROM_PYTEST' not in os.environ:
            states_provs = cfeature.NaturalEarthFeature(
                category='cultural',
                name='admin_1_states_provinces_lines',
                scale='10m',
                facecolor='none')

            countries = cfeature.NaturalEarthFeature(
                category='cultural',
                name='admin_0_countries',
                scale='10m',
                facecolor='none')

            oceans = cfeature.NaturalEarthFeature(
                category='physical',
                name='ocean',
                scale='10m',
                facecolor=WATERCOLOR)

            lakes = cfeature.NaturalEarthFeature(
                category='physical',
                name='lakes',
                scale='10m',
                facecolor=WATERCOLOR)

        if faultfile is not None:
            faults = ShapelyFeature(Reader(faultfile).geometries(),
                                    ccrs.PlateCarree(), facecolor='none')
        else:
            faults = None

        if roadfile is not None:
            roads = ShapelyFeature(Reader(roadfile).geometries(),
                                   ccrs.PlateCarree(), facecolor='none')
        else:
            roads = None

        alist = []
        for imtype in imtlist:
            component, imtype = imtype.split('/')
            comp = container.getComponents(imtype)[0]
            d = {'imtype': imtype,
                 'topogrid': topogrid,
                 'allcities': allcities,
                 'states_provinces': states_provs,
                 'countries': countries,
                 'oceans': oceans,
                 'lakes': lakes,
                 'roads': roads,
                 'faults': faults,
                 'datadir': datadir,
                 'operator': operator,
                 'filter_size': filter_size,
                 'info': info,
                 'component': comp,
                 'imtdict': container.getIMTGrids(imtype, comp),
                 'ruptdict': copy.deepcopy(container.getRuptureDict()),
                 'stationdict': container.getStationDict(),
                 'config': model_config,
                 'tdict': text_dict,
                 'display_magnitude': self.display_magnitude,
                 }
            alist.append(d)
            if imtype == 'MMI':
                g = copy.deepcopy(d)
                g['imtype'] = 'thumbnail'
                alist.append(g)
                h = copy.deepcopy(d)
                h['imtype'] = 'overlay'
                alist.append(h)
                self.contents.addFile('intensityMap', 'Intensity Map',
                                      'Map of macroseismic intensity.',
                                      'intensity.jpg', 'image/jpeg')
                self.contents.addFile('intensityMap', 'Intensity Map',
                                      'Map of macroseismic intensity.',
                                      'intensity.pdf', 'application/pdf')
                self.contents.addFile('intensityThumbnail',
                                      'Intensity Thumbnail',
                                      'Thumbnail of intensity map.',
                                      'pin-thumbnail.png', 'image/png')
                self.contents.addFile('intensityOverlay',
                                      'Intensity Overlay and World File',
                                      'Macroseismic intensity rendered as a '
                                      'PNG overlay and associated world file',
                                      'intensity_overlay.png', 'image/png')
                self.contents.addFile('intensityOverlay',
                                      'Intensity Overlay and World File',
                                      'Macroseismic intensity rendered as a '
                                      'PNG overlay and associated world file',
                                      'intensity_overlay.pngw', 'text/plain')
            else:
                fileimt = oq_to_file(imtype)
                self.contents.addFile(fileimt + 'Map',
                                      fileimt.upper() + ' Map',
                                      'Map of ' + imtype + '.',
                                      fileimt + '.jpg', 'image/jpeg')
                self.contents.addFile(fileimt + 'Map',
                                      fileimt.upper() + ' Map',
                                      'Map of ' + imtype + '.',
                                      fileimt + '.pdf', 'application/pdf')

        if max_workers > 0:
            with cf.ProcessPoolExecutor(max_workers=max_workers) as ex:
                results = ex.map(make_map, alist)
                list(results)
        else:
            for adict in alist:
                make_map(adict)

        container.close()
Exemplo n.º 30
0
file_out = 'map_%s.png' % main_var

# Load CSV file into DataFrame
df = pd.read_csv(file_in)

# Prepare map
plt.figure(figsize=(10, 8))
ax = plt.axes(projection=ccrs.PlateCarree())
lon_formatter = LongitudeFormatter(number_format='.1f', degree_symbol='',\
 dateline_direction_label=True)
lat_formatter = LatitudeFormatter(number_format='.1f', degree_symbol='')
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)

# Add feature - political contours
shape_feature = ShapelyFeature(shpreader.Reader(feat_file).geometries(),\
 ccrs.PlateCarree(), facecolor='none', edgecolor='k', linewidth=0.5)
ax.add_feature(shape_feature)

# Plot stations names
for index, row in df.iterrows():
    plt.text(row['lon'], row['lat'], row['id'])

# Add info from DataFrame
normalize = colors.Normalize(vmin=min(df[main_var]), vmax=max(df[main_var]))
cs = ax.scatter(df['lon'].values, df['lat'].values,\
 c=df[main_var].values, cmap=plt.get_cmap('jet'),\
 transform=ccrs.PlateCarree(), marker='o', s=40)

# Add a colorbar
cax, _ = colorbar.make_axes(ax)
cbar = colorbar.ColorbarBase(cax, cmap=plt.get_cmap('jet'),\