Debian Codegraph @

docs/gallery/plot_generic_data_chunk_tutorial.py

raw
1 """
2
3 .. _genericdci-tutorial:
4
5 GenericDataChunkIterator Tutorial
6 ==================================
7
8 This is a tutorial for interacting with :py:class:`~hdmf.data_utils.GenericDataChunkIterator` objects. This tutorial
9 is written for beginners and does not describe the full capabilities and nuances
10 of the functionality. This tutorial is designed to give
11 you basic familiarity with how :py:class:`~hdmf.data_utils.GenericDataChunkIterator` works and help you get started
12 with creating a specific instance for your data format or API access pattern.
13
14 Introduction
15 ------------
16 The :py:class:`~hdmf.data_utils.GenericDataChunkIterator` class represents a semi-abstract
17 version of a :py:class:`~hdmf.data_utils.AbstractDataChunkIterator` that automatically handles the selection
18 of buffer regions
19 and resolves communication of compatible chunk regions within a H5DataIO wrapper. It does not,
20 however, know how data (values) or metadata (data type, full shape) ought to be directly
21 accessed. This is by intention to be fully agnostic to a range of indexing methods and
22 format-independent APIs, rather than make strong assumptions about how data ranges are to be sliced.
23
24 Constructing a simple child class
25 ---------------------------------
26 We will begin with a simple example case of data access to a standard Numpy array.
27 To create a :py:class:`~hdmf.data_utils.GenericDataChunkIterator` that accomplishes this,
28 we begin by defining our child class.
29 """
30
31 # sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnail_generic_data_chunk_tutorial.png'
32 import numpy as np
33
34 from hdmf.data_utils import GenericDataChunkIterator
35
36
37 class NumpyArrayDataChunkIterator(GenericDataChunkIterator):
38 def __init__(self, array: np.ndarray, **kwargs):
39 self.array = array
40 super().__init__(**kwargs)
41
42 def _get_data(self, selection):
43 return self.array[selection]
44
45 def _get_maxshape(self):
46 return self.array.shape
47
48 def _get_dtype(self):
49 return self.array.dtype
50
51
52 # To instantiate this class on an array to allow iteration over buffer_shapes,
53 my_array = np.random.randint(low=0, high=10, size=(12, 6), dtype="int16")
54 my_custom_iterator = NumpyArrayDataChunkIterator(array=my_array)
55
56 # and this iterator now behaves as a standard Python generator (i.e., it can only be exhausted once)
57 # that returns DataChunk objects for each buffer.
58 for buffer in my_custom_iterator:
59 print(buffer.data)
60
61 ###############################################################################
62 # Intended use for advanced data I/O
63 # ----------------------------------
64 # Of course, the real use case for this class is intended for when the amount of data stored on a
65 # hard drive is larger than what can be read into RAM. Hence the goal is to read only an amount of
66 # data with a size in gigabytes (GB) at or below the `buffer_gb` argument (defaults to 1 GB).
67
68 # This design can be seen if we increase the amount of data in our example code
69 my_array = np.random.randint(low=0, high=10, size=(20000, 5000), dtype="int32")
70 my_custom_iterator = NumpyArrayDataChunkIterator(array=my_array, buffer_gb=0.2)
71
72 for j, buffer in enumerate(my_custom_iterator, start=1):
73 print(f"Buffer number {j} returns data from selection: {buffer.selection}")
74
75 ###############################################################################
76 # .. note::
77 # Technically, in this example the total data is still fully loaded into RAM from the initial Numpy array.
78 # A more accurate use case would be achieved from writing the test_array to a temporary file on your system
79 # and loading it back with np.memmap, which is a subtype of Numpy arrays that do not immediately load the data.
80
81 ###############################################################################
82 # Writing to an HDF5 file with full control of shape arguments
83 # ------------------------------------------------------------
84 # The true intention of returning data selections of this form, and within a DataChunk object,
85 # is to write these piecewise to an HDF5 dataset.
86
87 # This is where the importance of the underlying `chunk_shape` comes in, and why it is critical to performance
88 # that it perfectly subsets the `buffer_shape`.
89 import h5py
90
91 maxshape = (20000, 5000)
92 buffer_shape = (10000, 2500)
93 chunk_shape = (1000, 250)
94
95 my_array = np.random.randint(low=0, high=10, size=maxshape, dtype="int32")
96 my_custom_iterator = NumpyArrayDataChunkIterator(array=my_array, buffer_shape=buffer_shape, chunk_shape=chunk_shape)
97 out_file = "my_temporary_test_file.hdf5"
98 with h5py.File(name=out_file, mode="w") as f:
99 dset = f.create_dataset(name="test", shape=maxshape, dtype="int16", chunks=my_custom_iterator.chunk_shape)
100 for buffer in my_custom_iterator:
101 dset[buffer.selection] = buffer.data
102 # Remember to remove the temporary file after running this and exploring the contents!
103
104 ###############################################################################
105 # .. note::
106 # Here we explicitly set the `chunks` value in the HDF5 dataset object; however, a nice part of the design of this
107 # iterator is that when wrapped in a ``hdmf.backends.hdf5.h5_utils.H5DataIO`` that is called within a
108 # ``hdmf.backends.hdf5.h5tools.HDF5IO`` context with a corresponding ``hdmf.container.Container``, these details
109 # will be automatically parsed.
110
111 ###############################################################################
112 # .. note::
113 # There is some overlap here in nomenclature between HDMF and HDF5. The term *chunk* in both
114 # HDMF and HDF5 refer to a subset of dataset, however, in HDF5 a chunk is a piece of dataset on disk,
115 # whereas in the context of the :py:class:`~hdmf.data_utils.DataChunk` iteration is a block of data in memory.
116 # As such, the
117 # requirements on the shape and size of chunks are different. In HDF5 these chunks are pieces
118 # of a dataset that get compressed and cached together, and they should usually be small in size for
119 # optimal performance (typically 1 MB or less). In contrast, a :py:class:`~hdmf.data_utils.DataChunk` in
120 # HDMF acts as a block of data for writing data to dataset, and spans multiple HDF5 chunks to improve performance.
121 # This is achieved by avoiding repeat
122 # updates to the same ``Chunk`` in the HDF5 file, :py:class:`~hdmf.data_utils.DataChunk` objects for write
123 # should align with ``Chunks`` in the HDF5 file, i.e., the ``DataChunk.selection``
124 # should fully cover one or more ``Chunks`` in the HDF5 file to avoid repeat updates to the same
125 # ``Chunks`` in the HDF5 file. This is what the `buffer` of the :py:class`~hdmf.data_utils.GenericDataChunkIterator`
126 # does, which upon each iteration returns a single
127 # :py:class:`~hdmf.data_utils.DataChunk` object (by default > 1 GB) that perfectly spans many HDF5 chunks
128 # (by default < 1 MB) to help reduce the number of small I/O operations
129 # and help improve performance. In practice, the `buffer` should usually be even larger than the default, i.e,
130 # as much free RAM as can be safely used.
131
132 ###############################################################################
133 # Remove the test file
134 import os
135 if os.path.exists(out_file):
136 os.remove(out_file)