Debian Codegraph @

tests/unit/common/test_table.py

raw
1 from collections import OrderedDict
2 import h5py
3 import numpy as np
4 import os
5 import pandas as pd
6 import unittest
7
8 from hdmf import Container
9 from hdmf import TermSet, TermSetWrapper
10 from hdmf.backends.hdf5 import H5DataIO, HDF5IO
11 from hdmf.backends.hdf5.h5tools import H5_TEXT, H5PY_3
12 from hdmf.common import (
13 DynamicTable,
14 VectorData,
15 VectorIndex,
16 ElementIdentifiers,
17 EnumData,
18 DynamicTableRegion,
19 get_manager,
20 SimpleMultiContainer)
21 from hdmf.testing import TestCase, H5RoundTripMixin, remove_test_file
22 from hdmf.utils import StrDataset
23 from hdmf.data_utils import DataChunkIterator
24
25 from tests.unit.helpers.utils import (
26 get_temp_filepath,
27 FooExtendDynamicTable0,
28 FooExtendDynamicTable1,
29 FooExtendDynamicTable2,
30 )
31
32 try:
33 import linkml_runtime # noqa: F401
34 REQUIREMENTS_INSTALLED = True
35 except ImportError:
36 REQUIREMENTS_INSTALLED = False
37
38
39 class TestDynamicTable(TestCase):
40
41 def setUp(self):
42 self.spec = [
43 {'name': 'foo', 'description': 'foo column'},
44 {'name': 'bar', 'description': 'bar column'},
45 {'name': 'baz', 'description': 'baz column'},
46 ]
47 self.data = [
48 [1, 2, 3, 4, 5],
49 [10.0, 20.0, 30.0, 40.0, 50.0],
50 ['cat', 'dog', 'bird', 'fish', 'lizard']
51 ]
52
53 def with_table_columns(self):
54 cols = [VectorData(**d) for d in self.spec]
55 table = DynamicTable(name="with_table_columns", description='a test table', columns=cols)
56 return table
57
58 def with_columns_and_data(self):
59 columns = [
60 VectorData(name=s['name'], description=s['description'], data=d)
61 for s, d in zip(self.spec, self.data)
62 ]
63 return DynamicTable(name="with_columns_and_data", description='a test table', columns=columns)
64
65 def with_spec(self):
66 table = DynamicTable(name="with_spec", description='a test table', columns=self.spec)
67 return table
68
69 def check_empty_table(self, table):
70 self.assertIsInstance(table.columns, tuple)
71 self.assertIsInstance(table.columns[0], VectorData)
72 self.assertEqual(len(table.columns), 3)
73 self.assertTupleEqual(table.colnames, ('foo', 'bar', 'baz'))
74
75 def test_constructor_table_columns(self):
76 table = self.with_table_columns()
77 self.assertEqual(table.name, 'with_table_columns')
78 self.check_empty_table(table)
79
80 def test_constructor_spec(self):
81 table = self.with_spec()
82 self.assertEqual(table.name, 'with_spec')
83 self.check_empty_table(table)
84
85 def check_table(self, table):
86 self.assertEqual(len(table), 5)
87 self.assertEqual(table.columns[0].data, [1, 2, 3, 4, 5])
88 self.assertEqual(table.columns[1].data, [10.0, 20.0, 30.0, 40.0, 50.0])
89 self.assertEqual(table.columns[2].data, ['cat', 'dog', 'bird', 'fish', 'lizard'])
90 self.assertEqual(table.id.data, [0, 1, 2, 3, 4])
91 self.assertTrue(hasattr(table, 'baz'))
92
93 def test_constructor_ids_default(self):
94 columns = [VectorData(name=s['name'], description=s['description'], data=d)
95 for s, d in zip(self.spec, self.data)]
96 table = DynamicTable(name="with_spec", description='a test table', columns=columns)
97 self.check_table(table)
98
99 def test_constructor_ids(self):
100 columns = [VectorData(name=s['name'], description=s['description'], data=d)
101 for s, d in zip(self.spec, self.data)]
102 table = DynamicTable(name="with_columns", description='a test table', id=[0, 1, 2, 3, 4], columns=columns)
103 self.check_table(table)
104
105 def test_constructor_ElementIdentifier_ids(self):
106 columns = [VectorData(name=s['name'], description=s['description'], data=d)
107 for s, d in zip(self.spec, self.data)]
108 ids = ElementIdentifiers(name='ids', data=[0, 1, 2, 3, 4])
109 table = DynamicTable(name="with_columns", description='a test table', id=ids, columns=columns)
110 self.check_table(table)
111
112 def test_constructor_ids_bad_ids(self):
113 columns = [VectorData(name=s['name'], description=s['description'], data=d)
114 for s, d in zip(self.spec, self.data)]
115 msg = "Must provide same number of ids as length of columns"
116 with self.assertRaisesWith(ValueError, msg):
117 DynamicTable(name="with_columns", description='a test table', id=[0, 1], columns=columns)
118
119 def test_constructor_all_columns_are_iterators(self):
120 """
121 All columns are specified via AbstractDataChunkIterator but no id's are given.
122 Test that an error is being raised because we can't determine the id's.
123 """
124 data = np.array([1., 2., 3.])
125 column = VectorData(name="TestColumn", description="", data=DataChunkIterator(data))
126 msg = ("Cannot determine row id's for table. Must provide ids with same length "
127 "as the columns when all columns are specified via DataChunkIterator objects.")
128 with self.assertRaisesWith(ValueError, msg):
129 _ = DynamicTable(name="TestTable", description="", columns=[column])
130 # now test that when we supply id's that the error goes away
131 _ = DynamicTable(name="TestTable", description="", columns=[column], id=list(range(3)))
132
133 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
134 def test_add_col_validate(self):
135 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
136 col1 = VectorData(
137 name='Species_1',
138 description='...',
139 data=TermSetWrapper(value=['Homo sapiens'], termset=terms)
140 )
141 species = DynamicTable(name='species', description='My species', columns=[col1])
142 species.add_column(name='Species_2',
143 description='Species data',
144 data=TermSetWrapper(value=['Mus musculus'], termset=terms))
145 expected_df_data = \
146 {'Species_1': {0: 'Homo sapiens'},
147 'Species_2': {0: 'Mus musculus'}}
148 expected_df = pd.DataFrame.from_dict(expected_df_data)
149 expected_df.index.name = 'id'
150 pd.testing.assert_frame_equal(species.to_dataframe(), expected_df)
151
152 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
153 def test_add_col_validate_bad_data(self):
154 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
155 col1 = VectorData(
156 name='Species_1',
157 description='...',
158 data=TermSetWrapper(value=['Homo sapiens'], termset=terms)
159 )
160 species = DynamicTable(name='species', description='My species', columns=[col1])
161 with self.assertRaises(ValueError):
162 species.add_column(name='Species_2',
163 description='Species data',
164 data=TermSetWrapper(value=['bad data'],
165 termset=terms))
166
167 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
168 def test_add_row_validate(self):
169 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
170 col1 = VectorData(
171 name='Species_1',
172 description='...',
173 data=TermSetWrapper(value=['Homo sapiens'], termset=terms)
174 )
175 col2 = VectorData(
176 name='Species_2',
177 description='...',
178 data=TermSetWrapper(value=['Mus musculus'], termset=terms)
179 )
180 species = DynamicTable(name='species', description='My species', columns=[col1,col2])
181 species.add_row(Species_1='Myrmecophaga tridactyla', Species_2='Ursus arctos horribilis')
182 expected_df_data = \
183 {'Species_1': {0: 'Homo sapiens', 1: 'Myrmecophaga tridactyla'},
184 'Species_2': {0: 'Mus musculus', 1: 'Ursus arctos horribilis'}}
185 expected_df = pd.DataFrame.from_dict(expected_df_data)
186 expected_df.index.name = 'id'
187 pd.testing.assert_frame_equal(species.to_dataframe(), expected_df)
188
189 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
190 def test_add_row_validate_bad_data_one_col(self):
191 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
192 col1 = VectorData(
193 name='Species_1',
194 description='...',
195 data=TermSetWrapper(value=['Homo sapiens'], termset=terms)
196 )
197 col2 = VectorData(
198 name='Species_2',
199 description='...',
200 data=TermSetWrapper(value=['Mus musculus'], termset=terms)
201 )
202 species = DynamicTable(name='species', description='My species', columns=[col1,col2])
203 with self.assertRaises(ValueError):
204 species.add_row(Species_1='bad', Species_2='Ursus arctos horribilis')
205
206 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
207 def test_add_row_validate_bad_data_all_col(self):
208 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
209 col1 = VectorData(
210 name='Species_1',
211 description='...',
212 data=TermSetWrapper(value=['Homo sapiens'], termset=terms)
213 )
214 col2 = VectorData(
215 name='Species_2',
216 description='...',
217 data=TermSetWrapper(value=['Mus musculus'], termset=terms)
218 )
219 species = DynamicTable(name='species', description='My species', columns=[col1,col2])
220 with self.assertRaises(ValueError):
221 species.add_row(Species_1='bad data', Species_2='bad data')
222
223 def test_compound_data_append(self):
224 c_data = np.array([('Homo sapiens', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
225 c_data2 = np.array([('Mus musculus', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
226 compound_vector_data = VectorData(
227 name='Species_1',
228 description='...',
229 data=c_data
230 )
231 compound_vector_data.append(c_data2)
232
233 np.testing.assert_array_equal(compound_vector_data.data, np.append(c_data, c_data2))
234
235 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
236 def test_array_append_error(self):
237 c_data = np.array(['Homo sapiens'])
238 c_data2 = np.array(['Mus musculus'])
239
240 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
241 vectordata_termset = VectorData(
242 name='Species_1',
243 description='...',
244 data=TermSetWrapper(value=c_data, termset=terms)
245 )
246
247 with self.assertRaises(ValueError):
248 vectordata_termset.append(c_data2)
249
250 def test_compound_data_extend(self):
251 c_data = np.array([('Homo sapiens', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
252 c_data2 = np.array([('Mus musculus', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
253 compound_vector_data = VectorData(
254 name='Species_1',
255 description='...',
256 data=c_data
257 )
258 compound_vector_data.extend(c_data2)
259
260 np.testing.assert_array_equal(compound_vector_data.data, np.vstack((c_data, c_data2)))
261
262 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
263 def test_add_ref_wrapped_array_append(self):
264 data = np.array(['Homo sapiens'])
265 data2 = 'Mus musculus'
266 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
267 vector_data = VectorData(
268 name='Species_1',
269 description='...',
270 data=TermSetWrapper(value=data, termset=terms)
271 )
272 vector_data.append(data2)
273
274 np.testing.assert_array_equal(vector_data.data.data, np.append(data, data2))
275
276 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
277 def test_add_ref_wrapped_array_extend(self):
278 data = np.array(['Homo sapiens'])
279 data2 = np.array(['Mus musculus'])
280 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
281 vector_data = VectorData(
282 name='Species_1',
283 description='...',
284 data=TermSetWrapper(value=data, termset=terms)
285 )
286 vector_data.extend(data2)
287
288 np.testing.assert_array_equal(vector_data.data.data, np.vstack((data, data2)))
289
290 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
291 def test_add_ref_wrapped_compound_data_append(self):
292 c_data = np.array([('Homo sapiens', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
293 c_data2 = np.array([('Mus musculus', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
294 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
295 compound_vector_data = VectorData(
296 name='Species_1',
297 description='...',
298 data=TermSetWrapper(value=c_data, field='species', termset=terms)
299 )
300 compound_vector_data.append(c_data2)
301
302 np.testing.assert_array_equal(compound_vector_data.data.data, np.append(c_data, c_data2))
303
304 @unittest.skipIf(not REQUIREMENTS_INSTALLED, "optional LinkML module is not installed")
305 def test_add_ref_wrapped_compound_data_extend(self):
306 c_data = np.array([('Homo sapiens', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
307 c_data2 = np.array([('Mus musculus', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
308 terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml')
309 compound_vector_data = VectorData(
310 name='Species_1',
311 description='...',
312 data=TermSetWrapper(value=c_data, field='species', termset=terms)
313 )
314 compound_vector_data.extend(c_data2)
315
316 np.testing.assert_array_equal(compound_vector_data.data.data, np.vstack((c_data, c_data2)))
317
318 def test_constructor_bad_columns(self):
319 columns = ['bad_column']
320 msg = "'columns' must be a list of dict, VectorData, DynamicTableRegion, or VectorIndex"
321 with self.assertRaisesWith(ValueError, msg):
322 DynamicTable(name="with_columns", description='a test table', columns=columns)
323
324 def test_constructor_unequal_length_columns(self):
325 columns = [VectorData(name='col1', description='desc', data=[1, 2, 3]),
326 VectorData(name='col2', description='desc', data=[1, 2])]
327 msg = "Columns must be the same length"
328 with self.assertRaisesWith(ValueError, msg):
329 DynamicTable(name="with_columns", description='a test table', columns=columns)
330
331 def test_constructor_colnames(self):
332 """Test that passing colnames correctly sets the order of the columns."""
333 cols = [VectorData(**d) for d in self.spec]
334 table = DynamicTable(name="with_columns", description='a test table',
335 columns=cols, colnames=['baz', 'bar', 'foo'])
336 self.assertTupleEqual(table.columns, tuple(cols[::-1]))
337
338 def test_constructor_colnames_no_columns(self):
339 """Test that passing colnames without columns raises an error."""
340 msg = "Must supply 'columns' if specifying 'colnames'"
341 with self.assertRaisesWith(ValueError, msg):
342 DynamicTable(name="with_columns", description='a test table', colnames=['baz', 'bar', 'foo'])
343
344 def test_constructor_colnames_vectorindex(self):
345 """Test that passing colnames with a VectorIndex column puts the index in the right location in columns."""
346 cols = [VectorData(**d) for d in self.spec]
347 ind = VectorIndex(name='foo_index', data=list(), target=cols[0])
348 cols.append(ind)
349 table = DynamicTable(name="with_columns", description='a test table', columns=cols,
350 colnames=['baz', 'bar', 'foo'])
351 self.assertTupleEqual(table.columns, (cols[2], cols[1], ind, cols[0]))
352
353 def test_constructor_colnames_vectorindex_rev(self):
354 """Test that passing colnames with a VectorIndex column puts the index in the right location in columns."""
355 cols = [VectorData(**d) for d in self.spec]
356 ind = VectorIndex(name='foo_index', data=list(), target=cols[0])
357 cols.insert(0, ind) # put index before its target
358 table = DynamicTable(name="with_columns", description='a test table', columns=cols,
359 colnames=['baz', 'bar', 'foo'])
360 self.assertTupleEqual(table.columns, (cols[3], cols[2], ind, cols[1]))
361
362 def test_constructor_dup_index(self):
363 """Test that passing two indices for the same column raises an error."""
364 cols = [VectorData(**d) for d in self.spec]
365 cols.append(VectorIndex(name='foo_index', data=list(), target=cols[0]))
366 cols.append(VectorIndex(name='foo_index2', data=list(), target=cols[0]))
367 msg = "'columns' contains index columns with the same target: ['foo', 'foo']"
368 with self.assertRaisesWith(ValueError, msg):
369 DynamicTable(name="with_columns", description='a test table', columns=cols)
370
371 def test_constructor_index_missing_target(self):
372 """Test that passing an index without its target raises an error."""
373 cols = [VectorData(**d) for d in self.spec]
374 missing_col = cols.pop(2)
375 cols.append(VectorIndex(name='foo_index', data=list(), target=missing_col))
376 msg = "Found VectorIndex 'foo_index' but not its target 'baz'"
377 with self.assertRaisesWith(ValueError, msg):
378 DynamicTable(name="with_columns", description='a test table', columns=cols)
379
380 def add_rows(self, table):
381 table.add_row({'foo': 1, 'bar': 10.0, 'baz': 'cat'})
382 table.add_row({'foo': 2, 'bar': 20.0, 'baz': 'dog'})
383 table.add_row({'foo': 3, 'bar': 30.0, 'baz': 'bird'})
384 table.add_row({'foo': 4, 'bar': 40.0, 'baz': 'fish'})
385 table.add_row({'foo': 5, 'bar': 50.0, 'baz': 'lizard'})
386
387 def test_add_row(self):
388 table = self.with_spec()
389 self.add_rows(table)
390 self.check_table(table)
391
392 def test_get(self):
393 table = self.with_spec()
394 self.add_rows(table)
395 self.assertIsInstance(table.get('foo'), VectorData)
396 self.assertEqual(table.get('foo'), table['foo'])
397
398 def test_get_not_found(self):
399 table = self.with_spec()
400 self.add_rows(table)
401 self.assertIsNone(table.get('qux'))
402
403 def test_get_not_found_default(self):
404 table = self.with_spec()
405 self.add_rows(table)
406 self.assertEqual(table.get('qux', 1), 1)
407
408 def test_get_item(self):
409 table = self.with_spec()
410 self.add_rows(table)
411 self.check_table(table)
412
413 def test_add_column(self):
414 table = self.with_spec()
415 table.add_column(name='qux', description='qux column')
416 self.assertTupleEqual(table.colnames, ('foo', 'bar', 'baz', 'qux'))
417 self.assertTrue(hasattr(table, 'qux'))
418
419 def test_add_column_twice(self):
420 table = self.with_spec()
421 table.add_column(name='qux', description='qux column')
422
423 msg = "column 'qux' already exists in DynamicTable 'with_spec'"
424 with self.assertRaisesWith(ValueError, msg):
425 table.add_column(name='qux', description='qux column')
426
427 def test_add_column_vectorindex(self):
428 table = self.with_spec()
429 table.add_column(name='qux', description='qux column')
430 ind = VectorIndex(name='quux', data=list(), target=table['qux'])
431
432 msg = ("Passing a VectorIndex in for index may lead to unexpected behavior. This functionality will be "
433 "deprecated in a future version of HDMF.")
434 with self.assertWarnsWith(FutureWarning, msg):
435 table.add_column(name='bad', description='bad column', index=ind)
436
437 def test_add_column_multi_index(self):
438 table = self.with_spec()
439 table.add_column(name='qux', description='qux column', index=2)
440 table.add_row(foo=5, bar=50.0, baz='lizard',
441 qux=[
442 [1, 2, 3],
443 [1, 2, 3, 4]
444 ])
445 table.add_row(foo=5, bar=50.0, baz='lizard',
446 qux=[
447 [1, 2]
448 ]
449 )
450
451 def test_add_column_without_required_index(self):
452 """
453 Add a column with different element lengths without specifying an index parameter
454 """
455 table = self.with_spec()
456 table.add_row(foo=5, bar=50.0, baz='lizard')
457 table.add_row(foo=5, bar=50.0, baz='lizard')
458
459 # testing adding column without a necessary index parameter
460 lol_data = [[1, 2, 3], [1, 2, 3, 4]]
461 str_data = [['a', 'b'], ['a', 'b', 'c']]
462 empty_data = [[1, 2], []]
463 multi_nested_data = [[[1, 2, 3], [1, 2, 3, 4]], [1, 2]]
464 tuple_data = ((1, 2, 3), (1, 2, 3, 4))
465
466 msg = ("Data has elements with different lengths and therefore cannot be coerced into an N-dimensional "
467 "array. Use the 'index' argument when adding a column of data with different lengths.")
468 with self.assertWarnsWith(UserWarning, msg):
469 table.add_column(name='col1', description='', data=lol_data,)
470 with self.assertWarnsWith(UserWarning, msg):
471 table.add_column(name='col2', description='', data=str_data,)
472 with self.assertWarnsWith(UserWarning, msg):
473 table.add_column(name='col3', description='', data=empty_data,)
474 with self.assertWarnsWith(UserWarning, msg):
475 table.add_column(name='col4', description='', data=multi_nested_data,)
476 with self.assertWarnsWith(UserWarning, msg):
477 table.add_column(name='col5', description='', data=tuple_data,)
478
479 def test_add_column_without_required_index_and_no_ragged_check(self):
480 """
481 Add a column with different element lengths without checking for raggedness
482 """
483 lol_data = [[1, 2, 3], [1, 2, 3, 4]]
484 table = self.with_spec()
485 table.add_row(foo=5, bar=50.0, baz='lizard')
486 table.add_row(foo=5, bar=50.0, baz='lizard')
487 table.add_column(name='col1', description='', data=lol_data, check_ragged=False)
488
489 def test_add_row_without_required_index(self):
490 """
491 Add rows with different element lengths without specifying an index parameter
492 """
493
494 # test adding row of list data with different lengths without index parameter
495 msg = ("Data has elements with different lengths and therefore cannot be coerced into an N-dimensional "
496 "array. Use the 'index' argument when creating a column to add rows with different lengths.")
497 table = self.with_spec()
498 table.add_column(name='qux', description='qux column')
499 table.add_row(foo=5, bar=50.0, baz='lizard', qux=[1, 2, 3])
500 with self.assertWarnsWith(UserWarning, msg):
501 table.add_row(foo=5, bar=50.0, baz='lizard', qux=[1, 2, 3 ,4])
502
503 # test adding row of tuple/str data with different lengths without index parameter
504 table = self.with_spec()
505 table.add_column(name='qux', description='qux column')
506 table.add_row(foo=5, bar=50.0, baz='lizard', qux=('a', 'b'))
507 with self.assertWarnsWith(UserWarning, msg):
508 table.add_row(foo=5, bar=50.0, baz='lizard', qux=('a', 'b', 'c'))
509
510 def test_add_row_without_required_index_and_no_ragged_check(self):
511 """
512 Add rows with different element lengths without checking for raggedness
513 """
514 table = self.with_spec()
515 table.add_column(name='qux', description='qux column')
516 table.add_row(foo=5, bar=50.0, baz='lizard', qux=[1, 2, 3])
517 table.add_row(foo=5, bar=50.0, baz='lizard', qux=[1, 2, 3 ,4], check_ragged=False)
518
519 def test_add_column_auto_index_int(self):
520 """
521 Add a column as a list of lists after we have already added data so that we need to create a single VectorIndex
522 with index=1 as parameter
523 """
524 table = self.with_spec()
525 table.add_row(foo=5, bar=50.0, baz='lizard')
526 table.add_row(foo=5, bar=50.0, baz='lizard')
527 expected = [[1, 2, 3],
528 [1, 2, 3, 4]]
529 table.add_column(name='qux',
530 description='qux column',
531 data=expected,
532 index=1)
533 self.assertListEqual(table['qux'][:], expected)
534 self.assertListEqual(table.qux_index.data, [3, 7])
535 # Add more rows after we created the column
536 table.add_row(foo=5, bar=50.0, baz='lizard', qux=[10, 11, 12])
537 self.assertListEqual(table['qux'][:], expected + [[10, 11, 12], ])
538 self.assertListEqual(table.qux_index.data, [3, 7, 10])
539
540 def test_add_column_auto_index_bool(self):
541 """
542 Add a column as a list of lists after we have already added data so that we need to create a single VectorIndex
543 with index=True as parameter
544 """
545 table = self.with_spec()
546 table.add_row(foo=5, bar=50.0, baz='lizard')
547 table.add_row(foo=5, bar=50.0, baz='lizard')
548 expected = [[1, 2, 3],
549 [1, 2, 3, 4]]
550 table.add_column(name='qux',
551 description='qux column',
552 data=expected,
553 index=True)
554 self.assertListEqual(table['qux'][:], expected)
555 self.assertListEqual(table.qux_index.data, [3, 7])
556 # Add more rows after we created the column
557 table.add_row(foo=5, bar=50.0, baz='lizard', qux=[10, 11, 12])
558 self.assertListEqual(table['qux'][:], expected + [[10, 11, 12], ])
559 self.assertListEqual(table.qux_index.data, [3, 7, 10])
560
561 def test_add_column_auto_multi_index_int(self):
562 """
563 Add a column as a list of lists of lists after we have already added data so that we need to create a
564 two VectorIndex for the column so we set index=2 as parameter
565 """
566 table = self.with_spec()
567 table.add_row(foo=5, bar=50.0, baz='lizard')
568 table.add_row(foo=5, bar=50.0, baz='lizard')
569 expected = [[[1, 2, 3], [1]],
570 [[1, 2, 3, 4], [1, 2]]]
571 table.add_column(name='qux',
572 description='qux column',
573 data=expected,
574 index=2)
575 self.assertListEqual(table['qux'][:], expected)
576 self.assertListEqual(table.qux_index_index.data, [2, 4])
577 self.assertListEqual(table.qux_index.data, [3, 4, 8, 10])
578 # Add more rows after we created the column
579 table.add_row(foo=5, bar=50.0, baz='lizard', qux=[[10, 11, 12], ])
580 self.assertListEqual(table['qux'][:], expected + [[[10, 11, 12], ]])
581 self.assertListEqual(table.qux_index_index.data, [2, 4, 5])
582 self.assertListEqual(table.qux_index.data, [3, 4, 8, 10, 13])
583
584 def test_add_column_auto_multi_index_int_bad_index_levels(self):
585 """
586 Add a column as a list of lists if lists after we have already added data so that we need to create a
587 a two-level index, but we ask for either too many or too few index levels.
588 """
589 table = self.with_spec()
590 table.add_row(foo=5, bar=50.0, baz='lizard')
591 table.add_row(foo=5, bar=50.0, baz='lizard')
592 expected = [[[1, 2, 3], [1]],
593 [[1, 2, 3, 4], [1, 2]]]
594 msg = "Cannot automatically construct VectorIndex for nested array. Invalid data array element found."
595 with self.assertRaisesWith(ValueError, msg):
596 table.add_column(name='qux',
597 description='qux column',
598 data=expected,
599 index=3) # Too many index levels given
600 # Asking for too few indexes will work here but should then later fail on write
601 msg = ("Cannot automatically construct VectorIndex for nested array. "
602 "Column data contains arrays as cell values. Please check the 'data' and 'index' parameters.")
603 with self.assertRaisesWith(ValueError, msg + " 'index=1' may be too small for the given data."):
604 table.add_column(name='qux',
605 description='qux column',
606 data=expected,
607 index=1)
608 with self.assertRaisesWith(ValueError, msg + " 'index=True' may be too small for the given data."):
609 table.add_column(name='qux',
610 description='qux column',
611 data=expected,
612 index=True)
613
614 def test_add_column_auto_multi_index_int_with_empty_slots(self):
615 """
616 Add a column as a list of lists of lists after we have already added data so that we need to create 2
617 VectorIndex levels so we set index=2 as parameter. For the data the first two rows have no entries in the
618 multi-indexed column.
619 """
620 table = self.with_spec()
621 table.add_row(foo=5, bar=50.0, baz='lizard')
622 table.add_row(foo=5, bar=50.0, baz='lizard')
623 expected = [[[], []],
624 [[], []]]
625 table.add_column(name='qux',
626 description='qux column',
627 data=expected,
628 index=2)
629 self.assertListEqual(table['qux'][:], expected)
630 self.assertListEqual(table.qux_index_index.data, [2, 4])
631 self.assertListEqual(table.qux_index.data, [0, 0, 0, 0])
632 # Add more rows after we created the column
633 table.add_row(foo=5, bar=50.0, baz='lizard', qux=[[10, 11, 12], ])
634 self.assertListEqual(table['qux'][:], expected + [[[10, 11, 12], ]])
635 self.assertListEqual(table.qux_index_index.data, [2, 4, 5])
636 self.assertListEqual(table.qux_index.data, [0, 0, 0, 0, 3])
637
638 def test_auto_multi_index_required(self):
639
640 class TestTable(DynamicTable):
641 __columns__ = (dict(name='qux', description='qux column', index=3, required=True),)
642
643 table = TestTable(name='table_name', description='table_description')
644 self.assertIsInstance(table.qux, VectorData) # check that the attribute is set
645 self.assertIsInstance(table.qux_index, VectorIndex) # check that the attribute is set
646 self.assertIsInstance(table.qux_index_index, VectorIndex) # check that the attribute is set
647 self.assertIsInstance(table.qux_index_index_index, VectorIndex) # check that the attribute is set
648 table.add_row(
649 qux=[
650 [
651 [1, 2, 3],
652 [1, 2, 3, 4]
653 ]
654 ]
655 )
656 table.add_row(
657 qux=[
658 [
659 [1, 2]
660 ]
661 ]
662 )
663
664 expected = [
665 [
666 [
667 [1, 2, 3],
668 [1, 2, 3, 4]
669 ]
670 ],
671 [
672 [
673 [1, 2]
674 ]
675 ]
676 ]
677 self.assertListEqual(table['qux'][:], expected)
678 self.assertEqual(table.qux_index_index_index.data, [1, 2])
679
680 def test_auto_multi_index(self):
681
682 class TestTable(DynamicTable):
683 __columns__ = (dict(name='qux', description='qux column', index=3),) # this is optional
684
685 table = TestTable(name='table_name', description='table_description')
686 self.assertIsNone(table.qux) # these are reserved as attributes but not yet initialized
687 self.assertIsNone(table.qux_index)
688 self.assertIsNone(table.qux_index_index)
689 self.assertIsNone(table.qux_index_index_index)
690 table.add_row(
691 qux=[
692 [
693 [1, 2, 3],
694 [1, 2, 3, 4]
695 ]
696 ]
697 )
698 table.add_row(
699 qux=[
700 [
701 [1, 2]
702 ]
703 ]
704 )
705
706 expected = [
707 [
708 [
709 [1, 2, 3],
710 [1, 2, 3, 4]
711 ]
712 ],
713 [
714 [
715 [1, 2]
716 ]
717 ]
718 ]
719 self.assertListEqual(table['qux'][:], expected)
720 self.assertEqual(table.qux_index_index_index.data, [1, 2])
721
722 def test_getitem_row_num(self):
723 table = self.with_spec()
724 self.add_rows(table)
725 row = table[2]
726 self.assertTupleEqual(row.shape, (1, 3))
727 self.assertTupleEqual(tuple(row.iloc[0]), (3, 30.0, 'bird'))
728
729 def test_getitem_row_slice(self):
730 table = self.with_spec()
731 self.add_rows(table)
732 rows = table[1:3]
733 self.assertIsInstance(rows, pd.DataFrame)
734 self.assertTupleEqual(rows.shape, (2, 3))
735 self.assertTupleEqual(tuple(rows.iloc[1]), (3, 30.0, 'bird'))
736
737 def test_getitem_row_slice_with_step(self):
738 table = self.with_spec()
739 self.add_rows(table)
740 rows = table[0:5:2]
741 self.assertIsInstance(rows, pd.DataFrame)
742 self.assertTupleEqual(rows.shape, (3, 3))
743 self.assertEqual(rows.iloc[2].iloc[0], 5)
744 self.assertEqual(rows.iloc[2].iloc[1], 50.0)
745 self.assertEqual(rows.iloc[2].iloc[2], 'lizard')
746
747 def test_getitem_invalid_keytype(self):
748 table = self.with_spec()
749 self.add_rows(table)
750 with self.assertRaises(KeyError):
751 _ = table[0.1]
752
753 def test_getitem_col_select_and_row_slice(self):
754 table = self.with_spec()
755 self.add_rows(table)
756 col = table[1:3, 'bar']
757 self.assertEqual(len(col), 2)
758 self.assertEqual(col[0], 20.0)
759 self.assertEqual(col[1], 30.0)
760
761 def test_getitem_column(self):
762 table = self.with_spec()
763 self.add_rows(table)
764 col = table['bar']
765 self.assertEqual(col[0], 10.0)
766 self.assertEqual(col[1], 20.0)
767 self.assertEqual(col[2], 30.0)
768 self.assertEqual(col[3], 40.0)
769 self.assertEqual(col[4], 50.0)
770
771 def test_getitem_list_idx(self):
772 table = self.with_spec()
773 self.add_rows(table)
774 row = table[[0, 2, 4]]
775 self.assertEqual(len(row), 3)
776 self.assertTupleEqual(tuple(row.iloc[0]), (1, 10.0, 'cat'))
777 self.assertTupleEqual(tuple(row.iloc[1]), (3, 30.0, 'bird'))
778 self.assertTupleEqual(tuple(row.iloc[2]), (5, 50.0, 'lizard'))
779
780 def test_getitem_point_idx_colname(self):
781 table = self.with_spec()
782 self.add_rows(table)
783 val = table[2, 'bar']
784 self.assertEqual(val, 30.0)
785
786 def test_getitem_point_idx(self):
787 table = self.with_spec()
788 self.add_rows(table)
789 row = table[2]
790 self.assertTupleEqual(tuple(row.iloc[0]), (3, 30.0, 'bird'))
791
792 def test_getitem_point_idx_colidx(self):
793 table = self.with_spec()
794 self.add_rows(table)
795 val = table[2, 2]
796 self.assertEqual(val, 30.0)
797
798 def test_pandas_roundtrip(self):
799 df = pd.DataFrame({
800 'a': [1, 2, 3, 4],
801 'b': ['a', 'b', 'c', '4']
802 }, index=pd.Index(name='an_index', data=[2, 4, 6, 8]))
803
804 table = DynamicTable.from_dataframe(df, 'foo')
805 obtained = table.to_dataframe()
806 self.assertTrue(df.equals(obtained))
807
808 def test_to_dataframe(self):
809 table = self.with_columns_and_data()
810 data = OrderedDict()
811 for name in table.colnames:
812 if name == 'foo':
813 data[name] = [1, 2, 3, 4, 5]
814 elif name == 'bar':
815 data[name] = [10.0, 20.0, 30.0, 40.0, 50.0]
816 elif name == 'baz':
817 data[name] = ['cat', 'dog', 'bird', 'fish', 'lizard']
818 expected_df = pd.DataFrame(data)
819 obtained_df = table.to_dataframe()
820 self.assertTrue(expected_df.equals(obtained_df))
821
822 def test_from_dataframe(self):
823 df = pd.DataFrame({
824 'foo': [1, 2, 3, 4, 5],
825 'bar': [10.0, 20.0, 30.0, 40.0, 50.0],
826 'baz': ['cat', 'dog', 'bird', 'fish', 'lizard']
827 }).loc[:, ('foo', 'bar', 'baz')]
828
829 obtained_table = DynamicTable.from_dataframe(df, 'test')
830 self.check_table(obtained_table)
831
832 def test_from_dataframe_eq(self):
833 expected = DynamicTable(name='test_table', description='the expected table')
834 expected.add_column('a', '2d column')
835 expected.add_column('b', '1d column')
836 expected.add_row(a=[1, 2, 3], b='4')
837 expected.add_row(a=[1, 2, 3], b='5')
838 expected.add_row(a=[1, 2, 3], b='6')
839
840 df = pd.DataFrame({
841 'a': [[1, 2, 3],
842 [1, 2, 3],
843 [1, 2, 3]],
844 'b': ['4', '5', '6']
845 })
846 coldesc = {'a': '2d column', 'b': '1d column'}
847 received = DynamicTable.from_dataframe(df,
848 'test_table',
849 table_description='the expected table',
850 column_descriptions=coldesc)
851 self.assertContainerEqual(expected, received, ignore_hdmf_attrs=True)
852
853 def test_from_dataframe_dup_attr(self):
854 """
855 Test that when a DynamicTable is generated from a dataframe where one of the column names is an existing
856 DynamicTable attribute (e.g., description), that the table can be created, the existing attribute is not
857 altered, a warning is raised, and the column can still be accessed using the table[col_name] syntax.
858 """
859 df = pd.DataFrame({
860 'parent': [1, 2, 3, 4, 5],
861 'name': [10.0, 20.0, 30.0, 40.0, 50.0],
862 'description': ['cat', 'dog', 'bird', 'fish', 'lizard']
863 })
864
865 # technically there are three separate warnings but just catch one here
866 msg1 = ("An attribute 'parent' already exists on DynamicTable 'test' so this column cannot be accessed "
867 "as an attribute, e.g., table.parent; it can only be accessed using other methods, e.g., "
868 "table['parent'].")
869 with self.assertWarnsWith(UserWarning, msg1):
870 table = DynamicTable.from_dataframe(df, 'test')
871 self.assertEqual(table.name, 'test')
872 self.assertEqual(table.description, '')
873 self.assertIsNone(table.parent)
874 self.assertEqual(table['name'].name, 'name')
875 self.assertEqual(table['description'].name, 'description')
876 self.assertEqual(table['parent'].name, 'parent')
877
878 def test_missing_columns(self):
879 table = self.with_spec()
880 with self.assertRaises(ValueError):
881 table.add_row({'bar': 60.0, 'foo': [6]}, None)
882
883 def test_enforce_unique_id_error(self):
884 table = self.with_spec()
885 table.add_row(id=10, data={'foo': 1, 'bar': 10.0, 'baz': 'cat'}, enforce_unique_id=True)
886 with self.assertRaises(ValueError):
887 table.add_row(id=10, data={'foo': 1, 'bar': 10.0, 'baz': 'cat'}, enforce_unique_id=True)
888
889 def test_not_enforce_unique_id_error(self):
890 table = self.with_spec()
891 table.add_row(id=10, data={'foo': 1, 'bar': 10.0, 'baz': 'cat'}, enforce_unique_id=False)
892 try:
893 table.add_row(id=10, data={'foo': 1, 'bar': 10.0, 'baz': 'cat'}, enforce_unique_id=False)
894 except ValueError as e:
895 self.fail("add row with non unique id raised error %s" % str(e))
896
897 def test_bad_id_type_error(self):
898 table = self.with_spec()
899 with self.assertRaises(TypeError):
900 table.add_row(id=10.1, data={'foo': 1, 'bar': 10.0, 'baz': 'cat'}, enforce_unique_id=True)
901 with self.assertRaises(TypeError):
902 table.add_row(id='str', data={'foo': 1, 'bar': 10.0, 'baz': 'cat'}, enforce_unique_id=True)
903
904 def test_extra_columns(self):
905 table = self.with_spec()
906
907 with self.assertRaises(ValueError):
908 table.add_row({'bar': 60.0, 'foo': 6, 'baz': 'oryx', 'qax': -1}, None)
909
910 def test_nd_array_to_df(self):
911 data = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
912 col = VectorData(name='data', description='desc', data=data)
913 df = DynamicTable(name='test', description='desc', id=np.arange(3, dtype='int'),
914 columns=(col, )).to_dataframe()
915 df2 = pd.DataFrame({'data': [x for x in data]},
916 index=pd.Index(name='id', data=[0, 1, 2]))
917 pd.testing.assert_frame_equal(df, df2)
918
919 def test_id_search(self):
920 table = self.with_spec()
921 data = [{'foo': 1, 'bar': 10.0, 'baz': 'cat'},
922 {'foo': 2, 'bar': 20.0, 'baz': 'dog'},
923 {'foo': 3, 'bar': 30.0, 'baz': 'bird'}, # id=2
924 {'foo': 4, 'bar': 40.0, 'baz': 'fish'},
925 {'foo': 5, 'bar': 50.0, 'baz': 'lizard'} # id=4
926 ]
927 for i in data:
928 table.add_row(i)
929 res = table[table.id == [2, 4]]
930 self.assertEqual(len(res), 2)
931 self.assertTupleEqual(tuple(res.iloc[0]), (3, 30.0, 'bird'))
932 self.assertTupleEqual(tuple(res.iloc[1]), (5, 50.0, 'lizard'))
933
934 def test_repr(self):
935 table = self.with_spec()
936 expected = """with_spec hdmf.common.table.DynamicTable at 0x%d
937 Fields:
938 colnames: ['foo' 'bar' 'baz']
939 columns: (
940 foo <class 'hdmf.common.table.VectorData'>,
941 bar <class 'hdmf.common.table.VectorData'>,
942 baz <class 'hdmf.common.table.VectorData'>
943 )
944 description: a test table
945 """
946 expected = expected % id(table)
947 self.assertEqual(str(table), expected)
948
949 def test_repr_html(self):
950 table = self.with_spec()
951 html = table._repr_html_()
952
953 assert html == (
954 '\n <style>\n .container-fields {\n font-family: "Open Sans", Arial, '
955 'sans-serif;\n }\n .container-fields .field-value {\n color: '
956 '#00788E;\n }\n .container-fields details > summary {\n cursor: '
957 'pointer;\n display: list-item;\n }\n .container-fields details > '
958 'summary:hover {\n color: #0A6EAA;\n }\n </style>\n \n '
959 '<script>\n function copyToClipboard(text) {\n navigator.clipboard.writeText('
960 'text).then(function() {\n console.log(\'Copied to clipboard: \' + text);\n '
961 ' }, function(err) {\n console.error(\'Could not copy text: \', err);\n '
962 ' });\n }\n\n document.addEventListener(\'DOMContentLoaded\', function() {\n '
963 ' let fieldKeys = document.querySelectorAll(\'.container-fields .field-key\');\n '
964 'fieldKeys.forEach(function(fieldKey) {\n fieldKey.addEventListener(\'click\', '
965 'function() {\n let accessCode = fieldKey.getAttribute(\'title\').replace(\'Access '
966 'code: \', \'\');\n copyToClipboard(accessCode);\n });\n '
967 ' });\n });\n </script>\n <div class=\'container-wrap\'><div '
968 'class=\'container-header\'><div class=\'xr-obj-type\'><h3>with_spec (DynamicTable)</h3></div></div><div '
969 'style="margin-left: 0px;" class="container-fields"><span class="field-key" title="">description: '
970 '</span><span class="field-value">a test table</span></div><details><summary style="display: list-item; '
971 'margin-left: 0px;" class="container-fields field-key" title=""><b>table</b></summary><table border="1" '
972 'class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n '
973 '<th>foo</th>\n <th>bar</th>\n <th>baz</th>\n </tr>\n <tr>\n <th>id</th>\n '
974 '<th></th>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody>\n '
975 '</tbody>\n</table></details></div>'
976 )
977
978
979 def test_add_column_existing_attr(self):
980 table = self.with_table_columns()
981 attrs = ['name', 'description', 'parent', 'id', 'fields'] # just a few
982 for attr in attrs:
983 with self.subTest(attr=attr):
984 msg = ("An attribute '%s' already exists on DynamicTable 'with_table_columns' so this column cannot be "
985 "accessed as an attribute, e.g., table.%s; it can only be accessed using other methods, "
986 "e.g., table['%s']." % (attr, attr, attr))
987 with self.assertWarnsWith(UserWarning, msg):
988 table.add_column(name=attr, description='')
989
990 def test_init_columns_existing_attr(self):
991 attrs = ['name', 'description', 'parent', 'id', 'fields'] # just a few
992 for attr in attrs:
993 with self.subTest(attr=attr):
994 cols = [VectorData(name=attr, description='')]
995 msg = ("An attribute '%s' already exists on DynamicTable 'test_table' so this column cannot be "
996 "accessed as an attribute, e.g., table.%s; it can only be accessed using other methods, "
997 "e.g., table['%s']." % (attr, attr, attr))
998 with self.assertWarnsWith(UserWarning, msg):
999 DynamicTable(name="test_table", description='a test table', columns=cols)
1000
1001 def test_colnames_none(self):
1002 table = DynamicTable(name='table0', description='an example table')
1003 self.assertTupleEqual(table.colnames, tuple())
1004 self.assertTupleEqual(table.columns, tuple())
1005
1006 def test_index_out_of_bounds(self):
1007 table = self.with_columns_and_data()
1008 msg = "Row index out of range for DynamicTable 'with_columns_and_data' (length 5)."
1009 with self.assertRaisesWith(IndexError, msg):
1010 table[5]
1011
1012 def test_no_df_nested(self):
1013 table = self.with_columns_and_data()
1014 msg = 'DynamicTable.get() with df=False and index=False is not yet supported.'
1015 with self.assertRaisesWith(ValueError, msg):
1016 table.get(0, df=False, index=False)
1017
1018 def test_multidim_col(self):
1019 multidim_data = [
1020 [[1, 2], [3, 4], [5, 6]],
1021 ((1, 2), (3, 4), (5, 6)),
1022 [(1, 'a', True), (2, 'b', False), (3, 'c', True)],
1023 ]
1024 columns = [
1025 VectorData(name=s['name'], description=s['description'], data=d)
1026 for s, d in zip(self.spec, multidim_data)
1027 ]
1028 table = DynamicTable(name="with_columns_and_data", description='a test table', columns=columns)
1029 df = table.to_dataframe()
1030 df2 = pd.DataFrame({'foo': multidim_data[0],
1031 'bar': multidim_data[1],
1032 'baz': multidim_data[2]},
1033 index=pd.Index(name='id', data=[0, 1, 2]))
1034 pd.testing.assert_frame_equal(df, df2)
1035
1036 df3 = pd.DataFrame({'foo': [multidim_data[0][0]],
1037 'bar': [multidim_data[1][0]],
1038 'baz': [multidim_data[2][0]]},
1039 index=pd.Index(name='id', data=[0]))
1040 pd.testing.assert_frame_equal(table.get(0), df3)
1041
1042 def test_multidim_col_one_elt_list(self):
1043 data = [[1, 2]]
1044 col = VectorData(name='data', description='desc', data=data)
1045 table = DynamicTable(name='test', description='desc', columns=(col, ))
1046 df = table.to_dataframe()
1047 df2 = pd.DataFrame({'data': [x for x in data]},
1048 index=pd.Index(name='id', data=[0]))
1049 pd.testing.assert_frame_equal(df, df2)
1050 pd.testing.assert_frame_equal(table.get(0), df2)
1051
1052 def test_multidim_col_one_elt_tuple(self):
1053 data = [(1, 2)]
1054 col = VectorData(name='data', description='desc', data=data)
1055 table = DynamicTable(name='test', description='desc', columns=(col, ))
1056 df = table.to_dataframe()
1057 df2 = pd.DataFrame({'data': [x for x in data]},
1058 index=pd.Index(name='id', data=[0]))
1059 pd.testing.assert_frame_equal(df, df2)
1060 pd.testing.assert_frame_equal(table.get(0), df2)
1061
1062 def test_eq(self):
1063 columns = [
1064 VectorData(name=s['name'], description=s['description'], data=d)
1065 for s, d in zip(self.spec, self.data)
1066 ]
1067 test_table = DynamicTable(name="with_columns_and_data", description='a test table', columns=columns)
1068
1069 table = self.with_columns_and_data()
1070 self.assertTrue(table == test_table)
1071
1072 def test_eq_from_df(self):
1073 df = pd.DataFrame({
1074 'foo': [1, 2, 3, 4, 5],
1075 'bar': [10.0, 20.0, 30.0, 40.0, 50.0],
1076 'baz': ['cat', 'dog', 'bird', 'fish', 'lizard']
1077 }).loc[:, ('foo', 'bar', 'baz')]
1078
1079 test_table = DynamicTable.from_dataframe(df, 'with_columns_and_data', table_description='a test table')
1080 table = self.with_columns_and_data()
1081 self.assertTrue(table == test_table)
1082
1083 def test_eq_diff_missing_col(self):
1084 columns = [
1085 VectorData(name=s['name'], description=s['description'], data=d)
1086 for s, d in zip(self.spec, self.data)
1087 ]
1088 del columns[-1]
1089 test_table = DynamicTable(name="with_columns_and_data", description='a test table', columns=columns)
1090
1091 table = self.with_columns_and_data()
1092 self.assertFalse(table == test_table)
1093
1094 def test_eq_diff_name(self):
1095 columns = [
1096 VectorData(name=s['name'], description=s['description'], data=d)
1097 for s, d in zip(self.spec, self.data)
1098 ]
1099 test_table = DynamicTable(name="wrong name", description='a test table', columns=columns)
1100
1101 table = self.with_columns_and_data()
1102 self.assertFalse(table == test_table)
1103
1104 def test_eq_diff_desc(self):
1105 columns = [
1106 VectorData(name=s['name'], description=s['description'], data=d)
1107 for s, d in zip(self.spec, self.data)
1108 ]
1109 test_table = DynamicTable(name="with_columns_and_data", description='wrong description', columns=columns)
1110
1111 table = self.with_columns_and_data()
1112 self.assertFalse(table == test_table)
1113
1114 def test_eq_bad_type(self):
1115 container = Container('test_container')
1116 table = self.with_columns_and_data()
1117 self.assertFalse(table == container)
1118
1119
1120 class TestDynamicTableRoundTrip(H5RoundTripMixin, TestCase):
1121
1122 def setUpContainer(self):
1123 table = DynamicTable(name='table0', description='an example table')
1124 table.add_column(name='foo', description='an int column')
1125 table.add_column(name='bar', description='a float column')
1126 table.add_column(name='baz', description='a string column')
1127 table.add_column(name='qux', description='a boolean column')
1128 table.add_column(name='corge', description='a doubly indexed int column', index=2)
1129 table.add_column(name='quux', description='an enum column', enum=True)
1130 table.add_row(foo=27, bar=28.0, baz="cat", corge=[[1, 2, 3], [4, 5, 6]], qux=True, quux='a')
1131 table.add_row(foo=37, bar=38.0, baz="dog", corge=[[11, 12, 13], [14, 15, 16]], qux=False, quux='b')
1132 table.add_column(name='agv', description='a column with autogenerated multi vector index',
1133 data=[[[1, 2, 3], [4, 5]], [[6, 7], [8, 9, 10]]], index=2)
1134 return table
1135
1136 def test_index_out_of_bounds(self):
1137 table = self.roundtripContainer()
1138 msg = "Row index 5 out of range for DynamicTable 'root' (length 2)."
1139 with self.assertRaisesWith(IndexError, msg):
1140 table[5]
1141
1142
1143 class TestEmptyDynamicTableRoundTrip(H5RoundTripMixin, TestCase):
1144 """Test roundtripping a DynamicTable with no rows and no columns."""
1145
1146 def setUpContainer(self):
1147 table = DynamicTable(name='table0', description='an example table')
1148 return table
1149
1150
1151 class TestDynamicTableRegion(TestCase):
1152
1153 def setUp(self):
1154 self.spec = [
1155 {'name': 'foo', 'description': 'foo column'},
1156 {'name': 'bar', 'description': 'bar column'},
1157 {'name': 'baz', 'description': 'baz column'},
1158 ]
1159 self.data = [
1160 [1, 2, 3, 4, 5],
1161 [10.0, 20.0, 30.0, 40.0, 50.0],
1162 ['cat', 'dog', 'bird', 'fish', 'lizard']
1163 ]
1164
1165 def with_columns_and_data(self):
1166 columns = [
1167 VectorData(name=s['name'], description=s['description'], data=d)
1168 for s, d in zip(self.spec, self.data)
1169 ]
1170 return DynamicTable(name="with_columns_and_data", description='a test table', columns=columns)
1171
1172 def test_indexed_dynamic_table_region(self):
1173 table = self.with_columns_and_data()
1174 dynamic_table_region = DynamicTableRegion(name='dtr', data=[1, 2, 2], description='desc', table=table)
1175 fetch_ids = dynamic_table_region[:3].index.values
1176 self.assertListEqual(fetch_ids.tolist(), [1, 2, 2])
1177
1178 def test_dynamic_table_region_iteration(self):
1179 table = self.with_columns_and_data()
1180 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 3, 4], description='desc', table=table)
1181 for ii, item in enumerate(dynamic_table_region):
1182 self.assertTrue(table[ii].equals(item))
1183
1184 def test_dynamic_table_region_shape(self):
1185 table = self.with_columns_and_data()
1186 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 3, 4], description='desc', table=table)
1187 self.assertTupleEqual(dynamic_table_region.shape, (5, 3))
1188
1189 def test_dynamic_table_region_to_dataframe(self):
1190 table = self.with_columns_and_data()
1191 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1192 res = dynamic_table_region.to_dataframe()
1193 self.assertListEqual(res.index.tolist(), [0, 1, 2, 2])
1194 self.assertListEqual(res['foo'].tolist(), [1, 2, 3, 3])
1195 self.assertListEqual(res['bar'].tolist(), [10.0, 20.0, 30.0, 30.0])
1196 self.assertListEqual(res['baz'].tolist(), ['cat', 'dog', 'bird', 'bird'])
1197
1198 def test_dynamic_table_region_to_dataframe_exclude_cols(self):
1199 table = self.with_columns_and_data()
1200 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1201 res = dynamic_table_region.to_dataframe(exclude={'baz', 'foo'})
1202 self.assertListEqual(res.index.tolist(), [0, 1, 2, 2])
1203 self.assertEqual(len(res.columns), 1)
1204 self.assertListEqual(res['bar'].tolist(), [10.0, 20.0, 30.0, 30.0])
1205
1206 def test_dynamic_table_region_getitem_slice(self):
1207 table = self.with_columns_and_data()
1208 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1209 res = dynamic_table_region[1:3]
1210 self.assertListEqual(res.index.tolist(), [1, 2])
1211 self.assertListEqual(res['foo'].tolist(), [2, 3])
1212 self.assertListEqual(res['bar'].tolist(), [20.0, 30.0])
1213 self.assertListEqual(res['baz'].tolist(), ['dog', 'bird'])
1214
1215 def test_dynamic_table_region_getitem_single_row_by_index(self):
1216 table = self.with_columns_and_data()
1217 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1218 res = dynamic_table_region[2]
1219 self.assertListEqual(res.index.tolist(), [2, ])
1220 self.assertListEqual(res['foo'].tolist(), [3, ])
1221 self.assertListEqual(res['bar'].tolist(), [30.0, ])
1222 self.assertListEqual(res['baz'].tolist(), ['bird', ])
1223
1224 def test_dynamic_table_region_getitem_single_cell(self):
1225 table = self.with_columns_and_data()
1226 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1227 res = dynamic_table_region[2, 'foo']
1228 self.assertEqual(res, 3)
1229 res = dynamic_table_region[1, 'baz']
1230 self.assertEqual(res, 'dog')
1231
1232 def test_dynamic_table_region_getitem_slice_of_column(self):
1233 table = self.with_columns_and_data()
1234 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1235 res = dynamic_table_region[0:3, 'foo']
1236 self.assertListEqual(res, [1, 2, 3])
1237 res = dynamic_table_region[1:3, 'baz']
1238 self.assertListEqual(res, ['dog', 'bird'])
1239
1240 def test_dynamic_table_region_getitem_bad_index(self):
1241 table = self.with_columns_and_data()
1242 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1243 with self.assertRaises(ValueError):
1244 _ = dynamic_table_region[True]
1245
1246 def test_dynamic_table_region_table_prop(self):
1247 table = self.with_columns_and_data()
1248 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1249 self.assertEqual(table, dynamic_table_region.table)
1250
1251 def test_dynamic_table_region_set_table_prop(self):
1252 table = self.with_columns_and_data()
1253 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc')
1254 dynamic_table_region.table = table
1255 self.assertEqual(table, dynamic_table_region.table)
1256
1257 def test_dynamic_table_region_set_table_prop_to_none(self):
1258 table = self.with_columns_and_data()
1259 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1260 try:
1261 dynamic_table_region.table = None
1262 except AttributeError:
1263 self.fail("DynamicTableRegion table setter raised AttributeError unexpectedly!")
1264
1265 @unittest.skip('we no longer check data contents for performance reasons')
1266 def test_dynamic_table_region_set_with_bad_data(self):
1267 table = self.with_columns_and_data()
1268 # index 5 is out of range
1269 dynamic_table_region = DynamicTableRegion(name='dtr', data=[5, 1], description='desc')
1270 with self.assertRaises(IndexError):
1271 dynamic_table_region.table = table
1272 self.assertIsNone(dynamic_table_region.table)
1273
1274 def test_repr(self):
1275 table = self.with_columns_and_data()
1276 dynamic_table_region = DynamicTableRegion(name='dtr', data=[1, 2, 2], description='desc', table=table)
1277 expected = """dtr hdmf.common.table.DynamicTableRegion at 0x%d
1278 Target table: with_columns_and_data hdmf.common.table.DynamicTable at 0x%d
1279 """
1280 expected = expected % (id(dynamic_table_region), id(table))
1281 self.assertEqual(str(dynamic_table_region), expected)
1282
1283 def test_no_df_nested(self):
1284 table = self.with_columns_and_data()
1285 dynamic_table_region = DynamicTableRegion(name='dtr', data=[0, 1, 2, 2], description='desc', table=table)
1286 msg = 'DynamicTableRegion.get() with df=False and index=False is not yet supported.'
1287 with self.assertRaisesWith(ValueError, msg):
1288 dynamic_table_region.get(0, df=False, index=False)
1289
1290
1291 class DynamicTableRegionRoundTrip(H5RoundTripMixin, TestCase):
1292
1293 def make_tables(self):
1294 self.spec2 = [
1295 {'name': 'qux', 'description': 'qux column'},
1296 {'name': 'quz', 'description': 'quz column'},
1297 ]
1298 self.data2 = [
1299 ['qux_1', 'qux_2'],
1300 ['quz_1', 'quz_2'],
1301 ]
1302
1303 target_columns = [
1304 VectorData(name=s['name'], description=s['description'], data=d)
1305 for s, d in zip(self.spec2, self.data2)
1306 ]
1307 target_table = DynamicTable(name="target_table",
1308 description='example table to target with a DynamicTableRegion',
1309 columns=target_columns)
1310
1311 self.spec1 = [
1312 {'name': 'foo', 'description': 'foo column'},
1313 {'name': 'bar', 'description': 'bar column'},
1314 {'name': 'baz', 'description': 'baz column'},
1315 {'name': 'dtr', 'description': 'DTR'},
1316 ]
1317 self.data1 = [
1318 [1, 2, 3, 4, 5],
1319 [10.0, 20.0, 30.0, 40.0, 50.0],
1320 ['cat', 'dog', 'bird', 'fish', 'lizard']
1321 ]
1322 columns = [
1323 VectorData(name=s['name'], description=s['description'], data=d)
1324 for s, d in zip(self.spec1, self.data1)
1325 ]
1326 columns.append(DynamicTableRegion(name='dtr', description='example DynamicTableRegion',
1327 data=[0, 1, 1, 0, 1], table=target_table))
1328 table = DynamicTable(name="table_with_dtr",
1329 description='a test table that has a DynamicTableRegion',
1330 columns=columns)
1331 return table, target_table
1332
1333 def setUp(self):
1334 self.table, self.target_table = self.make_tables()
1335 super().setUp()
1336
1337 def setUpContainer(self):
1338 multi_container = SimpleMultiContainer(name='multi', containers=[self.target_table, self.table])
1339 return multi_container
1340
1341 def _get(self, arg):
1342 mc = self.roundtripContainer()
1343 table = mc.containers['table_with_dtr']
1344 return table.get(arg)
1345
1346 def _get_nested(self, arg):
1347 mc = self.roundtripContainer()
1348 table = mc.containers['table_with_dtr']
1349 return table.get(arg, index=False)
1350
1351 def _get_nodf(self, arg):
1352 mc = self.roundtripContainer()
1353 table = mc.containers['table_with_dtr']
1354 return table.get(arg, df=False)
1355
1356 def _getitem(self, arg):
1357 mc = self.roundtripContainer()
1358 table = mc.containers['table_with_dtr']
1359 return table[arg]
1360
1361 def test_getitem_oor(self):
1362 msg = 'Row index 12 out of range for DynamicTable \'table_with_dtr\' (length 5).'
1363 with self.assertRaisesWith(IndexError, msg):
1364 self._getitem(12)
1365
1366 def test_getitem_badcol(self):
1367 with self.assertRaises(KeyError):
1368 self._getitem('boo')
1369
1370 def _assert_two_elem_df(self, rec):
1371 columns = ['foo', 'bar', 'baz', 'dtr']
1372 data = [[1, 10.0, 'cat', 0],
1373 [2, 20.0, 'dog', 1]]
1374 exp = pd.DataFrame(data=data, columns=columns, index=pd.Series(name='id', data=[0, 1]))
1375 pd.testing.assert_frame_equal(rec, exp, check_dtype=False)
1376
1377 def _assert_one_elem_df(self, rec):
1378 columns = ['foo', 'bar', 'baz', 'dtr']
1379 data = [[1, 10.0, 'cat', 0]]
1380 exp = pd.DataFrame(data=data, columns=columns, index=pd.Series(name='id', data=[0]))
1381 pd.testing.assert_frame_equal(rec, exp, check_dtype=False)
1382
1383 def _assert_two_elem_df_nested(self, rec):
1384 nested_columns = ['qux', 'quz']
1385 nested_data = [['qux_1', 'quz_1'], ['qux_2', 'quz_2']]
1386 nested_df = pd.DataFrame(data=nested_data, columns=nested_columns, index=pd.Series(name='id', data=[0, 1]))
1387
1388 columns = ['foo', 'bar', 'baz']
1389 data = [[1, 10.0, 'cat'],
1390 [2, 20.0, 'dog']]
1391 exp = pd.DataFrame(data=data, columns=columns, index=pd.Series(name='id', data=[0, 1]))
1392
1393 # remove nested dataframe and test each df separately
1394 pd.testing.assert_frame_equal(rec['dtr'][0], nested_df.iloc[[0]])
1395 pd.testing.assert_frame_equal(rec['dtr'][1], nested_df.iloc[[1]])
1396 del rec['dtr']
1397 pd.testing.assert_frame_equal(rec, exp, check_dtype=False)
1398
1399 def _assert_one_elem_df_nested(self, rec):
1400 nested_columns = ['qux', 'quz']
1401 nested_data = [['qux_1', 'quz_1'], ['qux_2', 'quz_2']]
1402 nested_df = pd.DataFrame(data=nested_data, columns=nested_columns, index=pd.Series(name='id', data=[0, 1]))
1403
1404 columns = ['foo', 'bar', 'baz']
1405 data = [[1, 10.0, 'cat']]
1406 exp = pd.DataFrame(data=data, columns=columns, index=pd.Series(name='id', data=[0]))
1407
1408 # remove nested dataframe and test each df separately
1409 pd.testing.assert_frame_equal(rec['dtr'][0], nested_df.iloc[[0]])
1410 del rec['dtr']
1411 pd.testing.assert_frame_equal(rec, exp, check_dtype=False)
1412
1413 #####################
1414 # tests DynamicTableRegion.__getitem__
1415 def test_getitem_int(self):
1416 rec = self._getitem(0)
1417 self._assert_one_elem_df(rec)
1418
1419 def test_getitem_list_single(self):
1420 rec = self._getitem([0])
1421 self._assert_one_elem_df(rec)
1422
1423 def test_getitem_list(self):
1424 rec = self._getitem([0, 1])
1425 self._assert_two_elem_df(rec)
1426
1427 def test_getitem_slice(self):
1428 rec = self._getitem(slice(0, 2, None))
1429 self._assert_two_elem_df(rec)
1430
1431 #####################
1432 # tests DynamicTableRegion.get, return a DataFrame
1433 def test_get_int(self):
1434 rec = self._get(0)
1435 self._assert_one_elem_df(rec)
1436
1437 def test_get_list_single(self):
1438 rec = self._get([0])
1439 self._assert_one_elem_df(rec)
1440
1441 def test_get_list(self):
1442 rec = self._get([0, 1])
1443 self._assert_two_elem_df(rec)
1444
1445 def test_get_slice(self):
1446 rec = self._get(slice(0, 2, None))
1447 self._assert_two_elem_df(rec)
1448
1449 #####################
1450 # tests DynamicTableRegion.get, return a DataFrame with nested DataFrame
1451 def test_get_nested_int(self):
1452 rec = self._get_nested(0)
1453 self._assert_one_elem_df_nested(rec)
1454
1455 def test_get_nested_list_single(self):
1456 rec = self._get_nested([0])
1457 self._assert_one_elem_df_nested(rec)
1458
1459 def test_get_nested_list(self):
1460 rec = self._get_nested([0, 1])
1461 self._assert_two_elem_df_nested(rec)
1462
1463 def test_get_nested_slice(self):
1464 rec = self._get_nested(slice(0, 2, None))
1465 self._assert_two_elem_df_nested(rec)
1466
1467 #####################
1468 # tests DynamicTableRegion.get, DO NOT return a DataFrame
1469 def test_get_nodf_int(self):
1470 rec = self._get_nodf(0)
1471 exp = [0, 1, 10.0, 'cat', 0]
1472 self.assertListEqual(rec, exp)
1473
1474 def _assert_list_of_ndarray_equal(self, l1, l2):
1475 """
1476 This is a helper function for test_get_nodf_list and test_get_nodf_slice.
1477 It compares ndarrays from a list of ndarrays
1478 """
1479 for a1, a2 in zip(l1, l2):
1480 if isinstance(a1, list):
1481 self._assert_list_of_ndarray_equal(a1, a2)
1482 else:
1483 np.testing.assert_array_equal(a1, a2)
1484
1485 def test_get_nodf_list_single(self):
1486 rec = self._get_nodf([0])
1487 exp = [np.array([0]), np.array([1]), np.array([10.0]), np.array(['cat']), np.array([0])]
1488 self._assert_list_of_ndarray_equal(exp, rec)
1489
1490 def test_get_nodf_list(self):
1491 rec = self._get_nodf([0, 1])
1492 exp = [np.array([0, 1]), np.array([1, 2]), np.array([10.0, 20.0]), np.array(['cat', 'dog']), np.array([0, 1])]
1493 self._assert_list_of_ndarray_equal(exp, rec)
1494
1495 def test_get_nodf_slice(self):
1496 rec = self._get_nodf(slice(0, 2, None))
1497 exp = [np.array([0, 1]), np.array([1, 2]), np.array([10.0, 20.0]), np.array(['cat', 'dog']), np.array([0, 1])]
1498 self._assert_list_of_ndarray_equal(exp, rec)
1499
1500 def test_getitem_int_str(self):
1501 """Test DynamicTableRegion.__getitem__ with (int, str)."""
1502 mc = self.roundtripContainer()
1503 table = mc.containers['table_with_dtr']
1504 rec = table['dtr'][0, 'qux']
1505 self.assertEqual(rec, 'qux_1')
1506
1507 def test_getitem_str(self):
1508 """Test DynamicTableRegion.__getitem__ with str."""
1509 mc = self.roundtripContainer()
1510 table = mc.containers['table_with_dtr']
1511 rec = table['dtr']['qux']
1512 self.assertIs(rec, mc.containers['target_table']['qux'])
1513
1514
1515 class TestElementIdentifiers(TestCase):
1516
1517 def setUp(self):
1518 self.e = ElementIdentifiers(name='ids', data=[0, 1, 2, 3, 4])
1519
1520 def test_identifier_search_single_list(self):
1521 a = (self.e == [1])
1522 np.testing.assert_array_equal(a, [1])
1523
1524 def test_identifier_search_single_int(self):
1525 a = (self.e == 2)
1526 np.testing.assert_array_equal(a, [2])
1527
1528 def test_identifier_search_single_list_not_found(self):
1529 a = (self.e == [10])
1530 np.testing.assert_array_equal(a, [])
1531
1532 def test_identifier_search_single_int_not_found(self):
1533 a = (self.e == 10)
1534 np.testing.assert_array_equal(a, [])
1535
1536 def test_identifier_search_single_list_all_match(self):
1537 a = (self.e == [1, 2, 3])
1538 np.testing.assert_array_equal(a, [1, 2, 3])
1539
1540 def test_identifier_search_single_list_partial_match(self):
1541 a = (self.e == [1, 2, 10])
1542 np.testing.assert_array_equal(a, [1, 2])
1543 a = (self.e == [-1, 2, 10])
1544 np.testing.assert_array_equal(a, [2, ])
1545
1546 def test_identifier_search_with_element_identifier(self):
1547 a = (self.e == ElementIdentifiers(name='ids', data=[1, 2, 10]))
1548 np.testing.assert_array_equal(a, [1, 2])
1549
1550 def test_identifier_search_with_bad_ids(self):
1551 with self.assertRaises(TypeError):
1552 _ = (self.e == 0.1)
1553 with self.assertRaises(TypeError):
1554 _ = (self.e == 'test')
1555
1556
1557 class TestBadElementIdentifiers(TestCase):
1558
1559 def test_bad_dtype(self):
1560 with self.assertRaisesWith(ValueError, "ElementIdentifiers must contain integers"):
1561 ElementIdentifiers(name='ids', data=["1", "2"])
1562
1563 with self.assertRaisesWith(ValueError, "ElementIdentifiers must contain integers"):
1564 ElementIdentifiers(name='ids', data=np.array(["1", "2"]))
1565
1566 with self.assertRaisesWith(ValueError, "ElementIdentifiers must contain integers"):
1567 ElementIdentifiers(name='ids', data=[1.0, 2.0])
1568
1569 def test_dci_int_ok(self):
1570 a = np.arange(30)
1571 dci = DataChunkIterator(data=a, buffer_size=1)
1572 e = ElementIdentifiers(name='ids', data=dci) # test that no error is raised
1573 self.assertIs(e.data, dci)
1574
1575 def test_dci_float_bad(self):
1576 a = np.arange(30.0)
1577 dci = DataChunkIterator(data=a, buffer_size=1)
1578 with self.assertRaisesWith(ValueError, "ElementIdentifiers must contain integers"):
1579 ElementIdentifiers(name='ids', data=dci)
1580
1581 def test_dataio_dci_ok(self):
1582 a = np.arange(30)
1583 dci = DataChunkIterator(data=a, buffer_size=1)
1584 dio = H5DataIO(dci)
1585 e = ElementIdentifiers(name='ids', data=dio) # test that no error is raised
1586 self.assertIs(e.data, dio)
1587
1588
1589 class SubTable(DynamicTable):
1590
1591 __columns__ = (
1592 {'name': 'col1', 'description': 'required column', 'required': True},
1593 {'name': 'col2', 'description': 'optional column'},
1594 {'name': 'col3', 'description': 'required, indexed column', 'required': True, 'index': True},
1595 {'name': 'col4', 'description': 'optional, indexed column', 'index': True},
1596 {'name': 'col5', 'description': 'required region', 'required': True, 'table': True},
1597 {'name': 'col6', 'description': 'optional region', 'table': True},
1598 {'name': 'col7', 'description': 'required, indexed region', 'required': True, 'index': True, 'table': True},
1599 {'name': 'col8', 'description': 'optional, indexed region', 'index': True, 'table': True},
1600 {'name': 'col10', 'description': 'optional, indexed enum column', 'index': True, 'class': EnumData},
1601 {'name': 'col11', 'description': 'optional, enumerable column', 'enum': True, 'index': True},
1602 )
1603
1604
1605 class SubSubTable(SubTable):
1606
1607 __columns__ = (
1608 {'name': 'col9', 'description': 'required column', 'required': True},
1609 # TODO handle edge case where subclass re-defines a column from superclass
1610 # {'name': 'col2', 'description': 'optional column subsub', 'required': True}, # make col2 required
1611 )
1612
1613
1614 class TestDynamicTableClassColumns(TestCase):
1615 """Test functionality related to the predefined __columns__ field of a DynamicTable class."""
1616
1617 def test_init(self):
1618 """Test that required columns, and not optional columns, in __columns__ are created on init."""
1619 table = SubTable(name='subtable', description='subtable description')
1620 self.assertEqual(table.colnames, ('col1', 'col3', 'col5', 'col7'))
1621 # test different access methods. note: table.get('col1') is equivalent to table['col1']
1622 self.assertEqual(table.col1.description, 'required column')
1623 self.assertEqual(table.col3.description, 'required, indexed column')
1624 self.assertEqual(table.col5.description, 'required region')
1625 self.assertEqual(table.col7.description, 'required, indexed region')
1626 self.assertEqual(table['col1'].description, 'required column')
1627 # self.assertEqual(table['col3'].description, 'required, indexed column') # TODO this should work
1628
1629 self.assertIsNone(table.col2)
1630 self.assertIsNone(table.col4)
1631 self.assertIsNone(table.col4_index)
1632 self.assertIsNone(table.col6)
1633 self.assertIsNone(table.col8)
1634 self.assertIsNone(table.col8_index)
1635 self.assertIsNone(table.col11)
1636 self.assertIsNone(table.col11_index)
1637
1638 # uninitialized optional predefined columns cannot be accessed in this manner
1639 with self.assertRaises(KeyError):
1640 table['col2']
1641
1642 def test_gather_columns_inheritance(self):
1643 """Test that gathering columns across a type hierarchy works."""
1644 table = SubSubTable(name='subtable', description='subtable description')
1645 self.assertEqual(table.colnames, ('col1', 'col3', 'col5', 'col7', 'col9'))
1646
1647 def test_bad_predefined_columns(self):
1648 """Test that gathering columns across a type hierarchy works."""
1649 msg = "'__columns__' must be of type tuple, found <class 'list'>"
1650 with self.assertRaisesWith(TypeError, msg):
1651 class BadSubTable(DynamicTable):
1652
1653 __columns__ = []
1654
1655 def test_add_req_column(self):
1656 """Test that adding a required column from __columns__ raises an error."""
1657 table = SubTable(name='subtable', description='subtable description')
1658 msg = "column 'col1' already exists in SubTable 'subtable'"
1659 with self.assertRaisesWith(ValueError, msg):
1660 table.add_column(name='col1', description='column #1')
1661
1662 def test_add_req_ind_column(self):
1663 """Test that adding a required, indexed column from __columns__ raises an error."""
1664 table = SubTable(name='subtable', description='subtable description')
1665 msg = "column 'col3' already exists in SubTable 'subtable'"
1666 with self.assertRaisesWith(ValueError, msg):
1667 table.add_column(name='col3', description='column #3')
1668
1669 def test_add_opt_column(self):
1670 """Test that adding an optional column from __columns__ with matching specs except for description works."""
1671 table = SubTable(name='subtable', description='subtable description')
1672
1673 table.add_column(name='col2', description='column #2') # override __columns__ description
1674 self.assertEqual(table.col2.description, 'column #2')
1675
1676 table.add_column(name='col4', description='column #4', index=True)
1677 self.assertEqual(table.col4.description, 'column #4')
1678
1679 table.add_column(name='col6', description='column #6', table=True)
1680 self.assertEqual(table.col6.description, 'column #6')
1681
1682 table.add_column(name='col8', description='column #8', index=True, table=True)
1683 self.assertEqual(table.col8.description, 'column #8')
1684
1685 table.add_column(name='col10', description='column #10', index=True, col_cls=EnumData)
1686 self.assertIsInstance(table.col10, EnumData)
1687
1688 table.add_column(name='col11', description='column #11', enum=True, index=True)
1689 self.assertIsInstance(table.col11, EnumData)
1690
1691 def test_add_opt_column_mismatched_table_true(self):
1692 """Test that adding an optional column from __columns__ with non-matched table raises a warning."""
1693 table = SubTable(name='subtable', description='subtable description')
1694 msg = ("Column 'col2' is predefined in SubTable with table=False which does not match the entered table "
1695 "argument. The predefined table spec will be ignored. "
1696 "Please ensure the new column complies with the spec. "
1697 "This will raise an error in a future version of HDMF.")
1698 with self.assertWarnsWith(UserWarning, msg):
1699 table.add_column(name='col2', description='column #2', table=True)
1700 self.assertEqual(table.col2.description, 'column #2')
1701 self.assertEqual(type(table.col2), DynamicTableRegion) # not VectorData
1702
1703 def test_add_opt_column_mismatched_table_table(self):
1704 """Test that adding an optional column from __columns__ with non-matched table raises a warning."""
1705 table = SubTable(name='subtable', description='subtable description')
1706 msg = ("Column 'col2' is predefined in SubTable with table=False which does not match the entered table "
1707 "argument. The predefined table spec will be ignored. "
1708 "Please ensure the new column complies with the spec. "
1709 "This will raise an error in a future version of HDMF.")
1710 with self.assertWarnsWith(UserWarning, msg):
1711 table.add_column(name='col2', description='column #2',
1712 table=DynamicTable(name='dummy', description='dummy'))
1713 self.assertEqual(table.col2.description, 'column #2')
1714 self.assertEqual(type(table.col2), DynamicTableRegion) # not VectorData
1715
1716 def test_add_opt_column_mismatched_index_true(self):
1717 """Test that adding an optional column from __columns__ with non-matched table raises a warning."""
1718 table = SubTable(name='subtable', description='subtable description')
1719 msg = ("Column 'col2' is predefined in SubTable with index=False which does not match the entered index "
1720 "argument. The predefined index spec will be ignored. "
1721 "Please ensure the new column complies with the spec. "
1722 "This will raise an error in a future version of HDMF.")
1723 with self.assertWarnsWith(UserWarning, msg):
1724 table.add_column(name='col2', description='column #2', index=True)
1725 self.assertEqual(table.col2.description, 'column #2')
1726 self.assertEqual(type(table.get('col2')), VectorIndex) # not VectorData
1727
1728 def test_add_opt_column_mismatched_index_data(self):
1729 """Test that adding an optional column from __columns__ with non-matched table raises a warning."""
1730 table = SubTable(name='subtable', description='subtable description')
1731 table.add_row(col1='a', col3='c', col5='e', col7='g')
1732 table.add_row(col1='a', col3='c', col5='e', col7='g')
1733 msg = ("Column 'col2' is predefined in SubTable with index=False which does not match the entered index "
1734 "argument. The predefined index spec will be ignored. "
1735 "Please ensure the new column complies with the spec. "
1736 "This will raise an error in a future version of HDMF.")
1737 with self.assertWarnsWith(UserWarning, msg):
1738 table.add_column(name='col2', description='column #2', data=[1, 2, 3], index=[1, 2])
1739 self.assertEqual(table.col2.description, 'column #2')
1740 self.assertEqual(type(table.get('col2')), VectorIndex) # not VectorData
1741
1742 def test_add_opt_column_mismatched_col_cls(self):
1743 """Test that adding an optional column from __columns__ with non-matched table raises a warning."""
1744 table = SubTable(name='subtable', description='subtable description')
1745 msg = ("Column 'col10' is predefined in SubTable with class=<class 'hdmf.common.table.EnumData'> "
1746 "which does not match the entered col_cls "
1747 "argument. The predefined class spec will be ignored. "
1748 "Please ensure the new column complies with the spec. "
1749 "This will raise an error in a future version of HDMF.")
1750 with self.assertWarnsWith(UserWarning, msg):
1751 table.add_column(name='col10', description='column #10', index=True)
1752 self.assertEqual(table.col10.description, 'column #10')
1753 self.assertEqual(type(table.col10), VectorData)
1754 self.assertEqual(type(table.get('col10')), VectorIndex)
1755
1756 def test_add_opt_column_twice(self):
1757 """Test that adding an optional column from __columns__ twice fails the second time."""
1758 table = SubTable(name='subtable', description='subtable description')
1759 table.add_column(name='col2', description='column #2')
1760
1761 msg = "column 'col2' already exists in SubTable 'subtable'"
1762 with self.assertRaisesWith(ValueError, msg):
1763 table.add_column(name='col2', description='column #2b')
1764
1765 def test_add_opt_column_after_data(self):
1766 """Test that adding an optional column from __columns__ with data works."""
1767 table = SubTable(name='subtable', description='subtable description')
1768 table.add_row(col1='a', col3='c', col5='e', col7='g')
1769 table.add_column(name='col2', description='column #2', data=('b', ))
1770 self.assertTupleEqual(table.col2.data, ('b', ))
1771
1772 def test_add_opt_ind_column_after_data(self):
1773 """Test that adding an optional, indexed column from __columns__ with data works."""
1774 table = SubTable(name='subtable', description='subtable description')
1775 table.add_row(col1='a', col3='c', col5='e', col7='g')
1776 # TODO this use case is tricky and should not be allowed
1777 # table.add_column(name='col4', description='column #4', data=(('b', 'b2'), ))
1778
1779 def test_add_row_opt_column(self):
1780 """Test that adding a row with an optional column works."""
1781 table = SubTable(name='subtable', description='subtable description')
1782 table.add_row(col1='a', col2='b', col3='c', col4=('d1', 'd2'), col5='e', col7='g')
1783 table.add_row(col1='a', col2='b2', col3='c', col4=('d3', 'd4'), col5='e', col7='g')
1784 self.assertTupleEqual(table.colnames, ('col1', 'col3', 'col5', 'col7', 'col2', 'col4'))
1785 self.assertEqual(table.col2.description, 'optional column')
1786 self.assertEqual(table.col4.description, 'optional, indexed column')
1787 self.assertListEqual(table.col2.data, ['b', 'b2'])
1788 # self.assertListEqual(table.col4.data, [('d1', 'd2'), ('d3', 'd4')]) # TODO this should work
1789
1790 def test_add_row_opt_column_after_data(self):
1791 """Test that adding a row with an optional column after adding a row without the column raises an error."""
1792 table = SubTable(name='subtable', description='subtable description')
1793 table.add_row(col1='a', col3='c', col5='e', col7='g')
1794 msg = "column must have the same number of rows as 'id'" # TODO improve error message
1795 with self.assertRaisesWith(ValueError, msg):
1796 table.add_row(col1='a', col2='b', col3='c', col5='e', col7='g')
1797
1798 def test_init_columns_add_req_column(self):
1799 """Test that passing a required column to init works."""
1800 col1 = VectorData(name='col1', description='column #1') # override __columns__ description
1801 table = SubTable(name='subtable', description='subtable description', columns=[col1])
1802 self.assertEqual(table.colnames, ('col1', 'col3', 'col5', 'col7'))
1803 self.assertEqual(table.col1.description, 'column #1')
1804 self.assertTrue(hasattr(table, 'col1'))
1805
1806 def test_init_columns_add_req_column_mismatch_index(self):
1807 """Test that passing a required column that does not match the predefined column specs raises an error."""
1808 col1 = VectorData(name='col1', description='column #1') # override __columns__ description
1809 col1_ind = VectorIndex(name='col1_index', data=list(), target=col1)
1810
1811 # TODO raise an error
1812 SubTable(name='subtable', description='subtable description', columns=[col1_ind, col1])
1813
1814 def test_init_columns_add_req_column_mismatch_table(self):
1815 """Test that passing a required column that does not match the predefined column specs raises an error."""
1816 dummy_table = DynamicTable(name='dummy', description='dummy table')
1817 col1 = DynamicTableRegion(name='col1', data=list(), description='column #1', table=dummy_table)
1818
1819 # TODO raise an error
1820 SubTable(name='subtable', description='subtable description', columns=[col1])
1821
1822 def test_init_columns_add_opt_column(self):
1823 """Test that passing an optional column to init works."""
1824 col2 = VectorData(name='col2', description='column #2') # override __columns__ description
1825 table = SubTable(name='subtable', description='subtable description', columns=[col2])
1826 self.assertEqual(table.colnames, ('col2', 'col1', 'col3', 'col5', 'col7'))
1827 self.assertEqual(table.col2.description, 'column #2')
1828
1829 def test_init_columns_add_dup_column(self):
1830 """Test that passing two columns with the same name raises an error."""
1831 col1 = VectorData(name='col1', description='column #1') # override __columns__ description
1832 col1_ind = VectorIndex(name='col1', data=list(), target=col1)
1833
1834 msg = "'columns' contains columns with duplicate names: ['col1', 'col1']"
1835 with self.assertRaisesWith(ValueError, msg):
1836 SubTable(name='subtable', description='subtable description', columns=[col1_ind, col1])
1837
1838 def test_no_set_target_tables(self):
1839 """Test that the target table of a predefined DTR column is None."""
1840 table = SubTable(name='subtable', description='subtable description')
1841 self.assertIsNone(table.col5.table)
1842
1843 def test_set_target_tables(self):
1844 """Test setting target tables for predefined DTR columns."""
1845 table1 = SubTable(name='subtable1', description='subtable description')
1846 table2 = SubTable(
1847 name='subtable2',
1848 description='subtable description',
1849 target_tables={
1850 'col5': table1,
1851 'col6': table1,
1852 'col7': table1,
1853 'col8': table1,
1854 },
1855 )
1856 self.assertIs(table2.col5.table, table1)
1857 self.assertIs(table2.col6.table, table1)
1858 self.assertIs(table2.col7.table, table1)
1859 self.assertIs(table2.col8.table, table1)
1860
1861 def test_set_target_tables_unknown_col(self):
1862 """Test setting target tables for unknown columns."""
1863 table1 = SubTable(name='subtable1', description='subtable description')
1864 msg = r"'bad_col' is not the name of a predefined column of table subtable2 .*"
1865 with self.assertRaisesRegex(ValueError, msg):
1866 SubTable(
1867 name='subtable2',
1868 description='subtable description',
1869 target_tables={
1870 'bad_col': table1,
1871 },
1872 )
1873
1874 def test_set_target_tables_bad_init_col(self):
1875 """Test setting target tables for predefined, required non-DTR columns."""
1876 table1 = SubTable(name='subtable1', description='subtable description')
1877 msg = "Column 'col1' must be a DynamicTableRegion to have a target table."
1878 with self.assertRaisesWith(ValueError, msg):
1879 SubTable(
1880 name='subtable2',
1881 description='subtable description',
1882 target_tables={
1883 'col1': table1,
1884 },
1885 )
1886
1887 def test_set_target_tables_bad_opt_col(self):
1888 """Test setting target tables for predefined, optional non-DTR columns."""
1889 table1 = SubTable(name='subtable1', description='subtable description')
1890 msg = "Column 'col2' must be a DynamicTableRegion to have a target table."
1891 with self.assertRaisesWith(ValueError, msg):
1892 SubTable(
1893 name='subtable2',
1894 description='subtable description',
1895 target_tables={
1896 'col2': table1,
1897 },
1898 )
1899
1900 def test_set_target_tables_existing_col_mismatch(self):
1901 """Test setting target tables for an existing DTR column with a mismatched, existing target table."""
1902 table1 = SubTable(name='subtable1', description='subtable description')
1903 table2 = SubTable(name='subtable2', description='subtable description')
1904 dtr = DynamicTableRegion(name='dtr', data=[], description='desc', table=table1)
1905 msg = "Column 'dtr' already has a target table that is not the passed table."
1906 with self.assertRaisesWith(ValueError, msg):
1907 SubTable(
1908 name='subtable3',
1909 description='subtable description',
1910 columns=[dtr],
1911 target_tables={
1912 'dtr': table2,
1913 },
1914 )
1915
1916 def test_set_target_tables_existing_col_match(self):
1917 """Test setting target tables for an existing DTR column with a matching, existing target table."""
1918 table1 = SubTable(name='subtable1', description='subtable description')
1919 dtr = DynamicTableRegion(name='dtr', data=[], description='desc', table=table1)
1920 SubTable(
1921 name='subtable2',
1922 description='subtable description',
1923 columns=[dtr],
1924 target_tables={
1925 'dtr': table1,
1926 },
1927 )
1928
1929
1930 class TestEnumData(TestCase):
1931
1932 def test_init(self):
1933 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'],
1934 data=np.array([0, 0, 1, 1, 2, 2]))
1935 self.assertIsInstance(ed.elements, VectorData)
1936
1937 def test_get(self):
1938 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'],
1939 data=np.array([0, 0, 1, 1, 2, 2]))
1940 dat = ed[2]
1941 self.assertEqual(dat, 'b')
1942 dat = ed[-1]
1943 self.assertEqual(dat, 'c')
1944 dat = ed[0]
1945 self.assertEqual(dat, 'a')
1946
1947 def test_get_list(self):
1948 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'],
1949 data=np.array([0, 0, 1, 1, 2, 2]))
1950 dat = ed[[0, 1, 2]]
1951 np.testing.assert_array_equal(dat, ['a', 'a', 'b'])
1952
1953 def test_get_list_join(self):
1954 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'],
1955 data=np.array([0, 0, 1, 1, 2, 2]))
1956 dat = ed.get([0, 1, 2], join=True)
1957 self.assertEqual(dat, 'aab')
1958
1959 def test_get_list_indices(self):
1960 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'],
1961 data=np.array([0, 0, 1, 1, 2, 2]))
1962 dat = ed.get([0, 1, 2], index=True)
1963 np.testing.assert_array_equal(dat, [0, 0, 1])
1964
1965 def test_get_2d(self):
1966 ed = EnumData(name='cv_data', description='a test EnumData',
1967 elements=['a', 'b', 'c'],
1968 data=np.array([[0, 0], [1, 1], [2, 2]]))
1969 dat = ed[0]
1970 np.testing.assert_array_equal(dat, ['a', 'a'])
1971
1972 def test_get_2d_w_2d(self):
1973 ed = EnumData(name='cv_data', description='a test EnumData',
1974 elements=['a', 'b', 'c'],
1975 data=np.array([[0, 0], [1, 1], [2, 2]]))
1976 dat = ed[[0, 1]]
1977 np.testing.assert_array_equal(dat, [['a', 'a'], ['b', 'b']])
1978
1979 def test_add_row(self):
1980 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'])
1981 ed.add_row('b')
1982 ed.add_row('a')
1983 ed.add_row('c')
1984 np.testing.assert_array_equal(ed.data, np.array([1, 0, 2], dtype=np.uint8))
1985
1986 def test_add_row_index(self):
1987 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'])
1988 ed.add_row(1, index=True)
1989 ed.add_row(0, index=True)
1990 ed.add_row(2, index=True)
1991 np.testing.assert_array_equal(ed.data, np.array([1, 0, 2], dtype=np.uint8))
1992
1993
1994 class TestIndexedEnumData(TestCase):
1995
1996 def test_init(self):
1997 ed = EnumData(name='cv_data', description='a test EnumData',
1998 elements=['a', 'b', 'c'], data=np.array([0, 0, 1, 1, 2, 2]))
1999 idx = VectorIndex(name='enum_index', data=[2, 4, 6], target=ed)
2000 self.assertIsInstance(ed.elements, VectorData)
2001 self.assertIsInstance(idx.target, EnumData)
2002
2003 def test_add_row(self):
2004 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'])
2005 idx = VectorIndex(name='enum_index', data=list(), target=ed)
2006 idx.add_row(['a', 'a', 'a'])
2007 idx.add_row(['b', 'b'])
2008 idx.add_row(['c', 'c', 'c', 'c'])
2009 np.testing.assert_array_equal(idx[0], ['a', 'a', 'a'])
2010 np.testing.assert_array_equal(idx[1], ['b', 'b'])
2011 np.testing.assert_array_equal(idx[2], ['c', 'c', 'c', 'c'])
2012
2013 def test_add_row_index(self):
2014 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'])
2015 idx = VectorIndex(name='enum_index', data=list(), target=ed)
2016 idx.add_row([0, 0, 0], index=True)
2017 idx.add_row([1, 1], index=True)
2018 idx.add_row([2, 2, 2, 2], index=True)
2019 np.testing.assert_array_equal(idx[0], ['a', 'a', 'a'])
2020 np.testing.assert_array_equal(idx[1], ['b', 'b'])
2021 np.testing.assert_array_equal(idx[2], ['c', 'c', 'c', 'c'])
2022
2023 @unittest.skip("feature is not yet supported")
2024 def test_add_2d_row_index(self):
2025 ed = EnumData(name='cv_data', description='a test EnumData', elements=['a', 'b', 'c'])
2026 idx = VectorIndex(name='enum_index', data=list(), target=ed)
2027 idx.add_row([['a', 'a'], ['a', 'a'], ['a', 'a']])
2028 idx.add_row([['b', 'b'], ['b', 'b']])
2029 idx.add_row([['c', 'c'], ['c', 'c'], ['c', 'c'], ['c', 'c']])
2030 np.testing.assert_array_equal(idx[0], [['a', 'a'], ['a', 'a'], ['a', 'a']])
2031 np.testing.assert_array_equal(idx[1], [['b', 'b'], ['b', 'b']])
2032 np.testing.assert_array_equal(idx[2], [['c', 'c'], ['c', 'c'], ['c', 'c'], ['c', 'c']])
2033
2034
2035 class SelectionTestMixin:
2036
2037 def setUp(self):
2038 # table1 contains a non-ragged DTR and a ragged DTR, both of which point to table2
2039 # table2 contains a non-ragged DTR and a ragged DTR, both of which point to table3
2040 self.table3 = DynamicTable(
2041 name='table3',
2042 description='a test table',
2043 id=[20, 21, 22]
2044 )
2045 self.table3.add_column('foo', 'scalar column', data=self._wrap([20.0, 21.0, 22.0]))
2046 self.table3.add_column('bar', 'ragged column', index=self._wrap([2, 3, 6]),
2047 data=self._wrap(['t11', 't12', 't21', 't31', 't32', 't33']))
2048 self.table3.add_column('baz', 'multi-dimension column',
2049 data=self._wrap([[210.0, 211.0, 212.0],
2050 [220.0, 221.0, 222.0],
2051 [230.0, 231.0, 232.0]]))
2052 # generate expected dataframe for table3
2053 data = OrderedDict()
2054 data['foo'] = [20.0, 21.0, 22.0]
2055 data['bar'] = [['t11', 't12'], ['t21'], ['t31', 't32', 't33']]
2056 data['baz'] = [[210.0, 211.0, 212.0], [220.0, 221.0, 222.0], [230.0, 231.0, 232.0]]
2057 idx = [20, 21, 22]
2058 self.table3_df = pd.DataFrame(data=data, index=pd.Index(name='id', data=idx))
2059
2060 self.table2 = DynamicTable(
2061 name='table2',
2062 description='a test table',
2063 id=[10, 11, 12]
2064 )
2065 self.table2.add_column('foo', 'scalar column', data=self._wrap([10.0, 11.0, 12.0]))
2066 self.table2.add_column('bar', 'ragged column', index=self._wrap([2, 3, 6]),
2067 data=self._wrap(['s11', 's12', 's21', 's31', 's32', 's33']))
2068 self.table2.add_column('baz', 'multi-dimension column',
2069 data=self._wrap([[110.0, 111.0, 112.0],
2070 [120.0, 121.0, 122.0],
2071 [130.0, 131.0, 132.0]]))
2072 self.table2.add_column('qux', 'DTR column', table=self.table3, data=self._wrap([0, 1, 0]))
2073 self.table2.add_column('corge', 'ragged DTR column', index=self._wrap([2, 3, 6]), table=self.table3,
2074 data=self._wrap([0, 1, 2, 0, 1, 2]))
2075 # TODO test when ragged DTR indices are not in ascending order
2076
2077 # generate expected dataframe for table2 *without DTR*
2078 data = OrderedDict()
2079 data['foo'] = [10.0, 11.0, 12.0]
2080 data['bar'] = [['s11', 's12'], ['s21'], ['s31', 's32', 's33']]
2081 data['baz'] = [[110.0, 111.0, 112.0], [120.0, 121.0, 122.0], [130.0, 131.0, 132.0]]
2082 idx = [10, 11, 12]
2083 self.table2_df = pd.DataFrame(data=data, index=pd.Index(name='id', data=idx))
2084
2085 self.table1 = DynamicTable(
2086 name='table1',
2087 description='a table to test slicing',
2088 id=[0, 1]
2089 )
2090 self.table1.add_column('foo', 'scalar column', data=self._wrap([0.0, 1.0]))
2091 self.table1.add_column('bar', 'ragged column', index=self._wrap([2, 3]),
2092 data=self._wrap(['r11', 'r12', 'r21']))
2093 self.table1.add_column('baz', 'multi-dimension column',
2094 data=self._wrap([[10.0, 11.0, 12.0],
2095 [20.0, 21.0, 22.0]]))
2096 self.table1.add_column('qux', 'DTR column', table=self.table2, data=self._wrap([0, 1]))
2097 self.table1.add_column('corge', 'ragged DTR column', index=self._wrap([2, 3]), table=self.table2,
2098 data=self._wrap([0, 1, 2]))
2099 self.table1.add_column('barz', 'ragged column of tuples (cpd type)', index=self._wrap([2, 3]),
2100 data=self._wrap([(1.0, 11), (2.0, 12), (3.0, 21)]))
2101
2102 # generate expected dataframe for table1 *without DTR*
2103 data = OrderedDict()
2104 data['foo'] = self._wrap_check([0.0, 1.0])
2105 data['bar'] = [self._wrap_check(['r11', 'r12']), self._wrap_check(['r21'])]
2106 data['baz'] = [self._wrap_check([10.0, 11.0, 12.0]),
2107 self._wrap_check([20.0, 21.0, 22.0])]
2108 data['barz'] = [self._wrap_check([(1.0, 11), (2.0, 12)]), self._wrap_check([(3.0, 21)])]
2109 idx = [0, 1]
2110 self.table1_df = pd.DataFrame(data=data, index=pd.Index(name='id', data=idx))
2111
2112 def _check_two_rows_df(self, rec):
2113 data = OrderedDict()
2114 data['foo'] = self._wrap_check([0.0, 1.0])
2115 data['bar'] = [self._wrap_check(['r11', 'r12']), self._wrap_check(['r21'])]
2116 data['baz'] = [self._wrap_check([10.0, 11.0, 12.0]),
2117 self._wrap_check([20.0, 21.0, 22.0])]
2118 data['qux'] = self._wrap_check([0, 1])
2119 data['corge'] = [self._wrap_check([0, 1]), self._wrap_check([2])]
2120 data['barz'] = [self._wrap_check([(1.0, 11), (2.0, 12)]), self._wrap_check([(3.0, 21)])]
2121 idx = [0, 1]
2122 exp = pd.DataFrame(data=data, index=pd.Index(name='id', data=idx))
2123 pd.testing.assert_frame_equal(rec, exp)
2124
2125 def _check_two_rows_df_nested(self, rec):
2126 # first level: cache nested df cols and remove them before calling pd.testing.assert_frame_equal
2127 qux_series = rec['qux']
2128 corge_series = rec['corge']
2129 del rec['qux']
2130 del rec['corge']
2131
2132 idx = [0, 1]
2133 pd.testing.assert_frame_equal(rec, self.table1_df.loc[idx])
2134
2135 # second level: compare the nested columns separately
2136 self.assertEqual(len(qux_series), 2)
2137 rec_qux1 = qux_series[0]
2138 rec_qux2 = qux_series[1]
2139 self._check_table2_first_row_qux(rec_qux1)
2140 self._check_table2_second_row_qux(rec_qux2)
2141
2142 self.assertEqual(len(corge_series), 2)
2143 rec_corge1 = corge_series[0]
2144 rec_corge2 = corge_series[1]
2145 self._check_table2_first_row_corge(rec_corge1)
2146 self._check_table2_second_row_corge(rec_corge2)
2147
2148 def _check_one_row_df(self, rec):
2149 data = OrderedDict()
2150 data['foo'] = self._wrap_check([0.0])
2151 data['bar'] = [self._wrap_check(['r11', 'r12'])]
2152 data['baz'] = [self._wrap_check([10.0, 11.0, 12.0])]
2153 data['qux'] = self._wrap_check([0])
2154 data['corge'] = [self._wrap_check([0, 1])]
2155 data['barz'] = [self._wrap_check([(1.0, 11), (2.0, 12)])]
2156 idx = [0]
2157 exp = pd.DataFrame(data=data, index=pd.Index(name='id', data=idx))
2158 pd.testing.assert_frame_equal(rec, exp)
2159
2160 def _check_one_row_df_nested(self, rec):
2161 # first level: cache nested df cols and remove them before calling pd.testing.assert_frame_equal
2162 qux_series = rec['qux']
2163 corge_series = rec['corge']
2164 del rec['qux']
2165 del rec['corge']
2166
2167 idx = [0]
2168 pd.testing.assert_frame_equal(rec, self.table1_df.loc[idx])
2169
2170 # second level: compare the nested columns separately
2171 self.assertEqual(len(qux_series), 1)
2172 rec_qux = qux_series[0]
2173 self._check_table2_first_row_qux(rec_qux)
2174
2175 self.assertEqual(len(corge_series), 1)
2176 rec_corge = corge_series[0]
2177 self._check_table2_first_row_corge(rec_corge)
2178
2179 def _check_table2_first_row_qux(self, rec_qux):
2180 # second level: cache nested df cols and remove them before calling pd.testing.assert_frame_equal
2181 qux_qux_series = rec_qux['qux']
2182 qux_corge_series = rec_qux['corge']
2183 del rec_qux['qux']
2184 del rec_qux['corge']
2185
2186 qux_idx = [10]
2187 pd.testing.assert_frame_equal(rec_qux, self.table2_df.loc[qux_idx])
2188
2189 # third level: compare the nested columns separately
2190 self.assertEqual(len(qux_qux_series), 1)
2191 pd.testing.assert_frame_equal(qux_qux_series[qux_idx[0]], self.table3_df.iloc[[0]])
2192 self.assertEqual(len(qux_corge_series), 1)
2193 pd.testing.assert_frame_equal(qux_corge_series[qux_idx[0]], self.table3_df.iloc[[0, 1]])
2194
2195 def _check_table2_second_row_qux(self, rec_qux):
2196 # second level: cache nested df cols and remove them before calling pd.testing.assert_frame_equal
2197 qux_qux_series = rec_qux['qux']
2198 qux_corge_series = rec_qux['corge']
2199 del rec_qux['qux']
2200 del rec_qux['corge']
2201
2202 qux_idx = [11]
2203 pd.testing.assert_frame_equal(rec_qux, self.table2_df.loc[qux_idx])
2204
2205 # third level: compare the nested columns separately
2206 self.assertEqual(len(qux_qux_series), 1)
2207 pd.testing.assert_frame_equal(qux_qux_series[qux_idx[0]], self.table3_df.iloc[[1]])
2208 self.assertEqual(len(qux_corge_series), 1)
2209 pd.testing.assert_frame_equal(qux_corge_series[qux_idx[0]], self.table3_df.iloc[[2]])
2210
2211 def _check_table2_first_row_corge(self, rec_corge):
2212 # second level: cache nested df cols and remove them before calling pd.testing.assert_frame_equal
2213 corge_qux_series = rec_corge['qux']
2214 corge_corge_series = rec_corge['corge']
2215 del rec_corge['qux']
2216 del rec_corge['corge']
2217
2218 corge_idx = [10, 11]
2219 pd.testing.assert_frame_equal(rec_corge, self.table2_df.loc[corge_idx])
2220
2221 # third level: compare the nested columns separately
2222 self.assertEqual(len(corge_qux_series), 2)
2223 pd.testing.assert_frame_equal(corge_qux_series[corge_idx[0]], self.table3_df.iloc[[0]])
2224 pd.testing.assert_frame_equal(corge_qux_series[corge_idx[1]], self.table3_df.iloc[[1]])
2225 self.assertEqual(len(corge_corge_series), 2)
2226 pd.testing.assert_frame_equal(corge_corge_series[corge_idx[0]], self.table3_df.iloc[[0, 1]])
2227 pd.testing.assert_frame_equal(corge_corge_series[corge_idx[1]], self.table3_df.iloc[[2]])
2228
2229 def _check_table2_second_row_corge(self, rec_corge):
2230 # second level: cache nested df cols and remove them before calling pd.testing.assert_frame_equal
2231 corge_qux_series = rec_corge['qux']
2232 corge_corge_series = rec_corge['corge']
2233 del rec_corge['qux']
2234 del rec_corge['corge']
2235
2236 corge_idx = [12]
2237 pd.testing.assert_frame_equal(rec_corge, self.table2_df.loc[corge_idx])
2238
2239 # third level: compare the nested columns separately
2240 self.assertEqual(len(corge_qux_series), 1)
2241 pd.testing.assert_frame_equal(corge_qux_series[corge_idx[0]], self.table3_df.iloc[[0]])
2242 self.assertEqual(len(corge_corge_series), 1)
2243 pd.testing.assert_frame_equal(corge_corge_series[corge_idx[0]], self.table3_df.iloc[[0, 1, 2]])
2244
2245 def _check_two_rows_no_df(self, rec):
2246 self.assertEqual(rec[0], [0, 1])
2247 np.testing.assert_array_equal(rec[1], self._wrap_check([0.0, 1.0]))
2248 expected = [self._wrap_check(['r11', 'r12']), self._wrap_check(['r21'])]
2249 self._assertNestedRaggedArrayEqual(rec[2], expected)
2250 np.testing.assert_array_equal(rec[3], self._wrap_check([[10.0, 11.0, 12.0], [20.0, 21.0, 22.0]]))
2251 np.testing.assert_array_equal(rec[4], self._wrap_check([0, 1]))
2252 expected = [self._wrap_check([0, 1]), self._wrap_check([2])]
2253 for i, j in zip(rec[5], expected):
2254 np.testing.assert_array_equal(i, j)
2255
2256 def _check_one_row_no_df(self, rec):
2257 self.assertEqual(rec[0], 0)
2258 self.assertEqual(rec[1], 0.0)
2259 np.testing.assert_array_equal(rec[2], self._wrap_check(['r11', 'r12']))
2260 np.testing.assert_array_equal(rec[3], self._wrap_check([10.0, 11.0, 12.0]))
2261 self.assertEqual(rec[4], 0)
2262 np.testing.assert_array_equal(rec[5], self._wrap_check([0, 1]))
2263 np.testing.assert_array_equal(rec[6], self._wrap_check([(1.0, 11), (2.0, 12)]))
2264
2265 def _check_one_row_multiselect_no_df(self, rec):
2266 # difference from _check_one_row_no_df is that everything is wrapped in a list
2267 self.assertEqual(rec[0], [0])
2268 self.assertEqual(rec[1], [0.0])
2269 np.testing.assert_array_equal(rec[2], [self._wrap_check(['r11', 'r12'])])
2270 np.testing.assert_array_equal(rec[3], [self._wrap_check([10.0, 11.0, 12.0])])
2271 self.assertEqual(rec[4], [0])
2272 np.testing.assert_array_equal(rec[5], [self._wrap_check([0, 1])])
2273 np.testing.assert_array_equal(rec[6], [self._wrap_check([(1.0, 11), (2.0, 12)])])
2274
2275 def _assertNestedRaggedArrayEqual(self, arr1, arr2):
2276 """
2277 This is a helper function for _check_two_rows_no_df.
2278 It compares arrays or lists containing numpy arrays that may be ragged
2279 """
2280 self.assertEqual(type(arr1), type(arr2))
2281 self.assertEqual(len(arr1), len(arr2))
2282 if isinstance(arr1, np.ndarray):
2283 if arr1.dtype == object: # both are arrays containing arrays, lists, or h5py.Dataset strings
2284 for i, j in zip(arr1, arr2):
2285 self._assertNestedRaggedArrayEqual(i, j)
2286 elif np.issubdtype(arr1.dtype, np.number):
2287 np.testing.assert_allclose(arr1, arr2)
2288 else:
2289 np.testing.assert_array_equal(arr1, arr2)
2290 elif isinstance(arr1, list):
2291 for i, j in zip(arr1, arr2):
2292 self._assertNestedRaggedArrayEqual(i, j)
2293 else: # scalar
2294 self.assertEqual(arr1, arr2)
2295
2296 def test_single_item(self):
2297 rec = self.table1[0]
2298 self._check_one_row_df(rec)
2299
2300 def test_single_item_nested(self):
2301 rec = self.table1.get(0, index=False)
2302 self._check_one_row_df_nested(rec)
2303
2304 def test_single_item_no_df(self):
2305 rec = self.table1.get(0, df=False)
2306 self._check_one_row_no_df(rec)
2307
2308 def test_slice(self):
2309 rec = self.table1[0:2]
2310 self._check_two_rows_df(rec)
2311
2312 def test_slice_nested(self):
2313 rec = self.table1.get(slice(0, 2), index=False)
2314 self._check_two_rows_df_nested(rec)
2315
2316 def test_slice_no_df(self):
2317 rec = self.table1.get(slice(0, 2), df=False)
2318 self._check_two_rows_no_df(rec)
2319
2320 def test_slice_single(self):
2321 rec = self.table1[0:1]
2322 self._check_one_row_df(rec)
2323
2324 def test_slice_single_nested(self):
2325 rec = self.table1.get(slice(0, 1), index=False)
2326 self._check_one_row_df_nested(rec)
2327
2328 def test_slice_single_no_df(self):
2329 rec = self.table1.get(slice(0, 1), df=False)
2330 self._check_one_row_multiselect_no_df(rec)
2331
2332 def test_list(self):
2333 rec = self.table1[[0, 1]]
2334 self._check_two_rows_df(rec)
2335
2336 def test_list_nested(self):
2337 rec = self.table1.get([0, 1], index=False)
2338 self._check_two_rows_df_nested(rec)
2339
2340 def test_list_no_df(self):
2341 rec = self.table1.get([0, 1], df=False)
2342 self._check_two_rows_no_df(rec)
2343
2344 def test_list_single(self):
2345 rec = self.table1[[0]]
2346 self._check_one_row_df(rec)
2347
2348 def test_list_single_nested(self):
2349 rec = self.table1.get([0], index=False)
2350 self._check_one_row_df_nested(rec)
2351
2352 def test_list_single_no_df(self):
2353 rec = self.table1.get([0], df=False)
2354 self._check_one_row_multiselect_no_df(rec)
2355
2356 def test_array(self):
2357 rec = self.table1[np.array([0, 1])]
2358 self._check_two_rows_df(rec)
2359
2360 def test_array_nested(self):
2361 rec = self.table1.get(np.array([0, 1]), index=False)
2362 self._check_two_rows_df_nested(rec)
2363
2364 def test_array_no_df(self):
2365 rec = self.table1.get(np.array([0, 1]), df=False)
2366 self._check_two_rows_no_df(rec)
2367
2368 def test_array_single(self):
2369 rec = self.table1[np.array([0])]
2370 self._check_one_row_df(rec)
2371
2372 def test_array_single_nested(self):
2373 rec = self.table1.get(np.array([0]), index=False)
2374 self._check_one_row_df_nested(rec)
2375
2376 def test_array_single_no_df(self):
2377 rec = self.table1.get(np.array([0]), df=False)
2378 self._check_one_row_multiselect_no_df(rec)
2379
2380 def test_to_dataframe_nested(self):
2381 rec = self.table1.to_dataframe()
2382 self._check_two_rows_df_nested(rec)
2383
2384 def test_to_dataframe(self):
2385 rec = self.table1.to_dataframe(index=True)
2386 self._check_two_rows_df(rec)
2387
2388
2389 class TestSelectionArray(SelectionTestMixin, TestCase):
2390
2391 def _wrap(self, my_list):
2392 return np.array(my_list)
2393
2394 def _wrap_check(self, my_list):
2395 return self._wrap(my_list)
2396
2397
2398 class TestSelectionList(SelectionTestMixin, TestCase):
2399
2400 def _wrap(self, my_list):
2401 return my_list
2402
2403 def _wrap_check(self, my_list):
2404 return self._wrap(my_list)
2405
2406
2407 class TestSelectionH5Dataset(SelectionTestMixin, TestCase):
2408
2409 def setUp(self):
2410 self.path = get_temp_filepath()
2411 self.file = h5py.File(self.path, 'w')
2412 self.dset_counter = 0
2413 super().setUp()
2414
2415 def tearDown(self):
2416 super().tearDown()
2417 self.file.close()
2418 if os.path.exists(self.path):
2419 os.remove(self.path)
2420
2421 def _wrap(self, my_list):
2422 self.dset_counter = self.dset_counter + 1
2423 kwargs = dict()
2424 if isinstance(my_list[0], str):
2425 kwargs['dtype'] = H5_TEXT
2426 elif isinstance(my_list[0], tuple): # compound dtype
2427 # normally for cpd dtype, __resolve_dtype__ takes a list of DtypeSpec objects
2428 cpd_type = [dict(name='cpd_float', dtype=np.dtype('float64')),
2429 dict(name='cpd_int', dtype=np.dtype('int32'))]
2430 kwargs['dtype'] = HDF5IO.__resolve_dtype__(cpd_type, my_list[0])
2431 dset = self.file.create_dataset('dset%d' % self.dset_counter, data=np.array(my_list, **kwargs))
2432 if H5PY_3 and isinstance(my_list[0], str):
2433 return StrDataset(dset, None) # return a wrapper to read data as str instead of bytes
2434 else:
2435 # NOTE: h5py.Dataset with compound dtype are read as numpy arrays with compound dtype, not tuples
2436 return dset
2437
2438 def _wrap_check(self, my_list):
2439 # getitem on h5dataset backed data will return np.array
2440 kwargs = dict()
2441 if isinstance(my_list[0], str):
2442 kwargs['dtype'] = H5_TEXT
2443 elif isinstance(my_list[0], tuple):
2444 cpd_type = [dict(name='cpd_float', dtype=np.dtype('float64')),
2445 dict(name='cpd_int', dtype=np.dtype('int32'))]
2446 kwargs['dtype'] = np.dtype([(x['name'], x['dtype']) for x in cpd_type])
2447 # compound dtypes with str are read as bytes, see https://github.com/h5py/h5py/issues/1751
2448 return np.array(my_list, **kwargs)
2449
2450
2451 class TestVectorIndex(TestCase):
2452
2453 def test_init_empty(self):
2454 foo = VectorData(name='foo', description='foo column')
2455 foo_ind = VectorIndex(name='foo_index', target=foo, data=list())
2456 self.assertEqual(foo_ind.name, 'foo_index')
2457 self.assertEqual(foo_ind.description, "Index for VectorData 'foo'")
2458 self.assertIs(foo_ind.target, foo)
2459 self.assertListEqual(foo_ind.data, list())
2460
2461 def test_init_data(self):
2462 foo = VectorData(name='foo', description='foo column', data=['a', 'b', 'c'])
2463 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3])
2464 self.assertListEqual(foo_ind.data, [2, 3])
2465 self.assertListEqual(foo_ind[0], ['a', 'b'])
2466 self.assertListEqual(foo_ind[1], ['c'])
2467
2468
2469 class TestDoubleIndex(TestCase):
2470
2471 def test_index(self):
2472 # row 1 has three entries
2473 # the first entry has two sub-entries
2474 # the first sub-entry has two values, the second sub-entry has one value
2475 # the second entry has one sub-entry, which has one value
2476 foo = VectorData(name='foo', description='foo column', data=['a11', 'a12', 'a21', 'b11'])
2477 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2478 foo_ind_ind = VectorIndex(name='foo_index_index', target=foo_ind, data=[2, 3])
2479
2480 self.assertListEqual(foo_ind[0], ['a11', 'a12'])
2481 self.assertListEqual(foo_ind[1], ['a21'])
2482 self.assertListEqual(foo_ind[2], ['b11'])
2483 self.assertListEqual(foo_ind_ind[0], [['a11', 'a12'], ['a21']])
2484 self.assertListEqual(foo_ind_ind[1], [['b11']])
2485
2486 def test_add_vector(self):
2487 # row 1 has three entries
2488 # the first entry has two sub-entries
2489 # the first sub-entry has two values, the second sub-entry has one value
2490 # the second entry has one sub-entry, which has one value
2491 foo = VectorData(name='foo', description='foo column', data=['a11', 'a12', 'a21', 'b11'])
2492 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2493 foo_ind_ind = VectorIndex(name='foo_index_index', target=foo_ind, data=[2, 3])
2494
2495 foo_ind_ind.add_vector([['c11', 'c12', 'c13'], ['c21', 'c22']])
2496
2497 self.assertListEqual(foo.data, ['a11', 'a12', 'a21', 'b11', 'c11', 'c12', 'c13', 'c21', 'c22'])
2498 self.assertListEqual(foo_ind.data, [2, 3, 4, 7, 9])
2499 self.assertListEqual(foo_ind[3], ['c11', 'c12', 'c13'])
2500 self.assertListEqual(foo_ind[4], ['c21', 'c22'])
2501 self.assertListEqual(foo_ind_ind.data, [2, 3, 5])
2502 self.assertListEqual(foo_ind_ind[2], [['c11', 'c12', 'c13'], ['c21', 'c22']])
2503
2504
2505 class TestDTDoubleIndex(TestCase):
2506
2507 def test_double_index(self):
2508 foo = VectorData(name='foo', description='foo column', data=['a11', 'a12', 'a21', 'b11'])
2509 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2510 foo_ind_ind = VectorIndex(name='foo_index_index', target=foo_ind, data=[2, 3])
2511
2512 table = DynamicTable(name='table0', description='an example table', columns=[foo, foo_ind, foo_ind_ind])
2513
2514 self.assertIs(table['foo'], foo_ind_ind)
2515 self.assertIs(table.foo, foo)
2516 self.assertListEqual(table['foo'][0], [['a11', 'a12'], ['a21']])
2517 self.assertListEqual(table[0, 'foo'], [['a11', 'a12'], ['a21']])
2518 self.assertListEqual(table[1, 'foo'], [['b11']])
2519
2520 def test_double_index_reverse(self):
2521 foo = VectorData(name='foo', description='foo column', data=['a11', 'a12', 'a21', 'b11'])
2522 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2523 foo_ind_ind = VectorIndex(name='foo_index_index', target=foo_ind, data=[2, 3])
2524
2525 table = DynamicTable(name='table0', description='an example table', columns=[foo_ind_ind, foo_ind, foo])
2526
2527 self.assertIs(table['foo'], foo_ind_ind)
2528 self.assertIs(table.foo, foo)
2529 self.assertListEqual(table['foo'][0], [['a11', 'a12'], ['a21']])
2530 self.assertListEqual(table[0, 'foo'], [['a11', 'a12'], ['a21']])
2531 self.assertListEqual(table[1, 'foo'], [['b11']])
2532
2533 def test_double_index_colnames(self):
2534 foo = VectorData(name='foo', description='foo column', data=['a11', 'a12', 'a21', 'b11'])
2535 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2536 foo_ind_ind = VectorIndex(name='foo_index_index', target=foo_ind, data=[2, 3])
2537 bar = VectorData(name='bar', description='bar column', data=[1, 2])
2538
2539 table = DynamicTable(name='table0', description='an example table', columns=[foo, foo_ind, foo_ind_ind, bar],
2540 colnames=['foo', 'bar'])
2541
2542 self.assertTupleEqual(table.columns, (foo_ind_ind, foo_ind, foo, bar))
2543
2544 def test_double_index_reverse_colnames(self):
2545 foo = VectorData(name='foo', description='foo column', data=['a11', 'a12', 'a21', 'b11'])
2546 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2547 foo_ind_ind = VectorIndex(name='foo_index_index', target=foo_ind, data=[2, 3])
2548 bar = VectorData(name='bar', description='bar column', data=[1, 2])
2549
2550 table = DynamicTable(name='table0', description='an example table', columns=[foo_ind_ind, foo_ind, foo, bar],
2551 colnames=['bar', 'foo'])
2552
2553 self.assertTupleEqual(table.columns, (bar, foo_ind_ind, foo_ind, foo))
2554
2555
2556 class TestDTDoubleIndexSkipMiddle(TestCase):
2557
2558 def test_index(self):
2559 foo = VectorData(name='foo', description='foo column', data=['a11', 'a12', 'a21', 'b11'])
2560 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2561 foo_ind_ind = VectorIndex(name='foo_index_index', target=foo_ind, data=[2, 3])
2562
2563 msg = "Found VectorIndex 'foo_index_index' but not its target 'foo_index'"
2564 with self.assertRaisesWith(ValueError, msg):
2565 DynamicTable(name='table0', description='an example table', columns=[foo_ind_ind, foo])
2566
2567
2568 class TestDynamicTableAddIndexRoundTrip(H5RoundTripMixin, TestCase):
2569
2570 def setUpContainer(self):
2571 table = DynamicTable(name='table0', description='an example table')
2572 table.add_column('foo', 'an int column', index=True)
2573 table.add_row(foo=[1, 2, 3])
2574 return table
2575
2576
2577 class TestDynamicTableAddEnumRoundTrip(H5RoundTripMixin, TestCase):
2578
2579 def setUpContainer(self):
2580 table = DynamicTable(name='table0', description='an example table')
2581 table.add_column('bar', 'an enumerable column', enum=True)
2582 table.add_row(bar='a')
2583 table.add_row(bar='b')
2584 table.add_row(bar='a')
2585 table.add_row(bar='c')
2586 return table
2587
2588
2589 class TestDynamicTableAddEnum(TestCase):
2590
2591 def test_enum(self):
2592 table = DynamicTable(name='table0', description='an example table')
2593 table.add_column('bar', 'an enumerable column', enum=True)
2594 table.add_row(bar='a')
2595 table.add_row(bar='b')
2596 table.add_row(bar='a')
2597 table.add_row(bar='c')
2598 rec = table.to_dataframe()
2599 exp = pd.DataFrame(data={'bar': ['a', 'b', 'a', 'c']}, index=pd.Series(name='id', data=[0, 1, 2, 3]))
2600 pd.testing.assert_frame_equal(exp, rec)
2601
2602 def test_enum_index(self):
2603 table = DynamicTable(name='table0', description='an example table')
2604 table.add_column('bar', 'an indexed enumerable column', enum=True, index=True)
2605 table.add_row(bar=['a', 'a', 'a'])
2606 table.add_row(bar=['b', 'b', 'b', 'b'])
2607 table.add_row(bar=['c', 'c'])
2608 rec = table.to_dataframe()
2609 exp = pd.DataFrame(data={'bar': [['a', 'a', 'a'],
2610 ['b', 'b', 'b', 'b'],
2611 ['c', 'c']]},
2612 index=pd.Series(name='id', data=[0, 1, 2]))
2613 pd.testing.assert_frame_equal(exp, rec)
2614
2615
2616 class TestDynamicTableInitIndexRoundTrip(H5RoundTripMixin, TestCase):
2617
2618 def setUpContainer(self):
2619 foo = VectorData(name='foo', description='foo column', data=['a', 'b', 'c'])
2620 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3])
2621
2622 # NOTE: on construct, columns are ordered such that indices go before data, so create the table that way
2623 # for proper comparison of the columns list
2624 table = DynamicTable(name='table0', description='an example table', columns=[foo_ind, foo])
2625 return table
2626
2627
2628 class TestDoubleIndexRoundtrip(H5RoundTripMixin, TestCase):
2629
2630 def setUpContainer(self):
2631 foo = VectorData(name='foo', description='foo column', data=['a11', 'a12', 'a21', 'b11'])
2632 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2633 foo_ind_ind = VectorIndex(name='foo_index_index', target=foo_ind, data=[2, 3])
2634
2635 # NOTE: on construct, columns are ordered such that indices go before data, so create the table that way
2636 # for proper comparison of the columns list
2637 table = DynamicTable(name='table0', description='an example table', columns=[foo_ind_ind, foo_ind, foo])
2638 return table
2639
2640
2641 class TestDataIOColumns(H5RoundTripMixin, TestCase):
2642 def setUpContainer(self):
2643 self.chunked_data = H5DataIO(
2644 data=[i for i in range(10)],
2645 chunks=(3,),
2646 fillvalue=-1,
2647 )
2648 self.compressed_data = H5DataIO(
2649 data=np.arange(10),
2650 compression=1,
2651 shuffle=True,
2652 fletcher32=True,
2653 allow_plugin_filters=True,
2654 )
2655 foo = VectorData(name='foo', description='chunked column', data=self.chunked_data)
2656 bar = VectorData(name='bar', description='chunked column', data=self.compressed_data)
2657
2658 # NOTE: on construct, columns are ordered such that indices go before data, so create the table that way
2659 # for proper comparison of the columns list
2660 table = DynamicTable(name='table0', description='an example table', columns=[foo, bar])
2661 table.add_row(foo=1, bar=1)
2662 return table
2663
2664 def test_roundtrip(self):
2665 super().test_roundtrip()
2666
2667 with h5py.File(self.filename, 'r') as f:
2668 chunked_dset = f['foo']
2669 self.assertTrue(np.all(chunked_dset[:] == self.chunked_data.data))
2670 self.assertEqual(chunked_dset.chunks, (3,))
2671 self.assertEqual(chunked_dset.fillvalue, -1)
2672
2673 compressed_dset = f['bar']
2674 self.assertTrue(np.all(compressed_dset[:] == self.compressed_data.data))
2675 self.assertEqual(compressed_dset.compression, 'gzip')
2676 self.assertEqual(compressed_dset.shuffle, True)
2677 self.assertEqual(compressed_dset.fletcher32, True)
2678
2679
2680 class TestDataIOIndexedColumns(H5RoundTripMixin, TestCase):
2681
2682 def setUpContainer(self):
2683 self.chunked_data = H5DataIO(
2684 data=np.arange(30).reshape(5, 2, 3),
2685 chunks=(1, 1, 3),
2686 fillvalue=-1,
2687 )
2688 self.compressed_data = H5DataIO(
2689 data=np.arange(30).reshape(5, 2, 3),
2690 compression=1,
2691 shuffle=True,
2692 fletcher32=True,
2693 allow_plugin_filters=True,
2694 )
2695 foo = VectorData(name='foo', description='chunked column', data=self.chunked_data)
2696 foo_ind = VectorIndex(name='foo_index', target=foo, data=[2, 3, 4])
2697 bar = VectorData(name='bar', description='chunked column', data=self.compressed_data)
2698 bar_ind = VectorIndex(name='bar_index', target=bar, data=[2, 3, 4])
2699
2700 # NOTE: on construct, columns are ordered such that indices go before data, so create the table that way
2701 # for proper comparison of the columns list
2702 table = DynamicTable(name='table0', description='an example table', columns=[foo_ind, foo, bar_ind, bar])
2703
2704 # check for add_row
2705 table.add_row(foo=np.arange(30).reshape(5, 2, 3), bar=np.arange(30).reshape(5, 2, 3))
2706
2707 return table
2708
2709 def test_roundtrip(self):
2710 super().test_roundtrip()
2711
2712 with h5py.File(self.filename, 'r') as f:
2713 chunked_dset = f['foo']
2714 self.assertTrue(np.all(chunked_dset[:] == self.chunked_data.data))
2715 self.assertEqual(chunked_dset.chunks, (1, 1, 3))
2716 self.assertEqual(chunked_dset.fillvalue, -1)
2717
2718 compressed_dset = f['bar']
2719 self.assertTrue(np.all(compressed_dset[:] == self.compressed_data.data))
2720 self.assertEqual(compressed_dset.compression, 'gzip')
2721 self.assertEqual(compressed_dset.shuffle, True)
2722 self.assertEqual(compressed_dset.fletcher32, True)
2723
2724
2725 class TestDataIOIndex(H5RoundTripMixin, TestCase):
2726
2727 def setUpContainer(self):
2728 self.chunked_data = H5DataIO(
2729 data=np.arange(30).reshape(5, 2, 3),
2730 chunks=(1, 1, 3),
2731 fillvalue=-1,
2732 maxshape=(None, 2, 3)
2733 )
2734 self.chunked_index_data = H5DataIO(
2735 data=np.array([2, 3, 5], dtype=np.uint),
2736 chunks=(2, ),
2737 fillvalue=np.uint(10),
2738 maxshape=(None,)
2739 )
2740 self.compressed_data = H5DataIO(
2741 data=np.arange(30).reshape(5, 2, 3),
2742 compression=1,
2743 shuffle=True,
2744 fletcher32=True,
2745 allow_plugin_filters=True,
2746 maxshape=(None, 2, 3)
2747 )
2748 self.compressed_index_data = H5DataIO(
2749 data=np.array([2, 4, 5], dtype=np.uint),
2750 compression=1,
2751 shuffle=True,
2752 fletcher32=False,
2753 allow_plugin_filters=True,
2754 maxshape=(None,)
2755 )
2756 foo = VectorData(name='foo', description='chunked column', data=self.chunked_data)
2757 foo_ind = VectorIndex(name='foo_index', target=foo, data=self.chunked_index_data)
2758 bar = VectorData(name='bar', description='chunked column', data=self.compressed_data)
2759 bar_ind = VectorIndex(name='bar_index', target=bar, data=self.compressed_index_data)
2760
2761 # NOTE: on construct, columns are ordered such that indices go before data, so create the table that way
2762 # for proper comparison of the columns list
2763 table = DynamicTable(name='table0', description='an example table', columns=[foo_ind, foo, bar_ind, bar],
2764 id=H5DataIO(data=[0, 1, 2], chunks=True, maxshape=(None,)))
2765
2766 # check for add_row
2767 table.add_row(foo=np.arange(30).reshape(5, 2, 3),
2768 bar=np.arange(30).reshape(5, 2, 3))
2769
2770 return table
2771
2772 def test_append(self, cache_spec=False):
2773 """Write the container to an HDF5 file, read the container from the file, and append to it."""
2774 with HDF5IO(self.filename, manager=get_manager(), mode='w') as write_io:
2775 write_io.write(self.container, cache_spec=cache_spec)
2776
2777 self.reader = HDF5IO(self.filename, manager=get_manager(), mode='a')
2778 read_table = self.reader.read()
2779
2780 data = np.arange(30, 60).reshape(5, 2, 3)
2781 read_table.add_row(foo=data, bar=data)
2782
2783 np.testing.assert_array_equal(read_table['foo'][-1], data)
2784
2785
2786 class TestDTRReferences(TestCase):
2787
2788 def setUp(self):
2789 self.filename = 'test_dtr_references.h5'
2790
2791 def tearDown(self):
2792 remove_test_file(self.filename)
2793
2794 def test_dtr_references(self):
2795 """Test roundtrip of a table with a ragged DTR to another table containing a column of references."""
2796 group1 = Container('group1')
2797 group2 = Container('group2')
2798
2799 table1 = DynamicTable(
2800 name='table1',
2801 description='test table 1'
2802 )
2803 table1.add_column(
2804 name='x',
2805 description='test column of ints'
2806 )
2807 table1.add_column(
2808 name='y',
2809 description='test column of reference'
2810 )
2811 table1.add_row(id=101, x=1, y=group1)
2812 table1.add_row(id=102, x=2, y=group1)
2813 table1.add_row(id=103, x=3, y=group2)
2814
2815 table2 = DynamicTable(
2816 name='table2',
2817 description='test table 2'
2818 )
2819
2820 # create a ragged column that references table1
2821 # each row of table2 corresponds to one or more rows of table 1
2822 table2.add_column(
2823 name='electrodes',
2824 description='column description',
2825 index=True,
2826 table=table1
2827 )
2828
2829 table2.add_row(id=10, electrodes=[1, 2])
2830
2831 multi_container = SimpleMultiContainer(name='multi')
2832 multi_container.add_container(group1)
2833 multi_container.add_container(group2)
2834 multi_container.add_container(table1)
2835 multi_container.add_container(table2)
2836
2837 with HDF5IO(self.filename, manager=get_manager(), mode='w') as io:
2838 io.write(multi_container)
2839
2840 with HDF5IO(self.filename, manager=get_manager(), mode='r') as io:
2841 read_multi_container = io.read()
2842 self.assertContainerEqual(read_multi_container, multi_container, ignore_name=True)
2843
2844 # test DTR access
2845 read_group1 = read_multi_container['group1']
2846 read_group2 = read_multi_container['group2']
2847 read_table = read_multi_container['table2']
2848 ret = read_table[0, 'electrodes']
2849 expected = pd.DataFrame({'x': np.array([2, 3]),
2850 'y': [read_group1, read_group2]},
2851 index=pd.Index(data=[102, 103], name='id'))
2852 pd.testing.assert_frame_equal(ret, expected)
2853
2854
2855 class TestVectorIndexDtype(TestCase):
2856
2857 def set_up_array_index(self):
2858 data = VectorData(name='data', description='desc')
2859 index = VectorIndex(name='index', data=np.array([]), target=data)
2860 return index
2861
2862 def set_up_list_index(self):
2863 data = VectorData(name='data', description='desc')
2864 index = VectorIndex(name='index', data=[], target=data)
2865 return index
2866
2867 def test_array_inc_precision(self):
2868 index = self.set_up_array_index()
2869 index.add_vector(np.empty((255, )))
2870 self.assertEqual(index.data[0], 255)
2871 self.assertEqual(index.data.dtype, np.uint8)
2872
2873 def test_array_inc_precision_1step(self):
2874 index = self.set_up_array_index()
2875 index.add_vector(np.empty((65535, )))
2876 self.assertEqual(index.data[0], 65535)
2877 self.assertEqual(index.data.dtype, np.uint16)
2878
2879 def test_array_inc_precision_2steps(self):
2880 index = self.set_up_array_index()
2881 index.add_vector(np.empty((65536, )))
2882 self.assertEqual(index.data[0], 65536)
2883 self.assertEqual(index.data.dtype, np.uint32)
2884
2885 def test_array_prev_data_inc_precision_2steps(self):
2886 index = self.set_up_array_index()
2887 index.add_vector(np.empty((255, ))) # dtype is still uint8
2888 index.add_vector(np.empty((65536, )))
2889 self.assertEqual(index.data[0], 255) # make sure the 255 is upgraded
2890 self.assertEqual(index.data.dtype, np.uint32)
2891
2892 def test_list_inc_precision(self):
2893 index = self.set_up_list_index()
2894 index.add_vector(list(range(255)))
2895 self.assertEqual(index.data[0], 255)
2896 self.assertEqual(type(index.data[0]), np.uint8)
2897
2898 def test_list_inc_precision_1step(self):
2899 index = self.set_up_list_index()
2900 index.add_vector(list(range(65535)))
2901 self.assertEqual(index.data[0], 65535)
2902 self.assertEqual(type(index.data[0]), np.uint16)
2903
2904 def test_list_inc_precision_2steps(self):
2905 index = self.set_up_list_index()
2906 index.add_vector(list(range(65536)))
2907 self.assertEqual(index.data[0], 65536)
2908 self.assertEqual(type(index.data[0]), np.uint32)
2909
2910 def test_list_prev_data_inc_precision_2steps(self):
2911 index = self.set_up_list_index()
2912 index.add_vector(list(range(255)))
2913 index.add_vector(list(range(65536 - 255)))
2914 self.assertEqual(index.data[0], 255) # make sure the 255 is upgraded
2915 self.assertEqual(type(index.data[0]), np.uint32)
2916
2917
2918 class TestDynamicTableSubclassColumns(TestCase):
2919 def setUp(self):
2920 self.foo1 = FooExtendDynamicTable0()
2921 self.foo2 = FooExtendDynamicTable1()
2922 self.foo3 = FooExtendDynamicTable2()
2923
2924 def test_columns(self):
2925 self.assertEqual(self.foo1.__columns__,
2926 ({'name': 'col1', 'description': '...'}, {'name': 'col2', 'description': '...'}))
2927 self.assertEqual(self.foo2.__columns__,
2928 ({'name': 'col1', 'description': '...'}, {'name': 'col2', 'description': '...'},
2929 {'name': 'col3', 'description': '...'}, {'name': 'col4', 'description': '...'})
2930 )
2931 self.assertEqual(self.foo2.__columns__, self.foo3.__columns__)