../../_images/dask_horizontal.svg

Dask Arrays with Xarray

The scientific Python package known as Dask provides Dask Arrays: parallel, larger-than-memory, n-dimensional arrays that make use of blocked algorithms. They are analogous to Numpy arrays, but are distributed. These terms are defined below:

  • Parallel code uses many or all of the cores on the computer running the code.

  • Larger-than-memory refers to algorithms that break up data arrays into small pieces, operate on these pieces in an optimized fashion, and stream data from a storage device. This allows a user or programmer to work with datasets of a size larger than the available memory.

  • A blocked algorithm speeds up large computations by converting them into a series of smaller computations.

In this tutorial, we cover the use of Xarray to wrap Dask arrays. By using Dask arrays instead of Numpy arrays in Xarray data objects, it becomes possible to execute analysis code in parallel with much less code and effort.

Learning Objectives

  • Learn the distinction between eager and lazy execution, and performing both types of execution with Xarray

  • Understand key features of Dask Arrays

  • Learn to perform operations with Dask Arrays in similar ways to performing operations with NumPy arrays

  • Understand the use of Xarray DataArrays and Datasets as “Dask collections”, and the use of top-level Dask functions such as dask.visualize() on such collections

  • Understand the ability to use Dask transparently in all built-in Xarray operations

Prerequisites

Concepts

Importance

Notes

Introduction to NumPy

Necessary

Familiarity with Data Arrays

Introduction to Xarray

Necessary

Familiarity with Xarray Data Structures

  • Time to learn: 30-40 minutes

Imports

For this tutorial, as we are working with Dask, there are a number of Dask packages that must be imported. Also, this is technically an Xarray tutorial, so Xarray and NumPy must also be imported. Finally, the Pythia datasets package is imported, allowing access to the Project Pythia example data library.

import dask
import dask.array as da
import numpy as np
import xarray as xr
from dask.diagnostics import ProgressBar
from dask.utils import format_bytes
from pythia_datasets import DATASETS

Blocked algorithms

As described above, the definition of “blocked algorithm” is an algorithm that replaces a large operation with many small operations. In the case of datasets, this means that a blocked algorithm separates a dataset into chunks, and performs an operation on each.

As an example of how blocked algorithms work, consider a dataset containing a billion numbers, and assume that the sum of the numbers is needed. Using a non-blocked algorithm, all of the numbers are added in one operation, which is extremely inefficient. However, by using a blocked algorithm, the dataset is broken into chunks. (For the purposes of this example, assume that 1,000 chunks are created, with 1,000,000 numbers each.) The sum of the numbers in each chunk is taken, most likely in parallel, and then each of those sums are summed to obtain the final result.

By using blocked algorithms, we achieve the result, in this case one sum of one billion numbers, through the results of many smaller operations, in this case one thousand sums of one million numbers each. (Also note that each of the one thousand sums must then be summed, making the total number of sums 1,001.) This allows for a much greater degree of parallelism, potentially speeding up the code execution dramatically.

dask.array contains these algorithms

The main object type used in Dask is dask.array, which implements a subset of the ndarray (NumPy array) interface. However, unlike ndarray, dask.array uses blocked algorithms, which break up the array into smaller arrays, as described above. This allows for the execution of computations on arrays larger than memory, by using parallelism to divide the computation among multiple cores. Dask manages and coordinates blocked algorithms for any given computation by using Dask graphs, which lay out in detail the steps Dask takes to solve a problem. In addition, dask.array objects, known as Dask Arrays, are lazy; in other words, any computation performed on them is delayed until a specific method is called.

Create a dask.array object

As stated earlier, Dask Arrays are loosely based on NumPy arrays. In the next set of examples, we illustrate the main differences between Dask Arrays and NumPy arrays. In order to illustrate the differences, we must have both a Dask Array object and a NumPy array object. Therefore, this first example creates a 3-D NumPy array of random data:

shape = (600, 200, 200)
arr = np.random.random(shape)
arr
array([[[0.77595036, 0.86227873, 0.73744047, ..., 0.40059662,
         0.42929604, 0.41031862],
        [0.32681228, 0.27270689, 0.04117909, ..., 0.57030987,
         0.6497793 , 0.25019797],
        [0.62228517, 0.48303762, 0.68530418, ..., 0.66133131,
         0.22094101, 0.88639919],
        ...,
        [0.18950829, 0.75590319, 0.65511729, ..., 0.96792538,
         0.32379941, 0.32046408],
        [0.88086306, 0.4744451 , 0.78001368, ..., 0.13930667,
         0.39672109, 0.01478958],
        [0.54593733, 0.31306234, 0.93190252, ..., 0.83885116,
         0.03555387, 0.02073545]],

       [[0.78592602, 0.13633049, 0.29152447, ..., 0.40888503,
         0.52167521, 0.9778949 ],
        [0.02330012, 0.63273866, 0.70879179, ..., 0.1256922 ,
         0.82186585, 0.40647585],
        [0.21166489, 0.56890893, 0.04102758, ..., 0.3385126 ,
         0.89798456, 0.41891784],
        ...,
        [0.63861104, 0.49782013, 0.87698124, ..., 0.35706881,
         0.89766974, 0.43746129],
        [0.35306897, 0.7114361 , 0.84651009, ..., 0.82487391,
         0.4587161 , 0.42640579],
        [0.160398  , 0.21169053, 0.75381045, ..., 0.6401045 ,
         0.77702337, 0.85198208]],

       [[0.18661741, 0.0960651 , 0.88357673, ..., 0.63365859,
         0.46940759, 0.85348335],
        [0.54514893, 0.18551179, 0.83958215, ..., 0.12975394,
         0.34290457, 0.11250011],
        [0.53001436, 0.28033684, 0.29979442, ..., 0.3052258 ,
         0.10293233, 0.68949928],
        ...,
        [0.56226575, 0.44959465, 0.71219621, ..., 0.89646601,
         0.30879731, 0.30598299],
        [0.4526167 , 0.87937665, 0.29154076, ..., 0.47076711,
         0.97234021, 0.0561465 ],
        [0.66799005, 0.70335684, 0.84687932, ..., 0.3186133 ,
         0.29802127, 0.75788872]],

       ...,

       [[0.11117813, 0.17665176, 0.07107021, ..., 0.55451764,
         0.74656342, 0.35578777],
        [0.78661335, 0.74105128, 0.18079754, ..., 0.10528323,
         0.85232742, 0.03724523],
        [0.59142735, 0.51980442, 0.50656919, ..., 0.62939831,
         0.32416453, 0.57019531],
        ...,
        [0.07688477, 0.99784497, 0.4611103 , ..., 0.57336087,
         0.46713206, 0.81986381],
        [0.22534835, 0.40101732, 0.4816464 , ..., 0.84466225,
         0.85962452, 0.78007531],
        [0.10297331, 0.88351509, 0.70734667, ..., 0.72065477,
         0.02014898, 0.10369116]],

       [[0.88560179, 0.68501502, 0.1698313 , ..., 0.40564416,
         0.4462295 , 0.06875045],
        [0.24729425, 0.68824759, 0.78261701, ..., 0.14028468,
         0.81506353, 0.37841763],
        [0.95368514, 0.83617178, 0.7740401 , ..., 0.86515261,
         0.60267579, 0.1722913 ],
        ...,
        [0.04801367, 0.43203799, 0.50090908, ..., 0.84232571,
         0.04908442, 0.28328914],
        [0.13610106, 0.81098838, 0.12796783, ..., 0.86202572,
         0.68393783, 0.70678691],
        [0.32356991, 0.66789188, 0.69404391, ..., 0.83556155,
         0.21272838, 0.73479314]],

       [[0.97516009, 0.03767103, 0.26713478, ..., 0.79208096,
         0.14306978, 0.10634994],
        [0.42832657, 0.72093287, 0.07683367, ..., 0.96369702,
         0.40875509, 0.39682522],
        [0.83766348, 0.4328336 , 0.16355495, ..., 0.45378973,
         0.96565905, 0.39699147],
        ...,
        [0.14070334, 0.60124122, 0.39252067, ..., 0.23262461,
         0.23434486, 0.94508668],
        [0.2127689 , 0.38013845, 0.19672934, ..., 0.87918237,
         0.23815511, 0.30109874],
        [0.64702991, 0.04967063, 0.6134769 , ..., 0.51391633,
         0.07860372, 0.36662715]]])
format_bytes(arr.nbytes)
'183.11 MiB'

As shown above, this NumPy array contains about 183 MB of data.

As stated above, we must also create a Dask Array. This next example creates a Dask Array with the same dimension sizes as the existing NumPy array:

darr = da.random.random(shape, chunks=(300, 100, 200))

By specifying values to the chunks keyword argument, we can specify the array pieces that Dask’s blocked algorithms break the array into; in this case, we specify (300, 100, 200).

Specifying Chunks

In this tutorial, we specify Dask Array chunks in a block shape. However, there are many additional ways to specify chunks; see this documentation for more details.

If you are viewing this page as a Jupyter Notebook, the next Jupyter cell will produce a rich information graphic giving in-depth details about the array and each individual chunk.

darr
Array Chunk
Bytes 183.11 MiB 45.78 MiB
Shape (600, 200, 200) (300, 100, 200)
Dask graph 4 chunks in 1 graph layer
Data type float64 numpy.ndarray
200 200 600

The above graphic contains a symbolic representation of the array, including shape, dtype, and chunksize. (Your view may be different, depending on how you are accessing this page.) Notice that there is no data shown for this array; this is because Dask Arrays are lazy, as described above. Before we call a compute method for this array, we first illustrate the structure of a Dask graph. In this example, we show the Dask graph by calling .visualize() on the array:

darr.visualize()
../../_images/57f39e3d0829df5b12fc9298b4722d64bea6b8ef6a3e0b911e26309374691f26.png

As shown in the above Dask graph, our array has four chunks, each one created by a call to NumPy’s “random” method (np.random.random). These chunks are concatenated into a single array after the calculation is performed.

Manipulate a dask.array object as you would a numpy array

We can perform computations on the Dask Array created above in a similar fashion to NumPy arrays. These computations include arithmetic, slicing, and reductions, among others.

Although the code for performing these computations is similar between NumPy arrays and Dask Arrays, the process by which they are performed is quite different. For example, it is possible to call sum() on both a NumPy array and a Dask Array; however, these two sum() calls are definitely not the same, as shown below.

What’s the difference?

When sum() is called on a Dask Array, the computation is not performed; instead, an expression of the computation is built. The sum() computation, as well as any other computation methods called on the same Dask Array, are not performed until a specific method (known as a compute method) is called on the array. (This is known as lazy execution.) On the other hand, calling sum() on a NumPy array performs the calculation immediately; this is known as eager execution.

Why the difference?

As described earlier, a Dask Array is divided into chunks. Any computations run on the Dask Array run on each chunk individually. If the result of the computation is obtained before the computation runs through all of the chunks, Dask can stop the computation to save CPU time and memory resources.

This example illustrates calling sum() on a Dask Array; it also includes a demonstration of lazy execution, as well as another Dask graph display:

total = darr.sum()
total
Array Chunk
Bytes 8 B 8 B
Shape () ()
Dask graph 1 chunks in 3 graph layers
Data type float64 numpy.ndarray
total.visualize()
../../_images/caf93b42a7330563cb488018fff85a8cb1fef4526fde9351f6620316599f258c.png

Compute the result

As described above, Dask Array objects make use of lazy execution. Therefore, operations performed on a Dask Array wait to execute until a compute method is called. As more operations are queued in this way, the Dask Array’s Dask graph increases in complexity, reflecting the steps Dask will take to perform all of the queued operations.

In this example, we call a compute method, simply called .compute(), to run on the Dask Array all of the stored computations:

%%time
total.compute()
CPU times: user 369 ms, sys: 51.7 ms, total: 421 ms
Wall time: 221 ms
12001041.638651783

Exercise with dask.arrays

In this section of the page, the examples are hands-on exercises pertaining to Dask Arrays. If these exercises are not interesting to you, this section can be used strictly as examples regardless of how the page is viewed. However, if you wish to participate in the exercises, make sure that you are viewing this page as a Jupyter Notebook.

For the first exercise, modify the chunk size or shape of the Dask Array created earlier. Call .sum() on the modified Dask Array, and visualize the Dask graph to view the changes.

da.random.random(shape, chunks=(50, 200, 400)).sum().visualize()
../../_images/c72da04b1bfe3a506395391dafe24ac8521e9cf45f986769fdc135046116258b.png

As is obvious from the above exercise, Dask quickly and easily determines a strategy for performing the operations, in this case a sum. This illustrates the appeal of Dask: automatic algorithm generation that scales from simple arithmetic problems to highly complex scientific equations with large datasets and multiple operations.

In this next set of examples, we demonstrate that increasing the complexity of the operations performed also increases the complexity of the Dask graph.

In this example, we use randomly selected functions, arguments and Python slices to create a complex set of operations. We then visualize the Dask graph to illustrate the increased complexity:

z = darr.dot(darr.T).mean(axis=0)[::2, :].std(axis=1)
z
Array Chunk
Bytes 468.75 kiB 117.19 kiB
Shape (100, 600) (50, 300)
Dask graph 4 chunks in 12 graph layers
Data type float64 numpy.ndarray
600 100
z.visualize()
../../_images/a75f3ba474e4d57105fe3c2cdb9111b3716c368c48feaa67dbaf0068330e50ca.png

Testing a bigger calculation

While the earlier examples in this tutorial described well the basics of Dask, the size of the data in those examples, about 180 MB, is far too small for an actual use of Dask.

In this example, we create a much larger array, more indicative of data actually used in Dask:

darr = da.random.random((4000, 100, 4000), chunks=(1000, 100, 500)).astype('float32')
darr
Array Chunk
Bytes 5.96 GiB 190.73 MiB
Shape (4000, 100, 4000) (1000, 100, 500)
Dask graph 32 chunks in 2 graph layers
Data type float32 numpy.ndarray
4000 100 4000

The dataset created in the previous example is much larger, approximately 6 GB. Depending on how many programs are running on your computer, this may be greater than the amount of free RAM on your computer. However, as Dask is larger-than-memory, the amount of free RAM does not impede Dask’s ability to work on this dataset.

In this example, we again perform randomly selected operations, but this time on the much larger dataset. We also visualize the Dask graph, and then run the compute method. However, as computing complex functions on large datasets is inherently time-consuming, we show a progress bar to track the progress of the computation.

z = (darr + darr.T)[::2, :].mean(axis=2)
z.visualize()
../../_images/03a452653f639ce6fedd47ff7e889b73e4ca9042f111475cba5b328d84aecd06.png
with ProgressBar():
    computed_ds = z.compute()
