コード例 #1
0
def lu_subplot(var, pos, res, title, hgt, par=True, mer=True):
    ax = plt.subplot(pos)
    ax.set_title(title, fontsize=10)
    # Get the basemap object
    bm = get_basemap(var, projection='lcc', resolution=res, ax=ax)
    # Convert the lats and lons to x and y.  Make sure you convert the lats and lons to
    # numpy arrays via to_np, or basemap crashes with an undefined RuntimeError.
    x, y = bm(to_np(lons), to_np(lats))
    # Define gridlines
    parallels = np.arange(-90,90,0.2)
    meridians = np.arange(0,360,0.2)
    # Add geographic outlines
    if par == True:
        bm.drawparallels(parallels,labels=[1,0,0,0],fontsize=8)
    else:
        bm.drawparallels(parallels,fontsize=8)
    if mer == True:
        bm.drawmeridians(meridians,labels=[0,0,0,1],fontsize=8)
    else:
        bm.drawmeridians(meridians,fontsize=8)
    bm.drawrivers(linewidth=0.75,color='blue') #only for high resolution plots
    bm.readshapefile('/home/kristofh/projects/shp_files/BEZIRKSGRENZEOGDPolygon', 'BEZIRKSGRENZEOGDPolygon', linewidth=0.6)
    
    
    heights = np.arange(100, 800, 50)
    categ = np.arange(1,34, 1)
    
    # Draw the contours and filled contours
    hgt_cont = bm.contour(x,y,to_np(hgt), levels=heights, colors="magenta", linewidths=0.4, alpha=1)
    var_contf = bm.pcolormesh(x,y,to_np(var), cmap=get_cmap("viridis"), alpha=0.9)
    cb_var = fig.colorbar(var_contf, ticks=categ[::3], ax=ax, shrink=0.7)
    cb_var.ax.tick_params(labelsize=8)
    return
コード例 #2
0
def allmodelrunpercent(directories, hubheight):

    #got the total points working. need to figure out if it is the right number
    #
    totalcount = 0
    totalpercentup = np.zeros((19, 29))
    for directory in directories:
        os.chdir(directory)
        files = gatherfiles('wrfout*')
        for file in files:
            ncfile = Dataset(file)
            windmatrix = verticalwindinterpolation(ncfile, hubheight)
            for i in range(0, len(totalpercentup)):
                for k in range(0, len(totalpercentup[0])):
                    if (windmatrix[i, k] > 3.0) and (windmatrix[i, k] < 22.0):
                        totalpercentup[i, k] = totalpercentup[i, k] + 1
            totalcount += 1
    press = getvar(ncfile, 'pressure')  #hPa
    pressground = press[0, :, :]
    bm = get_basemap(pressground)
    fig = plt.figure(figsize=(12, 9))
    lat, lon = latlon_coords(pressground)
    x, y = bm(to_np(lon), to_np(lat))
    bm.drawcoastlines(linewidth=0.25)
    bm.drawstates(linewidth=0.25)
    bm.drawcountries(linewidth=0.25)
    bm.contourf(x,
                y,
                to_np((totalpercentup / totalcount) * 100),
                cmap=get_cmap('jet'))
    plt.colorbar(shrink=.62)
    plt.title('Percent in threshold for ALL model runs')
    os.chdir('/Users/twsee/Desktop/renewableoutput/')
    plt.savefig('Percent in threshold for ALL model runs quick fix')
    plt.close()
コード例 #3
0
def var_diff_subplot(var, pos, res, title, tmin, trange,  cmap=blrd, levels=levels, steps=0.25, par=True, mer=True):
    ax = plt.subplot(pos)
    ax.set_title(title, fontsize=16)
    # Get the basemap object
    bm = get_basemap(var, projection='lcc', resolution=res, ax=ax)
    # Convert the lats and lons to x and y.  Make sure you convert the lats and lons to
    # numpy arrays via to_np, or basemap crashes with an undefined RuntimeError.
    x, y = bm(to_np(lons), to_np(lats))
    # Define gridlines
    parallels = np.arange(-90,90,0.2)
    meridians = np.arange(0,360,0.2)
    # Add geographic outlines
    if par == True:
        bm.drawparallels(parallels,labels=[1,0,0,0],fontsize=12)
    else:
        bm.drawparallels(parallels,fontsize=12)
    if mer == True:
        bm.drawmeridians(meridians,labels=[0,0,0,1],fontsize=12)
    else:
        bm.drawmeridians(meridians,fontsize=12)
