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.


Overview

Output from one run of CESM is the main dataset that we’ll be looking at in this cookbook. Let’s learn how to read it in. And note that this is just one way that CESM output can look. This run has been post-processed, so the data are in the form of “time-series” files, where each file stores one variable across the full timespan of the run. Before this processing, CESM actually outputs data in the form of “history” files instead, where each file contains all variables over a shorter time-slice. We won’t dive into the specifics of CESM data processing here, but this Jupyter book from the CESM tutorial has some more info!

Prerequisites

ConceptsImportanceNotes
Intro to XarrayNecessary
  • Time to learn: 5 min


Imports

Loading our data into xarray

Our data is stored in the cloud on Jetstream2. We load in each file path, then use xarray’s open_mfdataset() function to load all the files into an xarray Dataset, dropping a few variables whose coordinates don’t fit nicely.

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[2], line 14
     10 # Open all files from folder
     11 fileset = [s3.open(file) for file in remote_files]
     12 
     13 # Open with xarray
---> 14 ds = xr.open_mfdataset(fileset, data_vars="minimal", coords='minimal', compat="override", parallel=True,
     15                        drop_variables=["transport_components", "transport_regions", 'moc_components'], decode_times=True)

File ~/micromamba/envs/ocean-bgc-cookbook-dev/lib/python3.14/site-packages/xarray/backends/api.py:1674, in open_mfdataset(paths, chunks, concat_dim, compat, preprocess, engine, data_vars, coords, combine, parallel, join, attrs_file, combine_attrs, errors, **kwargs)
   1669     datasets = [preprocess(ds) for ds in datasets]
   1671 if parallel:
   1672     # calling compute here will return the datasets/file_objs lists,
   1673     # the underlying datasets will still be stored as dask arrays
-> 1674     datasets, closers = dask.compute(datasets, closers)
   1676 # Combine all datasets, closing them in case of a ValueError
   1677 try:

File ~/micromamba/envs/ocean-bgc-cookbook-dev/lib/python3.14/site-packages/dask/base.py:769, in compute(traverse, optimize_graph, scheduler, get, *args, **kwargs)
    766     expr = expr.optimize()
    767     keys = list(flatten(expr.__dask_keys__()))
--> 769     results = schedule(expr, keys, **kwargs)
    771 return repack(results)

File ~/micromamba/envs/ocean-bgc-cookbook-dev/lib/python3.14/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/ocean-bgc-cookbook-dev/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py:558, in H5netcdfBackendEntrypoint.open_dataset(self, filename_or_obj, mask_and_scale, decode_times, concat_characters, decode_coords, drop_variables, use_cftime, decode_timedelta, format, group, lock, invalid_netcdf, phony_dims, decode_vlen_strings, driver, driver_kwds, storage_options, open_kwargs)
    555 emit_phony_dims_warning, phony_dims = _check_phony_dims(phony_dims)
    557 filename_or_obj = _normalize_filename_or_obj(filename_or_obj)
--> 558 store = H5NetCDFStore.open(
    559     filename_or_obj,
    560     format=format,
    561     group=group,
    562     lock=lock,
    563     invalid_netcdf=invalid_netcdf,
    564     phony_dims=phony_dims,
    565     decode_vlen_strings=decode_vlen_strings,
    566     driver=driver,
    567     driver_kwds=driver_kwds,
    568     storage_options=storage_options,
    569     open_kwargs=open_kwargs,
    570 )
    572 store_entrypoint = StoreBackendEntrypoint()
    574 with store._manager.acquire_context():

File ~/micromamba/envs/ocean-bgc-cookbook-dev/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py:257, in H5NetCDFStore.open(cls, filename, mode, format, group, lock, autoclose, invalid_netcdf, phony_dims, decode_vlen_strings, driver, driver_kwds, storage_options, open_kwargs)
    250         lock = combine_locks([HDF5_LOCK, get_write_lock(filename)])
    252 manager_cls = (
    253     CachingFileManager
    254     if isinstance(filename, str) and not is_remote_uri(filename)
    255     else PickleableFileManager
    256 )
--> 257 manager = manager_cls(h5netcdf.File, filename, mode=mode, kwargs=kwargs)
    259 return cls(
    260     manager,
    261     group=group,
   (...)    265     autoclose=autoclose,
    266 )

File ~/micromamba/envs/ocean-bgc-cookbook-dev/lib/python3.14/site-packages/xarray/backends/file_manager.py:428, in PickleableFileManager.__init__(self, opener, mode, lock, kwargs, *args)
    426 if mode != _OMIT_MODE:
    427     kwargs = kwargs | {"mode": mode}
--> 428 self._file: T_File | None = opener(*args, **kwargs)

File ~/micromamba/envs/ocean-bgc-cookbook-dev/lib/python3.14/site-packages/h5netcdf/core.py:1876, in File.__init__(self, path, mode, format, invalid_netcdf, phony_dims, backend, **kwargs)
   1873 self._preexisting_file = True
   1875 try:
-> 1876     self._backend = _parse_backend(path, mode, backend, **kwargs)
   1877     if self.backend == "pyfive":
   1878         self._unsupported_hdf5_features = kwargs.pop(
   1879             "unsupported_hdf5_features",
   1880             os.environ.get("PYFIVE_UNSUPPORTED_FEATURE", "error"),
   1881         )

File ~/micromamba/envs/ocean-bgc-cookbook-dev/lib/python3.14/site-packages/h5netcdf/core.py:169, in _parse_backend(path, mode, backend, **kwargs)
    162 no_backend = {
    163     "pyfive": no_pyfive,
    164     "h5py": no_h5py,
    165     "h5pyd": no_h5pyd,
    166 }
    168 if no_backend.get(backend, False):
--> 169     raise ImportError(
    170         f"No module named {backend!r}, backend not available. "
    171         f"Please install {backend!r} into your Python environment."
    172     )
    174 return backend

ImportError: No module named 'h5py', backend not available. Please install 'h5py' into your Python environment.

Looks good!


Summary

You’ve learned how to read in CESM output, which we’ll be using for all the following notebooks in this cookbook.