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()
Example #2
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 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()
Example #4
0
File: xlsm.py Project: erdc/pangaea
    def latlon(self):
        """Returns lat,lon arrays

            .. warning:: The grids always be returned with [0,0]
                as Northeast and [-1,-1] as Southwest.
        """
        if 'MAP_PROJ' in self._obj.attrs:
            lat, lon = wrf.latlon_coords(self._obj, as_np=True)
            if lat.ndim == 3:
                lat = lat[0]
            if lon.ndim == 3:
                lon = lon[0]
            # WRF Grid is upside down
            lat = lat[::-1]
            lon = lon[::-1]
        else:
            lat, lon = self._raw_coords

        if self.coords_projected:
            lon, lat = transform(Proj(self.projection.ExportToProj4()),
                                 Proj(init='epsg:4326'),
                                 lon,
                                 lat)

        if self.lon_to_180:
            lon = (lon + 180) % 360 - 180  # convert [0, 360] to [-180, 180]

        return lat, lon
Example #5
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
Example #6
0
def get_plot_element(infile):
    rootgroup = Dataset(infile, 'r')
    p = getvar(rootgroup, 'RAINNC')
    lats, lons = latlon_coords(p)
    cart_proj = get_cartopy(p)
    xlim = cartopy_xlim(p)
    ylim = cartopy_ylim(p)
    rootgroup.close()
    return cart_proj, xlim, ylim, lons, lats
Example #7
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
Example #8
0
def load_wrfdata(data_dir, domain):
    wrf_files = [f for f in os.listdir(data_dir) if f[11]==f'{domain}']
    wrflist = [Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files] # 

    T_lake3d = w.getvar(wrflist, 'T_LAKE3D', timeidx=w.ALL_TIMES, method='cat')

    lats, lons = w.latlon_coords(T_lake3d)
    time = T_lake3d.Time.to_index() 

    return T_lake3d, lats, lons, time 
Example #9
0
    def get_info(self, wrf_path, fname, vnames):
        # self.wrf = xr.open_dataset(wrf_path+fname)._file_obj.ds
        self.ds = Dataset(wrf_path+fname)
        self.xrds = xr.open_dataset(wrf_path+fname)

        # check vname and read all of them
        self.dv = {}
        if isinstance(vnames, str):
            self.dv.update({vnames: getvar(self.ds, vnames, timeidx=ALL_TIMES)})
            if vnames != 'Times' and 'lon' not in self.dv:
                self.dv.update({'lat': latlon_coords(self.dv[vnames])[0]})
                self.dv.update({'lon': latlon_coords(self.dv[vnames])[1]})
        elif isinstance(vnames, list):
            for index, v in enumerate(vnames):
                self.dv.update({v: getvar(self.ds, v, timeidx=ALL_TIMES)})
                if v != 'Times' and 'lon' not in self.dv:
                    self.dv.update({'lat': latlon_coords(self.dv[v])[0]})
                    self.dv.update({'lon': latlon_coords(self.dv[v])[1]})

        # get proj
        attrs = self.xrds.attrs
        i = attrs['WEST-EAST_GRID_DIMENSION']
        j = attrs['SOUTH-NORTH_GRID_DIMENSION']

        # calculate attrs for area definition
        shape = (j, i)
        radius = (i*attrs['DX']/2, j*attrs['DY']/2)

        # create area as same as WRF
        area_id = 'wrf_circle'
        proj_dict = {'proj': wrf_projs[attrs['MAP_PROJ']],
                     'lat_0': attrs['MOAD_CEN_LAT'],
                     'lon_0': attrs['STAND_LON'],
                     'lat_1': attrs['TRUELAT1'],
                     'lat_2': attrs['TRUELAT2'],
                     'a': 6370000,
                     'b': 6370000}
        center = (0, 0)
        self.area_def = AreaDefinition.from_circle(area_id, proj_dict,
                                                   center, radius,
                                                   shape=shape)
Example #10
0
def load_wrfdata2(data_dir, domain):
    wrf_files = [f for f in os.listdir(data_dir) if f[11] == f'{domain}']
    wrflist = [
        Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files
    ]  #

    tsk = w.getvar(wrflist, 'T2', timeidx=w.ALL_TIMES, method='cat')

    lats, lons = w.latlon_coords(tsk)
    time = tsk.Time.to_index()

    return tsk, lats, lons, time
Example #11
0
def load_t(data_dir,
           domain,
           t_name='TSK'):  # t_name: 'TSK' or 'T2' or 'T_LAKE3D'
    wrf_files = [f for f in os.listdir(data_dir) if f[11] == f'{domain}']
    wrflist = [
        Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files
    ]  #

    t = w.getvar(wrflist, t_name, timeidx=w.ALL_TIMES, method='cat')

    lats, lons = w.latlon_coords(t)
    time = t.Time.to_index()
    return t, lats, lons, time
