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.

Parallelizing Xarray with Dask

Dask logo Xarray

In this tutorial, you learn:

  • Using Dask with Xarray

  • Read/write netCDF files with Dask

  • Dask backed Xarray objects and operations

  • Extract Dask arrays from Xarray objects and use Dask array directly.

  • Xarray built-in operations can transparently use dask

Prerequisites

ConceptsImportanceNotes
Intro to XarrayNecessary
Dask ArraysNecessary
Dask DataFramesNecessary
  • Time to learn: 40 minutes


Introduction

Xarray Quick Overview

Xarray is an open-source Python library designed for working with labelled multi-dimensional data. By multi-dimensional data (also often called N-dimensional), we mean data that has many independent dimensions or axes (e.g. latitude, longitude, time). By labelled we mean that these axes or dimensions are associated with coordinate names (like “latitude”) and coordinate labels like “30 degrees North”.

Xarray provides pandas-level convenience for working with this type of data.

Xarray

Image credit: Xarray Contributors

The dataset illustrated has two variables (temperature and precipitation) that have three dimensions. Coordinate vectors (e.g., latitude, longitude, time) that describe the data are also included.

Xarray Data Structures

Xarray has two fundamental data structures:

  • DataArray : holds a single multi-dimensional variable and its coordinates

  • Dataset : holds multiple DataArrays that potentially share the same coordinates

Xarray DataArray

A DataArray has four essential attributes:

  • data: a numpy.ndarray holding the values.

  • dims: dimension names for each axis (e.g., latitude, longitude, time).

  • coords: a dict-like container of arrays (coordinates) that label each point (e.g., 1-dimensional arrays of numbers, datetime objects or strings).

  • attrs: a dictionary to hold arbitrary metadata (attributes).

Xarray DataSet

A dataset is simply an object containing multiple Xarray DataArrays indexed by variable name.

Xarray can wrap many array types like Numpy and Dask.

Let’s start with a random 2D NumPy array, for example this can be SST (sea-surface temperature) values of a domain with dimension of 300x450 grid:

numpy.ndarray

As we saw in the previous tutorial, we can convert them to a Dask Array:

Loading...

This is great and fast! BUT

  • What if we want to attach coordinate values to this array?

  • What if we want to add metadata (e.g. units) to this array?

Loading...

A simple DataArray without dimensions or coordinates isn’t much use.

('lat', 'lon')

We can add our coordinates with values to it :

Loading...

Xarray data structures are a very powerful tool that allows us to use metadata to express different analysis patterns (slicing, selecting, groupby, averaging, and many other things).

Take Away

Xarray DataArray provides a wrapper around arrays, and uses labeled dimensions and coordinates to support metadata-aware operations (e.g. da.sum(dim="time") instead of array.sum(axis=-1))

Xarray can wrap dask arrays instead of numpy arrays.

This capability turns Xarray into an extremely useful tool for Big Data earth science.

With this introduction, let’s start our tutorial on features of Xarray and Dask:

Setup: Spinning up a cluster

Loading...

Reading data with Dask and Xarray

Reading multiple netCDF files with open_mfdataset

Xarray provides a function called open_dataset function that allows us to load a netCDF dataset into a Python data structure. To read more about this function, please see xarray open_dataset API documentation.

Xarray also provides open_mfdataset, which open multiple files as a single xarray dataset. Passing the argument parallel=True will speed up reading multiple datasets by executing these tasks in parallel using Dask Delayed under the hood.

In this example, we are going to examine a subset of CESM2 Large Ensemble Data Sets (LENS). We will use 2m temperature (TREFHT) for this analysis.

To learn more about LENS dataset, please visit:

For this tutorial, we only look at a small subset of data. If you don’t have the data, running the following code enables you to download, prepare, and stage the required datasets (../data/ folder) for this cookbook.