[                                        ] | 0% Completed | 330.65 us
[                                        ] | 0% Completed | 106.26 ms
[                                        ] | 0% Completed | 207.11 ms
[                                        ] | 0% Completed | 307.73 ms
[                                        ] | 0% Completed | 408.33 ms
[                                        ] | 0% Completed | 508.93 ms
[                                        ] | 1% Completed | 609.54 ms
[#                                       ] | 4% Completed | 710.83 ms
[###                                     ] | 8% Completed | 812.03 ms
[####                                    ] | 10% Completed | 912.82 ms
[####                                    ] | 10% Completed | 1.01 s
[####                                    ] | 10% Completed | 1.11 s
[####                                    ] | 10% Completed | 1.21 s
[####                                    ] | 10% Completed | 1.32 s
[####                                    ] | 11% Completed | 1.42 s
[#####                                   ] | 14% Completed | 1.52 s
[#######                                 ] | 17% Completed | 1.62 s
[########                                ] | 21% Completed | 1.72 s
[########                                ] | 21% Completed | 1.82 s
[########                                ] | 21% Completed | 1.92 s
[########                                ] | 21% Completed | 2.02 s
[########                                ] | 21% Completed | 2.12 s
[########                                ] | 21% Completed | 2.22 s
[##########                              ] | 25% Completed | 2.32 s
[###########                             ] | 27% Completed | 2.42 s
[############                            ] | 31% Completed | 2.52 s
[#############                           ] | 34% Completed | 2.62 s
[#############                           ] | 34% Completed | 2.73 s
[#############                           ] | 34% Completed | 2.83 s
[#############                           ] | 34% Completed | 2.93 s
[#############                           ] | 34% Completed | 3.03 s
[#############                           ] | 34% Completed | 3.13 s
[###############                         ] | 37% Completed | 3.23 s
[################                        ] | 40% Completed | 3.33 s
[#################                       ] | 44% Completed | 3.43 s
[###################                     ] | 48% Completed | 3.53 s
[###################                     ] | 48% Completed | 3.63 s
[###################                     ] | 48% Completed | 3.73 s
[###################                     ] | 48% Completed | 3.83 s
[###################                     ] | 48% Completed | 3.93 s
[###################                     ] | 48% Completed | 4.03 s
[####################                    ] | 51% Completed | 4.14 s
[#####################                   ] | 54% Completed | 4.24 s
[#######################                 ] | 58% Completed | 4.34 s
[#######################                 ] | 59% Completed | 4.44 s
[#######################                 ] | 59% Completed | 4.54 s
[#######################                 ] | 59% Completed | 4.64 s
[#######################                 ] | 59% Completed | 4.74 s
[#######################                 ] | 59% Completed | 4.84 s
[########################                ] | 62% Completed | 4.94 s
[#########################               ] | 64% Completed | 5.04 s
[###########################             ] | 68% Completed | 5.14 s
[############################            ] | 72% Completed | 5.24 s
[#############################           ] | 74% Completed | 5.34 s
[#############################           ] | 74% Completed | 5.45 s
[#############################           ] | 74% Completed | 5.55 s
[#############################           ] | 74% Completed | 5.65 s
[#############################           ] | 74% Completed | 5.75 s
[##############################          ] | 76% Completed | 5.85 s
[###############################         ] | 78% Completed | 5.95 s
[#################################       ] | 82% Completed | 6.05 s
[##################################      ] | 85% Completed | 6.15 s
[##################################      ] | 85% Completed | 6.25 s
[##################################      ] | 85% Completed | 6.35 s
[##################################      ] | 85% Completed | 6.45 s
[##################################      ] | 85% Completed | 6.55 s
[##################################      ] | 85% Completed | 6.65 s
[###################################     ] | 88% Completed | 6.75 s
[#####################################   ] | 92% Completed | 6.85 s
[######################################  ] | 96% Completed | 6.96 s
[########################################] | 100% Completed | 7.06 s

Dask Arrays with Xarray

While directly interacting with Dask Arrays can be useful on occasion, more often than not Dask Arrays are interacted with through Xarray. Since Xarray wraps NumPy arrays, and Dask Arrays contain most of the functionality of NumPy arrays, Xarray can also wrap Dask Arrays, allowing anyone with knowledge of Xarray to easily start using the Dask interface.

Reading data with Dask and Xarray

As demonstrated in previous examples, a Dask Array consists of many smaller arrays, called chunks:

darr
Array Chunk
Bytes 5.96 GiB 190.73 MiB
Shape (4000, 100, 4000) (1000, 100, 500)
Dask graph 32 chunks in 2 graph layers
Data type float32 numpy.ndarray
4000 100 4000

As shown in the following example, to read data into Xarray as Dask Arrays, simply specify the chunks keyword argument when calling the open_dataset() function:

ds = xr.open_dataset(DATASETS.fetch('CESM2_sst_data.nc'), chunks={})
ds.tos
/home/runner/miniconda3/envs/pythia-book-dev/lib/python3.12/site-packages/xarray/conventions.py:448: SerializationWarning: variable 'tos' has multiple fill values {1e+20, 1e+20}, decoding all values to NaN.
  new_vars[k] = decode_cf_variable(
<xarray.DataArray 'tos' (time: 180, lat: 180, lon: 360)>
dask.array<open_dataset-tos, shape=(180, 180, 360), dtype=float32, chunksize=(1, 180, 360), chunktype=numpy.ndarray>
Coordinates:
  * time     (time) object 2000-01-15 12:00:00 ... 2014-12-15 12:00:00
  * lat      (lat) float64 -89.5 -88.5 -87.5 -86.5 -85.5 ... 86.5 87.5 88.5 89.5
  * lon      (lon) float64 0.5 1.5 2.5 3.5 4.5 ... 355.5 356.5 357.5 358.5 359.5
Attributes: (12/19)
    cell_measures:  area: areacello
    cell_methods:   area: mean where sea time: mean
    comment:        Model data on the 1x1 grid includes values in all cells f...
    description:    This may differ from "surface temperature" in regions of ...
    frequency:      mon
    id:             tos
    ...             ...
    time_label:     time-mean
    time_title:     Temporal mean
    title:          Sea Surface Temperature
    type:           real
    units:          degC
    variable_id:    tos

While it is a valid operation to pass an empty list to the chunks keyword argument, this technique does not specify how to chunk the data, and therefore the resulting Dask Array contains only one chunk.

Correct usage of the chunks keyword argument specifies how many values in each dimension are contained in a single chunk. In this example, specifying the chunks keyword argument as chunks={'time':90} indicates to Xarray and Dask that 90 time slices are allocated to each chunk on the temporal axis.

Since this dataset contains 180 total time slices, the data variable tos (holding the sea surface temperature data) is now split into two chunks in the temporal dimension.

ds = xr.open_dataset(
    DATASETS.fetch('CESM2_sst_data.nc'),
    engine="netcdf4",
    chunks={"time": 90, "lat": 180, "lon": 360},
)
ds.tos
/home/runner/miniconda3/envs/pythia-book-dev/lib/python3.12/site-packages/xarray/conventions.py:448: SerializationWarning: variable 'tos' has multiple fill values {1e+20, 1e+20}, decoding all values to NaN.
  new_vars[k] = decode_cf_variable(
<xarray.DataArray 'tos' (time: 180, lat: 180, lon: 360)>
dask.array<open_dataset-tos, shape=(180, 180, 360), dtype=float32, chunksize=(90, 180, 360), chunktype=numpy.ndarray>
Coordinates:
  * time     (time) object 2000-01-15 12:00:00 ... 2014-12-15 12:00:00
  * lat      (lat) float64 -89.5 -88.5 -87.5 -86.5 -85.5 ... 86.5 87.5 88.5 89.5
  * lon      (lon) float64 0.5 1.5 2.5 3.5 4.5 ... 355.5 356.5 357.5 358.5 359.5
Attributes: (12/19)
    cell_measures:  area: areacello
    cell_methods:   area: mean where sea time: mean
    comment:        Model data on the 1x1 grid includes values in all cells f...
    description:    This may differ from "surface temperature" in regions of ...
    frequency:      mon
    id:             tos
    ...             ...
    time_label:     time-mean
    time_title:     Temporal mean
    title:          Sea Surface Temperature
    type:           real
    units:          degC
    variable_id:    tos

It is fairly straightforward to retrieve a list of the chunks and their sizes for each dimension; simply call the .chunks method on an Xarray DataArray. In this example, we show that the tos DataArray now contains two chunks on the time dimension, with each chunk containing 90 time slices.

ds.tos.chunks
((90, 90), (180,), (360,))

Xarray data structures are first-class dask collections

If an Xarray Dataset or DataArray object uses a Dask Array, rather than a NumPy array, it counts as a first-class Dask collection. This means that you can pass such an object to dask.visualize() and dask.compute(), in the same way as an individual Dask Array.

In this example, we call dask.visualize on our Xarray DataArray, displaying a Dask graph for the DataArray object:

dask.visualize(ds)
../../_images/14823a00387a43fce8fd7b4035c5b98e68204d306bb0ab6a33c23ad5d09dd244.png

Parallel and lazy computation using dask.array with Xarray

As described above, Xarray Datasets and DataArrays containing Dask Arrays are first-class Dask collections. Therefore, computations performed on such objects are deferred until a compute method is called. (This is the definition of lazy computation.)

z = ds.tos.mean(['lat', 'lon']).dot(ds.tos.T)
z
<xarray.DataArray 'tos' (lon: 360, lat: 180)>
dask.array<sum-aggregate, shape=(360, 180), dtype=float32, chunksize=(360, 180), chunktype=numpy.ndarray>
Coordinates:
  * lat      (lat) float64 -89.5 -88.5 -87.5 -86.5 -85.5 ... 86.5 87.5 88.5 89.5
  * lon      (lon) float64 0.5 1.5 2.5 3.5 4.5 ... 355.5 356.5 357.5 358.5 359.5

As shown in the above example, the result of the applied operations is an Xarray DataArray that contains a Dask Array, an identical object type to the object that the operations were performed on. This is true for any operations that can be applied to Xarray DataArrays, including subsetting operations; this next example illustrates this:

z.isel(lat=0)
<xarray.DataArray 'tos' (lon: 360)>
dask.array<getitem, shape=(360,), dtype=float32, chunksize=(360,), chunktype=numpy.ndarray>
Coordinates:
    lat      float64 -89.5
  * lon      (lon) float64 0.5 1.5 2.5 3.5 4.5 ... 355.5 356.5 357.5 358.5 359.5

Because the data subset created above is also a first-class Dask collection, we can view its Dask graph using the dask.visualize() function, as shown in this example:

dask.visualize(z)
../../_images/1ae1aba7705f9f4c003ebc48f3b0f687a2031ed7f9d6cb8c8393bf159c6b7188.png

Since this object is a first-class Dask collection, the computations performed on it have been deferred. To run these computations, we must call a compute method, in this case .compute(). This example also uses a progress bar to track the computation progress.

with ProgressBar():
    computed_ds = z.compute()
[                                        ] | 0% Completed | 106.93 us
[########################################] | 100% Completed | 100.99 ms


Summary

This tutorial covered the use of Xarray to access Dask Arrays, and the use of the chunks keyword argument to open datasets with Dask data instead of NumPy data. Another important concept introduced in this tutorial is the usage of Xarray Datasets and DataArrays as Dask collections, allowing Xarray objects to be manipulated in a similar manner to Dask Arrays. Finally, the concepts of larger-than-memory datasets, lazy computation, and parallel computation, and how they relate to Xarray and Dask, were covered.

Dask Shortcomings

Although Dask Arrays and NumPy arrays are generally interchangeable, NumPy offers some functionality that is lacking in Dask Arrays. The usage of Dask Array comes with the following relevant issues:

  1. Operations where the resulting shape depends on the array values can produce erratic behavior, or fail altogether, when used on a Dask Array. If the operation succeeds, the resulting Dask Array will have unknown chunk sizes, which can cause other sections of code to fail.

  2. Operations that are by nature difficult to parallelize or less useful on very large datasets, such as sort, are not included in the Dask Array interface. Some of these operations have supported versions that are inherently more intuitive to parallelize, such as topk.

  3. Development of new Dask functionality is only initiated when such functionality is required; therefore, some lesser-used NumPy functions, such as np.sometrue, are not yet implemented in Dask. However, many of these functions can be added as community contributions, or have already been added in this manner.

Learn More

For more in-depth information on Dask Arrays, visit the official documentation page. In addition, this screencast reinforces the concepts covered in this tutorial. (If you are viewing this page as a Jupyter Notebook, the screencast will appear below as an embedded YouTube video.)

from IPython.display import YouTubeVideo

YouTubeVideo(id="9h_61hXCDuI", width=600, height=300)

Resources and references