Downloading GFS with Siphon

Unidata Logo

Using Siphon to query the NetCDF Subset Service

Unidata Python Workshop


Objectives

  1. Learn what Siphon is
  2. Employ Siphon's NCSS class to retrieve data from a THREDDS Data Server (TDS)
  3. Plot a map using numpy arrays, matplotlib, and cartopy!

Introduction:

Siphon is a python package that makes downloading data from Unidata data technologies a breeze! In our examples, we'll focus on interacting with the netCDF Subset Service (NCSS) as well as the radar server to retrieve grid data and radar data.

But first! Bookmark these resources for when you want to use Siphon later!

Let's get started!

First, we'll import the TDSCatalog class from Siphon and put the special 'matplotlib' line in so our map will show up later in the notebook. Let's construct an instance of TDSCatalog pointing to our dataset of interest. In this case, I've chosen the TDS' "Best" virtual dataset for the GFS global 0.25 degree collection of GRIB files. This will give us a good resolution for our map. This catalog contains a single dataset.

In [1]:
%matplotlib inline
from siphon.catalog import TDSCatalog
best_gfs = TDSCatalog('http://thredds.ucar.edu/thredds/catalog/grib/NCEP/GFS/'
                      'Global_0p25deg/catalog.xml?dataset=grib/NCEP/GFS/Global_0p25deg/Best')
best_gfs.datasets
Out[1]:
['Best GFS Quarter Degree Forecast Time Series']

We pull out this dataset and call subset() to set up requesting a subset of the data.

In [2]:
best_ds = list(best_gfs.datasets.values())[0]
ncss = best_ds.subset()

We can then use the ncss object to create a new query object, which facilitates asking for data from the server.

In [3]:
query = ncss.query()

We can look at the ncss.variables object to see what variables are available from the dataset:

In [4]:
ncss.variables
Out[4]:
{'5-Wave_Geopotential_Height_isobaric',
 'Absolute_vorticity_isobaric',
 'Albedo_surface_Mixed_intervals_Average',
 'Apparent_temperature_height_above_ground',
 'Best_4_layer_Lifted_Index_surface',
 'Categorical_Freezing_Rain_surface',
 'Categorical_Freezing_Rain_surface_Mixed_intervals_Average',
 'Categorical_Ice_Pellets_surface',
 'Categorical_Ice_Pellets_surface_Mixed_intervals_Average',
 'Categorical_Rain_surface',
 'Categorical_Rain_surface_Mixed_intervals_Average',
 'Categorical_Snow_surface',
 'Categorical_Snow_surface_Mixed_intervals_Average',
 'Cloud_Work_Function_entire_atmosphere_single_layer_Mixed_intervals_Average',
 'Cloud_mixing_ratio_hybrid',
 'Cloud_mixing_ratio_isobaric',
 'Cloud_water_entire_atmosphere_single_layer',
 'Composite_reflectivity_entire_atmosphere',
 'Convective_Precipitation_Rate_surface_Mixed_intervals_Average',
 'Convective_available_potential_energy_pressure_difference_layer',
 'Convective_available_potential_energy_surface',
 'Convective_inhibition_pressure_difference_layer',
 'Convective_inhibition_surface',
 'Convective_precipitation_rate_surface',
 'Convective_precipitation_surface_Mixed_intervals_Accumulation',
 'Dewpoint_temperature_height_above_ground',
 'Downward_Long-Wave_Radp_Flux_surface_Mixed_intervals_Average',
 'Downward_Short-Wave_Radiation_Flux_surface_Mixed_intervals_Average',
 'Field_Capacity_surface',
 'Geopotential_height_highest_tropospheric_freezing',
 'Geopotential_height_isobaric',
 'Geopotential_height_maximum_wind',
 'Geopotential_height_potential_vorticity_surface',
 'Geopotential_height_surface',
 'Geopotential_height_tropopause',
 'Geopotential_height_zeroDegC_isotherm',
 'Graupel_snow_pellets_hybrid',
 'Graupel_snow_pellets_isobaric',
 'Ground_Heat_Flux_surface_Mixed_intervals_Average',
 'Haines_index_surface',
 'ICAO_Standard_Atmosphere_Reference_Height_maximum_wind',
 'ICAO_Standard_Atmosphere_Reference_Height_tropopause',
 'Ice_cover_surface',
 'Ice_growth_rate_altitude_above_msl',
 'Ice_water_mixing_ratio_hybrid',
 'Ice_water_mixing_ratio_isobaric',
 'Icing_severity_isobaric',
 'Land-sea_coverage_nearest_neighbor_land1sea0_surface',
 'Land_cover_0__sea_1__land_surface',
 'Latent_heat_net_flux_surface_Mixed_intervals_Average',
 'MSLP_Eta_model_reduction_msl',
 'Maximum_temperature_height_above_ground_Mixed_intervals_Maximum',
 'Meridional_Flux_of_Gravity_Wave_Stress_surface_Mixed_intervals_Average',
 'Minimum_temperature_height_above_ground_Mixed_intervals_Minimum',
 'Momentum_flux_u-component_surface_Mixed_intervals_Average',
 'Momentum_flux_v-component_surface_Mixed_intervals_Average',
 'Ozone_Mixing_Ratio_isobaric',
 'Per_cent_frozen_precipitation_surface',
 'Planetary_Boundary_Layer_Height_surface',
 'Potential_Evaporation_Rate_surface',
 'Potential_temperature_sigma',
 'Precipitable_water_entire_atmosphere_single_layer',
 'Precipitation_rate_surface',
 'Precipitation_rate_surface_Mixed_intervals_Average',
 'Pressure_convective_cloud_bottom',
 'Pressure_convective_cloud_top',
 'Pressure_height_above_ground',
 'Pressure_high_cloud_bottom_Mixed_intervals_Average',
 'Pressure_high_cloud_top_Mixed_intervals_Average',
 'Pressure_low_cloud_bottom_Mixed_intervals_Average',
 'Pressure_low_cloud_top_Mixed_intervals_Average',
 'Pressure_maximum_wind',
 'Pressure_middle_cloud_bottom_Mixed_intervals_Average',
 'Pressure_middle_cloud_top_Mixed_intervals_Average',
 'Pressure_of_level_from_which_parcel_was_lifted_pressure_difference_layer',
 'Pressure_potential_vorticity_surface',
 'Pressure_reduced_to_MSL_msl',
 'Pressure_surface',
 'Pressure_tropopause',
 'Rain_mixing_ratio_hybrid',
 'Rain_mixing_ratio_isobaric',
 'Relative_humidity_entire_atmosphere_single_layer',
 'Relative_humidity_height_above_ground',
 'Relative_humidity_highest_tropospheric_freezing',
 'Relative_humidity_isobaric',
 'Relative_humidity_pressure_difference_layer',
 'Relative_humidity_sigma',
 'Relative_humidity_sigma_layer',
 'Relative_humidity_zeroDegC_isotherm',
 'Sensible_heat_net_flux_surface_Mixed_intervals_Average',
 'Snow_depth_surface',
 'Snow_mixing_ratio_hybrid',
 'Snow_mixing_ratio_isobaric',
 'Soil_temperature_depth_below_surface_layer',
 'Specific_humidity_height_above_ground',
 'Specific_humidity_pressure_difference_layer',
 'Storm_relative_helicity_height_above_ground_layer',
 'Sunshine_Duration_surface',
 'Surface_Lifted_Index_surface',
 'Temperature_altitude_above_msl',
 'Temperature_height_above_ground',
 'Temperature_high_cloud_top_Mixed_intervals_Average',
 'Temperature_isobaric',
 'Temperature_low_cloud_top_Mixed_intervals_Average',
 'Temperature_maximum_wind',
 'Temperature_middle_cloud_top_Mixed_intervals_Average',
 'Temperature_potential_vorticity_surface',
 'Temperature_pressure_difference_layer',
 'Temperature_sigma',
 'Temperature_surface',
 'Temperature_tropopause',
 'Total_cloud_cover_boundary_layer_cloud_Mixed_intervals_Average',
 'Total_cloud_cover_convective_cloud',
 'Total_cloud_cover_entire_atmosphere_Mixed_intervals_Average',
 'Total_cloud_cover_high_cloud_Mixed_intervals_Average',
 'Total_cloud_cover_isobaric',
 'Total_cloud_cover_low_cloud_Mixed_intervals_Average',
 'Total_cloud_cover_middle_cloud_Mixed_intervals_Average',
 'Total_ozone_entire_atmosphere_single_layer',
 'Total_precipitation_surface_Mixed_intervals_Accumulation',
 'U-Component_Storm_Motion_height_above_ground_layer',
 'Upward_Long-Wave_Radp_Flux_atmosphere_top_Mixed_intervals_Average',
 'Upward_Long-Wave_Radp_Flux_surface_Mixed_intervals_Average',
 'Upward_Short-Wave_Radiation_Flux_atmosphere_top_Mixed_intervals_Average',
 'Upward_Short-Wave_Radiation_Flux_surface_Mixed_intervals_Average',
 'V-Component_Storm_Motion_height_above_ground_layer',
 'Ventilation_Rate_planetary_boundary',
 'Vertical_Speed_Shear_potential_vorticity_surface',
 'Vertical_Speed_Shear_tropopause',
 'Vertical_velocity_geometric_isobaric',
 'Vertical_velocity_pressure_isobaric',
 'Vertical_velocity_pressure_sigma',
 'Visibility_surface',
 'Volumetric_Soil_Moisture_Content_depth_below_surface_layer',
 'Water_equivalent_of_accumulated_snow_depth_surface',
 'Water_runoff_surface_Mixed_intervals_Accumulation',
 'Wilting_Point_surface',
 'Wind_speed_gust_surface',
 'Zonal_Flux_of_Gravity_Wave_Stress_surface_Mixed_intervals_Average',
 'u-component_of_wind_altitude_above_msl',
 'u-component_of_wind_height_above_ground',
 'u-component_of_wind_isobaric',
 'u-component_of_wind_maximum_wind',
 'u-component_of_wind_planetary_boundary',
 'u-component_of_wind_potential_vorticity_surface',
 'u-component_of_wind_pressure_difference_layer',
 'u-component_of_wind_sigma',
 'u-component_of_wind_tropopause',
 'v-component_of_wind_altitude_above_msl',
 'v-component_of_wind_height_above_ground',
 'v-component_of_wind_isobaric',
 'v-component_of_wind_maximum_wind',
 'v-component_of_wind_planetary_boundary',
 'v-component_of_wind_potential_vorticity_surface',
 'v-component_of_wind_pressure_difference_layer',
 'v-component_of_wind_sigma',
 'v-component_of_wind_tropopause'}