Example #12
0
def load_wrfdata(data_dir, domain):
    wrf_files = [f for f in os.listdir(data_dir) if f[11]==f'{domain}']
    wrflist = [Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files]

    rainc = w.getvar(wrflist, 'RAINC', timeidx=w.ALL_TIMES, method='cat')
    rainnc = w.getvar(wrflist, 'RAINNC', timeidx=w.ALL_TIMES, method='cat')
    total_rain = rainc + rainnc

    prec = total_rain.diff('Time', 1)
    lats, lons = w.latlon_coords(prec)
    time = total_rain.Time.to_index() 

    return prec, lats, lons, time, wrflist
Example #13
0
def load_wrfdata(data_dir):
    wrf_files = [f for f in os.listdir(data_dir) if f[9]=='2']
    wrflist = [Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files]

    rainc = w.getvar(wrflist, 'RAINC', timeidx=w.ALL_TIMES, method='cat')
    rainnc = w.getvar(wrflist, 'RAINNC', timeidx=w.ALL_TIMES, method='cat')
    total_rain = rainc + rainnc

    prec = total_rain.diff('Time', 1)#.sel(Time=pd.date_range('2017-06-01 3:00:00', '2017-06-8 00:00:00', freq='3H'))
    # prec = total_rain.isel(Time=-1)
    lats, lons = w.latlon_coords(prec)
    time = total_rain.Time.to_index() 

    return prec, lats, lons, time 
Example #14
0
def getWrfData(wrfPath, dx, dy, dz, levs, debug=True):

    # Open the file
    perDat = Dataset(wrfPath)
    refDat = Dataset("/home/iarsenea/trajs/wrfoutREFd01")

    #print(data.variables)

    # Pull in the values from the base state that we will add to the perturbations
    ref_h = getvar(refDat, "height", units="m", timeidx=0)
    thght = np.asarray(refDat.variables["HGT"])[0] * units.meter
    lats, lons = latlon_coords(ref_h)

    # Pull in the values from the perturbation
    ph = np.asarray(destagger(perDat.variables["PH"][0], 0)) * units('m^2/s^2')
    phb = np.asarray(destagger(refDat.variables["PHB"][0],
                               0)) * units('m^2/s^2')
    ua = np.asarray(destagger(perDat.variables["U"][0], 2)) * units('m/s')
    va = np.asarray(destagger(perDat.variables["V"][0], 1)) * units('m/s')

    # Calculate geopotential
    print("Converting from perturbation height to height AGL...")
    geo = ph + phb

    # Convert to height
    hght = mcalc.geopotential_to_height(geo)

    # Convert to height_agl
    h = np.zeros_like(hght)
    for i in range(hght.shape[0]):
        h[i] = hght[i] - thght
    print("Done.\n")

    # Get the x and y values of the lat and lon coordinates
    x, y = ll_to_xy(refDat, lats, lons)
    x = np.arange(0, np.max(x.data) + 1) * dx
    y = np.arange(0, np.max(y.data) + 1) * dy

    # Interpolate the winds speeds and temps to the heights specified in levs
    if debug:
        print("\nInterpolating wind values to every " + str(dz.m) +
              " meters... \n")
    ua_m = metpy.interpolate.interpolate_1d(levs, h, ua)
    va_m = metpy.interpolate.interpolate_1d(levs, h, va)

    perDat.close()
    refDat.close()

    return h, x, y, ua_m, va_m
Example #15
0
def load_wind(data_dir, domain):
    wrf_files = [f for f in os.listdir(data_dir) if f[11] == f'{domain}']
    wrf_list = [
        Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files
    ]

    var_list = ['U10', 'V10']
    u10, v10 = [
        w.getvar(wrf_list, var, timeidx=w.ALL_TIMES, method='cat')
        for var in var_list
    ]

    lats, lons = w.latlon_coords(u10)
    time = u10.Time.to_index()
    return u10, v10, lats, lons, time
Example #16
0
def load_wrfdata(data_dir):
    wrf_files = [f for f in os.listdir(data_dir) if f[9] == '2']
    wrf_list = [
        Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files
    ]

    var_list = ['U10', 'V10']
    u10, v10 = [
        w.getvar(wrf_list, var, timeidx=w.ALL_TIMES, method='cat')
        for var in var_list
    ]

    lats, lons = w.latlon_coords(u10)

    return u10, v10, lats, lons
