Overview¶
xarray can open remote OPeNDAP datasets directly from the GDEX THREDDS server, enabling lazy, memory-efficient access without downloading files.
Construct an OPeNDAP URL from the TDS catalog
Open the dataset lazily with xarray
Select a spatial and temporal subset
Plot the result
Prerequisites¶
| Concepts | Importance | Notes |
|---|---|---|
| tds_intro | Necessary | GDEX TDS catalog and OPeNDAP concept |
| xarray | Necessary | |
| matplotlib / cartopy | Helpful | Visualization |
Time to learn: 20 minutes
Imports¶
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrsBuilding an OPeNDAP URL¶
OPeNDAP URLs on the GDEX TDS follow the pattern:
https://thredds.rda.ucar.edu/thredds/dodsC/<path-to-file>
# Construct the OPeNDAP URL for your target file
OPeNDAP_URL = (
"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"
)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.
import os
import psutil
# check the memory usage of the current notebook process only
process = psutil.Process(os.getpid())
mem_info = process.memory_info()
print(f"Notebook process memory usage: {mem_info.rss / (1024 ** 2):.2f} MB (RSS)")Notebook process memory usage: 192.37 MB (RSS)
import xarray as xr
# Open the remote dataset
ds_lazy = xr.open_dataset(OPeNDAP_URL, engine="netcdf4", chunks={})
ds_lazyERR: 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'mem_info = process.memory_info()
print(f"Notebook process memory usage: {mem_info.rss / (1024 ** 2):.2f} MB (RSS)")# Open the remote dataset
ds_load = xr.open_dataset(OPeNDAP_URL, engine="netcdf4").isel(time=0).load()
ds_loadmem_info = process.memory_info()
print(f"Notebook process memory usage: {mem_info.rss / (1024 ** 2):.2f} MB (RSS)")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 → 300in 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.
# Subset from lazy dataset: CONUS-like box, first time step, two pressure levels
subset = ds_lazy["T"].isel(time=0).sel(
level=[1000, 500],
latitude=slice(55, 20),
longitude=slice(230, 300),
)
fig, axes = plt.subplots(
1, 2, figsize=(13, 4.5),
subplot_kw={"projection": ccrs.PlateCarree()}
)
for ax, lev in zip(axes, [1000, 500]):
da = subset.sel(level=lev)
im = da.plot(
ax=ax,
transform=ccrs.PlateCarree(),
cmap="coolwarm",
add_colorbar=False
)
ax.coastlines()
ax.set_extent([230, 300, 20, 55], crs=ccrs.PlateCarree())
ax.set_title(f"T at {lev} hPa (time=0)")
fig.colorbar(im, ax=axes, orientation="horizontal", pad=0.08, label="Temperature (K)")
plt.tight_layout()
# Use RdBu_r colormap on both panels (and linked colorbar mappable)
for a in axes:
if a.collections:
a.collections[0].set_cmap("RdBu_r")
im.set_cmap("RdBu_r")
# Put actual datetime in titles
time_str = subset.time.dt.strftime("%Y-%m-%d %H:%M UTC").item()
for a, lev in zip(axes, subset.level.values):
a.set_title(f"T at {int(lev)} hPa ({time_str})")
# Move colorbar down to avoid overlap
fig.subplots_adjust(bottom=0.18)
cbar_ax = fig.axes[-1]
pos = cbar_ax.get_position()
cbar_ax.set_position([pos.x0, pos.y0 - 0.1, pos.width, pos.height])
plt.show()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.