You can run this notebook in a live session Binder or view it on Github.

Xarray with Dask Arrays

`Xarray <http://xarray.pydata.org/en/stable/>`__ is an open source project and Python package that extends the labeled data functionality of Pandas to N-dimensional array-like datasets. It shares a similar API to NumPy and Pandas and supports both Dask and NumPy arrays under the hood.

In [1]:
%matplotlib inline

from dask.distributed import Client
import xarray as xr

Start Dask Client for Dashboard

Starting the Dask Client is optional. It will provide a dashboard which is useful to gain insight on the computation.

The link to the dashboard will become visible when you create the client below. We recommend having it open on one side of your screen while using your notebook on the other side. This can take some effort to arrange your windows, but seeing them both at the same is very useful when learning.

In [2]:
client = Client(n_workers=2, threads_per_worker=2, memory_limit='1GB')
client
Out[2]:

Client

Cluster

  • Workers: 2
  • Cores: 4
  • Memory: 2.00 GB

Open a sample dataset

We will use some of xarray’s tutorial data for this example. By specifying the chunk shape, xarray will automatically create Dask arrays for each data variable in the Dataset. In xarray, Datasets are dict-like container of labeled arrays, analogous to the pandas.DataFrame. Note that we’re taking advantage of xarray’s dimension labels when specifying chunk shapes.

In [3]:
ds = xr.tutorial.open_dataset('air_temperature',
                              chunks={'lat': 25, 'lon': 25, 'time': -1})
ds
Out[3]:
<xarray.Dataset>
Dimensions:  (lat: 25, lon: 53, time: 2920)
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
  * time     (time) datetime64[ns] 2013-01-01 ... 2014-12-31T18:00:00
Data variables:
    air      (time, lat, lon) float32 dask.array<shape=(2920, 25, 53), chunksize=(2920, 25, 25)>
Attributes:
    Conventions:  COARDS
    title:        4x daily NMC reanalysis (1948)
    description:  Data is from NMC initialized reanalysis\n(4x/day).  These a...
    platform:     Model
    references:   http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanaly...

Quickly inspecting the Dataset above, we’ll note that this Dataset has three dimensions akin to axes in NumPy (lat, lon, and time), three coordinate variables akin to pandas.Index objects (also named lat, lon, and time), and one data variable (air). Xarray also holds Dataset specific metadata in as attributes.

In [4]:
da = ds['air']
da
Out[4]:
<xarray.DataArray 'air' (time: 2920, lat: 25, lon: 53)>
dask.array<shape=(2920, 25, 53), dtype=float32, chunksize=(2920, 25, 25)>
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
  * time     (time) datetime64[ns] 2013-01-01 ... 2014-12-31T18:00:00
Attributes:
    long_name:     4xDaily Air temperature at sigma level 995
    units:         degK
    precision:     2
    GRIB_id:       11
    GRIB_name:     TMP
    var_desc:      Air temperature
    dataset:       NMC Reanalysis
    level_desc:    Surface
    statistic:     Individual Obs
    parent_stat:   Other
    actual_range:  [185.16 322.1 ]

Each data variable in xarray is called a DataArray. These are the fundemental labeled array object in xarray. Much like the Dataset, DataArrays also have dimensions and coordinates that support many of its label-based opperations.

In [5]:
da.data
Out[5]:
dask.array<open_dataset-6a245df4b0e00bdd8e5306ca1e90064cair, shape=(2920, 25, 53), dtype=float32, chunksize=(2920, 25, 25)>

Accessing the underlying array of data is done via the data property. Here we can see that we have a Dask array. If this array were to be backed by a NumPy array, this property would point to the actual values in the array.

Use Standard Xarray Operations

In almost all cases, operations using xarray objects are identical, regardless if the underlying data is stored as a Dask array or a NumPy array.

In [6]:
da2 = da.groupby('time.month').mean('time')
da3 = da - da2
da3
Out[6]:
<xarray.DataArray 'air' (time: 2920, lat: 25, lon: 53, month: 12)>
dask.array<shape=(2920, 25, 53, 12), dtype=float32, chunksize=(2920, 25, 25, 1)>
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
  * time     (time) datetime64[ns] 2013-01-01 ... 2014-12-31T18:00:00
  * month    (month) int64 1 2 3 4 5 6 7 8 9 10 11 12

Call .compute() or .load() when you want your result as a xarray.DataArray with data stored as NumPy arrays.

If you started Client() above then you may want to watch the status page during computation.

In [7]:
computed_da = da3.load()
type(computed_da.data)
Out[7]:
numpy.ndarray
In [8]:
computed_da
Out[8]:
<xarray.DataArray 'air' (time: 2920, lat: 25, lon: 53, month: 12)>
array([[[[-5.149872, ..., -6.770996],
         ...,
         [-7.046707, ..., -4.028244]],

        ...,

        [[-0.864166, ..., -1.590881],
         ...,
         [ 0.963531, ..., -0.937622]]],


       ...,


       [[[-1.259872, ..., -2.880997],
         ...,
         [-3.856705, ..., -0.838242]],

        ...,

        [[ 0.535828, ..., -0.190887],
         ...,
         [ 0.053528, ..., -1.847626]]]], dtype=float32)
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
  * time     (time) datetime64[ns] 2013-01-01 ... 2014-12-31T18:00:00
  * month    (month) int64 1 2 3 4 5 6 7 8 9 10 11 12

Persist data in memory

If you have the available RAM for your dataset then you can persist data in memory.

This allows future computations to be much faster.