Example #17
0
def load_wrfdata(data_dir):
    wrf_files = [f for f in os.listdir(data_dir) if f[11]=='2']
    wrflist = [Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files] # 

    tsk = w.getvar(wrflist, 'TSK', timeidx=w.ALL_TIMES, method='cat')

    # ### 强制附上salem的grid属性,才能施以salem独有的方法
    # tsk.attrs['pyproj_srs'] = salem.open_wrf_dataset(os.path.join(data_dir, wrf_files[0])).attrs['pyproj_srs']

    # del tsk.attrs['projection']
    # del tsk.attrs['coordinates']

    lats, lons = w.latlon_coords(tsk)
    time = tsk.Time.to_index() 

    return tsk, lats, lons, time 
Example #18
0
def load_wrfdata_windspeed(data_dir):
    wrf_files = [f for f in os.listdir(data_dir) if f[9] == '2']
    wrflist = [
        Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files
    ]

    uu, vv, ww, qv = [
        w.getvar(wrflist, var, timeidx=w.ALL_TIMES, method='cat')
        for var in ['ua', 'va', 'wa', 'QVAPOR']
    ]
    h, ter = [w.getvar(wrflist, var, timeidx=-1) for var in ['height', 'ter']]

    lats, lons = w.latlon_coords(uu)
    time = uu.Time.to_index()

    return uu, vv, ww, qv, h, ter, lats, lons, time, wrflist
Example #19
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
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()
Example #21
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()
Example #22
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
Example #23
0
hgt = getvar(ncfile, 'HGT_M')
ref_lu = getvar(ncfile, 'LU_INDEX').rename('REF Landuse Category\'s')
#spr_lu = getvar(ncfile1, 'LU_INDEX').rename('SPR Landuse Category\'s')
#opt_lu = getvar(ncfile2, 'LU_INDEX').rename('OPT Landuse Category\'s')

#spr_lu_diff = spr_lu.where(ref_lu.data != spr_lu.data)
#opt_lu_diff = opt_lu.where(ref_lu.data != opt_lu.data)


""" START Plotting routine for SPR """


fig, ax = plt.subplots(figsize=(20,9))

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

""" REF LU_INDEX Plot """
ref_lu_plt = lu_subplot(ref_lu, 231, res, ref_lu.name, hgt, par=True, mer=False)

""" SPR LU_INDEX Plot """
#spr_lu_plt = lu_subplot(spr_lu, 232, res, spr_lu.name, hgt, par=False, mer=False)
#
#""" opt LU_INDEX Plot """
#opt_lu_plt = lu_subplot(opt_lu, 233, res, opt_lu.name, hgt, par=False, mer=False)
#
#
#""" DIFF LU_INDEX Plot """
#spr_lu_diff_plt = lu_subplot(spr_lu_diff, 235, res, 'Difference ' + spr_lu_diff.name, hgt, par=True, mer=True)
#
#""" DIFF LU_INDEX Plot """
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
#minmintemp = 20.
#steps= 1.

""" preferences for 2015 run """
maxrange = 9.
minrange = 8.
maxmintemp = 28.
minmintemp = 19.
steps= 1.
#%%

# Create a figure for MAX PLOTS
fig, ax = plt.subplots(figsize=(16,16))

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


""" REF LU_INDEX Plot """
ref_lu_plt = lu_subplot(ref_lu, 331, res, ref_lu.name, hgt, par=True, mer=False)

""" SPR LU_INDEX Plot """
spr_lu_plt = lu_subplot(spr_lu, 332, res, spr_lu.name, hgt, par=False, mer=False)


""" DIFF LU_INDEX Plot """
spr_lu_diff_plt = lu_subplot(spr_lu_diff, 333, res, 'Difference ' + spr_lu_diff.name, hgt, par=False, mer=False)


""" REF MAX Plot """
ref_max_plt = var_subplot(ref_med_max, 334, res, ref_med_max.description, steps, maxmintemp, maxrange, par=True, mer=False)
Example #26
0
# Open the NetCDF file.
ncfile = Dataset("/media/uesleisutil/Ueslei/INPE/2014/Outputs/wrf_I_t01.nc")

# Get the data.
slp     = getvar(ncfile, "slp", timeidx=78)
uvmet10 = getvar(ncfile, "uvmet10", units="km h-1", timeidx=78)
u10     = uvmet10[1,:,:]
v10     = uvmet10[0,:,:]
lh      = getvar(ncfile, "LH", timeidx=78)

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

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

