08 Demo: SNOTEL Query and Download
Contents
08 Demo: SNOTEL Query and Download¶
UW Geospatial Data Analysis
CEE498/CEWA599
David Shean
SNOTEL Introduction¶
Read a bit about SNOTEL data for the Western U.S.:
https://www.wcc.nrcs.usda.gov/snow/
This is actually a nice web interface, with some advanced querying and interactive visualization. You can also download formatted ASCII files (csv) for analysis. This is great for one-time projects, but it’s nice to have reproducible code that can be updated as new data appear, without manual steps. That’s what we’re going to do here.
About SNOTEL sites and data:¶
Sample plots for SNOTEL site at Paradise, WA (south side of Mt. Rainier)¶
We will reproduce some of these plots/metrics during this lab
Interactive dashboard¶
Snow today¶
CUAHSI WOF server and automated Python data queries¶
We are going to use a server set up by CUAHSI to serve the SNOTEL data, using a standardized database storage format and query structure. You don’t need to worry about this, but please quickly review the following:
Acronym soup¶
SNOTEL = Snow Telemetry
CUAHSI = Consortium of Universities for the Advancement of Hydrologic Science, Inc
WOF = WaterOneFlow
WSDL = Web Services Description Language
USDA = United States Department of Agriculture
NRCS = National Resources Conservation Service
AWDB = Air-Water Database
Python options¶
There are a few packages out there that offer convenience functions to query the online SNOTEL databases and unpack the results.
climata (https://pypi.org/project/climata/) - last commit Sept 2017 (not a good sign)
ulmo (https://github.com/ulmo-dev/ulmo) - last commit Sept 2021 (will be superseded by a package called Quest, but still maintained by Emilio Mayorga over at UW APL)
You can also write your own queries using the Python requests module and some built-in XML parsing libraries.
Hopefully not overwhelming amount of information - let’s just go with ulmo for now. I’ve done most of the work to prepare functions for querying and processing the data. Once you wrap your head around all of the acronyms, it’s pretty simple, basically running a few functions here: https://ulmo.readthedocs.io/en/latest/api.html#module-ulmo.cuahsi.wof
We will use ulmo with daily data for this exercise, but please feel free to experiment with hourly data, other variables or other approaches to fetch SNOTEL data.
ulmo installation¶
Note that
ulmois not part of the default Hub environmentWe will cover more on conda and environment management in coming weeks, but know that you can temporarily install packages from terminal or even in Jupyterhub notebook
When running conda install from notebook, make sure to use the
-yflag to avoid interactive prompt
Note that packages installed this way won’t persist when your server is shut down, so you will need to reinstall to use again
Fortunately, once we’ve used ulmo for data access and download, we won’t need it again
#Doesn't work until ulmo is installed
import ulmo
#Install directly from github repo main branch
#%pip install git+https://github.com/ulmo-dev/ulmo.git
#!python -m pip install git+https://github.com/ulmo-dev/ulmo.git
#!conda install -q -u ulmo
!mamba install -q -y ulmo
import ulmo
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
Load state polygons for later use¶
states_url = 'http://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_5m.json'
#states_url = 'http://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_500k.json'
states_gdf = gpd.read_file(states_url)
CUAHSI WOF server information¶
Try typing this in a browser, note what you get back (xml)
#http://his.cuahsi.org/wofws.html
wsdlurl = 'https://hydroportal.cuahsi.org/Snotel/cuahsi_1_1.asmx?WSDL'
ulmo.cuahsi.wof.get_sites?
Run the query for available sites¶
sites = ulmo.cuahsi.wof.get_sites(wsdlurl)
If you get an error (AttributeError: module 'ulmo' has no attribute 'cuahsi'), you need to restart your kernel and “Run All Above Selected Cell”
Take a moment to inspect the output¶
What is the
type?Note data structure and different key/value pairs for each site
type(sites)
#Preview first item in dictionary
next(iter(sites.items()))
Store as a Pandas DataFrame called sites_df¶
See the
from_dictfunctionUse
orientoption so the sites comprise the DataFrame index, with columns for ‘name’, ‘elevation_m’, etcUse the
dropnamethod to remove any empty records
sites_df = pd.DataFrame.from_dict(sites, orient='index').dropna()
sites_df.head()
Clean up the DataFrame and prepare Point geometry objects¶
We covered this with the GLAS data conversion to GeoPandas
Convert
'location'column (contains dictionary with'latitude'and'longitude'values) to ShapelyPointobjectsStore as a new
'geometry'columnDrop the
'location'column, as this is no longer neededUpdate the
dtypeof the'elevation_m'column to float
sites_df['location']
sites_df['geometry'] = [Point(float(l['longitude']), float(l['latitude'])) for l in sites_df['location']]
sites_df = sites_df.drop(columns='location')
sites_df = sites_df.astype({"elevation_m":float})
Review output¶
Take a moment to familiarize yourself with the DataFrame structure and different columns.
Note that the index is a set of strings with format ‘SNOTEL:1000_OR_SNTL’
Extract the first record with
locReview the
'site_property'dictionary - could parse this and store as separate fields in the DataFrame if desired
sites_df.head()
sites_df.loc['SNOTEL:301_CA_SNTL']
sites_df.loc['SNOTEL:301_CA_SNTL']['site_property']
Convert to a Geopandas GeoDataFrame¶
We already have
'geometry'column, but still need to define thecrsNote the number of records
sites_gdf_all = gpd.GeoDataFrame(sites_df, crs='EPSG:4326')
sites_gdf_all.shape
sites_gdf_all.head()
Create a scatterplot showing elevation values for all sites¶
f, ax = plt.subplots(figsize=(10,6))
sites_gdf_all.plot(ax=ax, column='elevation_m', markersize=3, cmap='inferno', legend=True)
ax.autoscale(False)
states_gdf.plot(ax=ax, facecolor='none', edgecolor='k', alpha=0.3);
Exclude the Alaska (AK) points to isolate points over Western U.S.¶
Can remove points where the site name contains ‘AK’ or can use a spatial filter (see GeoPandas cx indexer functionality)
Note the number of records
sites_gdf_all = sites_gdf_all[~(sites_gdf_all.index.str.contains('AK'))]
#xmin, xmax, ymin, ymax = [-126, 102, 30, 50]
#sites_gdf_all = sites_gdf_all.cx[xmin:xmax, ymin:ymax]
sites_gdf_all.shape
Update scatterplot as sanity check¶
Should look something like the Western U.S.
f, ax = plt.subplots(figsize=(10,6))
sites_gdf_all.plot(ax=ax, column='elevation_m', markersize=3, cmap='inferno', legend=True)
ax.autoscale(False)
states_gdf.plot(ax=ax, facecolor='none', edgecolor='k', alpha=0.3);
Export SNOTEL site GeoDataFrame as a geojson¶
Maybe useful for later lab or other analysis
sites_fn = 'snotel_conus_sites.json'
if not os.path.exists(sites_fn):
sites_gdf_all.to_file(sites_fn, driver='GeoJSON')
Part 2: Time series analysis for one station¶
Now that we’ve identified sites of interest, let’s query the API to obtain the time series data for variables of interest (snow!).
#Interactive basemap - useful to select a site of interest
#sites_gdf_all.explore(column='elevation_m')
#Hart's Pass
#sitecode = 'SNOTEL:515_WA_SNTL'
#Paradise
sitecode = 'SNOTEL:679_WA_SNTL'
Query the server for information about this site¶
Use the ulmo cuahsi
get_site_infomethod hereLots of output here, try to skim and get a sense of the different parameters and associated metadata
Note that there are many standard meteorological variables that can be downloaded for this site, in addition to the snow depth and snow water equivalent.
Careful about using some variables - documented bias in measurements
https://agupubs.onlinelibrary.wiley.com/doi/full/10.1002/2014GL062803
site_info = ulmo.cuahsi.wof.get_site_info(wsdlurl, sitecode)
#site_info
Inspect the returned information¶
Note number of available variables in the time series data!
dict_keys = site_info['series'].keys()
dict_keys
len(dict_keys)
Note on units:
_H = “hourly”
_D = “daily”
_sm, _m = “monthly”
_y = “yearly”
_wy = “water year”
Let’s consider the ‘SNOTEL:SNWD_D’ variable (Daily Snow Depth)¶
Assign ‘SNOTEL:SNWD_D’ to a variable named
variablecodeGet some information about the variable using
get_variable_infomethodNote the units, nodata value, etc.
Note: The snow depth records are almost always shorter/noisier than the SWE records for SNOTEL sites
#Daily SWE
#variablecode = 'SNOTEL:WTEQ_D'
#Daily snow depth
variablecode = 'SNOTEL:SNWD_D'
#Hourly SWE
#variablecode = 'SNOTEL:WTEQ_H'
#Hourly snow depth
#variablecode = 'SNOTEL:SNWD_H'
ulmo.cuahsi.wof.get_variable_info(wsdlurl, variablecode)
Define a function to fetch time series data¶
Can define specific start and end dates, or get full record (default)
I’ve done this for you, but please review the comments and steps to see what is going on under the hood
You’ll probably have to do similar data wrangling for another project at some point in the future
today = pd.to_datetime("today")
today.strftime('%Y-%m-%d')
#Get current datetime
today = pd.to_datetime("today").strftime('%Y-%m-%d')
def snotel_fetch(sitecode, variablecode='SNOTEL:SNWD_D', start_date='1950-10-01', end_date=today):
#print(sitecode, variablecode, start_date, end_date)
values_df = None
try:
#Request data from the server
site_values = ulmo.cuahsi.wof.get_values(wsdlurl, sitecode, variablecode, start=start_date, end=end_date)
except:
print(f"Unable to fetch {variablecode} for {sitecode}")
else:
#Convert to a Pandas DataFrame
values_df = pd.DataFrame.from_dict(site_values['values'])
#Parse the datetime values to Pandas Timestamp objects
values_df['datetime'] = pd.to_datetime(values_df['datetime'], utc=True)
#Set the DataFrame index to the Timestamps
values_df = values_df.set_index('datetime')
#Convert values to float and replace -9999 nodata values with NaN
values_df['value'] = pd.to_numeric(values_df['value']).replace(-9999, np.nan)
#Remove any records flagged with lower quality
values_df = values_df[values_df['quality_control_level_code'] == '1']
return values_df
Use this function to get the full ‘SNOTEL:SNWD_D’ record for one station¶
Inspect the results
We used a dummy start date of Jan 1, 1950. What is the actual the first date returned?
%%time
print(sitecode)
#values_df = snotel_fetch(sitecode, variablecode, start_date, end_date)
values_df = snotel_fetch(sitecode, variablecode)
values_df.head()
values_df.tail()
Create a quick plot to view the time series¶
Take a moment to inspect the
valuecolumn, which is where theSNWD_Dvalues are storedSanity check thought question: What are the units again?
values_df.plot();
Write out the dataframe to disk¶
Can use a number of different formats here, easiest to use a “pickle”: https://www.pythoncentral.io/how-to-pickle-unpickle-tutorial/
Define a unique filename for the dataset (e.g.,
pkl_fn='snotel_wa_snwd_d.pkl')Write the DataFrame to disk
pkl_fn = f"{variablecode.replace(':','-')}_{sitecode.split(':')[-1]}.pkl"
pkl_fn
print(f"Writing out: {pkl_fn}")
values_df.to_pickle(pkl_fn)
Read it back in to check¶
pd.read_pickle(pkl_fn)
Part 3: Retrieve time series records for All SNOTEL Sites¶
Now that we’ve explored one site, let’s look at them all!
Probably going to be some interesting spatial/temporal variability in these metrics
Notes:¶
I’ve providing the following code to do this for you. Please review so you understand what’s going on:
Loop through all sites names in the sites GeoDataFrame and run the above
snotel_fetchfunctionStore output in a dictionary
Convert the dictionary to a Pandas Dataframe
Write final output to disk
Note that this could take some time to run for all SNOTEL sites (~10-40 min, depending on server load)
Progress will be printed out incrementally
While you wait, explore some of the above links, or review remainder of lab
Several sites may return an error (e.g.,
<suds.sax.document.Document object at 0x7f0813040730>)Fortunately, this is handled by the
try-exceptblock in thesnotel_fetchfunction aboveThis warning could arise for a number of reasons:
The site doesn’t have an ultrasonic snow depth sensor: https://doi.org/10.1175/2007JTECHA947.1
The site was decomissioned or never produced valid data
The data are not available on the CUAHSI server
There was an issue connecting with the CUAHSI server
Most likely the first issue. Some of these sites should have valid records for SWE, but not SD
#All SNOTEL sites
pkl_fn = f"{variablecode.replace(':','-')}_CONUS_all.pkl"
print(pkl_fn)
#Can include start and end dates in filename, but will trigger re-download every day
#pkl_fn = variablecode.replace(':','_')+'_'+start_date+'_'+end_date+'.pkl'
#Define variable for the site geodataframe
gdf = sites_gdf_all
#Isolated to WA SNOTEL sites
#pkl_fn = 'snotel_snwd_d_wa.pkl'
#gdf = sites_gdf_wa
%%time
if os.path.exists(pkl_fn):
snwd_df = pd.read_pickle(pkl_fn)
else:
#Define an empty dictionary to store returns for each site
value_dict = {}
#Loop through each site and add record to dictionary
for i, sitecode in enumerate(gdf.index):
print('%i of %i sites: %s' % (i+1, len(gdf.index), sitecode))
#out = snotel_fetch(sitecode, variablecode, start_date, end_date)
out = snotel_fetch(sitecode, variablecode)
if out is not None:
value_dict[sitecode] = out['value']
#Convert the dictionary to a DataFrame, automatically handles different datetime ranges (nice!)
snwd_df = pd.DataFrame.from_dict(value_dict)
#Write out
print(f"Writing out: {pkl_fn}")
snwd_df.to_pickle(pkl_fn)
Inspect the DataFrame¶
Note structure, number of timestamps, NaNs
What is the date of the first snow depth measurement in the network?
Note that the water equivalent (WTEQ_D) measurements from snow pillows extend much farther back in time, back to the early 1980s, before the ultrasonic snow depth instruments were incorporated across the network. These are better to use for long-term studies.
snwd_df.shape
snwd_df.head()
snwd_df.tail()
snwd_df.describe()