Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

02_GriddedDiagnostics_Dewpoint_ERA5

Overview

  1. Select a date and access the ERA5 dataset

  2. Subset the desired variables along their dimensions

  3. Calculate and visualize diagnostic quantities.

Imports

import xarray as xr
import pandas as pd
import numpy as np
from datetime import datetime as dt
from metpy.units import units
import metpy.calc as mpcalc
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

Specify a starting and ending date/time, regional extent, vertical levels, and access/subset the ERA5

# 1. Set the bounds of your map.
# Set the four values in the code cell below. Test the values.
latN = 39
latS = 29
lonW = -105
lonE = -90

if ( latN > latS ) and ( lonE > lonW):
    cLat = (latN + latS)/2
    cLon = (lonW + lonE)/2
else:
    e = ("Northern (eastern) latitude (longitude) must be greater than southern (western). Go back and re-adjust!")
    raise ValueError(f"Error in lat/lon specification: {e}")

# Recall that in ERA5, longitudes run between 0 and 360, not -180 and 180
if (lonW < 0 ):
    lonW = lonW + 360
if (lonE < 0 ):
    lonE = lonE + 360
    
# 2. Select the map projection for your figure.
proj_map = ccrs.LambertConformal(central_latitude=cLat, central_longitude=cLon)

# 3. Select the projection on which the dataset is based
proj_data = ccrs.PlateCarree()

# 4. Select the resolution of the Cartopy cartographic features, and, if desired, MetPy's county shapefiles.

# Uncomment / comment as desired
#res = '10m' # Most detailed, best for small regions (e.g. NYS)
res = '50m' # Medium detail, best for medium-sized regions (e.g. CONUS)
#res = '110m' # Least detailed, best for large/global maps

#res_county = '5m' # Higher-res MetPy US County shapefiles
res_county = '20m' # Lower-res MetPy US County shapefiles

# Apply the latitude/longitude ranges and extend the data region if desired

expand_lon = 1
expand_lat = 1
latRange = np.arange(latS - expand_lat,latN + expand_lat,.25) # expand the data range a bit beyond the plot range
lonRange = np.arange((lonW - expand_lon),(lonE + expand_lon),.25) # Need to match longitude values to those of the coordinate variable

# Specify desired pressure levels: in this case, a list of one or more
plevel_list = [850, 925,1000]

startYear = 2013
startMonth = 5
startDay = 31
startHour = 12
startMinute = 0
startDateTime = dt(startYear,startMonth,startDay, startHour, startMinute)

endYear = 2013
endMonth = 6
endDay = 1
endHour = 0
endMinute = 0
endDateTime = dt(endYear,endMonth,endDay, endHour, endMinute)

delta_time = endDateTime - startDateTime
time_range_max = 7*86400

if (delta_time.total_seconds() > time_range_max):
    raise RuntimeError("Your time range must not exceed 7 days. Go back and try again.")

# Create a list of date and times based on what we specified for the initial and final times, 
#  using Pandas’ date_range function
dateRange = pd.date_range(startDateTime, endDateTime,freq="6h")

Print out the lat/lon, pressure, and date/time arrays

print ("Summary of subsetted dimensions: \n\n")
print (f'Longitude Range: {lonRange} \n')
print (f'Latitude Range: {latRange} \n')
print (f'Pressure levels: {plevel_list} \n')
print(f'Date Range: {dateRange}')
Summary of subsetted dimensions: 


Longitude Range: [254.   254.25 254.5  254.75 255.   255.25 255.5  255.75 256.   256.25
 256.5  256.75 257.   257.25 257.5  257.75 258.   258.25 258.5  258.75
 259.   259.25 259.5  259.75 260.   260.25 260.5  260.75 261.   261.25
 261.5  261.75 262.   262.25 262.5  262.75 263.   263.25 263.5  263.75
 264.   264.25 264.5  264.75 265.   265.25 265.5  265.75 266.   266.25
 266.5  266.75 267.   267.25 267.5  267.75 268.   268.25 268.5  268.75
 269.   269.25 269.5  269.75 270.   270.25 270.5  270.75] 