# Get the cartopy mapping object.
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)
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
Example #28
0
def main(folder, wrffolder, append, sourceid, plotmap, plotcurves, plotcontour,
         plotcontourf, plotbarbs, resol):
    #z_unit = 'km'
    z_unit = 'dm'
    z_unitStr = 'dam'
    #u_unit = 'm s-1'
    u_unit = 'kt'
    w_unit = u_unit
    w_unitStr = 'm/s'
    w_unitStr = 'kt'
    p_unit = 'hPa'
    df_obs = pd.read_csv(folder + sourceid + '_json.txt', delimiter='\t')
    df_obs['time'] = pd.to_datetime(df_obs['CurrentTime'], unit='s')
    df_obs['air_temperature'] = df_obs['Temperature']
    df_obs['pressure'] = df_obs['Barometric Pressure']
    df_obs['wind_speed'] = df_obs[
        'Wind Speed'] * 1.852 / 3.6  # Convert from knots to m/s
    if z_unit == "km":
        feetScale = 0.3048 / 1000
    elif z_unit == "m":
        feetScale = 0.3048
    elif z_unit == "dm":
        feetScale = 0.3048 / 10

    df_obs['z'] = df_obs['Alt'].to_numpy(
    ) * feetScale  # Convert from feet to decameters (dam)
    # Get data from WRF file
    i_domain = 10
    isOutside = True
    while isOutside:
        if i_domain < 0:
            print('Parts of the flightpath for ' + str(sourceid) +
                  ' is not inside the solution domain')
            break

        i_domain -= 1
        try:
            ncfile = Dataset(wrffolder + '/wrfout_d0' + str(i_domain) + '.nc')
        except:
            continue

        fields = ['T', 'wind_speed', 'wind_from_direction']
        lat_e = df_obs['Latitude'].to_numpy()
        lon_e = df_obs['Longitude'].to_numpy()
        z_e = df_obs['z'].to_numpy()
        time_e = df_obs['time'].to_numpy()
        dummy = pd.DataFrame(
            {'time': wrf.getvar(ncfile, 'Times', wrf.ALL_TIMES)})
        time = dummy['time'].to_numpy()
        indices = (time[0] <= time_e) & (time_e <= time[-1])
        if not np.any(indices):
            raise OutOfRange('The mode-S data is out of range')

        lat_e = lat_e[indices]
        lon_e = lon_e[indices]
        z_e = z_e[indices]
        time_e = time_e[indices]

        x = np.zeros((lat_e.shape[0], 4))
        xy = wrf.ll_to_xy(ncfile, lat_e, lon_e, as_int=False, meta=False)
        if ncfile.MAP_PROJ_CHAR == 'Cylindrical Equidistant' and i_domain == 1:
            xy[0] += 360 / 0.25

        x[:, 0] = xy[0]
        x[:, 1] = xy[1]
        e_we = ncfile.dimensions['west_east'].size
        e_sn = ncfile.dimensions['south_north'].size
        if np.any(xy < 0) or np.any(xy[0] > e_we - 1) or np.any(
                xy[1] > e_sn - 1):
            print('Flight path is outside domain d0' + str(i_domain))
            continue
        else:
            print('Extracting WRF-data from domain d0' + str(i_domain))

        if plotcurves:
            xy2 = np.zeros(xy.T.shape)
            xy2[:, :] = xy[:, :].T
            #zgrid = wrf.interp2dxy(wrf.getvar(ncfile,'z',units=z_unit),xy2,meta=False)
            zgrid = wrf.interp2dxy(wrf.g_geoht.get_height(ncfile,
                                                          units=z_unit),
                                   xy2,
                                   meta=False)  # Get geopotential height
            for i in range(0, len(z_e)):
                f_time = interp1d(zgrid[:, i],
                                  range(0, zgrid.shape[0]),
                                  kind='linear')
                x[i, 2] = f_time(z_e[i])

            f_time = interp1d(time.astype('int'),
                              range(0, len(time)),
                              kind='linear')
            x[:, 3] = f_time(time_e.astype('int'))
            df_wrf = pd.DataFrame()
            df_wrf['time'] = time_e
            df_wrf['air_temperature'] = linInterp(
                wrf.getvar(ncfile, 'tc', wrf.ALL_TIMES, meta=False), x)
            df_wrf['pressure'] = linInterp(
                wrf.g_pressure.get_pressure(ncfile,
                                            wrf.ALL_TIMES,
                                            meta=False,
                                            units=p_unit), x)
            df_wrf['wind_speed'] = linInterp(
                wrf.g_wind.get_destag_wspd(ncfile, wrf.ALL_TIMES, meta=False),
                x)
            df_wrf['wind_from_direction'] = linInterp(
                wrf.g_wind.get_destag_wdir(ncfile, wrf.ALL_TIMES, meta=False),
                x)

            if df_wrf.isnull().values.any():
                print('Some points are outside the domain ' + str(i_domain))
                continue
            else:
                isOutside = False
        else:
            isOutside = False

    if plotcurves:
        # Plot data
        sharex = True
        #fields = np.array([['air_temperature','wind_speed','pressure'],
        #                       ['windDirX', 'windDirY','z']])
        #ylabels = np.array([['Temperature [°C]', 'Wind speed [m/s]', 'Pressure ['+p_unit+']'],
        #                        ['Wind direction - X','Wind direction - Y', 'Altitude ['+z_unitStr+']']])
        fields = np.array([['air_temperature', 'wind_speed'],
                           ['windDirX', 'windDirY']])
        ylabels = np.array([['Temperature [°C]', 'Wind speed [m/s]'],
                            ['Wind direction - X', 'Wind direction - Y']])
        df_obs['windDirX'] = np.cos(np.radians(df_obs['Wind Direction']))
        df_obs['windDirY'] = np.sin(np.radians(df_obs['Wind Direction']))
        df_wrf['windDirX'] = np.cos(np.radians(df_wrf['wind_from_direction']))
        df_wrf['windDirY'] = np.sin(np.radians(df_wrf['wind_from_direction']))
        df_wrf['z'] = z_e

        fig, axs = plt.subplots(fields.shape[0],
                                fields.shape[1],
                                sharex=sharex)
        mng = plt.get_current_fig_manager()
        #mng.resize(*mng.window.maxsize())
        #mng.frame.Maximize(True)
        mng.window.showMaximized()
        title = 'Comparison between Mode-S data and WRF simulations for flight ' + sourceid
        if plotcurves:
            title += '. WRF data from domain d0' + str(
                i_domain) + ' with grid resolution {:.1f} km'.format(
                    max(ncfile.DX, ncfile.DY) / 1000)
        fig.suptitle(title)
        for i in range(0, fields.shape[0]):
            for j in range(0, fields.shape[1]):
                axs[i, j].plot(df_wrf.time.to_numpy(),
                               df_wrf[fields[i, j]].to_numpy(),
                               'b',
                               label='WRF forecast')
                axs[i, j].plot(df_obs.time.to_numpy(),
                               df_obs[fields[i, j]].to_numpy(),
                               'r',
                               label='Observation data')

                axs[i, j].legend()
                axs[i, j].set(xlabel='Time', ylabel=ylabels[i, j])
                axs[i, j].set_xlim(time_e[0], time_e[-1])
        axs[1, 0].set_ylim(-1, 1)
        axs[1, 1].set_ylim(-1, 1)
        plt.show()
        fig.savefig(folder + '/' + sourceid + '_curves.png', dpi=400)

    if plotmap:
        # Extract the pressure, geopotential height, and wind variables
        ncfile = Dataset(wrffolder + '/wrfout_d01.nc')
        p = wrf.g_pressure.get_pressure(ncfile, units=p_unit)
        #p = getvar(ncfile, "pressure",units=p_unit)
        z = getvar(ncfile, "z", units=z_unit)
        ua = getvar(ncfile, "ua", units=u_unit)
        va = getvar(ncfile, "va", units=u_unit)
        wspd = getvar(ncfile, "wspd_wdir", units=w_unit)[0, :]

        # 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 map projection information
        cart_proj = get_cartopy(ht_500)

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

        # Download and add the states and coastlines
        name = 'admin_0_boundary_lines_land'
        #name = 'admin_1_states_provinces_lines'
        #name = "admin_1_states_provinces_shp"
        bodr = cfeature.NaturalEarthFeature(category='cultural',
                                            name=name,
                                            scale=resol,
                                            facecolor='none')
        land = cfeature.NaturalEarthFeature('physical', 'land', \
            scale=resol, edgecolor='k', facecolor=cfeature.COLORS['land'])
        ocean = cfeature.NaturalEarthFeature('physical', 'ocean', \
            scale=resol, edgecolor='none', facecolor=cfeature.COLORS['water'])
        lakes = cfeature.NaturalEarthFeature('physical', 'lakes', \
            scale=resol, edgecolor='b', facecolor=cfeature.COLORS['water'])
        rivers = cfeature.NaturalEarthFeature('physical', 'rivers_lake_centerlines', \
            scale=resol, edgecolor='b', facecolor='none')

        ax.add_feature(land, facecolor='beige', zorder=0)
        ax.add_feature(ocean, linewidth=0.2, zorder=0)
        ax.add_feature(lakes, linewidth=0.2, zorder=1)
        ax.add_feature(bodr, edgecolor='k', zorder=1, linewidth=0.5)
        #ax.add_feature(rivers, linewidth=0.5,zorder=1)
        if plotcontour:
            # Add the 500 hPa geopotential height contour
            levels = np.arange(100., 2000., 10.)
            contours = plt.contour(to_np(lons),
                                   to_np(lats),
                                   to_np(ht_500),
                                   levels=levels,
                                   colors="forestgreen",
                                   linewidths=1,
                                   transform=ccrs.PlateCarree(),
                                   zorder=3)
            plt.clabel(contours, inline=1, fontsize=10, fmt="%i")

        if plotcontourf:
            try:
                with open(home + '/kode/colormaps/SINTEF1.json') as f:
                    json_data = json.load(f)
                SINTEF1 = np.reshape(json_data[0]['RGBPoints'], (-1, 4))
                cmap = ListedColormap(fill_colormap(SINTEF1))
            except:
                print(
                    'SINTEF1 colormap not found (can be found at https://github.com/Zetison/colormaps.git)'
                )
                cmap = get_cmap("rainbow")

            # Add the wind speed contours
            levels = np.linspace(20, 120, 101)
            wspd_contours = plt.contourf(to_np(lons),
                                         to_np(lats),
                                         to_np(wspd_500),
                                         levels=levels,
                                         cmap=cmap,
                                         alpha=0.7,
                                         antialiased=True,
                                         transform=ccrs.PlateCarree(),
                                         zorder=2)
            cbar_wspd = plt.colorbar(wspd_contours,
                                     ax=ax,
                                     orientation="horizontal",
                                     pad=.05,
                                     shrink=0.5,
                                     aspect=30,
                                     ticks=range(10, 110, 10))
            cbar_wspd.ax.set_xlabel('Wind speeds [' + w_unitStr +
                                    '] at 500 mbar height')
        # Add the 500 hPa wind barbs, only plotting every nthb data point.
        nthb = 10
        if plotbarbs:
            plt.barbs(to_np(lons[::nthb, ::nthb]),
                      to_np(lats[::nthb, ::nthb]),
                      to_np(u_500[::nthb, ::nthb]),
                      to_np(v_500[::nthb, ::nthb]),
                      transform=ccrs.PlateCarree(),
                      length=6,
                      zorder=3)

        track = sgeom.LineString(
            zip(df_obs['Longitude'].to_numpy(), df_obs['Latitude'].to_numpy()))
        fullFlightPath = ax.add_geometries([track],
                                           ccrs.PlateCarree(),
                                           facecolor='none',
                                           zorder=4,
                                           edgecolor='red',
                                           linewidth=2,
                                           label='Flight path')
        track = sgeom.LineString(zip(lon_e, lat_e))
        flightPath = ax.add_geometries([track],
                                       ccrs.PlateCarree(),
                                       facecolor='none',
                                       zorder=4,
                                       linestyle=':',
                                       edgecolor='green',
                                       linewidth=2,
                                       label='Extracted flight path')
        #plt.legend(handles=[fullFlightPath])
        #blue_line = mlines.Line2D([], [], color='red',linestyle='--', label='Flight path',linewidth=2)
        #plt.legend(handles=[blue_line])
        # Set the map bounds
        ax.set_xlim(cartopy_xlim(ht_500))
        ax.set_ylim(cartopy_ylim(ht_500))

        #ax.gridlines(draw_labels=True)
        ax.gridlines()
        startdate = pd.to_datetime(str(
            time_e[0])).strftime("%Y-%m-%d %H:%M:%S")
        plt.title('Flight ' + sourceid +
                  ', with visualization of WRF simulation (' + startdate +
                  ') at 500 mbar Height (' + z_unitStr + '), Wind Speed (' +
                  w_unitStr + '), Barbs (' + w_unitStr + ')')

        # Plot domain boundaries
        infile_d01 = wrffolder + '/wrfout_d01.nc'
        cart_proj, xlim_d01, ylim_d01 = get_plot_element(infile_d01)

        infile_d02 = wrffolder + '/wrfout_d02.nc'
        _, xlim_d02, ylim_d02 = get_plot_element(infile_d02)

        infile_d03 = wrffolder + '/wrfout_d03.nc'
        _, xlim_d03, ylim_d03 = get_plot_element(infile_d03)

        infile_d04 = wrffolder + '/wrfout_d04.nc'
        _, xlim_d04, ylim_d04 = get_plot_element(infile_d04)

        # d01
        ax.set_xlim([
            xlim_d01[0] - (xlim_d01[1] - xlim_d01[0]) / 15,
            xlim_d01[1] + (xlim_d01[1] - xlim_d01[0]) / 15
        ])
        ax.set_ylim([
            ylim_d01[0] - (ylim_d01[1] - ylim_d01[0]) / 15,
            ylim_d01[1] + (ylim_d01[1] - ylim_d01[0]) / 15
        ])

        # d01 box
        textSize = 10
        colors = ['blue', 'orange', 'brown', 'deepskyblue']
        linewidth = 1
        txtscale = 0.003
        ax.add_patch(
            mpl.patches.Rectangle((xlim_d01[0], ylim_d01[0]),
                                  xlim_d01[1] - xlim_d01[0],
                                  ylim_d01[1] - ylim_d01[0],
                                  fill=None,
                                  lw=linewidth,
                                  edgecolor=colors[0],
                                  zorder=10))
        ax.text(xlim_d01[0],
                ylim_d01[0] + (ylim_d01[1] - ylim_d01[0]) * (1 + txtscale),
                'd01',
                size=textSize,
                color=colors[0],
                zorder=10)

        # d02 box
        ax.add_patch(
            mpl.patches.Rectangle((xlim_d02[0], ylim_d02[0]),
                                  xlim_d02[1] - xlim_d02[0],
                                  ylim_d02[1] - ylim_d02[0],
                                  fill=None,
                                  lw=linewidth,
                                  edgecolor=colors[1],
                                  zorder=10))
        ax.text(xlim_d02[0],
                ylim_d02[0] + (ylim_d02[1] - ylim_d02[0]) * (1 + txtscale * 3),
                'd02',
                size=textSize,
                color=colors[1],
                zorder=10)

        # d03 box
        ax.add_patch(
            mpl.patches.Rectangle((xlim_d03[0], ylim_d03[0]),
                                  xlim_d03[1] - xlim_d03[0],
                                  ylim_d03[1] - ylim_d03[0],
                                  fill=None,
                                  lw=linewidth,
                                  edgecolor=colors[2],
                                  zorder=10))
        ax.text(xlim_d03[0],
                ylim_d03[0] + (ylim_d03[1] - ylim_d03[0]) *
                (1 + txtscale * 3**2),
                'd03',
                size=textSize,
                color=colors[2],
                zorder=10)

        # d04 box
        ax.add_patch(
            mpl.patches.Rectangle((xlim_d04[0], ylim_d04[0]),
                                  xlim_d04[1] - xlim_d04[0],
                                  ylim_d04[1] - ylim_d04[0],
                                  fill=None,
                                  lw=linewidth,
                                  edgecolor=colors[3],
                                  zorder=10))
        ax.text(xlim_d04[0],
                ylim_d04[0] + (ylim_d04[1] - ylim_d04[0]) *
                (1 + txtscale * 3**3),
                'd04',
                size=textSize,
                color=colors[3],
                zorder=10)

        plt.show()
        fig.savefig(folder + '/' + sourceid + '_map.png', dpi=400)
#steps= 1.

""" preferences for 2015 run """
tminmax = -1
trangemax = 7
steps= 0.25
levels = [ -1.5, -1, 1., 5., 6., 6.5, 7., 7.5, 8.]
blrd = [  "#ccddff", "#ffffff", "#ffcccc","#ff9999","#ff6666","#ff3333","#cc0000","#b30000", "#990000", "#800000", "#660000"]
rdbl = ["#cc0000","#ff3333","#ff6666","#ff9999", "#ffcccc","#ffffff","#ccddff","#6699ff","#0055ff","#003399","#002266"]


# Create a figure for MAX PLOTS
fig, ax = plt.subplots(figsize=(16,12))

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

#fig.suptitle('difference 2069 - 2015 of OPT - SPR' )

""" REF LU_INDEX Plot """
ref_max_plt = var_diff_subplot(ref_max_diff, 111, res, 'Difference 2069 - 2015 REF MAX', tminmax, trangemax, levels=levels, cmap=blrd, steps=steps, par=True, mer=True)

#""" SPR LU_INDEX Plot """
#ref_min_plt = var_diff_subplot(min_diff, 122, res, 'MIN OPT - SPR', tminmax, trangemax, steps=steps, par=False, mer=True)


#""" DIFF LU_INDEX Plot """
#spr_lu_diff_plt = lu_subplot(lu_diff, 133, res, 'LU Diff', hgt, par=False, mer=True)


#""" REF MAX Plot """
Example #30
0
nivel = 700 

# SE EXTRAEN LAS VARIABLES A UTILIZAR
# SE HACE UN CICLO PARA TODOS LOS TIEMPOS DEL WRF_FILE

for tidx in range(0, tpos) :       # len(tpos)  
        p = getvar(wrf_file, "pressure", tidx)  # presion
        z = getvar(wrf_file, "z", tidx, units = 'm')     # geopotencial
        w = getvar(wrf_file, "wa", tidx, units="m s-1")   # vel vertical
        ter = getvar(wrf_file, "ter", tidx)     # terreno alturas

        # Se interpolan las variables al campo de presion correspondiente para podee graficarlas 
        w = interplevel(w, p, nivel)

        # Se extraen lat-lon
        lats, lons = latlon_coords(p)

        # Se extrae info de la proyeccion 
        cart_proj = get_cartopy(p)
        
############################################## GRAFICADO ############################################## 
        
        fig = plt.figure(figsize=(12,9))
        ax = plt.axes(projection=cart_proj)

        # Aniadiendo los sombreados
        #levels = [25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 110, 120]
        levels = np.arange(-1.5, 1.5, 0.25)
        wspd_contours = plt.contourf(to_np(lons), to_np(lats), to_np(w),
                             levels=levels,
                             cmap="bwr",
Example #31
0
ncfile = Dataset(filename)

######################################################################################################
# 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)
Example #32
0
        
        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]
        for i in range(w_cross_filled.shape[-1]):
                column_vals = w_cross_filled[:,i]
                first_idx = int(np.transpose((column_vals > -200).nonzero())[0])
                w_cross_filled[0:first_idx, i] = w_cross_filled[first_idx, i]

        # Para sacar las alturas del terreno del corte
        ter_line = interpline(ter, wrfin=wrf_file, start_point=cross_start,
                              end_point=cross_end)

        # Sacar las lat/lon
        lats, lons = latlon_coords(var)

        # Sacar la projeccion de cartopy
        cart_proj = get_cartopy(var)

        ############# GRAFICADO ############# 
        # Figura
        fig = plt.figure(figsize=(8,6))
        ax_cross = plt.axes()

        ## si se quiere tener un intervalo para los datos 
        #var_levels = np.arange(5, 100., 10.)

        # Se hace el grafico de la variable 
        xs = np.arange(0, var_cross.shape[-1], 1)
        ys = to_np(var_cross.coords["vertical"])
Example #33
0
    date_range = pd.date_range(date1, date2, freq='1D')

    wrf_files = [
        f'{data_dir}/wrfout_d01_{date.year}-{date.month:0>2d}-{date.day:0>2d}_{date.hour:0>2d}:00:00'
        for date in date_range
    ]

    wrflist = [Dataset(wrf_file) for wrf_file in wrf_files]

    u10_wrf, v10_wrf, pm10_wrf = [
        w.getvar(wrflist, var_name, timeidx=w.ALL_TIMES, method='cat')
        for var_name in ['U10', 'V10', 'PM10']
    ]
    pm10_wrf = pm10_wrf.isel(bottom_top=0)

    lats, lons = w.latlon_coords(u10_wrf)

    date_range = pd.date_range(start='2019-05-10 00:00:00',
                               end='2019-05-18 00:00:00',
                               freq='6H')
    #%%
    proj = ccrs.PlateCarree()
    crange = np.arange(0, 1000 + 25, 25)
    cmap = cmaps.WhiteBlueGreenYellowRed

    for t in date_range:
        fig, ax = plt.subplots(figsize=(8, 6), subplot_kw={'projection': proj})

        ax = add_artist(ax, proj)
        # ax = add_province(ax)
        ax = add_citylabel(ax, proj)
Example #34
0
fig = plt.figure(figsize=(16, 12))
#proj = ccrs.LambertConformal()
proj = ccrs.PlateCarree()
prow = 1
pcol = 2

nc8 = Dataset(mp8 + filename)
nc55 = Dataset(mp55 + filename)
shape_feature = ShapelyFeature(Reader(shppath + shpname).geometries(),
                               proj,
                               facecolor='none')
prec8 = nc8.variables['RAINNC'][7, :, :]  #降水
prec55 = nc55.variables['RAINNC'][7, :, :]
ctt8 = getvar(nc8, "ctt")
ctt55 = getvar(nc55, "ctt")
lats, lons = latlon_coords(ctt8)
cart_proj = get_cartopy(ctt8)
ax1 = fig.add_subplot(prow, pcol, 1, projection=cart_proj)
cf1 = ax1.contourf(to_np(lons),
                   to_np(lats),
                   to_np(ctt8),
                   cmap=cmaps.WhBlGrYeRe,
                   transform=proj)
plotdetails(ax1, ctt8, u'Cloud Top Temperature_mp8/$degC$')
color_bar(fig, ax2, cf1)

ax2 = fig.add_subplot(prow, pcol, 2, projection=cart_proj)
cf2 = ax2.contourf(to_np(lons),
                   to_np(lats),
                   to_np(ctt55),
                   cmap=cmaps.WhBlGrYeRe,
Example #35
0
#%%

for idx, time in enumerate(times):
    
    #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)