In [9]:
da = da.persist()

Time Series Operations

Because we have a datetime index time-series operations work efficiently. Here we demo the use of xarray’s resample method:

In [10]:
da.resample(time='1w').mean('time').std('time')
Out[10]:
<xarray.DataArray 'air' (lat: 25, lon: 53)>
dask.array<shape=(25, 53), dtype=float32, chunksize=(25, 25)>
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
In [11]:
da.resample(time='1w').mean('time').std('time').load().plot(figsize=(12, 8))
Out[11]:
<matplotlib.collections.QuadMesh at 0x7fcb352e49b0>
_images/xarray_20_1.png

and rolling window operations:

In [12]:
da_smooth = da.rolling(time=30).mean().persist()
da_smooth
Out[12]:
<xarray.DataArray '_trim-3da13017d4cd6a868d33f2a021eb99bd' (time: 2920, lat: 25, lon: 53)>
dask.array<shape=(2920, 25, 53), dtype=float32, chunksize=(2920, 25, 25)>
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
  * time     (time) datetime64[ns] 2013-01-01 ... 2014-12-31T18:00:00

Since xarray stores each of its coordinate variables in memory, slicing by label is trivial and entirely lazy.

In [13]:
%time da.sel(time='2013-01-01T18:00:00')
CPU times: user 8 ms, sys: 0 ns, total: 8 ms
Wall time: 7.82 ms
Out[13]:
<xarray.DataArray 'air' (lat: 25, lon: 53)>
dask.array<shape=(25, 53), dtype=float32, chunksize=(25, 25)>
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
    time     datetime64[ns] 2013-01-01T18:00:00
Attributes:
    long_name:     4xDaily Air temperature at sigma level 995
    units:         degK
    precision:     2
    GRIB_id:       11
    GRIB_name:     TMP
    var_desc:      Air temperature
    dataset:       NMC Reanalysis
    level_desc:    Surface
    statistic:     Individual Obs
    parent_stat:   Other
    actual_range:  [185.16 322.1 ]
In [14]:
%time da.sel(time='2013-01-01T18:00:00').load()
CPU times: user 40 ms, sys: 0 ns, total: 40 ms
Wall time: 49.4 ms
Out[14]:
<xarray.DataArray 'air' (lat: 25, lon: 53)>
array([[241.89   , 241.79999, 241.79999, ..., 234.39   , 235.5    , 237.59999],
       [246.29999, 245.29999, 244.2    , ..., 230.89   , 231.5    , 234.5    ],
       [256.6    , 254.7    , 252.09999, ..., 230.7    , 231.79999, 236.09999],
       ...,
       [296.6    , 296.4    , 296.     , ..., 296.5    , 295.79   , 295.29   ],
       [297.     , 297.5    , 297.1    , ..., 296.79   , 296.6    , 296.29   ],
       [297.5    , 297.69998, 297.5    , ..., 297.79   , 298.     , 297.9    ]],
      dtype=float32)
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
    time     datetime64[ns] 2013-01-01T18:00:00
Attributes:
    long_name:     4xDaily Air temperature at sigma level 995
    units:         degK
    precision:     2
    GRIB_id:       11
    GRIB_name:     TMP
    var_desc:      Air temperature
    dataset:       NMC Reanalysis
    level_desc:    Surface
    statistic:     Individual Obs
    parent_stat:   Other
    actual_range:  [185.16 322.1 ]

Custom workflows and automatic parallelization

Almost all of xarray’s built-in operations work on Dask arrays. If you want to use a function that isn’t wrapped by xarray, 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, which can automate embarrassingly parallel “map” type operations where a functions written for processing NumPy arrays should be repeatedly applied to xarray objects containing Dask arrays. It works similarly to dask.array.map_blocks() and dask.array.atop(), but without requiring an intermediate layer of abstraction.

Here we show an example using NumPy operations and a fast function from bottleneck, which we use to calculate Spearman’s rank-correlation coefficient:

In [15]:
import numpy as np
import xarray as xr
import bottleneck

def covariance_gufunc(x, y):
    return ((x - x.mean(axis=-1, keepdims=True))
            * (y - y.mean(axis=-1, keepdims=True))).mean(axis=-1)

def pearson_correlation_gufunc(x, y):
    return covariance_gufunc(x, y) / (x.std(axis=-1) * y.std(axis=-1))

def spearman_correlation_gufunc(x, y):
    x_ranks = bottleneck.rankdata(x, axis=-1)
    y_ranks = bottleneck.rankdata(y, axis=-1)
    return pearson_correlation_gufunc(x_ranks, y_ranks)

def spearman_correlation(x, y, dim):
    return xr.apply_ufunc(
        spearman_correlation_gufunc, x, y,
        input_core_dims=[[dim], [dim]],
        dask='parallelized',
        output_dtypes=[float])

In the examples above, we were working with an some air temperature data. For this example, we’ll calculate the spearman correlation using the raw air temperature data with the smoothed version that we also created (da_smooth). For this, we’ll also have to rechunk the data ahead of time.

In [16]:
corr = spearman_correlation(da.chunk({'time': -1}),
                            da_smooth.chunk({'time': -1}),
                            'time')
corr
Out[16]:
<xarray.DataArray (lat: 25, lon: 53)>
dask.array<shape=(25, 53), dtype=float64, chunksize=(25, 25)>
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
In [17]:
corr.plot(figsize=(12, 8))
Out[17]:
<matplotlib.collections.QuadMesh at 0x7fcb35513c88>
_images/xarray_31_1.png
In [18]: