Esempio n. 1
1
    def test(self):
        from netCDF4 import Dataset as NetCDF

        timeidx = 0
        in_wrfnc = NetCDF(wrf_in)

        if (varname == "interplevel"):
            ref_ht_850 = _get_refvals(referent, "interplevel", repeat, multi)
            hts = getvar(in_wrfnc, "z", timeidx=timeidx)
            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)
            hts_850 = interplevel(hts, p, 850)

            nt.assert_allclose(to_np(hts_850), ref_ht_850)

        elif (varname == "vertcross"):
            ref_ht_cross = _get_refvals(referent, "vertcross", repeat, multi)

            hts = getvar(in_wrfnc, "z", timeidx=timeidx)
            p = getvar(in_wrfnc, "pressure", timeidx=timeidx)

            pivot_point = CoordPair(hts.shape[-1] // 2, hts.shape[-2] // 2)
            ht_cross = vertcross(hts, p, pivot_point=pivot_point, angle=90.)

            nt.assert_allclose(to_np(ht_cross), ref_ht_cross, rtol=.01)

        elif (varname == "interpline"):

            ref_t2_line = _get_refvals(referent, "interpline", repeat, multi)

            t2 = getvar(in_wrfnc, "T2", timeidx=timeidx)
            pivot_point = CoordPair(t2.shape[-1] // 2, t2.shape[-2] // 2)

            t2_line1 = interpline(t2, pivot_point=pivot_point, angle=90.0)

            nt.assert_allclose(to_np(t2_line1), ref_t2_line)

        elif (varname == "vinterp"):
            # Tk to theta
            fld_tk_theta = _get_refvals(referent, "vinterp", repeat, multi)
            fld_tk_theta = np.squeeze(fld_tk_theta)

            tk = getvar(in_wrfnc, "temp", timeidx=timeidx, units="k")

            interp_levels = [200, 300, 500, 1000]

            field = vinterp(in_wrfnc,
                            field=tk,
                            vert_coord="theta",
                            interp_levels=interp_levels,
                            extrapolate=True,
                            field_type="tk",
                            timeidx=timeidx,
                            log_p=True)

            tol = 5 / 100.
            atol = 0.0001

            field = np.squeeze(field)

            nt.assert_allclose(to_np(field), fld_tk_theta, tol, atol)
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
    def quiver_draw(self, ua, va, wa, lonlist, plist, interval, interval_y,
                    start_lat, end_lat, start_lon, end_lon, quiver_width,
                    quiver_scale, quiver_color, quiver_headwidth, alpha):
        ua_vert, va_vert, wa_vert = to_np(ua), to_np(va), to_np(wa)
        ws_vert = np.sqrt(ua_vert**2 + va_vert**2)
        #计算风向夹角
        wdir_vert = np.arctan2(va_vert, ua_vert) * 180 / np.pi
        line_angel = np.arctan2(end_lat - start_lat,
                                end_lon - start_lon) * 180 / np.pi
        vl_angel = wdir_vert - line_angel
        vl_angel = np.cos(vl_angel / 180 * np.pi)
        ws_vert = ws_vert * vl_angel
        x, y = [], []
        y_temp, ws1, ws2 = plist.tolist(
        ), ws_vert[::interval_y, ::interval], wa_vert[::interval_y, ::interval]
        for i in range(len(y_temp[::interval_y])):
            x.append(lonlist[::interval])
        for i in range(len(lonlist[::interval])):
            y.append(y_temp[::interval_y])
        y = np.array(y)
        y = y.T
        x = np.array(x)

        quiver = self.axe.quiver(x,
                                 y,
                                 ws1,
                                 ws2,
                                 pivot='mid',
                                 width=quiver_width,
                                 scale=quiver_scale,
                                 color=quiver_color,
                                 headwidth=quiver_headwidth,
                                 alpha=alpha)
Esempio n. 4
0
def smooth_and_plot(var, passes, interp=False, height=False, doplot=True):

    X = getdata(var, interp=interp, height=height)

    yvals = getdata('lat')
    xvals = getdata('lon')

    print("Smoothing...")
    Xsmooth = wrf.smooth2d(X, passes)
    print("done")
    X = wrf.to_np(X)
    Xsmooth = wrf.to_np(Xsmooth)
    dX = X - Xsmooth

    yvals = wrf.to_np(yvals)
    xvals = wrf.to_np(xvals)

    nanwarning(X)
    nanwarning(Xsmooth)

    plottitle = str(passes) + "times smoothed " + var
    plotname = "Smooth" + str(passes) + "_" + var

    if not (interp == False):
        plottitle = plottitle + " at height " + str(height) + "km"
        plotname = plotname + "_height_" + str(height)

    if doplot:
        plotsmooth(X, Xsmooth, yvals, xvals, plottitle, plotname)

    return X, Xsmooth, dX, yvals, xvals
Esempio n. 5
0
    def test(self):
        from netCDF4 import Dataset as NetCDF

        timeidx = 0
        in_wrfnc = NetCDF(wrf_in)

        refnc = NetCDF(referent)

        if testid == "xy":
            # Since this domain is not moving, the reference values are the
            # same whether there are multiple or single files
            ref_vals = refnc.variables["xy"][:]
            # Lats/Lons taken from NCL script, just hard-coding for now
            lats = [22.0, 25.0, 27.0]
            lons = [-90.0, -87.5, -83.75]

            xy = ll_to_xy(in_wrfnc, lats[0], lons[0])

            nt.assert_allclose(to_np(xy), ref_vals)

        else:
            # Since this domain is not moving, the reference values are the
            # same whether there are multiple or single files
            ref_vals = refnc.variables["ll"][:]

            # i_s, j_s taken from NCL script, just hard-coding for now
            # NCL uses 1-based indexing for this, so need to subtract 1
            x_s = np.asarray([10, 50, 90], int)
            y_s = np.asarray([10, 50, 90], int)

            ll = xy_to_ll(in_wrfnc, x_s[0], y_s[0])

            nt.assert_allclose(to_np(ll), ref_vals)
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()
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()
Esempio n. 8
0
def info(ff, pyngl_map=True, print_timeid=False):
    ''' domain information of WRF output '''
    ts = getvar(ff, "times", timeidx=ALL_TIMES)  #-1 isn't work
    nt = np.int32(len(ts))
    dtimes = []
    #for t in ts:
    #    dtimes.append(str(t.values)[0:19])
    dtimes = [str(t.values)[0:19] for t in ts]
    #print("\033[44m{}\033[0m".format(dtimes[0]))
    var = getvar(ff, "QCLOUD", timeidx=0)  #Xarray
    (nz, ny, nx) = var.shape  #nz = np.int32(len(var[:,0,0]))
    (lat, lon) = latlon_coords(var)  # Get the latitude and longitude points
    lat = to_np(lat)
    lon = to_np(lon)
    print(u'nt:{}'.format(nt)+'|nz:{}'.format(nz)+\
    '|ny:{}'.format(ny)+'|nx:{} '.format(nx)+'.'*6+'Get Dimensions '+ \
    'and coordinates(lat. & long.)')
    if pyngl_map:
        #Set some map options based on information in WRF output file
        res = get_pyngl(var)
        del var
        res.tfDoNDCOverlay = True  # required for native projection
        print(
            'pyngl_map = {}, Get WRF map-related resources'.format(pyngl_map))
    else:
        res = Ngl.Resources()
    if print_timeid:
        for i, dtime in enumerate(dtimes):
            print('\033[95m({:02d}){}\033[0m'.format(i, dtime))

    return nt, nz, ny, nx, dtimes, lat, lon, res
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
Esempio n. 10
0
def readdiag(nvar):
	var = getvar(ncfile, nvar)
	smooth_var = smooth2d(var, 3)
	lats, lons = latlon_coords(smooth_var)
	lons = to_np(lons)
	lats = to_np(lats)
	cart_proj = get_cartopy(var)
	return lons,lats
Esempio n. 11
0
def print_cape_for_timestamp(wrf_data, timestamp, filepath):
    slp = pressure_lib.get_sea_level_pressure(wrf_data)
    cinfo = getvar(wrf_data, "cape_2d", missing=0.0)
    cape = cinfo[0, :, :].fillna(0)

    lat, lon = latlon_coords(slp)
    lat_normal = to_np(lat)
    lon_normal = to_np(lon)

    # rain sum
    cape_res = get_pyngl(cinfo)
    cape_res.nglDraw = False  # don't draw plot
    cape_res.nglFrame = False  # don't advance frame

    cape_res.cnFillOn = True  # turn on contour fill
    cape_res.cnLinesOn = False  # turn off contour lines
    cape_res.cnLineLabelsOn = False  # turn off line labels
    cape_res.cnFillMode = "RasterFill"  # These two resources
    cape_res.cnLevelSelectionMode = "ExplicitLevels"
    cape_res.cnFillColors        = numpy.array([ [255,255,255], [  0,255,  0], [  0,128,  0], \
                                                 [240,230,140], [255,255,  0], [255,140,  0], \
                                                 [255,  0,  0], [139,  0,  0], [186, 85,211],\
                                                 [153, 50,204], [139,  0,139], ],'f') / 255.
    cape_res.cnLevels = numpy.array(
        [.1, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500])

    cape_res = geography_lib.initialize_geography(cape_res, "gray50")

    cape_res.lbTitleString = "Convective available potential energy [CAPE] in (J/kg)"
    cape_res.lbOrientation = "horizontal"
    cape_res.lbTitleFontHeightF = 0.015
    cape_res.lbLabelFontHeightF = 0.015

    cape_res.tiMainString = "Thunderstorm probability (%s)" % timestamp.strftime(
        "%b %d %Y %HUTC")
    cape_res.trGridType = "TriangularMesh"  # can speed up plotting.
    cape_res.tfDoNDCOverlay = True  # required for native projection

    # pressure
    p_res = pressure_lib.get_pressure_resource(lat_normal, lon_normal)

    wk_res = Ngl.Resources()
    wk_res.wkWidth = 2500
    wk_res.wkHeight = 2500
    output_path = "%scape_%s" % (filepath, timestamp.strftime("%Y_%m_%d_%H"))
    wks_comp = Ngl.open_wks("png", output_path, wk_res)

    # creating plots for the measurands
    capeplot = Ngl.contour_map(wks_comp, cape, cape_res)
    pplot = Ngl.contour(wks_comp, slp, p_res)

    Ngl.overlay(capeplot, pplot)
    Ngl.maximize_plot(wks_comp, capeplot)
    Ngl.draw(capeplot)
    Ngl.frame(wks_comp)
    Ngl.delete_wks(wks_comp)  # delete currently used workstation
Esempio n. 12
0
    def test(self):

        from netCDF4 import Dataset as NetCDF
        timeidx = 0
        in_wrfnc = NetCDF(wrf_in)
        refnc = NetCDF(referent)

        # These have a left index that defines the product type
        multiproduct = varname in ("uvmet", "uvmet10", "cape_2d", "cape_3d",
                                   "cfrac")

        ref_vals = refnc.variables[varname][:]

        if (varname == "tc"):
            my_vals = getvar(in_wrfnc, "temp", timeidx=timeidx, units="c")
            tol = 1 / 100.
            atol = .1  # Note:  NCL uses 273.16 as conversion for some reason
            nt.assert_allclose(to_np(my_vals), ref_vals, tol, atol)
        elif (varname == "pw"):
            my_vals = getvar(in_wrfnc, "pw", timeidx=timeidx)
            tol = .5 / 100.0
            atol = 0  # NCL uses different constants and doesn't use same
            # handrolled virtual temp in method
            nt.assert_allclose(to_np(my_vals), ref_vals, tol, atol)
        elif (varname == "cape_2d"):
            cape_2d = getvar(in_wrfnc, varname, timeidx=timeidx)
            tol = 0 / 100.
            atol = 200.0
            # Let's only compare CAPE values until the F90 changes are
            # merged back in to NCL.  The modifications to the R and CP
            # changes TK enough that non-lifting parcels could lift, thus
            # causing wildly different values in LCL
            nt.assert_allclose(to_np(cape_2d[0, :]), ref_vals[0, :], tol, atol)
        elif (varname == "cape_3d"):
            cape_3d = getvar(in_wrfnc, varname, timeidx=timeidx)
            # Changing the R and CP constants, while keeping TK within
            # 2%, can lead to some big changes in CAPE.  Tolerances
            # have been set wide when comparing the with the original
            # NCL.  Change back when the F90 code is merged back with
            # NCL
            tol = 0 / 100.
            atol = 200.0

            #print np.amax(np.abs(to_np(cape_3d[0,:]) - ref_vals[0,:]))
            nt.assert_allclose(to_np(cape_3d), ref_vals, tol, atol)
        else:
            my_vals = getvar(in_wrfnc, varname, timeidx=timeidx)
            tol = 2 / 100.
            atol = 0.1
            #print (np.amax(np.abs(to_np(my_vals) - ref_vals)))
            nt.assert_allclose(to_np(my_vals), ref_vals, tol, atol)
Esempio n. 13
0
def check_delta_one_level(no2,lno2,lons,lats,p,Lat_min,Lat_max,Lon_min,Lon_max):
    delta = no2 - lno2
    level = 24
    delta = delta[level,:,:]

    fig,ax = plt.subplots()
    m = drawmap(ax,Lat_min,Lat_max,Lon_min,Lon_max)
    x, y = m(to_np(lons), to_np(lats))

    p = ax.pcolormesh(x, y, delta,cmap='seismic',norm=MidpointNormalize(midpoint=0))
    clb = fig.colorbar(p,ax=ax,pad=0.02,shrink=0.95,extend='neither', orientation='vertical')
    ax.set_title('$\Delta$NO$_2$ (NO2-LNO2) \n level '+str(level+1),fontsize=15)

    plt.show()
Esempio n. 14
0
def plot_dewpoint_temperature(ncFile, targetDir, windScaleFactor=50):
    logger = PyPostTools.pyPostLogger()
    fig, ax, X, Y = prepare_plot_object(ncFile)
    st, fh, fh_int = getTimeObjects(ncFile)

    TD = ncFile["TD"]
    TD_F = Conversions.C_to_F(TD)
    clevs = np.linspace(-20, 85, 36)
    norm = matplotlib.colors.BoundaryNorm(clevs, 36)

    contours = plt.contourf(X,
                            Y,
                            TD_F,
                            clevs,
                            norm=norm,
                            cmap=ColorMaps.td_colormap,
                            transform=ccrs.PlateCarree())
    cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
    cbar.set_label("Dewpoint Temperature ($^\circ$ F)")

    u = ncFile["SFC_U"]
    v = ncFile["SFC_V"]

    uKT = Conversions.ms_to_kts(u)
    vKT = Conversions.ms_to_kts(v)
    plt.barbs(to_np(X[::windScaleFactor, ::windScaleFactor]),
              to_np(Y[::windScaleFactor, ::windScaleFactor]),
              to_np(uKT[::windScaleFactor, ::windScaleFactor]),
              to_np(vKT[::windScaleFactor, ::windScaleFactor]),
              transform=ccrs.PlateCarree(),
              length=6)

    plt.title("Surface Dewpoint Temperature ($^\circ$F), Winds (kts)")
    plt.text(0.02,
             -0.02,
             "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.text(0.7,
             -0.02,
             "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.subplots_adjust(bottom=0.1)
    plt.savefig(targetDir + "/TD_F" + str(fh_int))
    plt.close(fig)
    return True
Esempio n. 15
0
def detrend(X):
    """ X should have shape (nt,ny,nx) or (ny,nx) """

    X = np.array(wrf.to_np(X))

    X = np.moveaxis(X, [-2, -1], [0, 1])

    #wherenans = np.isnan(X)
    #X[wherenans] = 0

    X = remove_nans(X)

    ny = X.shape[0]
    nx = X.shape[1]

    I = np.arange(0, nx)
    J = np.arange(0, ny)

    JX = np.tensordot(J, X[-1, ] - X[0, ], 0)
    XI = np.tensordot(I, X[:, -1, ] - X[:, 0, ], 0)
    XI = np.moveaxis(XI, [0, 1], [1, 0])
    JI = np.tensordot(J, I, 0)
    JIX = np.tensordot(JI, X[-1, -1, ] - X[-1, 0, ] - X[0, -1, ] + X[0, 0, ],
                       0)

    Xdetrend = X - JX / (ny - 1) - XI / (nx - 1) + JIX / ((ny - 1) * (nx - 1))

    Xdetrend = Xdetrend[:-1, :-1, ]

    Xdetrend = np.moveaxis(Xdetrend, [0, 1], [-2, -1])

    return (Xdetrend)
Esempio n. 16
0
def wrf_interp2d(points, Z, xi, Tindex):
    z = to_np(Z)
    name = Tindex.name
    da = xr.DataArray(dims=[name], coords={name: Tindex})
    for t in range(np.shape(z)[0]):
        da[t] = gd(points, z[t,:,:].flatten(), xi)[0]
    return (da)
Esempio n. 17
0
def get_ncfile_point_height2earth(path, point_lat, point_lon):
    ncfile = nc.Dataset(path)
    y, x = ll_to_xy(ncfile, point_lat, point_lon)
    hgt = ncfile.variables['HGT'][0, x, y]
    height = to_np(getvar(ncfile, "height"))[:, x, y]
    h2e = height - hgt
    return h2e
Esempio n. 18
0
def WindDataExtraction(WindFileName, t0):
    # Interpolates temporally (with fixed lat/lon/pres?)
    from wrf import to_np

    if isinstance(t0, np.ndarray): t0 = t0[0]

    WindFile = Dataset(WindFileName)
    times_all = extract_times(WindFile, timeidx=ALL_TIMES)
    times_jd = np.array(
        [Time(str(t), format='isot', scale='utc').jd for t in times_all])

    idx_after = np.searchsorted(times_jd, t0)
    idx_before = idx_after - 1

    interp_factor = (t0 - times_jd[idx_before]) / (times_jd[idx_after] -
                                                   times_jd[idx_before])
    if interp_factor < 0 or interp_factor > 1:
        print('WindWarning: The darkflight time is ouside the bounds of WindData' \
            ' by {0:.3f} times!'.format(interp_factor))

    WindArray = []
    for i in [idx_before, idx_after]:
        hei_3d = np.array([to_np(getvar(WindFile, 'z',
                                        timeidx=i))])  #[1,z,y,x]
        NumberLevels = np.shape(hei_3d)[1]  # Number heights

        lat_3d = np.array([
            np.stack([to_np(getvar(WindFile, 'lat', timeidx=i))] *
                     NumberLevels,
                     axis=0)
        ])  #[1,z,y,x]
        lon_3d = np.array([
            np.stack([to_np(getvar(WindFile, 'lon', timeidx=i))] *
                     NumberLevels,
                     axis=0)
        ])  #[1,z,y,x]

        wen_3d = to_np(getvar(WindFile, 'uvmet', timeidx=i))  #[2,z,y,x]
        wu_3d = np.array([to_np(getvar(WindFile, 'wa',
                                       timeidx=i))])  #[1,z,y,x]

        temp_3d = np.array([to_np(getvar(WindFile, 'tk',
                                         timeidx=i))])  #[1,z,y,x]
        pres_3d = np.array([to_np(getvar(WindFile, 'p',
                                         timeidx=i))])  #[1,z,y,x]
        rh_3d = np.array([to_np(getvar(WindFile, 'rh',
                                       timeidx=i))])  #[1,z,y,x]

        # Construct WindArray = [lat,lon,hei,we,wn,wu,temp,pres,rh]
        WindArray.append(
            np.vstack((lat_3d, lon_3d, hei_3d, wen_3d, wu_3d, temp_3d, pres_3d,
                       rh_3d)))

    WindArray = (1 -
                 interp_factor) * WindArray[0] + interp_factor * WindArray[1]

    return WindArray
Esempio n. 19
0
    def setUV(self, opts):

        if opts.at10:
            Ustring = 'U10'
            Vstring = 'V10'
        else:
            Ustring = 'ua'
            Vstring = 'va'

        self.derived = True
        if opts.getU:
            self.U = DATA(Ustring,
                          h=self.h,
                          passes=self.passes,
                          pars=self.pars,
                          autoplot=False,
                          initialise=False,
                          scaling_type=self.scaling_type,
                          load_coords=False,
                          hasUV=False)
        else:
            self.X = getdata(self.str_id, self.path)
            self.U = self
            self.derived = False

        if opts.getV:
            self.V = DATA(Vstring,
                          h=self.h,
                          passes=self.passes,
                          pars=self.pars,
                          autoplot=False,
                          initialise=False,
                          scaling_type=self.scaling_type,
                          load_coords=False,
                          hasUV=False)
        else:
            self.X = getdata(self.str_id, self.path)
            self.V = self
            self.derived = False

        U = np.array(wrf.to_np(self.U.X))
        V = np.array(wrf.to_np(self.V.X))
        self.X = switch[self.str_id](U, V)

        return
Esempio n. 20
0
def fill_gap(var_cross):
    #* 消除contourf与地形填色之间的空隙
    var_cross_filled = np.ma.copy(w.to_np(var_cross))
    for i in range(var_cross_filled.shape[-1]):
        column_vals = var_cross_filled[:, i]
        first_idx = int(np.transpose((column_vals > -200).nonzero())[0])
        var_cross_filled[0:first_idx, i] = var_cross_filled[first_idx, i]

    return var_cross_filled
Esempio n. 21
0
def get_3h_rainsum(previous_data, current_data, timestamp, filepath):
    slp = pressure_lib.get_sea_level_pressure(current_data)
    previous_sum, rain_con = get_cumulated_rain_sum(previous_data)
    current_sum, rain_con = get_cumulated_rain_sum(current_data)
    rain_sum = current_sum - previous_sum

    lat, lon = latlon_coords(rain_con)
    lat_normal = to_np(lat)
    lon_normal = to_np(lon)

    # rain sum
    rr_res = initialize_rain_resource(rain_con)

    rr_res.lbTitleString = "3h rainsum in (mm)"
    rr_res.lbOrientation = "horizontal"
    rr_res.lbTitleFontHeightF = 0.015
    rr_res.lbLabelFontHeightF = 0.015

    rr_res.tiMainString = "3h rainsum (%s)" % timestamp.strftime(
        "%b %d %Y %HUTC")
    rr_res.trGridType = "TriangularMesh"  # can speed up plotting.
    rr_res.tfDoNDCOverlay = True  # required for native projection

    # pressure
    p_res = pressure_lib.get_pressure_resource(lat_normal, lon_normal)

    wk_res = Ngl.Resources()
    wk_res.wkWidth = 2500
    wk_res.wkHeight = 2500
    output_path = "%srain_3h_%s" % (filepath,
                                    timestamp.strftime("%Y_%m_%d_%H"))
    wks_comp = Ngl.open_wks("png", output_path, wk_res)

    # creating plots for the measurands
    rrplot = Ngl.contour_map(wks_comp, rain_sum, rr_res)
    pplot = Ngl.contour(wks_comp, slp, p_res)

    Ngl.overlay(rrplot, pplot)
    Ngl.maximize_plot(wks_comp, rrplot)
    Ngl.draw(rrplot)
    Ngl.frame(wks_comp)
    Ngl.delete_wks(wks_comp)  # delete currently used workstation
Esempio n. 22
0
def plot_10m_max_winds(ncFile, targetDir, windScaleFactor=50):
    logger = PyPostTools.pyPostLogger()
    fig, ax, X, Y = prepare_plot_object(ncFile)
    st, fh, fh_int = getTimeObjects(ncFile)

    maxwnd = ncFile["MAX_WIND_SFC"]
    u = ncFile["SFC_U"]
    v = ncFile["SFC_V"]

    wndKT = Conversions.ms_to_kts(maxwnd)
    uKT = Conversions.ms_to_kts(u)
    vKT = Conversions.ms_to_kts(v)

    clevs = np.arange(10, 80, 2)
    smooth_wnd = gaussian_filter(to_np(wndKT), sigma=3)
    contours = plt.contourf(X,
                            Y,
                            smooth_wnd,
                            clevs,
                            cmap=get_cmap('rainbow'),
                            transform=ccrs.PlateCarree())
    cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
    cbar.set_label("Wind Speed (Kts)")

    SLP = to_np(ncFile["MSLP"])
    smooth_slp = gaussian_filter(SLP, sigma=3)
    levs = np.arange(950, 1050, 4)
    linesC = plt.contour(X,
                         Y,
                         smooth_slp,
                         levs,
                         colors="black",
                         transform=ccrs.PlateCarree(),
                         linewidths=1)
    plt.clabel(linesC, inline=1, fontsize=10, fmt="%i")

    plt.barbs(to_np(X[::windScaleFactor, ::windScaleFactor]),
              to_np(Y[::windScaleFactor, ::windScaleFactor]),
              to_np(uKT[::windScaleFactor, ::windScaleFactor]),
              to_np(vKT[::windScaleFactor, ::windScaleFactor]),
              transform=ccrs.PlateCarree(),
              length=6)

    plt.title("10m Wax Wind Speed (Kts), MSLP (mb)")
    plt.text(0.02,
             -0.02,
             "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.text(0.7,
             -0.02,
             "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.subplots_adjust(bottom=0.1)
    plt.savefig(targetDir + "/10m_maxwnd_F" + str(fh_int))
    plt.close(fig)
    return True
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
Esempio n. 24
0
def plot_surface_omega(ncFile, targetDir):
    logger = PyPostTools.pyPostLogger()
    fig, ax, X, Y = prepare_plot_object(ncFile)
    st, fh, fh_int = getTimeObjects(ncFile)

    # Convert Pa to dPA
    omega = ncFile["OMEGA"] / 10
    clevs = [
        50, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, -3, -6, -9, -12, -15,
        -18, -21, -24, -27, -30, -33, -36, -39, -45, -51, -57, -63, -69
    ]  #dPa/s
    norm = matplotlib.colors.BoundaryNorm(clevs, 30)

    contours = plt.contourf(X,
                            Y,
                            omega,
                            clevs,
                            norm=norm,
                            cmap=ColorMaps.omega_colormap,
                            transform=ccrs.PlateCarree())
    cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
    cbar.set_label("Omega (dPa / s)")

    SLP = to_np(ncFile["MSLP"])
    smooth_slp = gaussian_filter(SLP, sigma=3)
    levs = np.arange(950, 1050, 4)
    linesC = plt.contour(X,
                         Y,
                         smooth_slp,
                         levs,
                         colors="black",
                         transform=ccrs.PlateCarree(),
                         linewidths=1)
    plt.clabel(linesC, inline=1, fontsize=10, fmt="%i")

    plt.title("Surface Omega (dPa / s), MSLP (mb)")
    plt.text(0.02,
             -0.02,
             "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.text(0.7,
             -0.02,
             "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.subplots_adjust(bottom=0.1)
    plt.savefig(targetDir + "/sfc_omega_F" + str(fh_int))
    plt.close(fig)
    return True
Esempio n. 25
0
def plot_precipitable_water(ncFile, targetDir, withMSLP=True):
    logger = PyPostTools.pyPostLogger()
    fig, ax, X, Y = prepare_plot_object(ncFile)
    st, fh, fh_int = getTimeObjects(ncFile)

    titleAdd = ""

    PW = Conversions.kgm2_to_in(ncFile["PW"])
    clevs = np.linspace(0, 3, 32)
    norm = matplotlib.colors.BoundaryNorm(clevs, 32)

    contours = plt.contourf(X,
                            Y,
                            PW,
                            clevs,
                            norm=norm,
                            cmap=ColorMaps.pw_colormap,
                            transform=ccrs.PlateCarree())
    cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
    cbar.set_label("Precipitable Water (in)")

    if (withMSLP):
        SLP = to_np(ncFile["MSLP"])
        smooth_slp = gaussian_filter(SLP, sigma=3)
        levs = np.arange(950, 1050, 4)
        linesC = plt.contour(X,
                             Y,
                             smooth_slp,
                             levs,
                             colors="black",
                             transform=ccrs.PlateCarree(),
                             linewidths=1)
        plt.clabel(linesC, inline=1, fontsize=10, fmt="%i")
        titleAdd += ", MSLP (mb)"

    plt.title("Precipitable Water (in)" + titleAdd)
    plt.text(0.02,
             -0.02,
             "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.text(0.7,
             -0.02,
             "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.subplots_adjust(bottom=0.1)
    plt.savefig(targetDir + "/PW_F" + str(fh_int))
    plt.close(fig)
    return True
def get_ncfile_time(ncfile, timezone=0):
    timelist = []
    time = str(to_np(
        getvar(ncfile,
               'times')))  #这个输出的时间是nc文件中最开始的时间,例如2016-07-21T00:00:00.000000000
    time = time[0:-10]  #把最后一些无意义的东西筛掉
    times = getvar(ncfile, 'xtimes', timeidx=ALL_TIMES)  #这个输出的是分钟的时间
    formal_datetime = datetime.strptime(time, '%Y-%m-%dT%H:%M:%S')  #格式化时间
    for i in times:
        timelist.append(
            str(formal_datetime + timedelta(
                minutes=int(i) + 60 * timezone)))  #逐一把分钟加到最开始的时间上,并且格式化
    return timelist
Esempio n. 27
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()
Esempio n. 28
0
def pmdbz(wrf_file,times,m,save_dir,drawclb):
    for time in range(times.shape[0]):
        mdbz = getvar(wrf_file, "mdbz",timeidx=time)
        lats, lons = latlon_coords(mdbz)
        x, y = m(to_np(lons), to_np(lats))
        mdbz = to_np(mdbz)
        smooth_mdbz = smooth2d(mdbz, 3)
        smooth_mdbz = to_np(smooth_mdbz)

        mask = smooth_mdbz <= 0
        smooth_mdbz[mask] = np.nan

        bounds = np.arange(0,80,5)
        colors = ['#00FFFF','#009DFF','#0000FF','#0982AF','#00FF00',\
        '#08AF14','#FFD600','#FF9800','#FF0000','#DD001B','#BC0036',\
        '#79006D','#7933A0','#C3A3D4','#FFFFFF']

        im = m.contourf(x,y, smooth_mdbz,10,levels=bounds,colors=colors)

        if drawclb:
            cax = fig.add_axes([0.9, 0.1, 0.02, 0.78])
            clb = fig.colorbar(im,shrink=0.75,ticks=bounds,pad=0.05,cax=cax)
            clb.ax.tick_params(labelsize=15)
            clb.solids.set_edgecolor("face")
            for l in clb.ax.yaxis.get_ticklabels():
                l.set_family('Arial')
            clb.set_label('Reflectivity (dBZ)',fontsize=15)

        name = str(times[time])[:10] + '_' + str(times[time])[11:16] + 'UTC'
        plt.title(str(times[time])[11:13]+str(times[time])[14:16] + ' UTC WRF-Chem',{'size':28},x=0.02,y=0.91,loc='left',bbox=dict(facecolor=(1,1,1,0.5),edgecolor=(0,0,0,0)))
        plt.savefig(save_dir+name+'.png',bbox_inches = 'tight')
        
        # remove elements if times.shape[0] > 1
        if drawclb:
            cax.remove()
        for im in im.collections:
            im.remove()
Esempio n. 29
0
def wrf_extract_var_constants(path_to_file,filename,variables):
	##path_to_file is a string that either leads to one file or leads to directory that contains many netcdf files
	##variables is a list of strings that are variables within the netcdf files. These are case sensitive, and are assumed to be 
					##constants within the netcdf file (i.e. these do not change throughout the simulation)
	##save_label is the hanging label that will be used to save variables:
					##variables will be saved as VARNAME_savelabel

	##this will delete files that are of the same name in the path_to_save directory
	##creates a directory that is called exctracted_vars in the local directory

	##returns the location of the new directory where our files are saved
	##sets current directory
	directory_path = os.path.dirname(os.path.realpath(__file__))
	print(directory_path)

	new_directory = directory_path+'/exctracted_vars/'

	##attempts to create the new directory
	try: 
		os.makedirs(new_directory)
	except OSError:
		print('%s Directory Failed to Create. May be already present' %new_directory)

	####list files in path provided, and append as a dataset (netcdf data set class)
	file_names = glob.glob(path_to_file+'/' + filename)
	file_list= []

	
	file_list.append(Dataset(file_names[0]))

	#loop over variables desired
	for i,var in enumerate(variables):
		##print variable extraction
		print('------Extracting Variable %s------ '%var)

		variable = wrf.getvar(file_list,var,timeidx=0,method="cat")
		variable_np = wrf.to_np(variable)

		#create variable save name
		savefile_loop = new_directory + var 

		np.save(savefile_loop,variable_np)


	print('-----Extract Variables Finished----')

	return new_directory
Esempio n. 30
0
def add_to_ncfile(outfile, var, varname):
    dim_d = dict(zip(var.dims, var.shape))

    for dimname, dimsize in dim_d.items():
        if dimname not in outfile.dimensions:
            outfile.createDimension(dimname, dimsize)

    fill_value = None
    if "_FillValue" in var.attrs:
        fill_value = var.attrs["_FillValue"]

    ncvar = outfile.createVariable(varname,
                                   var.dtype,
                                   var.dims,
                                   zlib=True,
                                   fill_value=fill_value)

    var_vals = to_np(var)
    ncvar[:] = var_vals[:]
Esempio n. 31
0
def ncl_spectrum(X):

    try:
        os.remove(datapath + "X.nc")
    except:
        print(" ")

    X = np.array(wrf.to_np(X))
    X = remove_nans(X)
    X = xa.DataArray(X)
    X = X.to_dataset(name="X")
    X.to_netcdf(datapath + "X.nc")

    try:
        os.remove(datapath + "P.nc")
    except:
        print(" ")

    os.system("ncl spectrum.ncl")

    f = Dataset(datapath + "P.nc")

    P = f.variables["P"]
    return P
Esempio n. 32
0
def get_profile(data_path, xp=0, yp=0, tp=0):

    my_data = dict()

    my_data['file_list'] = glob.glob(
        data_path +
        '/wrfout_d01_*')  #Busco todos los wrfout en la carpeta indicada.
    my_data['file_list'].sort()

    ncfile = Dataset(my_data['file_list'][tp])
    my_data['p'] = to_np(getvar(ncfile, "pressure"))[:, yp, xp]
    my_data['z'] = to_np(getvar(ncfile, "height"))[:, yp, xp]
    my_data['t'] = to_np(getvar(ncfile, "temp", units='degC'))[:, yp, xp]
    my_data['td'] = to_np(getvar(ncfile, "td", units='degC'))[:, yp, xp]
    my_data['u'] = to_np(getvar(ncfile, "ua", units='ms-1'))[:, yp, xp]
    my_data['v'] = to_np(getvar(ncfile, "va", units='ms-1'))[:, yp, xp]
    my_data['xp'] = xp
    my_data['yp'] = yp
    my_data['tp'] = tp

    return my_data
Esempio n. 33
0
def metpy_read_wrf(tidx, froms, froms0, fwrf, lons_out, lats_out):

    wrfin = Dataset(fwrf)

    ds = xr.Dataset()

    slp = getvar(wrfin, "slp", timeidx=tidx)
    ds['slp'] = smooth2d(slp, 3, cenweight=4)

    lats, lons = latlon_coords(slp)
    ds['lats'] = lats
    ds['lons'] = lons
    landmask = extract_vars(wrfin, timeidx=tidx,
                            varnames=["LANDMASK"]).get("LANDMASK")
    u10 = extract_vars(wrfin, timeidx=tidx, varnames=["U10"]).get("U10")
    v10 = extract_vars(wrfin, timeidx=tidx, varnames=["V10"]).get("V10")
    ds['u10'] = u10.where(landmask == 0)
    ds['v10'] = v10.where(landmask == 0)
    latent = extract_vars(wrfin, timeidx=tidx, varnames=["LH"]).get("LH")
    ds['latent'] = smooth2d(latent, 3, cenweight=4)  #latent.where(landmask==0)
    t2m = extract_vars(wrfin, timeidx=tidx, varnames=["T2"]).get("T2") - 273.15
    ds['t2m'] = smooth2d(t2m, 3, cenweight=4)
    sst = extract_vars(wrfin, timeidx=tidx, varnames=["SST"]).get("SST")
    ds['sst'] = sst.where(landmask == 0)

    romsin = xr.open_dataset(froms)
    romsin = romsin.rename({"lat_rho": "lat", "lon_rho": "lon"})
    romsin = romsin.isel(ocean_time=tidx)

    ds['sst_5m'] = romsin.isel(z_r=0).temp
    ds['water_temp'] = romsin.temp
    ds['water_ucur'] = romsin.ucur / 100
    ds['water_vcur'] = romsin.vcur / 100
    ds.water_ucur.attrs['units'] = 'm/s'
    ds.water_vcur.attrs['units'] = 'm/s'

    romsin = xr.open_dataset(froms0)
    romsin = romsin.rename({"lat_rho": "lat", "lon_rho": "lon"})
    romsin = romsin.isel(ocean_time=tidx)
    ds['h'] = romsin.h

    mld = get_oml_depth(froms0, t_in=tidx)
    mld = smooth2d(mld, 3, cenweight=4)
    ds['oml_depth'] = xr.DataArray(mld, ds.sst_5m.coords, ds.sst_5m.dims,
                                   ds.sst_5m.attrs)
    ds['oml_depth2'] = ds.oml_depth.where(ds.h > 20)

    ds = ds.drop(['XLONG', 'XLAT', 'XTIME', 'Time'])
    ds = ds.rename({'south_north': 'eta_rho', 'west_east': 'xi_rho'})

    interp_method = 'bilinear'
    ds_out = xr.Dataset({
        'lat': (['lat'], lats_out),
        'lon': (['lon'], lons_out)
    })
    regridder = xe.Regridder(ds, ds_out, interp_method)
    regridder.clean_weight_file()
    ds = regridder(ds)
    ds = ds.squeeze()

    dxy = 10000.

    ds = ds.metpy.parse_cf().squeeze()

    utau, vtau = wind_stress(to_np(ds.u10), to_np(ds.v10))
    ds['u_tau'] = xr.DataArray(utau, ds.u10.coords, ds.u10.dims, ds.u10.attrs)
    ds['v_tau'] = xr.DataArray(vtau, ds.v10.coords, ds.v10.dims, ds.v10.attrs)
    curl = mpcalc.vorticity(utau * units('m/s'),
                            utau * units('m/s'),
                            dx=dxy * units.meter,
                            dy=dxy * units.meter)
    ds['wind_stress_curl'] = xr.DataArray(np.array(curl), ds.u10.coords,
                                          ds.u10.dims, ds.u10.attrs)

    div = []
    for z in range(len(ds.z_r)):
        div0 = mpcalc.divergence(ds.water_ucur.isel(z_r=z) * units('m/s'),
                                 ds.water_vcur.isel(z_r=z) * units('m/s'),
                                 dx=dxy * units.meter,
                                 dy=dxy * units.meter)
        div.append(div0)
    ds['cur_div'] = xr.DataArray(div, ds.water_ucur.coords, ds.water_ucur.dims,
                                 ds.water_ucur.attrs)

    div = mpcalc.divergence(ds.water_ucur.isel(z_r=2) * units('m/s'),
                            ds.water_vcur.isel(z_r=2) * units('m/s'),
                            dx=dxy * units.meter,
                            dy=dxy * units.meter)
    ds['surf_cur_div'] = xr.DataArray(np.array(div), ds.u10.coords,
                                      ds.u10.dims, ds.u10.attrs)

    print(ds)
    return ds
# Differences
#temp_cross_wrf_wrs = temp_cross_wrf-temp_cross_wrs
#temp_cross_wrf_wr  = temp_cross_wrf-temp_cross_wr
temp_cross_wrs_wr  = temp_cross_wrf-temp_cross_wrs


# Create the figure
fig = plt1.figure(1,figsize=(12,6))
ax  = fig.add_subplot(2,1,1)
ax  = plt1.axes()
gs = gridspec.GridSpec(2, 1, hspace=0)
ax.set_subplotspec(gs[0:1])
fig.tight_layout()

# Make the contour plot
temp_contours = ax.contourf(to_np(temp_cross_wrs_wr), cmap=cmap1,levels=clevs)

# Set the x-ticks to use latitude and longitude labels.
coord_pairs = to_np(temp_cross_wrs_wr.coords["xy_loc"])
x_ticks     = np.arange(coord_pairs.shape[0])
x_labels    = [pair.latlon_str(fmt="{:.2f}, {:.2f}") for pair in to_np(coord_pairs)]

# Disable xticks
plt1.setp( ax.get_xticklabels(), visible=False)
ax.xaxis.grid(False, which='minor')

# Set the y-ticks to be height.
vert_vals = to_np(temp_cross_wrs_wr.coords["vertical"])
v_ticks   = np.arange(vert_vals.shape[0])

ax.set_yticks(v_ticks[::wrf_spacing])
Esempio n. 35
0
fig = plt.figure(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
#bm.shadedrelief() #beautiful for bigger areas with mountains
bm.readshapefile('/home/kristofh/projects/shp_files/BEZIRKSGRENZEOGDPolygon', 'BEZIRKSGRENZEOGDPolygon', linewidth=1.2)
#bm.readshapefile('/home/kristofh/projects/shp_files/STATISTIK_AUSTRIA_NUTS2_20160101', 'STATISTIK_AUSTRIA_NUTS2_20160101', linewidth=1)

# 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))
steps = 1
levels=np.arange(1, 34, steps)
heights = np.arange(100, 800, 75)
# Draw the contours and filled contours
bm.contour(x, y, to_np(hgt), levels=heights, colors="magenta", linewidths=1.2, alpha=1.)
var_cont = bm.pcolormesh(x, y, to_np(var), cmap=get_cmap("viridis"), alpha=0.9)

cb = bm.colorbar(var_cont, spacing='uniform', ticks=levels, location='right', pad=0.2)

# setting colorbar with fixed limits
#m = plt.cm.ScalarMappable(cmap=get_cmap("jet"))
#m.set_array(to_np(t2))
#m.set_clim(int(data_min), int(data_max))
#plt.colorbar(t2_cont)
#cbar.set_ticks(clevs)
Esempio n. 36
0
cart_proj = get_cartopy(slp)

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

# Set the GeoAxes to the projection used by WRF.
ax = plt.axes(projection=cart_proj)

# Download and add the states and coastlines.
states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none',name='admin_0_countries')
ax.coastlines('50m', linewidth=1.7)
ax.add_feature(cfeature.BORDERS,linewidth=1.7)

# Make the contour outlines and filled contours for the smoothed Sea Level Pressure.
clevs1 = np.arange(980,1040.,2.)
c1 = ax.contour(lons, lats, to_np(smooth_slp), levels=clevs1, colors="white",transform=crs.PlateCarree(), linewidths=1.3)

# Make the contour outlines and filled contours for the Latent Heat Flux.
clevs2 = np.arange(-100,650.,5.)
c2 = plt.contourf(to_np(lons), to_np(lats), to_np(lh), clevs2, transform=crs.PlateCarree(),cmap=cm.thermal)
plt.colorbar(ax=ax, shrink=.62,orientation='horizontal',aspect=20,fraction=0.046, pad=0.04)

# Plot the wind barbs for the U10 and V10 from UVMET10.
c3 = plt.barbs(to_np(lons[::75,::75]), to_np(lats[::75,::75]), to_np(u10[::75, ::75]), to_np(v10[::75, ::75]),color='black',transform=crs.PlateCarree(), length=6)

# Set the map limits.  Not really necessary, but used for demonstration.
ax.set_xlim(cartopy_xlim(smooth_slp))
ax.set_ylim(cartopy_ylim(smooth_slp))

# Add the gridlines.
g1 = ax.gridlines(color="gray", linestyle="--",draw_labels=True,linewidth=0.2)
Esempio n. 37
0
# Create the start point and end point for the cross section
start_point = CoordPair(lat=48.19833, lon=16.36694)
end_point = CoordPair(lat=26.76, lon=-77.8)

# Compute the vertical cross-section interpolation.  Also, include the lat/lon
# points along the cross-section.
wspd_cross = vertcross(wspd, z, wrfin=ncfile, start_point=start_point, end_point=end_point,
                       latlon=True, meta=True)

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

# Make the contour plot
wspd_contours = ax.contourf(to_np(wspd_cross), cmap=get_cmap("jet"))

# Add the color bar
plt.colorbar(wspd_contours, ax=ax)

# Set the x-ticks to use latitude and longitude labels.
coord_pairs = to_np(wspd_cross.coords["xy_loc"])
x_ticks = np.arange(coord_pairs.shape[0])
x_labels = [pair.latlon_str(fmt="{:.2f}, {:.2f}") for pair in to_np(coord_pairs)]
ax.set_xticks(x_ticks[::20])
ax.set_xticklabels(x_labels[::20], rotation=45, fontsize=8)

# Set the y-ticks to be height.
vert_vals = to_np(wspd_cross.coords["vertical"])
v_ticks = np.arange(vert_vals.shape[0])
ax.set_yticks(v_ticks[::20])
Esempio n. 38
0
    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
    #bm.shadedrelief() #beautiful for bigger areas with mountains
    bm.readshapefile('/home/kristofh/projects/shp_files/BEZIRKSGRENZEOGDPolygon', 'BEZIRKSGRENZEOGDPolygon', linewidth=1.2)
    #bm.readshapefile('/home/kristofh/projects/shp_files/STATISTIK_AUSTRIA_NUTS2_20160101', 'STATISTIK_AUSTRIA_NUTS2_20160101', linewidth=1)

    # 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))
    steps = 1
    levels=np.arange(1, 25, steps)
    # Draw the contours and filled contours
    bm.contour(x, y, to_np(var), colors="black", levels=levels, linewidths=0.4, alpha=0.5)
    var_cont = bm.contourf(x, y, to_np(var), levels=levels, cmap=get_cmap("Paired"), alpha=0.9)
    
    cb = bm.colorbar(var_cont, location='right', pad=0.2)
    
    # setting colorbar with fixed limits
    #m = plt.cm.ScalarMappable(cmap=get_cmap("jet"))
    #m.set_array(to_np(t2))
    #m.set_clim(int(data_min), int(data_max))
    #plt.colorbar(t2_cont)
    #cbar.set_ticks(clevs)
    ax = plt.gca()