Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Reading GDEX THREDDS Data with xarray

Authors
Affiliations
NSF NCAR
NSF NCAR
NSF NCAR

Overview

xarray can open remote OPeNDAP datasets directly from the GDEX THREDDS server, enabling lazy, memory-efficient access without downloading files.

  1. Construct an OPeNDAP URL from the TDS catalog

  2. Open the dataset lazily with xarray

  3. Select a spatial and temporal subset

  4. Plot the result

Prerequisites

ConceptsImportanceNotes
tds_introNecessaryGDEX TDS catalog and OPeNDAP concept
xarrayNecessary
matplotlib / cartopyHelpfulVisualization
  • Time to learn: 20 minutes


Imports

Building an OPeNDAP URL

OPeNDAP URLs on the GDEX TDS follow the pattern: https://thredds.rda.ucar.edu/thredds/dodsC/<path-to-file>

Lazy Loading with xarray

xarray opens remote OPeNDAP datasets without downloading the full file. Data is fetched on demand when you call .load() or compute.

Notebook process memory usage: 192.37 MB (RSS)
ERR: curl error: Timeout was reached
curl error details: 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/xarray/backends/file_manager.py:265, in CachingFileManager._acquire_with_cache_info(self, needs_lock)
    264 try:
--> 265     file = self._cache[self._key]
    266 except KeyError:

File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/xarray/backends/lru_cache.py:56, in LRUCache.__getitem__(self, key)
     55 with self._lock:
---> 56     value = self._cache[key]
     57     self._cache.move_to_end(key)

KeyError: [<class 'netCDF4._netCDF4.Dataset'>, ('https://thredds.rda.ucar.edu/thredds/dodsC/files/g/d633000/e5.oper.an.pl/202001/e5.oper.an.pl.128_130_t.ll025sc.2020010100_2020010123.nc',), 'r', (('clobber', True), ('diskless', False), ('format', 'NETCDF4'), ('persist', False)), '7eb41596-2acd-451a-94c3-859dcf47fa4c']

During handling of the above exception, another exception occurred:

OSError                                   Traceback (most recent call last)
Cell In[4], line 3
      1 import xarray as xr
      2 # Open the remote dataset
----> 3 ds_lazy = xr.open_dataset(OPeNDAP_URL, engine="netcdf4", chunks={})
      4 ds_lazy

File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/xarray/backends/api.py:619, in open_dataset(filename_or_obj, engine, chunks, cache, decode_cf, mask_and_scale, decode_times, decode_timedelta, use_cftime, concat_characters, decode_coords, drop_variables, create_default_indexes, inline_array, chunked_array_type, from_array_kwargs, backend_kwargs, **kwargs)
    607 decoders = _resolve_decoders_kwargs(
    608     decode_cf,
    609     open_backend_dataset_parameters=backend.open_dataset_parameters,
   (...)    615     decode_coords=decode_coords,
    616 )
    618 overwrite_encoded_chunks = kwargs.pop("overwrite_encoded_chunks", None)
--> 619 backend_ds = backend.open_dataset(
    620     filename_or_obj,
    621     drop_variables=drop_variables,
    622     **decoders,
    623     **kwargs,
    624 )
    625 ds = _dataset_from_backend_dataset(
    626     backend_ds,
    627     filename_or_obj,
   (...)    638     **kwargs,
    639 )
    640 return ds

File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/xarray/backends/netCDF4_.py:797, in NetCDF4BackendEntrypoint.open_dataset(self, filename_or_obj, mask_and_scale, decode_times, concat_characters, decode_coords, drop_variables, use_cftime, decode_timedelta, group, mode, format, clobber, diskless, persist, auto_complex, lock, autoclose)
    775 def open_dataset(
    776     self,
    777     filename_or_obj: T_PathFileOrDataStore,
   (...)    794     autoclose=False,
    795 ) -> Dataset:
    796     filename_or_obj = _normalize_path(filename_or_obj)
