02_GriddedDiagnostics_Dewpoint_CFSR: Compute derived quantities using MetPy
Contents
02_GriddedDiagnostics_Dewpoint_CFSR: Compute derived quantities using MetPy¶
In this notebook, we’ll cover the following:¶
Select a date and access various CFSR Datasets
Subset the desired Datasets along their dimensions
Calculate and visualize dewpoint.
0) Preliminaries ¶
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
1) Specify a starting and ending date/time, and access several CFSR Datasets¶
startYear = 2013
startMonth = 5
startDay = 31
startHour = 12
startMinute = 0
startDateTime = dt(startYear,startMonth,startDay, startHour, startMinute)
endYear = 2013
endMonth = 5
endDay = 31
endHour = 18
endMinute = 0
endDateTime = dt(endYear,endMonth,endDay, endHour, endMinute)
Create Xarray Dataset
objects¶
dsZ = xr.open_dataset (f'/cfsr/data/{startYear}/g.{startYear}.0p5.anl.nc')
dsT = xr.open_dataset (f'/cfsr/data/{startYear}/t.{startYear}.0p5.anl.nc')
dsU = xr.open_dataset (f'/cfsr/data/{startYear}/u.{startYear}.0p5.anl.nc')
dsV = xr.open_dataset (f'/cfsr/data/{startYear}/v.{startYear}.0p5.anl.nc')
dsW = xr.open_dataset (f'/cfsr/data/{startYear}/w.{startYear}.0p5.anl.nc')
dsQ = xr.open_dataset (f'/cfsr/data/{startYear}/q.{startYear}.0p5.anl.nc')
dsSLP = xr.open_dataset (f'/cfsr/data/{startYear}/pmsl.{startYear}.0p5.anl.nc')
2) Specify a date/time range, and subset the desired Dataset
s along their dimensions.¶
Create a list of date and times based on what we specified for the initial and final times, using Pandas’ date_range function
dateList = pd.date_range(startDateTime, endDateTime,freq="6H")
dateList
DatetimeIndex(['2013-05-31 12:00:00', '2013-05-31 18:00:00'], dtype='datetime64[ns]', freq='6H')
# Areal extent
lonW = -105
lonE = -90
latS = 31
latN = 39
cLat, cLon = (latS + latN)/2, (lonW + lonE)/2
latRange = np.arange(latS,latN+.5,.5) # expand the data range a bit beyond the plot range
lonRange = np.arange(lonW,lonE+.5,.5) # Need to match longitude values to those of the coordinate variable
Specify the pressure level.
# Vertical level specificaton
pLevel = 900
levStr = f'{pLevel}'
We will calculate dewpoint and theta-e, which depend on temperature and specific humidity (and also pressure, as we will see), so read in those arrays. Read in U and V as well if we wish to visualize wind vectors.
Now create objects for our desired DataArrays based on the coordinates we have subsetted.¶
# Data variable selection
U = dsU['u'].sel(time=dateList,lev=pLevel,lat=latRange,lon=lonRange)
V = dsV['v'].sel(time=dateList,lev=pLevel,lat=latRange,lon=lonRange)
Q = dsQ['q'].sel(time=dateList,lev=pLevel,lat=latRange,lon=lonRange)
T = dsT['t'].sel(time=dateList,lev=pLevel,lat=latRange,lon=lonRange)
Define our subsetted coordinate arrays of lat and lon. Pull them from any of the DataArrays. We’ll need to pass these into the contouring functions later on.
lats = T.lat
lons = T.lon
3) Calculate and visualize dewpoint.¶
Let’s examine the MetPy diagnostic that calculates dewpoint if specific humidity is available [Dewpoint from specific humidity]:(https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.dewpoint_from_specific_humidity.html)
We can see that this function requires us to pass in arrays of pressure, temperature, and specific humidity. In this case, pressure is constant everywhere, since we are operating on an isobaric surface.
As such, we need to be sure we are attaching units to our previously specified pressure level.
#Attach units to pLevel for use in MetPy with new variable, P:
P = pLevel*units['hPa']
P
Now, we have everything we need to calculate dewpoint.
Td = mpcalc.dewpoint_from_specific_humidity(P, T, Q)
Td
<xarray.DataArray (time: 2, lat: 17, lon: 31)> <Quantity([[[-1.5106201e-02 -1.1964417e+00 6.5258789e-01 ... 1.5523804e+01 1.6057953e+01 1.6409210e+01] [ 8.0740356e-01 -4.1000366e-01 -8.1527710e-01 ... 1.5295227e+01 1.6057953e+01 1.6564423e+01] [ 1.4651489e-01 -1.7840576e-01 -1.5155334e+00 ... 1.5422577e+01 1.6155548e+01 1.6706482e+01] ... [-3.7670898e-01 -3.9174194e+00 -4.2143860e+00 ... 1.7252075e+01 1.7524323e+01 1.7714630e+01] [ 8.3819580e-01 -1.6595154e+00 -1.0915527e+00 ... 1.6765320e+01 1.7274933e+01 1.7847778e+01] [ 5.6730652e+00 2.1357422e+00 1.1427002e+00 ... 1.6812286e+01 1.7137421e+01 1.8012787e+01]] [[ 9.3017578e-01 4.3319702e-01 -1.7840576e-01 ... 1.7535583e+01 1.7546814e+01 1.7670044e+01] [-1.2315674e+00 -1.8780518e+00 -3.1798401e+00 ... 1.7274933e+01 1.7286346e+01 1.7647705e+01] [-3.5440979e+00 -3.3811035e+00 -4.1716003e+00 ... 1.6835693e+01 1.6753571e+01 1.7343292e+01] ... [-4.9162292e+00 -7.4596863e+00 -7.4596863e+00 ... 1.7736908e+01 1.7524323e+01 1.7513062e+01] [-7.0904236e+00 -8.5122681e+00 -7.6208801e+00 ... 1.7946960e+01 1.7445343e+01 1.7331909e+01] [-3.9174194e+00 -6.1328735e+00 -7.1425781e+00 ... 1.7880890e+01 1.7422729e+01 1.7137421e+01]]], 'degree_Celsius')> Coordinates: * time (time) datetime64[ns] 2013-05-31T12:00:00 2013-05-31T18:00:00 * lat (lat) float32 31.0 31.5 32.0 32.5 33.0 ... 37.0 37.5 38.0 38.5 39.0 * lon (lon) float32 -105.0 -104.5 -104.0 -103.5 ... -91.0 -90.5 -90.0 lev float32 900.0
Notice the units are in degrees Celsius.
Let’s do a quick visualization.
Td.sel(time=startDateTime).plot(figsize=(15,10),cmap='summer_r')
<matplotlib.collections.QuadMesh at 0x151eb2592990>

Find the min/max values (no scaling necessary). Use these to inform the setting of the contour fill intervals.¶
minTd = Td.min().values
maxTd = Td.max().values
print (minTd, maxTd)
-10.814972 20.720276
TdInc = 2
TdContours = np.arange (-12, 24, TdInc)
Now, let’s plot filled contours of dewpoint, and wind barbs on the map.¶
Convert U and V to knots
UKts = U.metpy.convert_units('kts')
VKts = V.metpy.convert_units('kts')
constrainLat, constrainLon = (0.5, 4.0)
proj_map = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)
proj_data = ccrs.PlateCarree() # Our data is lat-lon; thus its native projection is Plate Carree.
res = '50m'
for time in dateList:
print("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'CFSR, Valid at: {timeStr}'
tl2 = f'{levStr} hPa dewpoint (°C) and winds (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, Td.sel(time=time), levels=TdContours, 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)
# 4. 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',transform=proj_data)
title = plt.title(title_line,fontsize=16)
#Generate a string for the file name and save the graphic to your current directory.
fileName = f'{timeStrFile}_CFSR_{levStr}_Td_Wind.png'
fig.savefig(fileName)
Processing 2013-05-31 12:00:00
Processing 2013-05-31 18:00:00