#    bm.drawrivers(linewidth=0.75,color='blue') #only for high resolution plots
    bm.readshapefile('/home/kristofh/projects/shp_files/BEZIRKSGRENZEOGDPolygon', 'BEZIRKSGRENZEOGDPolygon', linewidth=0.6)
    
#    levels=np.arange(tmin, tmin+trange+steps, steps)
#    heights = np.arange(100, 800, 50)

    # Draw the contours and filled contours
#    hgt_cont = bm.contour(x,y,to_np(hgt), levels=heights, colors="magenta", linewidths=0.4, alpha=1)
    var_cont = bm.contour(x,y,to_np(var), colors="black", levels=levels, linewidths=0.4, alpha=0.5)
    var_contf = bm.contourf(x,y,to_np(var), levels=levels, colors=cmap, extend='both', alpha=0.9)
    cb_var = fig.colorbar(var_contf, ax=ax, ticks=levels, shrink=1.)
    cb_var.ax.tick_params(labelsize=8)
    return
コード例 #4
0
def averagewindspeed(directories, hubheight):
    total = 0
    count = 0
    for directory in directories:
        os.chdir(directory)
        files = gatherfiles('wrfout*')
        for file in files:
            ncfile = Dataset(file)
            windmatrix = verticalwindinterpolation(ncfile, hubheight)
            total = windmatrix + total
            count += 1
    average = total / count
    press = getvar(ncfile, 'pressure')  #hPa
    pressground = press[0, :, :]
    bm = get_basemap(pressground)
    fig = plt.figure(figsize=(12, 9))
    lat, lon = latlon_coords(pressground)
    x, y = bm(to_np(lon), to_np(lat))
    bm.drawcoastlines(linewidth=0.25)
    bm.drawstates(linewidth=0.25)
    bm.drawcountries(linewidth=0.25)
    bm.contourf(x, y, to_np(average), cmap=get_cmap('jet'))
    plt.colorbar(shrink=.62)
    plt.title('Average Wind Speed at ' + str(hubheight) +
              'm across all model runs')
    os.chdir('/Users/twsee/Desktop/renewableoutput/')
    plt.savefig('Average Wind Speed across all runs')
    plt.close()
コード例 #5
0
def var_subplot(var, pos, res, title, hgt, par=True, mer=True):
    ax = plt.subplot(pos)
    ax.set_title(title, fontsize=10)
    # Get the basemap object
    bm = get_basemap(var, projection='lcc', resolution=res, ax=ax)
    # Convert the lats and lons to x and y.  Make sure you convert the lats and lons to
    # numpy arrays via to_np, or basemap crashes with an undefined RuntimeError.
    x, y = bm(to_np(lons), to_np(lats))
    # Define gridlines
    parallels = np.arange(-90,90,0.2)
    meridians = np.arange(0,360,0.2)
    # Add geographic outlines
    if par == True:
        bm.drawparallels(parallels,labels=[1,0,0,0],fontsize=8)
    else:
        bm.drawparallels(parallels,fontsize=8)
    if mer == True:
        bm.drawmeridians(meridians,labels=[0,0,0,1],fontsize=8)
    else:
        bm.drawmeridians(meridians,fontsize=8)
    bm.drawrivers(linewidth=0.75,color='blue') #only for high resolution plots
    bm.readshapefile('/home/kristofh/projects/shp_files/BEZIRKSGRENZEOGDPolygon', 'BEZIRKSGRENZEOGDPolygon', linewidth=0.6)
    
#    levels=np.arange(-1.0, 1.0+steps, steps)
#    levels=np.insert(levels,0, np.arange((maxdiff_spr.min()*10).round()/10,-1,steps*6))
#    levels=np.append(levels, np.arange(1,(maxdiff_spr.max()*10).round()/10,steps*6))
#    
#    contour_levels=np.arange(-1.0, 1.0+steps, steps*2)
#    contour_levels=np.insert(contour_levels,0, (var.min()*10).round()/10)
#    contour_levels=np.append(contour_levels, (var.max()*10).round()/10)
    
    heights = np.arange(100, 800, 75)

    # Draw the contours and filled contours
    hgt_cont = bm.contour(x,y,to_np(hgt), levels=heights, colors="magenta", linewidths=0.4, alpha=1)
    var_cont = bm.contour(x,y,to_np(var), colors="black", linewidths=0.4, alpha=0.5)
    var_contf = bm.contourf(x,y,to_np(var), cmap=get_cmap("RdBu_r"), extend='both', alpha=0.9)
    cb_var = fig.colorbar(var_contf, ax=ax, shrink=0.4)
    cb_var.ax.tick_params(labelsize=8)
    return
