Overview¶
Siphon is Unidata’s Python library for accessing data from THREDDS Data Servers. This notebook shows how to use Siphon to browse the GDEX catalog and retrieve data via NCSS, CDMRemote, and WMS.
Navigate the GDEX TDS catalog with Siphon
Submit an NCSS (NetCDF Subset Service) query
Access remote arrays via CDMRemote
Render a variable as a map image via WMS (Web Map Service)
Prerequisites¶
| Concepts | Importance | Notes |
|---|---|---|
| tds_intro | Necessary | THREDDS concepts and GDEX catalog URL |
| Siphon | Necessary | |
| xarray | Helpful |
Time to learn: 20 minutes
Imports¶
from siphon.catalog import TDSCatalogBrowsing the Catalog¶
Use TDSCatalog to navigate the GDEX TDS hierarchy and locate a specific dataset or file.
# open catalog and select a dataset
cat = TDSCatalog("https://tds.gdex.ucar.edu/thredds/catalog/files/g/d633000/e5.oper.an.sfc/194305/catalog.xml")
# narrow down to the dataset of interest
variable_name = "sstk"
for dataset in cat.datasets:
if variable_name in dataset:
target_ds = cat.datasets[dataset]
print(f"{target_ds}")e5.oper.an.sfc.128_034_sstk.ll025sc.1943050100_1943053123.nc
NCSS Query¶
The NetCDF Subset Service lets you request a spatial/temporal subset and specific variables without downloading the whole file.
import datetime
# build and submit an NCSS query
ncss = target_ds.subset()
query = ncss.query()
# set the spatial constraints
query.lonlat_box(north=60, south=20, east=40, west=-30)
# set the temporal constraints
query.time_range(datetime.datetime(1943, 5, 2), datetime.datetime(1943, 5, 3))
# The variable name in the dataset is uppercase, so we need to convert it here
query.variables(variable_name.upper())
# submit the query and get the data
data = ncss.get_data(query)attribute type uint not understood. Keeping as String.
attribute type uint not understood. Keeping as String.
attribute type uint not understood. Keeping as String.
attribute type uint not understood. Keeping as String.
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
Cell In[3], line 12
8 query.time_range(datetime.datetime(1943, 5, 2), datetime.datetime(1943, 5, 3))
9 # The variable name in the dataset is uppercase, so we need to convert it here
10 query.variables(variable_name.upper())
11 # submit the query and get the data
---> 12 data = ncss.get_data(query)
File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/siphon/ncss.py:114, in NCSS.get_data(self, query)
93 def get_data(self, query):
94 """Fetch parsed data from a THREDDS server using NCSS.
95
96 Requests data from the NCSS endpoint given the parameters in `query` and
(...) 112
113 """
--> 114 resp = self.get_query(query)
115 return response_handlers(resp, self.unit_handler)
File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/siphon/http_util.py:406, in HTTPEndPoint.get_query(self, query)
386 """Make a GET request, including a query, to the endpoint.
387
388 The path of the request is to the base URL assigned to the endpoint.
(...) 403
404 """
405 url = self._base[:-1] if self._base[-1] == '/' else self._base
--> 406 return self.get(url, query)
File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/siphon/http_util.py:488, in HTTPEndPoint.get(self, path, params)
486 else:
487 text = resp.text
--> 488 raise requests.HTTPError(f'Error accessing {resp.request.url}\n'
489 f'Server Error ({resp.status_code: d}: {text})')
490 return resp
HTTPError: Error accessing https://tds.gdex.ucar.edu/thredds/ncss/grid/files/d633000/e5.oper.an.sfc/194305/e5.oper.an.sfc.128_034_sstk.ll025sc.1943050100_1943053123.nc?var=SSTK&time_start=1943-05-02T00%3A00%3A00&time_end=1943-05-03T00%3A00%3A00&west=-30&east=40&south=20&north=60
Server Error ( 500: Internal Server Error)# print out the data received from the query
dataimport xarray as xr
# Convert the data to an xarray dataset and print out the variable of interest
ds = xr.open_dataset(xr.backends.NetCDF4DataStore(data))
ds.SSTKds.SSTK.isel(time=0).plot()CDMRemote Access¶
CDMRemote provides efficient remote access to the full dataset structure without downloading the entire file. Unlike NCSS which returns a spatial/temporal subset of actual data, CDMRemote exposes the complete Common Data Model (CDM) hierarchy of a dataset, allowing you to:
Browse the full dataset structure and metadata
Access specific variables and dimensions on-demand
Query array-level data directly from the server
Work with large datasets without local storage constraints
This is particularly useful when you need flexibility to explore different parts of a dataset or when you only have intermittent access to specific array slices.
# access via CDMRemote
remote_ds = target_ds.remote_access()
print(remote_ds)WMS (Web Map Service)¶
WMS is an OGC standard protocol that lets a THREDDS server render a dataset variable as a georeferenced map image on the fly. Instead of downloading data arrays, you send an HTTP request describing:
Layer — the variable to render (e.g.,
SSTK)Bounding box and CRS — the spatial extent and coordinate reference system
Time — a specific timestamp to render
Style and color scale — how values are mapped to colors
The server returns a PNG (or other image format) that can be overlaid on any map. This is useful for:
Quick visual inspection of a variable across space and time
Integrating GDEX data into GIS tools or web map applications
Avoiding any local data download when only a visual overview is needed
import requests
import xml.etree.ElementTree as ET
wms_base = target_ds.access_urls["WMS"]
# Fetch GetCapabilities to discover what styles/palettes this server supports
cap_resp = requests.get(wms_base, params={"service": "WMS", "version": "1.3.0", "request": "GetCapabilities"})
root = ET.fromstring(cap_resp.text)
ns = {"wms": "http://www.opengis.net/wms"}
# Find the SSTK layer and print its advertised styles
for layer in root.iter("{http://www.opengis.net/wms}Layer"):
name_el = layer.find("{http://www.opengis.net/wms}Name")
if name_el is not None and name_el.text == variable_name.upper():
print(f"Styles available for {variable_name.upper()}:")
for style in layer.findall("{http://www.opengis.net/wms}Style"):
sname = style.find("{http://www.opengis.net/wms}Name")
if sname is not None:
print(" ", sname.text)import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from io import BytesIO
wms_base = target_ds.access_urls["WMS"]
params = dict(
service = "WMS",
version = "1.3.0",
request = "GetMap",
layers = variable_name.upper(),
styles = "raster/default",
crs = "CRS:84",
bbox = "-180,-90,180,90",
width = 800,
height = 600,
format = "image/png",
colorscalerange = "270,310", # K range from dataset metadata
time = "1943-05-01T00:00:00Z",
)
Fetching and Displaying the WMS Image¶
With the params dict defined above, this cell:
Assembles the full
GetMapURL by URL-encoding all parameters and appending them to the WMS base endpoint.Sends an HTTP GET request to the server, which renders the requested variable (
SSTK) as a georeferenced PNG image server-side.Reads the raw PNG bytes into a NumPy array with
matplotlib.image.imread.Displays the image inline using
imshow, with the bounding box set to global extent ([-180, 180, -90, 90]) so axes are labeled in degrees longitude/latitude.
from urllib.parse import urlencode
wms_url = wms_base + "?" + urlencode(params)
print("WMS URL:\n", wms_url)
# Fetch and display inline
resp = requests.get(wms_url, timeout=30)
resp.raise_for_status()
img = mpimg.imread(BytesIO(resp.content))
fig, ax = plt.subplots(figsize=(12, 8))
ax.imshow(img, extent=[-180, 180, -90, 90], aspect="auto")
ax.set_title(f"WMS — {variable_name} (GetMap)", fontsize=13)
ax.set_xlabel("Longitude"); ax.set_ylabel("Latitude")
plt.tight_layout()
plt.show()
Summary¶
Siphon provides a Pythonic interface to GDEX THREDDS services:
NCSS — ideal for pulling targeted spatial/temporal subsets of data into local memory as a
netCDF4.Dataset.CDMRemote — gives full, lazy remote access to the dataset structure without a local download; useful for exploring metadata and on-demand array slices.
WMS — renders a dataset variable as a georeferenced PNG image server-side via standard OGC
GetMaprequests; no data arrays are transferred, making it ideal for quick visual inspection.
What’s next?¶
See tds_xarray.ipynb to open TDS data via OPeNDAP directly in xarray.