Downloading...
From (original): https://drive.google.com/uc?id=1Tbuom1KMCwHjy7-eexEQcOXSr51i6mae
From (redirected): https://drive.google.com/uc?id=1Tbuom1KMCwHjy7-eexEQcOXSr51i6mae&confirm=t&uuid=67bfc67c-7860-463a-bb5b-6eea3e9a1d77
To: /home/runner/work/dask-cookbook/dask-cookbook/data/data.tar.gz
  0%|          | 0.00/127M [00:00<?, ?B/s]
  5%|▍         | 6.29M/127M [00:00<00:02, 59.3MB/s]
 12%|█▏        | 15.7M/127M [00:00<00:01, 78.5MB/s]
 19%|█▉        | 24.1M/127M [00:00<00:01, 77.4MB/s]
 25%|██▌       | 32.0M/127M [00:00<00:01, 76.9MB/s]
 35%|███▌      | 44.6M/127M [00:00<00:00, 93.9MB/s]
 43%|████▎     | 54.5M/127M [00:00<00:01, 61.5MB/s]
 52%|█████▏    | 66.1M/127M [00:00<00:00, 73.1MB/s]
 62%|██████▏   | 78.1M/127M [00:00<00:00, 84.2MB/s]
 70%|██████▉   | 88.1M/127M [00:01<00:00, 70.5MB/s]
 77%|███████▋  | 97.0M/127M [00:01<00:00, 71.9MB/s]
 88%|████████▊ | 112M/127M [00:01<00:00, 88.9MB/s] 
 96%|█████████▌| 122M/127M [00:01<00:00, 84.6MB/s]
100%|██████████| 127M/127M [00:01<00:00, 79.4MB/s]

We can open up multiple files using open_mfdataset function.

Constructing Xarray Datasets from files

All files: [ 9 files]
2026-11-29 06:01:41,523 - distributed.worker - ERROR - Compute Failed
Key:       open_dataset-65695b5f-1c73-47fc-8efe-dbc27fd8615d
State:     executing
Task:  <Task 'open_dataset-65695b5f-1c73-47fc-8efe-dbc27fd8615d' open_dataset(..., ...)>
Exception: 'ImportError("No module named \'h5py\', backend not available. Please install \'h5py\' into your Python environment.")'
Traceback: '  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/api.py", line 619, in open_dataset\n    backend_ds = backend.open_dataset(\n        filename_or_obj,\n    ...<2 lines>...\n        **kwargs,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 558, in open_dataset\n    store = H5NetCDFStore.open(\n        filename_or_obj,\n    ...<9 lines>...\n        open_kwargs=open_kwargs,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 259, in open\n    return cls(\n        manager,\n    ...<4 lines>...\n        autoclose=autoclose,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 152, in __init__\n    with manager.acquire_context():\n         ~~~~~~~~~~~~~~~~~~~~~~~^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/contextlib.py", line 141, in __enter__\n    return next(self.gen)\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py", line 235, in acquire_context\n    file, cached = self._acquire_with_cache_info(needs_lock)\n                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py", line 278, in _acquire_with_cache_info\n    file = self._opener(*self._args, **kwargs)\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/h5netcdf/core.py", line 1876, in __init__\n    self._backend = _parse_backend(path, mode, backend, **kwargs)\n                    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/h5netcdf/core.py", line 169, in _parse_backend\n    raise ImportError(\n    ...<2 lines>...\n    )\n'

2026-11-29 06:01:41,534 - distributed.worker - ERROR - Compute Failed
Key:       open_dataset-2eb712c3-0797-4d6f-9c47-ad027de1ac56
State:     executing
Task:  <Task 'open_dataset-2eb712c3-0797-4d6f-9c47-ad027de1ac56' open_dataset(..., ...)>
Exception: 'ImportError("No module named \'h5py\', backend not available. Please install \'h5py\' into your Python environment.")'
Traceback: '  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/api.py", line 619, in open_dataset\n    backend_ds = backend.open_dataset(\n        filename_or_obj,\n    ...<2 lines>...\n        **kwargs,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 558, in open_dataset\n    store = H5NetCDFStore.open(\n        filename_or_obj,\n    ...<9 lines>...\n        open_kwargs=open_kwargs,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 259, in open\n    return cls(\n        manager,\n    ...<4 lines>...\n        autoclose=autoclose,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 152, in __init__\n    with manager.acquire_context():\n         ~~~~~~~~~~~~~~~~~~~~~~~^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/contextlib.py", line 141, in __enter__\n    return next(self.gen)\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py", line 235, in acquire_context\n    file, cached = self._acquire_with_cache_info(needs_lock)\n                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py", line 278, in _acquire_with_cache_info\n    file = self._opener(*self._args, **kwargs)\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/h5netcdf/core.py", line 1876, in __init__\n    self._backend = _parse_backend(path, mode, backend, **kwargs)\n                    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/h5netcdf/core.py", line 169, in _parse_backend\n    raise ImportError(\n    ...<2 lines>...\n    )\n'