Latitude Range: [28.   28.25 28.5  28.75 29.   29.25 29.5  29.75 30.   30.25 30.5  30.75
 31.   31.25 31.5  31.75 32.   32.25 32.5  32.75 33.   33.25 33.5  33.75
 34.   34.25 34.5  34.75 35.   35.25 35.5  35.75 36.   36.25 36.5  36.75
 37.   37.25 37.5  37.75 38.   38.25 38.5  38.75 39.   39.25 39.5  39.75] 

Pressure levels: [850, 925, 1000] 

Date Range: DatetimeIndex(['2013-05-31 12:00:00', '2013-05-31 18:00:00',
               '2013-06-01 00:00:00'],
              dtype='datetime64[ns]', freq='6h')

Access either the cloud-served or local ERA5 repository. Then subset it according to your choices above.

endDate = dt(2023,1,10)
if (endDateTime <= endDate): # Use WeatherBench archive

    cloud_source = True
    ds = xr.open_dataset(
     'gs://weatherbench2/datasets/era5/1959-2023_01_10-wb13-6h-1440x721.zarr', 
     chunks={'time': 48},
     consolidated=True,
     engine='zarr'
    )
    
    # Attach units to the pressure coordinate
    ds.coords['level'].attrs['units'] = 'hPa'
    
    # Rename the variable names in this dataset so they use their corresponding short_name attributes
    # Construct a dictionary whose keys are the original variable names, and whose values are their 
    # short names
    
    rename_data_vars = {}
    seen_short_names = set()
    
    for var_name in ds.data_vars:
        short = ds[var_name].attrs.get("short_name")
        # Only rename if:
        # 1. short_name exists
        # 2. We haven't already used it
        if short and short not in seen_short_names:
            rename_data_vars[var_name] = short
            seen_short_names.add(short)
    # Apply renaming
    ds = ds.rename(rename_data_vars)

else: # Use local archive
    import glob, os
    cloud_source = False
    input_directory = '/free/ktyle/era5'
    files = glob.glob(os.path.join(input_directory,'*_era5.nc'))
    ds = xr.open_mfdataset(files,coords='minimal',compat='override')
    # Rename two of the coordinate variables so they match what is in the WeatherBench archive
    ds = ds.rename({'valid_time': 'time', 'pressure_level': 'level'})

# Perform the initial subset
ds = ds.sel(time = dateRange, longitude = lonRange, latitude = latRange, level = plevel_list)
Chunks: See this link for more info about chunking in Xarray.

Examine the subsetted Dataset

ds
Loading...

Now create DataArray objects for the data variables we are interested in. Since we are interested in computing dewpoint, as well as displaying wind barbs, what variables might we require?

# write your code here
Q = ds['q']
U = ds['u']
V = ds['v']
Q
Loading...

In preparation for calculating diagnostics, let’s first select just a single isobaric surface from the four that we previously listed. Subset the data variables based on that level.

p_level = 925
Qp = Q.sel(level=p_level).compute()
Up = U.sel(level=p_level).compute()
Vp = V.sel(level=p_level).compute()
Qp
Loading...

Calculate the dewpoint

Dp = mpcalc.dewpoint_from_specific_humidity(Qp.level,Qp)
Dp
Loading...

Let’s get a quick visualization, using Xarray’s built-in interface to Matplotlib.

Dp.isel(time=0).plot(figsize=(15,10),cmap='summer_r');
<Figure size 1500x1000 with 2 Axes>

Now, let’s prepare to make a nice-looking map.

We will plot wind barbs in knots, and dewpoint in degrees Celsius.

UKts = Up.metpy.convert_units('kts')
VKts = Vp.metpy.convert_units('kts')

Make the map

lats = Dp.latitude
lons = Dp.longitude
constrainLat, constrainLon = (0.5, 4.0) # trial and error