コード例 #6
0
def percentinthreshold(files, hubheight):
    totalcount = 0
    dailycount = 0
    date, hour = gettimeanddates(files[0])
    totalpercentup = np.zeros((19, 29))
    dailypercentup = np.zeros((19, 29))
    for file in files:
        ncfile = Dataset(file)
        windmatrix = verticalwindinterpolation(ncfile, hubheight)
        for i in range(0, len(dailypercentup)):
            for k in range(0, len(dailypercentup[0])):
                if (windmatrix[i, k] > 3.0) and (windmatrix[i, k] < 22.0):
                    dailypercentup[i, k] = dailypercentup[i, k] + 1
                    totalpercentup[i, k] = totalpercentup[i, k] + 1
        if dailycount == 23:
            dailycount = 0
            dailypercentup = np.zeros((19, 29))
            totalcount += 1
        else:
            dailycount += 1
            totalcount += 1
    press = getvar(ncfile, 'pressure')  #hPa
    pressground = press[0, :, :]
    bm = get_basemap(pressground)
    fig = plt.figure(figsize=(12, 9))
    lat, lon = latlon_coords(pressground)
    x, y = bm(to_np(lon), to_np(lat))
    bm.drawcoastlines(linewidth=0.25)
    bm.drawstates(linewidth=0.25)
    bm.drawcountries(linewidth=0.25)
    bm.contourf(x,
                y,
                to_np((totalpercentup / totalcount) * 100),
                cmap=get_cmap('jet'))
    plt.colorbar(shrink=.62)
    plt.title('Energy Production Percentage for ' + date + ' Model Run')
    plt.savefig('Energy-Production-Percentage-for-' + date + '-Model-Run')
    plt.close()
コード例 #7
0
def drawmap(ax,wrf_file,map_dir,Lat_min,Lat_max,Lon_min,Lon_max):
    m = get_basemap(wrfin=wrf_file,llcrnrlat=Lat_min,urcrnrlat=Lat_max,\
    llcrnrlon=Lon_min,urcrnrlon=Lon_max,resolution ='l',ax=ax)
    CHNshp = map_dir+'CHN_adm_shp/CHN_adm1'
    TWNshp = map_dir+'TWN_adm_shp/TWN_adm0'
    m.readshapefile(CHNshp,'CHN',drawbounds = True)
    m.readshapefile(TWNshp,'TWN',drawbounds = True)

    parallels = np.arange(-90.,91.,1.)
    meridians = np.arange(-180.,181.,2.)
    m.drawparallels(parallels,labels=[1,0,0,1],linewidth=0.2,xoffset=0.2,fontsize=12,fontname='Arial')
    m.drawmeridians(meridians,labels=[1,0,0,1],linewidth=0.2,yoffset=0.2,fontsize=12,fontname='Arial')

    xminor_ticks = np.arange(Lon_min,Lon_max,1)
    yminor_ticks = np.arange(Lat_min,Lat_max, 1)
    ax.set_xticks(xminor_ticks, minor=True)
    ax.set_yticks(yminor_ticks, minor=True)

    for info, shape in zip(m.CHN_info, m.CHN):
        if info['NAME_1'] =='Guangdong':
            x, y = zip(*shape)
            m.plot(x, y, marker = None, color= 'k',linewidth=1.5)

    return m
