<jupyter_start><jupyter_text>Using Xarray for Data read and selection========================================Use Xarray module to read in model data from nomads server.This example uses the xarray module to access data from the nomads server forarchive NAM analysis data via OPeNDAP. Xarray makes it easier to select timesand levels, although you still have to know the coordinate variable name. Asimple 500 hPa plot is created after selecting with xarray. Import all of our needed modules<jupyter_code>from datetime import datetime

import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage as ndimage
import xarray as xr<jupyter_output><empty_output><jupyter_text>Accessing data using Xarray---------------------------<jupyter_code># Specify our date/time of product desired
dt = datetime(2016, 4, 16, 18)

# Construct our OPeNDAP access URL
base_url = 'https://www.ncei.noaa.gov/thredds/dodsC/model-namanl-old/'
data = xr.open_dataset(f'{base_url}{dt:%Y%m}/{dt:%Y%m%d}/'
                       f'namanl_218_{dt:%Y%m%d}_{dt:%H}00_000.grb',
                       decode_times=True)<jupyter_output><empty_output><jupyter_text>NAM data is in a projected coordinate and you get back the projectionX and Y values in km<jupyter_code># Create a 2-d meshgrid of our x, y coordinates
# manually converted to meters (km * 1000)
x, y = np.meshgrid(data['x'].values * 1000, data['y'].values * 1000)<jupyter_output><empty_output><jupyter_text>Getting the valid times in a more useable format<jupyter_code># Get the valid times from the file
vtimes = []
for t in range(data.time.size):
    vtimes.append(datetime.utcfromtimestamp(data.time[t].data.astype('O') / 1e9))
print(vtimes)<jupyter_output><empty_output><jupyter_text>Xarray has some nice functionality to choose the time and level thatyou specifically want to use. In this example the time variable is 'time' andthe level variable is 'isobaric1'. Unfortunately, these can be different witheach file you use, so you'll always need to check what they are by listingthe coordinate variable names<jupyter_code># print(data.Geopotential_height.coords)
hght_500 = data['Geopotential_height_isobaric'].sel(time1=vtimes[0], isobaric=500)
uwnd_500 = data['u-component_of_wind_isobaric'].sel(time1=vtimes[0], isobaric=500)
vwnd_500 = data['v-component_of_wind_isobaric'].sel(time1=vtimes[0], isobaric=500)<jupyter_output><empty_output><jupyter_text>Now make the 500-hPa map------------------------<jupyter_code># Must set data projection, NAM is LCC projection
datacrs = ccrs.LambertConformal(
    central_latitude=data.LambertConformal_Projection.latitude_of_projection_origin,
    central_longitude=data.LambertConformal_Projection.longitude_of_central_meridian)

# A different LCC projection for the plot.
plotcrs = ccrs.LambertConformal(central_latitude=45., central_longitude=-100.,
                                standard_parallels=[30, 60])

fig = plt.figure(figsize=(17., 11.))
ax = plt.axes(projection=plotcrs)
ax.coastlines('50m', edgecolor='black')
ax.add_feature(cfeature.STATES, linewidth=0.5)
ax.set_extent([-130, -67, 20, 50], ccrs.PlateCarree())

clev500 = np.arange(5100, 6000, 60)
cs = ax.contour(x, y, ndimage.gaussian_filter(hght_500, sigma=5), clev500,
                colors='k', linewidths=2.5, linestyles='solid', transform=datacrs)
ax.clabel(cs, fontsize=12, colors='k', inline=1, inline_spacing=8,
          fmt='%i', rightside_up=True, use_clabeltext=True)

# Here we put boxes around the clabels with a black boarder white facecolor
# `labelTexts` necessary as ~cartopy.mpl.contour.GeoContourSet.clabel
# does not return list of texts as of 0.18
for t in cs.labelTexts:
    t.set_bbox({'fc': 'w'})

# Transform Vectors before plotting, then plot wind barbs.
ax.barbs(x, y, uwnd_500.data, vwnd_500.data, length=7, regrid_shape=20, transform=datacrs)

# Add some titles to make the plot readable by someone else
plt.title('500-hPa Geopotential Heights (m)', loc='left')
plt.title(f'VALID: {vtimes[0]}', loc='right');<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12579539892315222, 'fraction_numerical': 0.03206069505628977, 'mean_word_length': 5.136636636636637, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '123472', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1489, 'n_tokens_neox': 1356, 'n_words': 373, 'path': 'pages/gallery/xarray_500hPa_map.ipynb', 'repo_name': 'rrbuchholz/python-training', 'size': '4086'}