Debian Codegraph @

tests/unit/utils_test/test_core_GenericDataChunkIterator.py

raw
1 import unittest
2 import pickle
3 import numpy as np
4 from pathlib import Path
5 from tempfile import mkdtemp
6 from shutil import rmtree
7 from typing import Tuple, Iterable, Callable, Union
8 from sys import version_info
9
10 import h5py
11 from numpy.testing import assert_array_equal
12
13 from hdmf.data_utils import GenericDataChunkIterator
14 from hdmf.testing import TestCase
15
16 try:
17 import tqdm # noqa: F401
18 TQDM_INSTALLED = True
19 except ImportError:
20 TQDM_INSTALLED = False
21
22
23 class PickleableNumpyArrayDataChunkIterator(GenericDataChunkIterator):
24 def __init__(self, array: np.ndarray, **kwargs):
25 self.array = array
26 self._kwargs = kwargs
27 super().__init__(**kwargs)
28
29 def _get_data(self, selection) -> np.ndarray:
30 return self.array[selection]
31
32 def _get_maxshape(self) -> Tuple[int, ...]:
33 return self.array.shape
34
35 def _get_dtype(self) -> np.dtype:
36 return self.array.dtype
37
38 def _to_dict(self) -> dict:
39 return dict(array=pickle.dumps(self.array), kwargs=self._kwargs)
40
41 @staticmethod
42 def _from_dict(dictionary: dict) -> Callable:
43 array = pickle.loads(dictionary["array"])
44 return PickleableNumpyArrayDataChunkIterator(array=array, **dictionary["kwargs"])
45
46
47 class GenericDataChunkIteratorTests(TestCase):
48 class TestNumpyArrayDataChunkIterator(GenericDataChunkIterator):
49 def __init__(self, array: np.ndarray, **kwargs):
50 self.array = array
51 super().__init__(**kwargs)
52
53 def _get_data(self, selection) -> np.ndarray:
54 return self.array[selection]
55
56 def _get_maxshape(self) -> Tuple[int, ...]:
57 return self.array.shape
58
59 def _get_dtype(self) -> np.dtype:
60 return self.array.dtype
61
62 class TestNumpyArrayDataChunkIteratorWithNumpyDtypeShape(GenericDataChunkIterator):
63 def __init__(self, array: np.ndarray, **kwargs):
64 self.array = array
65 super().__init__(**kwargs)
66
67 def _get_data(self, selection) -> np.ndarray:
68 return self.array[selection]
69
70 def _get_maxshape(self) -> Tuple[np.uint64, ...]: # Undesirable return type, but can be handled
71 return tuple(np.uint64(x) for x in self.array.shape)
72
73 def _get_dtype(self) -> np.dtype:
74 return self.array.dtype
75
76 @classmethod
77 def setUpClass(cls):
78 cls.test_dir = Path(mkdtemp())
79 cls.test_array = np.empty(shape=(2000, 384), dtype="int16")
80
81 @classmethod
82 def tearDownClass(cls):
83 rmtree(cls.test_dir)
84
85 def check_first_data_chunk_call(self, expected_selection, iterator_options):
86 test = self.TestNumpyArrayDataChunkIterator(array=self.test_array, **iterator_options)
87 first_data_chunk = next(test)
88 self.assertEqual(first_data_chunk.selection, expected_selection)
89 np.testing.assert_array_equal(first_data_chunk, self.test_array[expected_selection])
90
91 def check_direct_hdf5_write(self, iterator_options):
92 iterator = self.TestNumpyArrayDataChunkIterator(
93 array=self.test_array, **iterator_options
94 )
95 with h5py.File(name=self.test_dir / "test_generic_iterator_array.hdf5", mode="w") as f:
96 dset = f.create_dataset(
97 name="test", shape=self.test_array.shape, dtype="int16", chunks=iterator.chunk_shape
98 )
99 for chunk in iterator:
100 dset[chunk.selection] = chunk.data
101 np.testing.assert_array_equal(np.array(dset), self.test_array)
102 self.assertEqual(dset.chunks, iterator.chunk_shape)
103
104 def check_all_of_iterable_is_python_int(self, iterable: Iterable):
105 assert all(
106 tuple( # Easier to visualize failures in pytest with tuple vs. generator
107 isinstance(x, int) for x in iterable
108 )
109 )
110
111 def test_abstract_assertions(self):
112 class TestGenericDataChunkIterator(GenericDataChunkIterator):
113 pass
114
115 with self.assertRaisesWith(
116 exc_type=TypeError,
117 exc_msg=(
118 "Can't instantiate abstract class TestGenericDataChunkIterator with abstract methods "
119 "_get_data, _get_dtype, _get_maxshape"
120 ) if version_info < (3, 12) else (
121 "Can't instantiate abstract class TestGenericDataChunkIterator without an "
122 "implementation for abstract methods '_get_data', '_get_dtype', '_get_maxshape'"
123 ),
124 ):
125 TestGenericDataChunkIterator()
126
127 def test_joint_option_assertions(self):
128 with self.assertRaisesWith(
129 exc_type=AssertionError,
130 exc_msg="Only one of 'buffer_gb' or 'buffer_shape' can be specified!",
131 ):
132 self.TestNumpyArrayDataChunkIterator(array=self.test_array, buffer_shape=(2000, 384), buffer_gb=1)
133
134 with self.assertRaisesWith(
135 exc_type=AssertionError,
136 exc_msg="Only one of 'chunk_mb' or 'chunk_shape' can be specified!",
137 ):
138 self.TestNumpyArrayDataChunkIterator(array=self.test_array, chunk_shape=(1580, 316), chunk_mb=1)
139
140 chunk_shape = (2001, 384)
141 with self.assertRaisesWith(
142 exc_type=AssertionError,
143 exc_msg=(
144 f"Some dimensions of chunk_shape ({chunk_shape}) exceed the "
145 f"data dimensions ((2000, 384))!"
146 ),
147 ):
148 self.TestNumpyArrayDataChunkIterator(
149 array=self.test_array, chunk_shape=chunk_shape
150 )
151
152 buffer_shape = (1000, 192)
153 chunk_shape = (100, 384)
154 with self.assertRaisesWith(
155 exc_type=AssertionError,
156 exc_msg=(
157 f"Some dimensions of chunk_shape ({chunk_shape}) exceed the "
158 f"buffer shape ({buffer_shape})!"
159 ),
160 ):
161 self.TestNumpyArrayDataChunkIterator(
162 array=self.test_array, buffer_shape=buffer_shape, chunk_shape=chunk_shape
163 )
164
165 buffer_shape = (1000, 192)
166 chunk_shape = (1000, 5)
167 with self.assertRaisesWith(
168 exc_type=AssertionError,
169 exc_msg=(
170 f"Some dimensions of chunk_shape ({chunk_shape}) do not evenly divide the "
171 f"buffer shape ({buffer_shape})!"
172 ),
173 ):
174 self.TestNumpyArrayDataChunkIterator(
175 array=self.test_array, buffer_shape=buffer_shape, chunk_shape=chunk_shape
176 )
177
178 def test_buffer_option_assertion_negative_buffer_gb(self):
179 buffer_gb = -1
180 with self.assertRaisesWith(
181 exc_type=AssertionError,
182 exc_msg=f"buffer_gb ({buffer_gb}) must be greater than zero!"
183 ):
184 self.TestNumpyArrayDataChunkIterator(array=self.test_array, buffer_gb=buffer_gb)
185
186 def test_buffer_option_assertion_exceed_maxshape(self):
187 buffer_shape = (2001, 384)
188 with self.assertRaisesWith(
189 exc_type=AssertionError,
190 exc_msg=(
191 f"Some dimensions of buffer_shape ({buffer_shape}) exceed the data "
192 f"dimensions ({self.test_array.shape})!"
193 )
194 ):
195 self.TestNumpyArrayDataChunkIterator(array=self.test_array, buffer_shape=buffer_shape)
196
197 def test_buffer_option_assertion_negative_shape(self):
198 buffer_shape = (-1, 384)
199 with self.assertRaisesWith(
200 exc_type=AssertionError,
201 exc_msg=f"Some dimensions of buffer_shape ({buffer_shape}) are less than zero!"
202 ):
203 self.TestNumpyArrayDataChunkIterator(array=self.test_array, buffer_shape=buffer_shape)
204
205 def test_chunk_option_assertion_negative_chunk_mb(self):
206 chunk_mb = -1
207 with self.assertRaisesWith(
208 exc_type=AssertionError,
209 exc_msg=f"chunk_mb ({chunk_mb}) must be greater than zero!"
210 ):
211 self.TestNumpyArrayDataChunkIterator(array=self.test_array, chunk_mb=chunk_mb)
212
213 def test_chunk_option_assertion_negative_shape(self):
214 chunk_shape = (-1, 384)
215 with self.assertRaisesWith(
216 exc_type=AssertionError,
217 exc_msg=f"Some dimensions of chunk_shape ({chunk_shape}) are less than zero!"
218 ):
219 self.TestNumpyArrayDataChunkIterator(array=self.test_array, chunk_shape=chunk_shape)
220
221 @unittest.skipIf(not TQDM_INSTALLED, "optional tqdm module is not installed")
222 def test_progress_bar_assertion(self):
223 with self.assertWarnsWith(
224 warn_type=UserWarning,
225 exc_msg="Option 'total' in 'progress_bar_options' is not allowed to be over-written! Ignoring."
226 ):
227 _ = self.TestNumpyArrayDataChunkIterator(
228 array=self.test_array,
229 display_progress=True,
230 progress_bar_options=dict(total=5),
231 )
232
233 def test_private_to_dict_assertion(self):
234 with self.assertRaisesWith(
235 exc_type=NotImplementedError,
236 exc_msg="The `._to_dict()` method for pickling has not been defined for this DataChunkIterator!"
237 ):
238 iterator = self.TestNumpyArrayDataChunkIterator(array=self.test_array)
239 _ = iterator._to_dict()
240
241 def test_private_from_dict_assertion(self):
242 with self.assertRaisesWith(
243 exc_type=NotImplementedError,
244 exc_msg="The `._from_dict()` method for pickling has not been defined for this DataChunkIterator!"
245 ):
246 _ = self.TestNumpyArrayDataChunkIterator._from_dict(dict())
247
248 def test_direct_pickle_assertion(self):
249 with self.assertRaisesWith(
250 exc_type=NotImplementedError,
251 exc_msg="The `._to_dict()` method for pickling has not been defined for this DataChunkIterator!"
252 ):
253 iterator = self.TestNumpyArrayDataChunkIterator(array=self.test_array)
254 _ = pickle.dumps(iterator)
255
256 def test_maxshape_attribute_contains_int_type(self):
257 """Motivated by issues described in https://github.com/hdmf-dev/hdmf/pull/780 & 781 regarding return types."""
258 self.check_all_of_iterable_is_python_int(
259 iterable=self.TestNumpyArrayDataChunkIterator(array=self.test_array).maxshape
260 )
261
262 def test_automated_buffer_shape_attribute_int_type(self):
263 """Motivated by issues described in https://github.com/hdmf-dev/hdmf/pull/780 & 781 regarding return types."""
264 self.check_all_of_iterable_is_python_int(
265 iterable=self.TestNumpyArrayDataChunkIterator(array=self.test_array).buffer_shape
266 )
267
268 def test_automated_chunk_shape_attribute_int_type(self):
269 """Motivated by issues described in https://github.com/hdmf-dev/hdmf/pull/780 & 781 regarding return types."""
270 self.check_all_of_iterable_is_python_int(
271 iterable=self.TestNumpyArrayDataChunkIterator(array=self.test_array).chunk_shape
272 )
273
274 def test_np_dtype_maxshape_attribute_int_type(self):
275 """Motivated by issues described in https://github.com/hdmf-dev/hdmf/pull/780 & 781 regarding return types."""
276 self.check_all_of_iterable_is_python_int(
277 iterable=self.TestNumpyArrayDataChunkIteratorWithNumpyDtypeShape(array=self.test_array).maxshape
278 )
279
280 def test_manual_buffer_shape_attribute_int_type(self):
281 """Motivated by issues described in https://github.com/hdmf-dev/hdmf/pull/780 & 781 regarding return types."""
282 self.check_all_of_iterable_is_python_int(
283 iterable=self.TestNumpyArrayDataChunkIterator(
284 array=self.test_array,
285 chunk_shape=(np.uint64(100), np.uint64(2)),
286 buffer_shape=(np.uint64(200), np.uint64(4)),
287 ).buffer_shape
288 )
289
290 def test_manual_chunk_shape_attribute_int_type(self):
291 """Motivated by issues described in https://github.com/hdmf-dev/hdmf/pull/780 & 781 regarding return types."""
292 self.check_all_of_iterable_is_python_int(
293 iterable=self.TestNumpyArrayDataChunkIterator(
294 array=self.test_array,
295 chunk_shape=(np.uint64(100), np.uint64(2))
296 ).chunk_shape
297 )
298
299 def test_selection_slices_int_type(self):
300 """Motivated by issues described in https://github.com/hdmf-dev/hdmf/pull/780 & 781 regarding return types."""
301 iterator = self.TestNumpyArrayDataChunkIterator(array=self.test_array)
302 first_chunk = next(iterator)
303 stop_0 = first_chunk.selection[0].stop
304 start_0 = first_chunk.selection[0].start
305 stop_1 = first_chunk.selection[1].stop
306 start_1 = first_chunk.selection[1].start
307
308 self.check_all_of_iterable_is_python_int(iterable=(stop_0, start_0, stop_1, start_1))
309
310 def test_num_buffers(self):
311 buffer_shape = (950, 190)
312 chunk_shape = (50, 38)
313 expected_num_buffers = 9
314
315 test = self.TestNumpyArrayDataChunkIterator(
316 array=self.test_array, buffer_shape=buffer_shape, chunk_shape=chunk_shape
317 )
318 self.assertEqual(first=test.num_buffers, second=expected_num_buffers)
319
320 def test_numpy_array_chunk_iterator(self):
321 iterator_options = dict()
322 self.check_first_data_chunk_call(
323 expected_selection=(slice(0, 2000), slice(0, 384)), iterator_options=iterator_options
324 )
325 self.check_direct_hdf5_write(iterator_options=iterator_options)
326
327 def test_buffer_shape_option(self):
328 expected_buffer_shape = (1580, 316)
329 iterator_options = dict(buffer_shape=expected_buffer_shape, chunk_mb=1.0)
330 self.check_first_data_chunk_call(
331 expected_selection=tuple([slice(0, buffer_shape_axis) for buffer_shape_axis in expected_buffer_shape]),
332 iterator_options=iterator_options,
333 )
334 self.check_direct_hdf5_write(iterator_options=iterator_options)
335
336 def test_buffer_gb_option(self):
337 # buffer is smaller than chunk; should collapse to chunk shape
338 resulting_buffer_shape = (1580, 316)
339 iterator_options = dict(buffer_gb=0.0005, chunk_mb=1.0)
340 self.check_first_data_chunk_call(
341 expected_selection=tuple(
342 [
343 slice(0, buffer_shape_axis)
344 for buffer_shape_axis in resulting_buffer_shape
345 ]
346 ),
347 iterator_options=iterator_options,
348 )
349 self.check_direct_hdf5_write(iterator_options=iterator_options)
350
351 # buffer is larger than total data size; should collapse to maxshape
352 resulting_buffer_shape = (2000, 384)
353 for buffer_gb_input_dtype_pass in [2, 2.0]:
354 iterator_options = dict(buffer_gb=2)
355 self.check_first_data_chunk_call(
356 expected_selection=tuple(
357 [
358 slice(0, buffer_shape_axis)
359 for buffer_shape_axis in resulting_buffer_shape
360 ]
361 ),
362 iterator_options=iterator_options,
363 )
364 self.check_direct_hdf5_write(iterator_options=iterator_options)
365
366 def test_chunk_shape_option(self):
367 test_chunk_shape = (1580, 316)
368 iterator = self.TestNumpyArrayDataChunkIterator(array=self.test_array, chunk_shape=test_chunk_shape)
369 self.assertEqual(iterator.chunk_shape, test_chunk_shape)
370
371 def test_chunk_mb_option(self):
372 expected_chunk_shape = (1115, 223)
373 iterator = self.TestNumpyArrayDataChunkIterator(array=self.test_array, chunk_mb=0.5)
374 self.assertEqual(iterator.chunk_shape, expected_chunk_shape)
375
376 def test_chunk_mb_option_larger_than_total_size(self):
377 """Chunk is larger than total data size; should collapse to maxshape."""
378 expected_chunk_shape = (2000, 384)
379 iterator = self.TestNumpyArrayDataChunkIterator(array=self.test_array, chunk_mb=2)
380 self.assertEqual(iterator.chunk_shape, expected_chunk_shape)
381
382 def test_chunk_mb_option_while_condition(self):
383 """Test to evoke while condition of default shaping method."""
384 expected_chunk_shape = (2, 79, 79)
385 special_array = np.random.randint(low=-(2 ** 15), high=2 ** 15 - 1, size=(2, 2000, 2000), dtype="int16")
386 iterator = self.TestNumpyArrayDataChunkIterator(array=special_array, chunk_mb=1.0)
387 self.assertEqual(iterator.chunk_shape, expected_chunk_shape)
388
389 def test_chunk_mb_option_while_condition_unit_maxshape_axis(self):
390 """Test to evoke while condition of default shaping method."""
391 expected_chunk_shape = (1, 79, 79)
392 special_array = np.random.randint(low=-(2 ** 15), high=2 ** 15 - 1, size=(1, 2000, 2000), dtype="int16")
393 iterator = self.TestNumpyArrayDataChunkIterator(array=special_array, chunk_mb=1.0)
394 self.assertEqual(iterator.chunk_shape, expected_chunk_shape)
395
396 @unittest.skipIf(not TQDM_INSTALLED, "optional tqdm module is not installed")
397 def test_progress_bar(self):
398 out_text_file = self.test_dir / "test_progress_bar.txt"
399 desc = "Testing progress bar..."
400 with open(file=out_text_file, mode="w") as file:
401 iterator = self.TestNumpyArrayDataChunkIterator(
402 array=self.test_array, display_progress=True, progress_bar_options=dict(file=file, desc=desc)
403 )
404 j = 0
405 for buffer in iterator:
406 j += 1 # dummy operation; must be silent for proper updating of bar
407 with open(file=out_text_file, mode="r") as file:
408 first_line = file.read()
409 self.assertIn(member=desc, container=first_line)
410
411 @unittest.skipIf(not TQDM_INSTALLED, "optional tqdm module is not installed")
412 def test_progress_bar_class(self):
413
414 class MyCustomProgressBar(tqdm.tqdm):
415 def update(self, n: int = 1) -> Union[bool, None]:
416 displayed = super().update(n)
417 print(f"Custom injection on step {n}") # noqa: T201
418
419 return displayed
420
421 out_text_file = self.test_dir / "test_progress_bar_class.txt"
422 desc = "Testing progress bar..."
423 with open(file=out_text_file, mode="w") as file:
424 iterator = self.TestNumpyArrayDataChunkIterator(
425 array=self.test_array,
426 display_progress=True,
427 progress_bar_class=MyCustomProgressBar,
428 progress_bar_options=dict(file=file, desc=desc),
429 )
430 j = 0
431 for buffer in iterator:
432 j += 1 # dummy operation; must be silent for proper updating of bar
433 with open(file=out_text_file, mode="r") as file:
434 first_line = file.read()
435 self.assertIn(member=desc, container=first_line)
436
437 @unittest.skipIf(not TQDM_INSTALLED, "optional tqdm module is installed")
438 def test_progress_bar_no_options(self):
439 dci = self.TestNumpyArrayDataChunkIterator(array=self.test_array, display_progress=True)
440 self.assertIsNotNone(dci.progress_bar)
441 self.assertTrue(dci.display_progress)
442
443 @unittest.skipIf(TQDM_INSTALLED, "optional tqdm module is not installed")
444 def test_tqdm_not_installed(self):
445 with self.assertWarnsWith(
446 warn_type=UserWarning,
447 exc_msg=("You must install tqdm to use the progress bar feature (pip install tqdm)! "
448 "Progress bar is disabled.")
449 ):
450 dci = self.TestNumpyArrayDataChunkIterator(
451 array=self.test_array,
452 display_progress=True,
453 )
454 self.assertFalse(dci.display_progress)
455
456 def test_pickle(self):
457 pre_dump_iterator = PickleableNumpyArrayDataChunkIterator(array=self.test_array)
458 post_dump_iterator = pickle.loads(pickle.dumps(pre_dump_iterator))
459
460 assert isinstance(post_dump_iterator, PickleableNumpyArrayDataChunkIterator)
461 assert post_dump_iterator.chunk_shape == pre_dump_iterator.chunk_shape
462 assert post_dump_iterator.buffer_shape == pre_dump_iterator.buffer_shape
463 assert_array_equal(post_dump_iterator.array, pre_dump_iterator.array)