コード例 #8
0
def energyproductioninterpolated(files, hubheight):
    """
    Creates hourly and daily energy production outputs for wind a turbine
    output plots interpolated from the surface to hub height

    Parameters
    ----------
    arg1: list
        A 1D glob list of the file outputs from WRF
    arg2: integer
        level of the wind turbine hub height 

    Returns
    -------
    None
    """
    count = 0
    dailyenergy = 0
    for file in files:
        date, hour = gettimeanddates(file)
        ncfile = Dataset(file)
        cbarticks = np.arange(0.0, 10.0, 0.5)
        r = 52.0  #meters, rotorlength
        Area = np.pi * r**2
        cp = 0.4  #unitless
        density = 1.23  #kg/m^3
        press = getvar(ncfile, 'pressure')  #hPa
        pressground = press[0, :, :]
        bm = get_basemap(pressground)
        fig = plt.figure(figsize=(12, 9))
        energyproduction = (
            0.5 * density * Area *
            verticalwindinterpolationenergy(ncfile, hubheight)**3 * cp) / 10**6
        lat, lon = latlon_coords(pressground)
        x, y = bm(to_np(lon), to_np(lat))
        bm.drawcoastlines(linewidth=0.25)
        bm.drawstates(linewidth=0.25)
        bm.drawcountries(linewidth=0.25)
        bm.contour(x,
                   y,
                   to_np(energyproduction),
                   cbarticks,
                   colors="black",
                   vmin=0,
                   vmax=10.0)
        bm.contourf(x,
                    y,
                    to_np(energyproduction),
                    cbarticks,
                    cmap=get_cmap('jet'),
                    vmin=0,
                    vmax=10.0)
        bm.barbs(x, y, uaground, vaground)
        plt.colorbar(shrink=.62, ticks=cbarticks)
        plt.title('Hourly Energy Production for ' + date + ' ' + hour +
                  '-Interpolated-to-' + str(hubheight) + 'm')
        plt.savefig('Hourly-output-' + date + '-' + hour +
                    '-Interpolated-to-' + str(hubheight) + 'm')
        plt.close()
        if count == 23:
            bm = get_basemap(pressground)
            fig = plt.figure(figsize=(12, 9))
            lat, lon = latlon_coords(pressground)
            x, y = bm(to_np(lon), to_np(lat))
            bm.drawcoastlines(linewidth=0.25)
            bm.drawstates(linewidth=0.25)
            bm.drawcountries(linewidth=0.25)
            dailyenergy = dailyenergy / 24.0
            bm.contour(x,
                       y,
                       to_np(dailyenergy),
                       cbarticks,
                       colors="black",
                       vmin=0,
                       vmax=10.0)
            bm.contourf(x,
                        y,
                        to_np(dailyenergy),
                        cbarticks,
                        cmap=get_cmap('jet'),
                        vmin=0,
                        vmax=10.0)
            plt.colorbar(shrink=.62, ticks=cbarticks)
            plt.title('Dialy Average ' + yesterdaysdate + '-Interpolated-to-' +
                      str(hubheight) + 'm')
            plt.savefig('Daily-Average-' + yesterdaysdate +
                        '-Interpolated-to-' + str(hubheight) + 'm')
            plt.show()
            plt.close()
            dailyenergy = 0
            count = 0
        else:
            dailyenergy = energyproduction + dailyenergy
            count = count + 1
        yesterdaysdate = date
コード例 #9
0
        
    plt.xticks(ind + width, stats_var)
    
    plt.legend(loc='best')
    plt.show()
    fig3.savefig(outputdir + '%s_bar_chart.png' %stat_name, bbox_inches='tight')
''' 
#######################################
##########     BIAS MAPS     ##########
#######################################

# Create 2D map with points representing stations 
# (larger points = greater bias, blue = negative bias, red = positive bias)

# Get the basemap object
bm = wrf.get_basemap(t_basemap)

x, y = bm(x_list, y_list)

# Get x, y coordinates for each of 6 stations (KSEA,KPUW,KPDX,KLMT,KBOI,KMLP)
xlist_few = [-122.309,-117.11]
ylist_few = [47.449,46.744]
x_few, y_few = bm(xlist_few,ylist_few)
label_few = ['KSEA','KPUW']

# Make array with all variable names (for each model) in "stats_all" data frame 
stat_var = np.unique(stats_all.index)

for sv in stat_var: 
    # Create a figure
    fig4 = plt.figure(figsize=(12,9))
コード例 #10
0
# pressure levels interpolation
######################################################################################################

# Extract the pressure, geopotential height, and wind variables
# p = getvar(ncfile, "pressure")
p = getvar(ncfile, "pressure")
LWC = getvar(ncfile, "QCLOUD")  #, meta=False)

# Interpolate geopotential height
LWC_750 = interplevel(LWC, p, 750)

# Get the lat/lon coordinates
lats, lons = latlon_coords(LWC_750)

# Get the basemap object
bm = get_basemap(LWC_750)

# Create the figure
fig = plt.figure(figsize=(12, 9))
ax = plt.axes()

# Convert the lat/lon coordinates to x/y coordinates in the projection space
x, y = bm(to_np(lons), to_np(lats))

# Add the 500 hPa geopotential height contours
lower_level = to_np(LWC_750).min().min()
upper_level = to_np(LWC_750).max().max()
levels = np.arange(lower_level, upper_level, (upper_level - lower_level) / 10)
contours = bm.contourf(x, y, to_np(LWC_750), levels=levels)
plt.clabel(contours, inline=1, fontsize=10, fmt="%i")
コード例 #11
0
ファイル: plot_area_allTimes.py プロジェクト: wasserblum/met
    
    #get vavriable from netCDF file
    var = getvar(ncfile, param, timeidx=idx)
    title = var.description
    title1 = var.name + ' [' + var.units + ']' + ' - ' + run 
    currtime = str(pd.to_datetime(time))
    var_mean = var.mean(dim={'south_north','west_east'})
    var_std = var.std(dim={'south_north','west_east'})
    # Smooth the sea level pressure since it tends to be noisy near the mountains
    # smooth_slp = smooth2d(slp, 3)
    
    # Get the latitude and longitude points
    lats, lons = latlon_coords(var)

    # Get the basemap object
    bm = get_basemap(var, resolution='h', projection='lcc')

    # Define gridlines
    parallels = np.arange(-90,90,0.2)
    meridians = np.arange(0,360,0.2)

    # Create a figure
    fig = plt.figure(idx, figsize=(12,9))

    # Add geographic outlines
    bm.drawcoastlines(linewidth=1)
    bm.drawstates(linewidth=1)
    bm.drawcountries(linewidth=1)
    bm.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
    bm.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)
    bm.drawrivers(linewidth=0.75,color='blue') #only for high resolution plots
コード例 #12
0
def plot_spatial_wrf_Tair_Wind(file_path,height,timeidx):

    ######################################################
    # Note that since I have updated Python, get_basemap cannot work 
    # for the new version. Thus the function cannot really work.
    ######################################################
    
    from wrf import get_basemap

    # Open the NetCDF file
    ncfile = Dataset(file_path)

    # Extract the pressure, geopotential height, and wind variables
    p = getvar(ncfile, "pressure",timeidx=timeidx)
    z = getvar(ncfile, "z", units="dm",timeidx=timeidx)
    ua = getvar(ncfile, "ua", units="kt",timeidx=timeidx)
    va = getvar(ncfile, "va", units="kt",timeidx=timeidx)
    wspd = getvar(ncfile, "wspd_wdir", units="kts",timeidx=timeidx)[0,:]

    # Interpolate geopotential height, u, and v winds to 500 hPa
    ht_hgt = interplevel(z, p, height)
    u_hgt = interplevel(ua, p, height)
    v_hgt = interplevel(va, p, height)
    wspd_hgt = interplevel(wspd, p, height)

    # Get the lat/lon coordinates
    lats, lons = latlon_coords(ht_hgt)

    # Get the basemap object
    bm = get_basemap(ht_hgt)

    # Create the figure
    fig = plt.figure(figsize=(12,9))
    ax = plt.axes()

    # Convert the lat/lon coordinates to x/y coordinates in the projection space
    x, y = bm(to_np(lons), to_np(lats))

    # Add the 500 hPa geopotential height contours
    levels = np.arange(520., 580., 6.)
    contours = bm.contour(x, y, to_np(ht_hgt), levels=levels, colors="black")
    plt.clabel(contours, inline=1, fontsize=10, fmt="%i")

    # Add the wind speed contours
    levels = [25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 110, 120]
    wspd_contours = bm.contourf(x, y, to_np(wspd_hgt), levels=levels,
                                cmap=get_cmap("rainbow"))
    plt.colorbar(wspd_contours, ax=ax, orientation="horizontal", pad=.05)

    # Add the geographic boundaries
    bm.drawcoastlines(linewidth=0.25)
    bm.drawstates(linewidth=0.25)
    bm.drawcountries(linewidth=0.25)

    # Add the 500 hPa wind barbs, only plotting every 125th data point.
    bm.barbs(x[::125,::125], y[::125,::125], to_np(u_hgt[::125, ::125]),
            to_np(v_hgt[::125, ::125]), length=6)

    plt.title("500 MB Height (dm), Wind Speed (kt), Barbs (kt)")

    plt.show()
コード例 #13
0
LWC = calculate_lwc_wrf(ncfile)
LWC_at_req_level = LWC[requested_level_index]

# The calculations below are for creating the map
p = getvar(ncfile, "pressure")
z = getvar(ncfile, "z", units="dm")

# Interpolate geopotential height
ht_for_map_creation = interplevel(z, p, requested_level)

# Get the lat/lon coordinates
lats, lons = latlon_coords(ht_for_map_creation)

# Get the basemap object
bm = get_basemap(ht_for_map_creation)

# Create the figure
fig = plt.figure(figsize=(12,9))
ax = plt.axes()

# Convert the lat/lon coordinates to x/y coordinates in the projection space
x, y = bm(to_np(lons), to_np(lats))

# Add the geographic boundaries
bm.drawcoastlines(linewidth=0.25)
bm.drawstates(linewidth=0.25)
bm.drawcountries(linewidth=0.25)

plt.title( str(requested_level) + "hPa LWC")
コード例 #14
0
# Open the NetCDF file
ncfile = Dataset("%s/%s/wrfout_d01_%s" %
                 (options.exp, options.dir, options.datetime))

# Get the WRF variables
dbz = getvar(ncfile, _variable)

# Get the latitude and longitude points
lats, lons = latlon_coords(dbz)

# Create the figure that will have 3 subplots
fig = plt.figure(figsize=(10, 7))
ax_dbz = fig.add_subplot(1, 1, 1)

# Get the basemap object
bm = get_basemap(dbz)

# Convert the lat/lon points in to x/y points in the projection space
x, y = bm(to_np(lons), to_np(lats))

# Make the contour plot for dbz
contour_levels = [25, 45]
c1 = bm.contour(x,
                y,
                to_np(dbz),
                levels=contour_levels,
                colors="black",
                zorder=3,
                linewidths=1.0,
                ax=ax_dbz)
コード例 #15
0
try:
    ncfile = Dataset(os.path.join(options.dir, "wrfinput_d01_ic"))
    suffix = os.path.split(options.dir)[-1]
except:
    print("\n NOPE --- cannot find a wrf netcdf file..... %s" %
          os.path.join(options.dir, "wrfinput_d01_ic"))
    sys.exit(-1)

# Get the WRF variables
var = getvar(ncfile, _variable)[0]

# Get the latitude and longitude points
lats, lons = latlon_coords(var)

# Get the basemap object
bm = get_basemap(var)

# Convert the lat/lon points in to x/y points in the projection space
x, y = bm(to_np(lons), to_np(lats))

# Make the contour plot for var, mask off min values

mask_var = np.ma.masked_less_equal(to_np(var), _var_min)
# If Clip,
if _clip_variable:
    mask_var = np.clip(mask_var, _clevels.min(), _clevels.max())

c1_contour = bm.contour(x,
                        y,
                        mask_var,
                        levels=_llevels,
コード例 #16
0
# Open the NetCDF file
ncfile = Dataset("wrfout_d01_2019-01-26_12_00_00")

# Get the sea level pressure
slp = getvar(ncfile, "slp")

# Smooth the sea level pressure since it tends to be noisy near the
# mountains
smooth_slp = smooth2d(slp, 3, cenweight=4)

# Get the latitude and longitude points
lats, lons = latlon_coords(slp)

# Get the basemap object
bm = get_basemap(slp)

# Create a figure
fig = plt.figure(figsize=(12,9))

# Add geographic outlines
bm.drawcoastlines(linewidth=0.25)
bm.drawstates(linewidth=0.25)
bm.drawcountries(linewidth=0.25)

# Convert the lats and lons to x and y.  Make sure you convert the lats and
# lons to numpy arrays via to_np, or basemap crashes with an undefined
# RuntimeError.
x, y = bm(to_np(lons), to_np(lats))

# Draw the contours and filled contours
コード例 #17
0
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from wrf import to_np, getvar, get_basemap, latlon_coords
import sys
import numpy as np
import landuse_colormap as lu_cm
geo_em_file = Dataset(sys.argv[1])
lis_input_file = Dataset(sys.argv[2])

var = getvar(geo_em_file, 'LU_INDEX', timeidx=0)

lats, lons = latlon_coords(var)
bm = get_basemap(var, resolution='h')
x, y = bm(to_np(lons), to_np(lats))

lu_index = lis_input_file['LANDCOVER'][:]
lu_index_proc = lu_index * np.reshape(np.arange(1,
                                                len(lu_index) + 1, 1),
                                      (len(lu_index), 1, 1))
lu_index_proc = np.sum(lu_index_proc, axis=0)

# Get land cover schemes
scheme = lis_input_file.LANDCOVER_SCHEME

if scheme == 'IGBPNCEP':
    cm, labels = lu_cm.LU_MODIS21()
elif scheme == 'USGS':
    cm, labels = lu_cm.LU_USGS24()
elif scheme == 'UMD':
    cm, labels = lu_cm.LU_UMD()
else:
コード例 #18
0
#
#    plt.title("Visibility (FSL method)",fontsize=12,color='k')
#    fileName=main+'ARW/wrf_output/'+date+'/plots/wrfout_d02_'
#    plt.savefig(fileName+'visibility_fsl_'+file_date_list[ii]+'.png',dpi=100)   

vis=vis_avg ; 
for ii in range(0,vis.shape[0]):
    fig=plt.figure(figsize=(8,8),dpi=100); ax = fig.add_axes([0.1,0.1,0.8,0.8]) 
    #lats, lons = wrf.latlon_coords(vis)

    lons=np.array(wrf.to_np(lon.data[0,:,:])) ; lats=np.array(wrf.to_np(lat.data[0,:,:]))
    #lons=lons[0,:]; lats=lats[:,0]
    #lons,lats=np.meshgrid(lons,lats)
    #m =Basemap(projection='mill',llcrnrlat=lats.min(),urcrnrlat=lats.max(),llcrnrlon=lons.min(),urcrnrlon=lons.max(),resolution='l') #wrf.get_basemap(vis)

    m = wrf.get_basemap(tmp) ;     x, y = m(wrf.to_np(lons), wrf.to_np(lats))
    Z=maskoceans(lons,lats,wrf.to_np(vis)[ii,:,:],inlands=False)#, resolution='c', grid=2.5)
    #Z=wrf.to_np(vis)[ii,:,:]
    #nice_cmap=plt.get_cmap('RdYlGn_r') ;     
    clevs=[0,1,2,3,4,5,6,7,8,9,10]    
    
    #['white 0 ','lime 1','limegreen 2','greenyellow 3','yellow 4','gold 5','orange 6','indianred 7',
    #'firebrick 8', 'darkred 9','lightskyblue 10','deepskyblue 11','royalblue 12 ','blue 13']
    
    mymap = mcolors.ListedColormap(['white','ghostwhite','floralwhite','greenyellow','yellow','gold','orange','indianred','firebrick', \
                                'darkred','lightskyblue','deepskyblue','royalblue','blue'])    
    nice_cmap= plt.get_cmap(mymap)
    #colors = nice_cmap([0,1, 2, 3, 4, 5,6,7,8,9,10,11,12,13])
    colors = nice_cmap([13,11,12,9,8,7,6,4,3,2,0,1])

    cmap, norm = mcolors.from_levels_and_colors(clevs, colors, extend='both')
コード例 #19
0
def energyproduction(files, level):
    """
    Creates hourly and daily energy production outputs for wind a turbine
    output plots

    Parameters
    ----------
    arg1: list
        A 1D glob list of the file outputs from WRF
    arg2: integer
        level of the WRF module to run the evaluation on, typicall 0-2
        for low levels of the atmosphere. 

    Returns
    -------
    None
    """
    count = 0
    dailyenergy = 0
    uaaverage = 0
    vaaverage = 0
    for file in files:
        date, hour = gettimeanddates(file)
        ncfile = Dataset(file)
        cbarticks = np.arange(0.0, 10.0, 0.5)
        r = 52.0  #meters, rotorlength
        Area = np.pi * r**2
        cp = 0.4  #unitless
        density = 1.23  #kg/m^3
        press = getvar(ncfile, 'pressure')  #hPa
        T = getvar(ncfile, 'T')  #K
        ua = getvar(ncfile, 'ua')  #m/s
        va = getvar(ncfile, 'va')  #m/s
        pressground, uaground, vaground, Tground = press[level, :, :], ua[
            level, :, :], va[level, :, :], T[level, :, :]
        bm = get_basemap(pressground)
        fig = plt.figure(figsize=(12, 9))
        totalwind = np.sqrt(uaground**2 + vaground**2)
        #set total wind so that if below 3.0 or above 22.0 wind is 0 meaning prod is zero
        wind = totalwind.to_pandas()
        windmatrix = wind.as_matrix()
        for i in range(0, len(windmatrix)):
            for k in range(0, len(windmatrix[0])):
                if windmatrix[i, k] < 3.0:
                    windmatrix[i, k] = 0.0
                elif windmatrix[i, k] > 22.0:
                    windmatrix[i, k] = 0.0
        energyproduction = (0.5 * density * Area * windmatrix**3 *
                            cp) / 10**6  #megawatts output
        lat, lon = latlon_coords(pressground)
        x, y = bm(to_np(lon), to_np(lat))
        bm.drawcoastlines(linewidth=0.25)
        bm.drawstates(linewidth=0.25)
        bm.drawcountries(linewidth=0.25)
        bm.contour(x,
                   y,
                   to_np(energyproduction),
                   cbarticks,
                   colors="black",
                   vmin=0,
                   vmax=10.0)
        bm.contourf(x,
                    y,
                    to_np(energyproduction),
                    cbarticks,
                    cmap=get_cmap('jet'),
                    vmin=0,
                    vmax=10.0)
        bm.barbs(x, y, uaground, vaground)
        plt.colorbar(shrink=.62, ticks=cbarticks)
        plt.title('Hourly Energy Production for ' + date + ' ' + hour)
        plt.savefig('Hourly-output-' + date + '-' + hour)
        plt.close()
        if count == 23:
            bm = get_basemap(pressground)
            fig = plt.figure(figsize=(12, 9))
            lat, lon = latlon_coords(pressground)
            x, y = bm(to_np(lon), to_np(lat))
            bm.drawcoastlines(linewidth=0.25)
            bm.drawstates(linewidth=0.25)
            bm.drawcountries(linewidth=0.25)
            dailyenergy = dailyenergy / 24.0
            uaaverage = uaaverage / 24.0
            vaaverage = vaaverage / 24.0
            bm.contour(x,
                       y,
                       to_np(dailyenergy),
                       cbarticks,
                       colors="black",
                       vmin=0,
                       vmax=10.0)
            bm.contourf(x,
                        y,
                        to_np(dailyenergy),
                        cbarticks,
                        cmap=get_cmap('jet'),
                        vmin=0,
                        vmax=10.0)
            bm.barbs(x, y, uaaverage, vaaverage)
            plt.colorbar(shrink=.62, ticks=cbarticks)
            plt.title('Dialy Average ' + yesterdaysdate)
            plt.savefig('Daily-Average-' + yesterdaysdate)
            plt.show()
            plt.close()
            dailyenergy = 0
            count = 0
            uaaverage = 0
            vaaverage = 0
        else:
            uaaverage = uaground + uaaverage
            vaaverage = vaground + vaaverage
            dailyenergy = energyproduction + dailyenergy
            count = count + 1
        yesterdaysdate = date
コード例 #20
0
    panelnr = 0
    panel_titles = ('00h UTC', '06h UTC', '12h UTC', '18h UTC')
    i = t
    for row in range(2):
        for col in range(2):
            # Interpolate geopotential height, u, and v winds to 500 hPa
            ht_500 = interplevel(z, p, 500)
            u_500 = interplevel(ua, p, 500)
            v_500 = interplevel(va, p, 500)
            wspd_500 = interplevel(wspd, p, 500)

            # Get the lat/lon coordinates
            lats, lons = latlon_coords(ht_500)

            # Get the basemap object
            bm = get_basemap(ht_500)

            # Create the figure
            #fig = plt.figure(figsize=(12,9))
            #ax = plt.axes()

            # Convert the lat/lon coordinates to x/y coordinates in the projection space
            x, y = bm(to_np(lons), to_np(lats))

            #norm = BoundaryNorm(levels, ncolors=custom_cmap.N, clip=True)
            #h = bm.pcolormesh(lons,lats,wspd[panelnr+i])#, cmap=custom_cmap, latlon=True, vmin=vmin, vmax=vmax, norm=norm)
            ax[row, col].set_title(panel_titles[panelnr], fontsize=11)

            # Add the 500 hPa geopotential height contours
            levels = np.arange(520., 580., 6.)
            contours = bm.contour(x,