We construct a query asking for data corresponding to a latitude and longitude box where 43 lat is the northern extent, 35 lat is the southern extent, 260 long is the western extent and 249 is the eastern extent. Note that longitude values are the longitude distance from the prime meridian. We request the data for the current time. This request will return all surface temperatures for points in our bounding box for a single time. Note the string representation of the query is a properly encoded query string.

In [5]:
from datetime import datetime
query.lonlat_box(north=43, south=35, east=260, west=249).time(datetime.utcnow())
query.accept('netcdf4')
query.variables('Temperature_surface')
Out[5]:
var=Temperature_surface&time=2020-01-17T15%3A15%3A40.778507&west=249&east=260&south=35&north=43&accept=netcdf4

We now request data from the server using this query. The NCSS class handles parsing this NetCDF data (using the netCDF4 module). If we print out the variable names, we see our requested variables, as well as a few others (more metadata information)

In [6]:
from xarray.backends import NetCDF4DataStore
import xarray as xr

data = ncss.get_data(query)
data = xr.open_dataset(NetCDF4DataStore(data))

list(data)
Out[6]:
['Temperature_surface', 'LatLon_Projection']

We'll pull out the temperature variable.

In [7]:
temp_3d = data['Temperature_surface']

We'll pull out the useful variables for latitude, and longitude, and time (which is the time, in hours since the forecast run). Notice the variable names are labeled to show how many dimensions each variable is. This will come in to play soon when we prepare to plot. Try printing one of the variables to see some info on the data!

In [8]:
# Helper function for finding proper time variable
def find_time_var(var, time_basename='time'):
    for coord_name in var.coords:
        if coord_name.startswith(time_basename):
            return var.coords[coord_name]
    raise ValueError('No time variable found for ' + var.name)
In [9]:
time_1d = find_time_var(temp_3d)
lat_1d = data['lat']
lon_1d = data['lon']
time_1d
Out[9]:
<xarray.DataArray 'time' (time: 1)>
array(['2020-01-17T15:00:00.000000000'], dtype='datetime64[ns]')
Coordinates:
    reftime  (time) datetime64[ns] ...
  * time     (time) datetime64[ns] 2020-01-17T15:00:00
Attributes:
    standard_name:        time
    long_name:            GRIB forecast or observation time
    _CoordinateAxisType:  Time

Now we make our data suitable for plotting. We'll import numpy so we can combine lat/longs (meshgrid) and remove one-dimensional entities from our arrays (squeeze). Also we'll use netCDF4's num2date to change the time since the model run to an actual date.

In [10]:
import numpy as np
from netCDF4 import num2date
from metpy.units import units

# Reduce the dimensions of the data and get as an array with units
temp_2d = temp_3d.metpy.unit_array.squeeze()

# Combine latitude and longitudes 
lon_2d, lat_2d = np.meshgrid(lon_1d, lat_1d)

Now we can plot these up using matplotlib. We import cartopy and matplotlib classes, create our figure, add a map, then add the temperature data and grid points.

In [11]:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from metpy.plots import ctables

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

# Add the map and set the extent
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([-100.03, -111.03, 35, 43])

# Retrieve the state boundaries using cFeature and add to plot
ax.add_feature(cfeature.STATES, edgecolor='gray')

# Contour temperature at each lat/long
contours = ax.contourf(lon_2d, lat_2d, temp_2d.to('degF'), 200, transform=ccrs.PlateCarree(),
                       cmap='RdBu_r')
#Plot a colorbar to show temperature and reduce the size of it
fig.colorbar(contours)

# Make a title with the time value
ax.set_title(f'Temperature forecast (\u00b0F) for {time_1d[0].values}Z', fontsize=20)

# Plot markers for each lat/long to show grid points for 0.25 deg GFS
ax.plot(lon_2d.flatten(), lat_2d.flatten(), linestyle='none', marker='o',
        color='black', markersize=2, alpha=0.3, transform=ccrs.PlateCarree());
EXERCISE: Create your own map using the same projection as above but plot different data variables such as dewpoint or relative humidity.
  • Explore the variables available in the NCSS dataset by printing NCSS.variables
  • Change the latitude/longitude values for the request and the map to a region of your own interest!
  • If you're feeling bold, pass in a different TDSCatalog reference url (such as the GFS half degree). Take a look at the full TDS catalog here.