Debian Codegraph @

docs/source/array-creation.rst

raw
1 Create Dask Arrays
2 ==================
3
4 You can load or store Dask arrays from a variety of common sources like HDF5,
5 NetCDF, `Zarr`_, or any format that supports NumPy-style slicing.
6
7 .. currentmodule:: dask.array
8
9 .. autosummary::
10 from_array
11 from_delayed
12 from_npy_stack
13 from_zarr
14 stack
15 concatenate
16
17 NumPy Slicing
18 -------------
19
20 .. autosummary::
21 from_array
22
23 Many storage formats have Python projects that expose storage using NumPy
24 slicing syntax. These include HDF5, NetCDF, BColz, Zarr, GRIB, etc. For
25 example, we can load a Dask array from an HDF5 file using `h5py <https://www.h5py.org/>`_:
26
27 .. code-block:: Python
28
29 >>> import h5py
30 >>> f = h5py.File('myfile.hdf5') # HDF5 file
31 >>> d = f['/data/path'] # Pointer on on-disk array
32 >>> d.shape # d can be very large
33 (1000000, 1000000)
34
35 >>> x = d[:5, :5] # We slice to get numpy arrays
36
37 Given an object like ``d`` above that has ``dtype`` and ``shape`` properties
38 and that supports NumPy style slicing, we can construct a lazy Dask array:
39
40 .. code-block:: Python
41
42 >>> import dask.array as da
43 >>> x = da.from_array(d, chunks=(1000, 1000))
44
45 This process is entirely lazy. Neither creating the h5py object nor wrapping
46 it with ``da.from_array`` have loaded any data.
47
48
49 Random Data
50 -----------
51
52 For experimentation or benchmarking it is common to create arrays of random
53 data. The ``dask.array.random`` module implements most of the functions in the
54 ``numpy.random`` module. We list some common functions below but for a full
55 list see the :doc:`Array API <array-api>`:
56
57 .. autosummary::
58 random.binomial
59 random.normal
60 random.poisson
61 random.random
62
63 .. code-block:: python
64
65 >>> import dask.array as da
66 >>> rng = da.random.default_rng()
67 >>> x = rng.random((10000, 10000), chunks=(1000, 1000))
68
69
70 Concatenation and Stacking
71 --------------------------
72
73 .. autosummary::
74 stack
75 concatenate
76
77 Often we store data in several different locations and want to stitch them together:
78
79 .. code-block:: Python
80
81 dask_arrays = []
82 for fn in filenames:
83 f = h5py.File(fn)
84 d = f['/data']
85 array = da.from_array(d, chunks=(1000, 1000))
86 dask_arrays.append(array)
87
88 x = da.concatenate(dask_arrays, axis=0) # concatenate arrays along first axis
89
90 For more information, see :doc:`concatenation and stacking <array-stack>` docs.
91
92
93 Using ``dask.delayed``
94 ----------------------
95
96 .. autosummary::
97 from_delayed
98 stack
99 concatenate
100
101 Sometimes NumPy-style data resides in formats that do not support NumPy-style
102 slicing. We can still construct Dask arrays around this data if we have a
103 Python function that can generate pieces of the full array if we use
104 :doc:`dask.delayed <delayed>`. Dask delayed lets us delay a single function
105 call that would create a NumPy array. We can then wrap this delayed object
106 with ``da.from_delayed``, providing a dtype and shape to produce a
107 single-chunked Dask array. Furthermore, we can use ``stack`` or ``concatenate`` from
108 before to construct a larger lazy array.
109
110 As an example, consider loading a stack of images using ``skimage.io.imread``:
111
112 .. code-block:: python
113
114 import skimage.io
115 import dask.array as da
116 import dask
117
118 imread = dask.delayed(skimage.io.imread, pure=True) # Lazy version of imread
119
120 filenames = sorted(glob.glob('*.jpg'))
121
122 lazy_images = [imread(path) for path in filenames] # Lazily evaluate imread on each path
123 sample = lazy_images[0].compute() # load the first image (assume rest are same shape/dtype)
124
125 arrays = [da.from_delayed(lazy_image, # Construct a small Dask array
126 dtype=sample.dtype, # for every lazy value
127 shape=sample.shape)
128 for lazy_image in lazy_images]
129
130 stack = da.stack(arrays, axis=0) # Stack all small Dask arrays into one
131
132 See :doc:`documentation on using dask.delayed with collections<delayed-collections>`.
133
134 Often it is substantially faster to use ``da.map_blocks`` rather than ``da.stack``
135
136 .. code-block:: python
137
138 import glob
139 import skimage.io
140 import numpy as np
141 import dask.array as da
142
143 filenames = sorted(glob.glob('*.jpg'))
144
145 def read_one_image(block_id, filenames=filenames, axis=0):
146 # a function that reads in one chunk of data
147 path = filenames[block_id[axis]]
148 image = skimage.io.imread(path)
149 return np.expand_dims(image, axis=axis)
150
151 # load the first image (assume rest are same shape/dtype)
152 sample = skimage.io.imread(filenames[0])
153
154 stack = da.map_blocks(
155 read_one_image,
156 dtype=sample.dtype,
157 chunks=((1,) * len(filenames), *sample.shape)
158 )
159
160
161 From Dask DataFrame
162 -------------------
163
164 There are several ways to create a Dask array from a Dask DataFrame. Dask DataFrames have a ``to_dask_array`` method:
165
166 .. code-block:: python
167
168 >>> df = dask.dataframes.from_pandas(...)
169 >>> df.to_dask_array()
170 dask.array<values, shape=(nan, 3), dtype=float64, chunksize=(nan, 3), chunktype=numpy.ndarray>
171
172 This mirrors the `to_numpy
173 <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html>`_
174 function in Pandas. The ``values`` attribute is also supported:
175
176 .. code-block:: python
177
178 >>> df.values
179 dask.array<values, shape=(nan, 3), dtype=float64, chunksize=(nan, 3), chunktype=numpy.ndarray>
180
181 However, these arrays do not have known chunk sizes because dask.dataframe does
182 not track the number of rows in each partition. This means that some operations
183 like slicing will not operate correctly.
184
185 The chunk sizes can be computed:
186
187 .. code-block:: python
188
189 >>> df.to_dask_array(lengths=True)
190 dask.array<array, shape=(100, 3), dtype=float64, chunksize=(50, 3), chunktype=numpy.ndarray>
191
192 Specifying ``lengths=True`` triggers immediate computation of the chunk sizes.
193 This enables downstream computations that rely on having known chunk sizes
194 (e.g., slicing).
195
196 The Dask DataFrame ``to_records`` method also returns a Dask Array, but does not compute the shape
197 information:
198
199 .. code-block:: python
200
201 >>> df.to_records()
202 dask.array<to_records, shape=(nan,), dtype=(numpy.record, [('index', '<i8'), ('x', '<f8'), ('y', '<f8'), ('z', '<f8')]), chunksize=(nan,), chunktype=numpy.ndarray>
203
204 If you have a function that converts a Pandas DataFrame into a NumPy array,
205 then calling ``map_partitions`` with that function on a Dask DataFrame will
206 produce a Dask array:
207
208 .. code-block:: python
209
210 >>> df.map_partitions(np.asarray)
211 dask.array<asarray, shape=(nan, 3), dtype=float64, chunksize=(nan, 3), chunktype=numpy.ndarray>
212
213
214 Interactions with NumPy arrays
215 ------------------------------
216
217 Dask array operations will automatically convert NumPy arrays into single-chunk
218 dask arrays:
219
220 .. code-block:: python
221
222 >>> x = da.sum(np.ones(5))
223 >>> x.compute()
224 5
225
226 When NumPy and Dask arrays interact, the result will be a Dask array. Automatic
227 rechunking rules will generally slice the NumPy array into the appropriate Dask
228 chunk shape:
229
230 .. code-block:: python
231
232 >>> x = da.ones(10, chunks=(5,))
233 >>> y = np.ones(10)
234 >>> z = x + y
235 >>> z
236 dask.array<add, shape=(10,), dtype=float64, chunksize=(5,), chunktype=numpy.ndarray>
237
238 These interactions work not just for NumPy arrays but for any object that has
239 shape and dtype attributes and implements NumPy slicing syntax.
240
241 Memory mapping
242 --------------
243
244 Memory mapping can be a highly effective method to access raw binary data since
245 it has nearly zero overhead if the data is already in the file system cache. For
246 the threaded scheduler, creating a Dask array from a raw binary file can be as simple as
247 :code:`a = da.from_array(np.memmap(filename, shape=shape, dtype=dtype, mode='r'))`.
248
249 For multiprocessing or distributed schedulers, the memory map for each array
250 chunk should be created on the correct worker process and not on the main
251 process to avoid data transfer through the cluster. This can be achieved by
252 wrapping the function that creates the memory map using :code:`dask.delayed`.
253
254 .. code-block:: python
255
256 import numpy as np
257 import dask
258 import dask.array as da
259
260
261 def mmap_load_chunk(filename, shape, dtype, offset, sl):
262 '''
263 Memory map the given file with overall shape and dtype and return a slice
264 specified by :code:`sl`.
265
266 Parameters
267 ----------
268
269 filename : str
270 shape : tuple
271 Total shape of the data in the file
272 dtype:
273 NumPy dtype of the data in the file
274 offset : int
275 Skip :code:`offset` bytes from the beginning of the file.
276 sl:
277 Object that can be used for indexing or slicing a NumPy array to
278 extract a chunk
279
280 Returns
281 -------
282
283 numpy.memmap or numpy.ndarray
284 View into memory map created by indexing with :code:`sl`,
285 or NumPy ndarray in case no view can be created using :code:`sl`.
286 '''
287 data = np.memmap(filename, mode='r', shape=shape, dtype=dtype, offset=offset)
288 return data[sl]
289
290
291 def mmap_dask_array(filename, shape, dtype, offset=0, blocksize=5):
292 '''
293 Create a Dask array from raw binary data in :code:`filename`
294 by memory mapping.
295
296 This method is particularly effective if the file is already
297 in the file system cache and if arbitrary smaller subsets are
298 to be extracted from the Dask array without optimizing its
299 chunking scheme.
300
301 It may perform poorly on Windows if the file is not in the file
302 system cache. On Linux it performs well under most circumstances.
303
304 Parameters
305 ----------
306
307 filename : str
308 shape : tuple
309 Total shape of the data in the file
310 dtype:
311 NumPy dtype of the data in the file
312 offset : int, optional
313 Skip :code:`offset` bytes from the beginning of the file.
314 blocksize : int, optional
315 Chunk size for the outermost axis. The other axes remain unchunked.
316
317 Returns
318 -------
319
320 dask.array.Array
321 Dask array matching :code:`shape` and :code:`dtype`, backed by
322 memory-mapped chunks.
323 '''
324 load = dask.delayed(mmap_load_chunk)
325 chunks = []
326 for index in range(0, shape[0], blocksize):
327 # Truncate the last chunk if necessary
328 chunk_size = min(blocksize, shape[0] - index)
329 chunk = dask.array.from_delayed(
330 load(
331 filename,
332 shape=shape,
333 dtype=dtype,
334 offset=offset,
335 sl=slice(index, index + chunk_size)
336 ),
337 shape=(chunk_size, ) + shape[1:],
338 dtype=dtype
339 )
340 chunks.append(chunk)
341 return da.concatenate(chunks, axis=0)
342
343 x = mmap_dask_array(
344 filename='testfile-50-50-100-100-float32.raw',
345 shape=(50, 50, 100, 100),
346 dtype=np.float32
347 )
348
349
350 Chunks
351 ------
352
353 See :doc:`documentation on Array Chunks <array-chunks>` for more information.
354
355
356 Store Dask Arrays
357 =================
358
359 .. autosummary::
360 store
361 to_hdf5
362 to_npy_stack
363 to_zarr
364 compute
365
366 In Memory
367 ---------
368
369 .. autosummary::
370 compute
371
372 If you have a small amount of data, you can call ``np.array`` or ``.compute()``
373 on your Dask array to turn in to a normal NumPy array:
374
375 .. code-block:: Python
376
377 >>> x = da.arange(6, chunks=3)
378 >>> y = x**2
379 >>> np.array(y)
380 array([0, 1, 4, 9, 16, 25])
381
382 >>> y.compute()
383 array([0, 1, 4, 9, 16, 25])
384
385
386 NumPy style slicing
387 -------------------
388
389 .. autosummary::
390 store
391
392 You can store Dask arrays in any object that supports NumPy-style slice
393 assignment like ``h5py.Dataset``:
394
395 .. code-block:: Python
396
397 >>> import h5py
398 >>> f = h5py.File('myfile.hdf5')
399 >>> d = f.require_dataset('/data', shape=x.shape, dtype=x.dtype)
400 >>> da.store(x, d)
401
402 Also, you can store several arrays in one computation by passing lists of sources and
403 destinations:
404
405 .. code-block:: Python
406
407 >>> da.store([array1, array2], [output1, output2]) # doctest: +SKIP
408
409 HDF5
410 ----
411
412 .. autosummary::
413 to_hdf5
414
415 HDF5 is sufficiently common that there is a special function ``to_hdf5`` to
416 store data into HDF5 files using ``h5py``:
417
418 .. code-block:: Python
419
420 >>> da.to_hdf5('myfile.hdf5', '/y', y) # doctest: +SKIP
421
422 You can store several arrays in one computation with the function
423 ``da.to_hdf5`` by passing in a dictionary:
424
425 .. code-block:: Python
426
427 >>> da.to_hdf5('myfile.hdf5', {'/x': x, '/y': y}) # doctest: +SKIP
428
429
430 Zarr
431 ----
432
433 The `Zarr`_ format is a chunk-wise binary array
434 storage file format with a good selection of encoding and compression options.
435 Due to each chunk being stored in a separate file, it is ideal for parallel
436 access in both reading and writing (for the latter, if the Dask array
437 chunks are aligned with the target). Furthermore, storage in
438 :doc:`remote data services <how-to/connect-to-remote-data>` such as S3 and GCS is
439 supported.
440
441 For example, to save data to a local zarr dataset you would do:
442
443 .. code-block:: Python
444
445 >>> arr.to_zarr('output.zarr')
446
447 or to save to a particular bucket on S3:
448
449 .. code-block:: Python
450
451 >>> arr.to_zarr('s3://mybucket/output.zarr', storage_option={'key': 'mykey',
452 'secret': 'mysecret'})
453
454 or your own custom zarr Array:
455
456 .. code-block:: Python
457
458 >>> z = zarr.create((10,), dtype=float, store=zarr.ZipStore("output.zarr"))
459 >>> arr.to_zarr(z)
460
461 To retrieve those data, you would do ``da.from_zarr`` with exactly the same arguments. The
462 chunking of the resultant Dask array is defined by how the files were saved, unless
463 otherwise specified.
464
465
466 TileDB
467 ------
468
469 `TileDB <https://docs.tiledb.io>`_ is a binary array format and storage manager with
470 tunable chunking, layout, and compression options. The TileDB storage manager library
471 includes support for scalable storage backends such as S3 API compatible object stores
472 and HDFS, with automatic scaling, and supports multi-threaded and multi-process
473 reads (consistent) and writes (eventually-consistent).
474
475 To save data to a local TileDB array:
476
477 .. code-block:: Python
478
479 >>> arr.to_tiledb('output.tdb')
480
481 or to save to a bucket on S3:
482
483 .. code-block:: python
484
485 >>> arr.to_tiledb('s3://mybucket/output.tdb',
486 storage_options={'vfs.s3.aws_access_key_id': 'mykey',
487 'vfs.s3.aws_secret_access_key': 'mysecret'})
488
489 Files may be retrieved by running `da.from_tiledb` with the same URI, and any
490 necessary arguments.
491
492
493 Intermediate storage
494 --------------------
495
496 .. autosummary::
497 store
498
499 In some cases, one may wish to store an intermediate result in long term
500 storage. This differs from ``persist``, which is mainly used to manage
501 intermediate results within Dask that don't necessarily have longevity.
502 Also it differs from storing final results as these mark the end of the Dask
503 graph. Thus intermediate results are easier to reuse without reloading data.
504 Intermediate storage is mainly useful in cases where the data is needed
505 outside of Dask (e.g. on disk, in a database, in the cloud, etc.). It can
506 be useful as a checkpoint for long running or error-prone computations.
507
508 The intermediate storage use case differs from the typical storage use case as
509 a Dask Array is returned to the user that represents the result of that
510 storage operation. This is typically done by setting the ``store`` function's
511 ``return_stored`` flag to ``True``.
512
513 .. code-block:: python
514
515 x.store() # stores data, returns nothing
516 x = x.store(return_stored=True) # stores data, returns new dask array backed by that data
517
518 The user can then decide whether the
519 storage operation happens immediately (by setting the ``compute`` flag to
520 ``True``) or later (by setting the ``compute`` flag to ``False``). In all
521 other ways, this behaves the same as a normal call to ``store``. Some examples
522 are shown below.
523
524 .. code-block:: Python
525
526 >>> import dask.array as da
527 >>> import zarr as zr
528 >>> c = (2, 2)
529 >>> d = da.ones((10, 11), chunks=c)
530 >>> z1 = zr.open_array('lazy.zarr', shape=d.shape, dtype=d.dtype, chunks=c)
531 >>> z2 = zr.open_array('eager.zarr', shape=d.shape, dtype=d.dtype, chunks=c)
532 >>> d1 = d.store(z1, compute=False, return_stored=True)
533 >>> d2 = d.store(z2, compute=True, return_stored=True)
534
535 This can be combined with any other storage strategies either noted above, in
536 the docs or for any specialized storage types.
537
538
539 Plugins
540 =======
541
542 We can run arbitrary user-defined functions on Dask arrays whenever they are
543 constructed. This allows us to build a variety of custom behaviors that improve
544 debugging, user warning, etc. You can register a list of functions to run on
545 all Dask arrays to the global ``array_plugins=`` value:
546
547 .. code-block:: python
548
549 >>> def f(x):
550 ... print(x.nbytes)
551
552 >>> with dask.config.set(array_plugins=[f]):
553 ... x = da.ones((10, 1), chunks=(5, 1))
554 ... y = x.dot(x.T)
555 80
556 80
557 800
558 800
559
560 If the plugin function returns None, then the input Dask array will be returned
561 without change. If the plugin function returns something else, then that value
562 will be the result of the constructor.
563
564 Examples
565 --------
566
567 Automatically compute
568 ~~~~~~~~~~~~~~~~~~~~~
569
570 We may wish to turn some Dask array code into normal NumPy code. This is
571 useful, for example, to track down errors immediately that would otherwise be
572 hidden by Dask's lazy semantics:
573
574 .. code-block:: python
575
576 >>> with dask.config.set(array_plugins=[lambda x: x.compute()]):
577 ... x = da.arange(5, chunks=2)
578
579 >>> x # this was automatically converted into a numpy array
580 array([0, 1, 2, 3, 4])
581
582 Warn on large chunks
583 ~~~~~~~~~~~~~~~~~~~~
584
585 We may wish to warn users if they are creating chunks that are too large:
586
587 .. code-block:: python
588
589 def warn_on_large_chunks(x):
590 shapes = list(itertools.product(*x.chunks))
591 nbytes = [x.dtype.itemsize * np.prod(shape) for shape in shapes]
592 if any(nb > 1e9 for nb in nbytes):
593 warnings.warn("Array contains very large chunks")
594
595 with dask.config.set(array_plugins=[warn_on_large_chunks]):
596 ...
597
598 Combine
599 ~~~~~~~
600
601 You can also combine these plugins into a list. They will run one after the
602 other, chaining results through them:
603
604 .. code-block:: python
605
606 with dask.config.set(array_plugins=[warn_on_large_chunks, lambda x: x.compute()]):
607 ...
608
609
610 .. _Zarr: https://zarr.readthedocs.io/en/stable/