2026-11-29 06:01:41,540 - distributed.worker - ERROR - Compute Failed
Key:       open_dataset-17ef0471-458e-4229-8526-70120577e9f1
State:     executing
Task:  <Task 'open_dataset-17ef0471-458e-4229-8526-70120577e9f1' open_dataset(..., ...)>
Exception: 'ImportError("No module named \'h5py\', backend not available. Please install \'h5py\' into your Python environment.")'
Traceback: '  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/api.py", line 619, in open_dataset\n    backend_ds = backend.open_dataset(\n        filename_or_obj,\n    ...<2 lines>...\n        **kwargs,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 558, in open_dataset\n    store = H5NetCDFStore.open(\n        filename_or_obj,\n    ...<9 lines>...\n        open_kwargs=open_kwargs,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 259, in open\n    return cls(\n        manager,\n    ...<4 lines>...\n        autoclose=autoclose,\n    )\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py", line 152, in __init__\n    with manager.acquire_context():\n         ~~~~~~~~~~~~~~~~~~~~~~~^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/contextlib.py", line 141, in __enter__\n    return next(self.gen)\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py", line 235, in acquire_context\n    file, cached = self._acquire_with_cache_info(needs_lock)\n                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py", line 278, in _acquire_with_cache_info\n    file = self._opener(*self._args, **kwargs)\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/h5netcdf/core.py", line 1876, in __init__\n    self._backend = _parse_backend(path, mode, backend, **kwargs)\n                    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File "/home/runner/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/h5netcdf/core.py", line 169, in _parse_backend\n    raise ImportError(\n    ...<2 lines>...\n    )\n'

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py:265, in _acquire_with_cache_info()
    264 try:
--> 265     file = self._cache[self._key]
    266 except KeyError:

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

KeyError: [<class 'h5netcdf.core.File'>, ('/home/runner/work/dask-cookbook/dask-cookbook/data/data_for_cesm/b.e21.BSSP370smbb.f09_g17.LE2-1301.013.cam.h0.TREFHT.208501-209412.nc',), 'r', (('decode_vlen_strings', True), ('driver', None), ('format', 'NETCDF4'), ('invalid_netcdf', None), ('phony_dims', 'access')), '3e36acc0-e851-4ce8-9679-9b8a97a77e25']

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
File <timed exec>:1

File ~/micromamba/envs/dask-cookbook/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/dask-cookbook/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/dask-cookbook/lib/python3.14/site-packages/xarray/backends/api.py:619, in open_dataset()
    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/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py:558, in open_dataset()
    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/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py:259, in open()
    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,
    262     format=format,
    263     mode=mode,
    264     lock=lock,
    265     autoclose=autoclose,
    266 )

File ~/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/h5netcdf_.py:152, in __init__()
    149 self.format = format or "NETCDF4"
    150 # todo: utilizing find_root_and_group seems a bit clunky
    151 #  making filename available on h5netcdf.Group seems better
--> 152 with manager.acquire_context():
    153     self._filename = find_root_and_group(self.ds)[0].filename
    154 self.is_remote = is_remote_uri(self._filename)

File ~/micromamba/envs/dask-cookbook/lib/python3.14/contextlib.py:141, in __enter__()
    139 del self.args, self.kwds, self.func
    140 try:
--> 141     return next(self.gen)
    142 except StopIteration:
    143     raise RuntimeError("generator didn't yield") from None

File ~/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py:235, in acquire_context()
    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/dask-cookbook/lib/python3.14/site-packages/xarray/backends/file_manager.py:278, in _acquire_with_cache_info()
    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 ~/micromamba/envs/dask-cookbook/lib/python3.14/site-packages/h5netcdf/core.py:1876, in __init__()
   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/dask-cookbook/lib/python3.14/site-packages/h5netcdf/core.py:169, in _parse_backend()
    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.

For complex scenarios, you can access each file individually by utilizing the open_dataset function with the specified chunks and then combine the outputs into a single dataset later.

Note that the “real” values are not displayed, since that would trigger actual computation.

Xarray automatically wraps Dask Arrays and Dask is lazy, meaning that operations are not computed until we explicitly request them, for example by calling .compute().

Please see previous notebooks for more information on “lazy evaluation”.

The represntation of TREFHT DataArray shows details of chunks and chunk-sizes of Xarray DataArray:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[11], line 1
----> 1 tref = ds.TREFHT
      2 tref

NameError: name 'ds' is not defined
  • How many chunks do we have?

  • What is the size of each chunk size?

Here we can see that we have a total of 9 chunks - equal to the number of our netCDF files. In general open_mfdataset will return one chunk per netCDF file.

WARNING: The chunk structure within the file is important. When re-chunking the dataset after creation with ds.chunk() it is recommended to only use multiples of the on-file chunk shape.

We can check what that shape is by looking at the encoding:

TIP: The chunks parameter can significantly affect total performance when using Dask Arrays. chunks should be small enough that each chunk fit in the memory, but large enough to avoid that the communication overhead.

A good rule of thumb is to create arrays with a minimum chunksize of at least one million elements. Here we have 120x192x288 elements in each chunk (except for the last chunk).
With large arrays (10+ GB), the cost of queuing up Dask operations can be noticeable, and you may need even larger chunksizes.

Additional Reading

Xarray data structures are Dask collections.

This means you can call the following Dask-related functions on Xarray Data Arrays and Datasets:

  • .visualize()

  • .compute()

  • .persist()

For more information about Dask Arrays, please see Dask Array chapter.

If we check Dask Task Graph for tref_mean, we can see all the steps required for calculating it (from opening the netcdf file to calculating mean and aggreagting it).

Getting concrete values

At some point, you will want to actually do the calculations and receive concrete values from Dask.

There are two ways to compute values on dask arrays.

  1. compute() returns a new xarray object with the data now represented as a numpy array.

  2. load() replaces the dask array in the xarray object with a numpy array. Equivalent to ds = ds.compute().

.load() operates inplace and .compute() returns a new xarray object.

Distributed non-blocking concrete values

There is another option available third option : “persisting”. .persist() loads the values into distributed RAM. The values are computed but remain distributed across workers. So essentially persist turns a lazy Dask collection into a Dask collection where the results are either fully computed or actively computing in the background.

So ds.air.persist() is still backed by a Dask array. This is useful if you will be repeatedly using a dataset for computation but it is too large to load into local memory.

Read more: Dask user guide

How to access underlying data in an Xarray object?

There are two basic ways to extract values from an Xarray object:

  1. Using .data will return a Dask array. For example:

This means that for Dask-backed Xarray object, we can access the values using .compute

  1. We can also use .values to see the “real” values of Xarray object. Another option is using .to_numpy. Both of these option return the values of underlying Dask object in a numpy array.

Computation

All built-in Xarray methods (.mean, .max, .rolling, .groupby etc.) support dask arrays.

Now, let’s do some computations on this Xarray dataset.

Single Point Calculations

To start out, let’s do the calculations on a single point first. First, we extract the time series data at a grid point and save it to a variable. Here we select the closest point using .sel and load the data.

WARNING: Remember as soon as you call .load() you are telling Dask to trigger computation.

We can either see the values of our DataArray in the text representation above or by plotting it:

Calculations over all grids

TIP: Using Xarray plotting functionality automatically triggers computations on the Dask Array, similar to .compute().

We can do more complex calculations too:

Supplementary Material: Advanced workflows and automatic parallelization using apply_ufunc

Most of xarray’s built-in operations work on Dask arrays. If you want to use a function that isn’t wrapped by Xarray to work with Dask, one option is to extract Dask arrays from xarray objects (.data) and use Dask directly.

Another option is to use xarray’s apply_ufunc() function. xr.apply_ufunc() can automate embarrassingly parallel “map” type operations where a function written for processing NumPy arrays, but we want to apply it on our Xarray DataArray.

xr.apply_ufunc() give users capability to run custom-written functions such as parameter calculations in a parallel way. See the Xarray tutorial material on apply_ufunc for more.

In the example below, we calculate the saturation vapor pressure by using apply_ufunc() to apply this function to our Dask Array chunk by chunk.

The data used for this tutorial is from one ensemble member. What if we want to use multiple ensemble members? So far, we only run on one machine, what if we run an HPC cluster? We will go over this in the next tutorial.

Dask + Xarray Good Practices

Summary of Dask + Xarray Good Practices

The good practices regarding Dask + Xarray is the same as the good practices for Dask only.

  • Similar to Dask DataFrames, it is more efficient to first do spatial and temporal indexing (e.g. .sel() or .isel()) and filter the dataset early in the pipeline, especially before calling resample() or groupby().

  • Chunk sizes should be small enough to fit into the memory at once but large enough to avoid the additional communication overhead. Good chunk size ~100 MB.

  • It is always better to chunk along the time dimension.

  • Avoid too many tasks since each task will introduce 1ms of overhead.

  • When possible, use xr.apply_ufunc to apply an unvectorized function to the Xarray object.

Close you local Dask Cluster

It is always a good practice to close the Dask cluster you created.

Summary

In this notebook, we have learned about:

  • Using Dask with Xarray

  • Read/write netCDF files with Dask

  • Dask backed Xarray objects and operations

  • Extract Dask arrays from Xarray objects and use Dask array directly..

  • Customized workflows using apply_ufunc

Resources and references

Reference

Ask for help