Find the min/max values. Use these to inform the setting of the contour fill intervals.

Dp.min().values, Dp.max().values
(array(-15.6224578), array(21.43601))
scale = 1e0
minDp= (Dp*scale).min().values
maxDp = (Dp*scale).max().values
print (minDp, maxDp)
-15.622457804032365 21.436010003769013
DpInc = 3
DpContours = np.arange (-30, 24, DpInc)
DpContours
array([-30, -27, -24, -21, -18, -15, -12, -9, -6, -3, 0, 3, 6, 9, 12, 15, 18, 21])

Smooth the diagnostic field

This is not a terribly “noisy” field. But let’s demonstrate the technique of employing a smoothing function. We will use a Gaussian filter, from the SciPy library, which, along with NumPy and Pandas, is one of the core packages in Python’s scientific software ecosystem.

MetPy includes the Gaussian smoother as one of its diagnostics.

sigma = 0.0 # this depends on how noisy your data is, adjust as necessary

DpSmooth = mpcalc.smooth_gaussian(Dp, sigma)

As we did before with the unsmoothed values, let’s look at the resulting DataArray and its extrema.

DpSmooth
Loading...
scale = 1e0
smoothMin = (DpSmooth * scale).min().values
smoothMax = (DpSmooth * scale).max().values
print (smoothMin, smoothMax)
-15.607345396879802 21.4244111418367

We probably don’t need to bother with smoothing this field.

Now, let’s make our map.

for time in dateRange:
    print(f'Processing {time}')
    
    # Create the time strings, for the figure title as well as for the file name.
    timeStr = dt.strftime(time,format="%Y-%m-%d %H%M UTC")
    timeStrFile = dt.strftime(time,format="%Y%m%d%H")
    
    tl1 = f'ERA5, Valid at: {timeStr}'
    tl2 = f'{p_level} hPa dewpoint (°C) and wind (kts))'

    title_line = f'{tl1}\n{tl2}\n'
    
    fig = plt.figure(figsize=(21,15)) # Increase size to adjust for the constrained lats/lons
    ax = fig.add_subplot(1,1,1,projection=proj_map)
    ax.set_extent ([lonW+constrainLon,lonE-constrainLon,latS+constrainLat,latN-constrainLat])
    ax.add_feature(cfeature.COASTLINE.with_scale(res))
    ax.add_feature(cfeature.STATES.with_scale(res),edgecolor='brown')
    
    # Need to use Xarray's sel method here to specify the current time for any DataArray you are plotting.

    # 1. Contour fill of dewpoint.
    cTd = ax.contourf(lons, lats, Dp.sel(time=time), levels=DpContours, cmap='summer_r', transform=proj_data)
    cbar = plt.colorbar(cTd,shrink=0.5)
    cbar.ax.tick_params(labelsize=16)
    cbar.ax.set_ylabel("Dew point temperature (°C)",fontsize=16)
      
    # 2. wind barbs
    # Plotting wind barbs uses the ax.barbs method. Here, you can't pass in the DataArray directly; you can only pass in the array's values.
    # Also need to sample (skip) a selected # of points to keep the plot readable.
    # Remember to use Xarray's sel method here as well to specify the current time.
    skip = 2
    ax.barbs(lons[::skip],lats[::skip],UKts.sel(time=time)[::skip,::skip].values, VKts.sel(time=time)[::skip,::skip].values, color='purple',zorder=2,transform=proj_data)

    title = ax.set_title(title_line,fontsize=16)
    #Generate a string for the file name and save the graphic to your current directory.
    fileName = f'{timeStrFile}_ERA5_{p_level}_DewpointWind.png'
    fig.savefig(fileName)
Processing 2013-05-31 12:00:00
Processing 2013-05-31 18:00:00
Processing 2013-06-01 00:00:00
<Figure size 2100x1500 with 2 Axes>
<Figure size 2100x1500 with 2 Axes>
<Figure size 2100x1500 with 2 Axes>

What’s next?

We will calculate a different diagnostic from another event.