--> 797     store = NetCDF4DataStore.open(
    798         filename_or_obj,
    799         mode=mode,
    800         format=format,
    801         group=group,
    802         clobber=clobber,
    803         diskless=diskless,
    804         persist=persist,
    805         auto_complex=auto_complex,
    806         lock=lock,
    807         autoclose=autoclose,
    808     )
    810     store_entrypoint = StoreBackendEntrypoint()
    811     with close_on_error(store), store._manager.acquire_context():

File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/xarray/backends/netCDF4_.py:555, in NetCDF4DataStore.open(cls, filename, mode, format, group, clobber, diskless, persist, auto_complex, lock, lock_maker, autoclose)
    551 else:
    552     manager = CachingFileManager(
    553         netCDF4.Dataset, filename, mode=mode, kwargs=kwargs, lock=lock
    554     )
--> 555 return cls(manager, group=group, mode=mode, lock=lock, autoclose=autoclose)

File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/xarray/backends/netCDF4_.py:454, in NetCDF4DataStore.__init__(self, manager, group, mode, lock, autoclose)
    452 self._group = group
    453 self._mode = mode
--> 454 with manager.acquire_context():
    455     self.format = self.ds.data_model
    456     self._filename = self.ds.filepath()

File ~/micromamba/envs/gdex-cookbook/lib/python3.12/contextlib.py:137, in _GeneratorContextManager.__enter__(self)
    135 del self.args, self.kwds, self.func
    136 try:
--> 137     return next(self.gen)
    138 except StopIteration:
    139     raise RuntimeError("generator didn't yield") from None

File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/xarray/backends/file_manager.py:235, in CachingFileManager.acquire_context(self, needs_lock)
    229 """Context manager for acquiring a file.
    230 
    231 The file stays open until the context exits, even if it is evicted
    232 from the cache in the meantime.
    233 """
    234 with self._pinned():
--> 235     file, cached = self._acquire_with_cache_info(needs_lock)
    236     try:
    237         yield file

File ~/micromamba/envs/gdex-cookbook/lib/python3.12/site-packages/xarray/backends/file_manager.py:278, in CachingFileManager._acquire_with_cache_info(self, needs_lock)
    276     kwargs = kwargs.copy()
    277     kwargs["mode"] = self._mode
--> 278 file = self._opener(*self._args, **kwargs)
    279 if self._mode == "w":
    280     # ensure file doesn't get overridden when opened again
    281     self._mode = "a"

File src/netCDF4/_netCDF4.pyx:2525
-> 2525 'Could not get source, probably due dynamically evaluated source code.'

File src/netCDF4/_netCDF4.pyx:2162
-> 2162 'Could not get source, probably due dynamically evaluated source code.'

OSError: [Errno -68] NetCDF: I/O failure: 'https://thredds.rda.ucar.edu/thredds/dodsC/files/g/d633000/e5.oper.an.pl/202001/e5.oper.an.pl.128_130_t.ll025sc.2020010100_2020010123.nc'

Selecting a Subset and Plotting

In this section, we subset temperature from the lazy-loaded dataset (ds_lazy) over a USA domain and visualize two pressure levels at the first time step.

  • Region: roughly CONUS (latitude: 55 → 20, longitude: 230 → 300 in 0–360 coordinates)

  • Time: first analysis hour (time=0)

  • Levels to compare:

    • 1000 hPa (lowest model pressure level; near-surface pattern)

    • 500 hPa (upper-air/mid-tropospheric pattern)

This demonstrates that with lazy loading, xarray only fetches the selected subset and levels needed for plotting, not the full global 4 GB field.


Summary

xarray’s OPeNDAP support turns GDEX THREDDS into a remote analysis environment — no local copy needed. Lazy evaluation means you only fetch the data you actually use.

What’s next?

See zarr_intro.ipynb for cloud-optimized Zarr access, which is often faster for large array operations.