| 1 |
import json |
| 2 |
import os |
| 3 |
from numbers import Number |
| 4 |
|
| 5 |
import numpy as np |
| 6 |
from h5py import File, Dataset, Reference |
| 7 |
from hdmf.backends.hdf5 import HDF5IO |
| 8 |
from hdmf.build import GroupBuilder, DatasetBuilder, LinkBuilder |
| 9 |
from hdmf.testing import TestCase |
| 10 |
from hdmf.utils import get_data_shape |
| 11 |
from tests.unit.helpers.utils import Foo, get_foo_buildmanager |
| 12 |
|
| 13 |
|
| 14 |
class HDF5Encoder(json.JSONEncoder): |
| 15 |
def default(self, obj): |
| 16 |
if isinstance(obj, Dataset): |
| 17 |
ret = None |
| 18 |
for t in (list, str): |
| 19 |
try: |
| 20 |
ret = t(obj) |
| 21 |
break |
| 22 |
except: # noqa: E722 |
| 23 |
pass |
| 24 |
if ret is None: |
| 25 |
return obj |
| 26 |
else: |
| 27 |
return ret |
| 28 |
elif isinstance(obj, np.int64): |
| 29 |
return int(obj) |
| 30 |
elif isinstance(obj, bytes): |
| 31 |
return str(obj) |
| 32 |
return json.JSONEncoder.default(self, obj) |
| 33 |
|
| 34 |
|
| 35 |
class GroupBuilderTestCase(TestCase): |
| 36 |
''' |
| 37 |
A TestCase class for comparing GroupBuilders. |
| 38 |
''' |
| 39 |
|
| 40 |
def __is_scalar(self, obj): |
| 41 |
if hasattr(obj, 'shape'): |
| 42 |
return len(obj.shape) == 0 |
| 43 |
else: |
| 44 |
if any(isinstance(obj, t) for t in (int, str, float, bytes, str)): |
| 45 |
return True |
| 46 |
return False |
| 47 |
|
| 48 |
def __convert_h5_scalar(self, obj): |
| 49 |
if isinstance(obj, Dataset): |
| 50 |
return obj[...] |
| 51 |
return obj |
| 52 |
|
| 53 |
def __compare_attr_dicts(self, a, b): |
| 54 |
reasons = list() |
| 55 |
b_keys = set(b.keys()) |
| 56 |
for k in a: |
| 57 |
if k not in b: |
| 58 |
reasons.append("'%s' attribute missing from second dataset" % k) |
| 59 |
else: |
| 60 |
if a[k] != b[k]: |
| 61 |
reasons.append("'%s' attribute on datasets not equal" % k) |
| 62 |
b_keys.remove(k) |
| 63 |
for k in b_keys: |
| 64 |
reasons.append("'%s' attribute missing from first dataset" % k) |
| 65 |
return reasons |
| 66 |
|
| 67 |
def __compare_dataset(self, a, b): |
| 68 |
reasons = self.__compare_attr_dicts(a.attributes, b.attributes) |
| 69 |
if not self.__compare_data(a.data, b.data): |
| 70 |
reasons.append("dataset '%s' not equal" % a.name) |
| 71 |
return reasons |
| 72 |
|
| 73 |
def __compare_data(self, a, b): |
| 74 |
if isinstance(a, Number) and isinstance(b, Number): |
| 75 |
return a == b |
| 76 |
elif isinstance(a, Number) != isinstance(b, Number): |
| 77 |
return False |
| 78 |
else: |
| 79 |
a_scalar = self.__is_scalar(a) |
| 80 |
b_scalar = self.__is_scalar(b) |
| 81 |
if a_scalar and b_scalar: |
| 82 |
return self.__convert_h5_scalar(a_scalar) == self.__convert_h5_scalar(b_scalar) |
| 83 |
elif a_scalar != b_scalar: |
| 84 |
return False |
| 85 |
if len(a) == len(b): |
| 86 |
for i in range(len(a)): |
| 87 |
if not self.__compare_data(a[i], b[i]): |
| 88 |
return False |
| 89 |
else: |
| 90 |
return False |
| 91 |
return True |
| 92 |
|
| 93 |
def __fmt(self, val): |
| 94 |
return "%s (%s)" % (val, type(val)) |
| 95 |
|
| 96 |
def __assert_helper(self, a, b): |
| 97 |
reasons = list() |
| 98 |
b_keys = set(b.keys()) |
| 99 |
for k, a_sub in a.items(): |
| 100 |
if k in b: |
| 101 |
b_sub = b[k] |
| 102 |
b_keys.remove(k) |
| 103 |
if isinstance(a_sub, LinkBuilder) and isinstance(a_sub, LinkBuilder): |
| 104 |
a_sub = a_sub['builder'] |
| 105 |
b_sub = b_sub['builder'] |
| 106 |
elif isinstance(a_sub, LinkBuilder) != isinstance(a_sub, LinkBuilder): |
| 107 |
reasons.append('%s != %s' % (a_sub, b_sub)) |
| 108 |
if isinstance(a_sub, DatasetBuilder) and isinstance(a_sub, DatasetBuilder): |
| 109 |
# if not self.__compare_dataset(a_sub, b_sub): |
| 110 |
# reasons.append('%s != %s' % (a_sub, b_sub)) |
| 111 |
reasons.extend(self.__compare_dataset(a_sub, b_sub)) |
| 112 |
elif isinstance(a_sub, GroupBuilder) and isinstance(a_sub, GroupBuilder): |
| 113 |
reasons.extend(self.__assert_helper(a_sub, b_sub)) |
| 114 |
else: |
| 115 |
equal = None |
| 116 |
a_array = isinstance(a_sub, np.ndarray) |
| 117 |
b_array = isinstance(b_sub, np.ndarray) |
| 118 |
if a_array and b_array: |
| 119 |
equal = np.array_equal(a_sub, b_sub) |
| 120 |
elif a_array or b_array: |
| 121 |
# if strings, convert before comparing |
| 122 |
if b_array: |
| 123 |
if b_sub.dtype.char in ('S', 'U'): |
| 124 |
a_sub = [np.bytes_(s) for s in a_sub] |
| 125 |
else: |
| 126 |
if a_sub.dtype.char in ('S', 'U'): |
| 127 |
b_sub = [np.bytes_(s) for s in b_sub] |
| 128 |
equal = np.array_equal(a_sub, b_sub) |
| 129 |
else: |
| 130 |
equal = a_sub == b_sub |
| 131 |
if not equal: |
| 132 |
reasons.append('%s != %s' % (self.__fmt(a_sub), self.__fmt(b_sub))) |
| 133 |
else: |
| 134 |
reasons.append("'%s' not in both" % k) |
| 135 |
for k in b_keys: |
| 136 |
reasons.append("'%s' not in both" % k) |
| 137 |
return reasons |
| 138 |
|
| 139 |
def assertBuilderEqual(self, a, b): |
| 140 |
''' Tests that two GroupBuilders are equal ''' |
| 141 |
reasons = self.__assert_helper(a, b) |
| 142 |
if len(reasons): |
| 143 |
raise AssertionError(', '.join(reasons)) |
| 144 |
return True |
| 145 |
|
| 146 |
|
| 147 |
class TestHDF5Writer(GroupBuilderTestCase): |
| 148 |
|
| 149 |
def setUp(self): |
| 150 |
self.manager = get_foo_buildmanager() |
| 151 |
self.path = "test_io_hdf5.h5" |
| 152 |
|
| 153 |
self.foo_builder = GroupBuilder('foo1', |
| 154 |
attributes={'data_type': 'Foo', |
| 155 |
'namespace': 'test_core', |
| 156 |
'attr1': "bar", |
| 157 |
'object_id': -1}, |
| 158 |
datasets={'my_data': DatasetBuilder('my_data', list(range(100, 200, 10)), |
| 159 |
attributes={'attr2': 17})}) |
| 160 |
self.foo = Foo('foo1', list(range(100, 200, 10)), attr1="bar", attr2=17, attr3=3.14) |
| 161 |
self.manager.prebuilt(self.foo, self.foo_builder) |
| 162 |
self.builder = GroupBuilder( |
| 163 |
'root', |
| 164 |
source=self.path, |
| 165 |
groups={'test_bucket': |
| 166 |
GroupBuilder('test_bucket', |
| 167 |
groups={'foo_holder': |
| 168 |
GroupBuilder('foo_holder', |
| 169 |
groups={'foo1': self.foo_builder})})}, |
| 170 |
attributes={'data_type': 'FooFile'}) |
| 171 |
|
| 172 |
def tearDown(self): |
| 173 |
if os.path.exists(self.path): |
| 174 |
os.remove(self.path) |
| 175 |
|
| 176 |
def check_fields(self): |
| 177 |
f = File(self.path, 'r') |
| 178 |
self.assertIn('test_bucket', f) |
| 179 |
bucket = f.get('test_bucket') |
| 180 |
self.assertIn('foo_holder', bucket) |
| 181 |
holder = bucket.get('foo_holder') |
| 182 |
self.assertIn('foo1', holder) |
| 183 |
return f |
| 184 |
|
| 185 |
def test_write_builder(self): |
| 186 |
writer = HDF5IO(self.path, manager=self.manager, mode='a') |
| 187 |
writer.write_builder(self.builder) |
| 188 |
writer.close() |
| 189 |
self.check_fields() |
| 190 |
|
| 191 |
def test_write_attribute_reference_container(self): |
| 192 |
writer = HDF5IO(self.path, manager=self.manager, mode='a') |
| 193 |
self.builder.set_attribute('ref_attribute', self.foo) |
| 194 |
writer.write_builder(self.builder) |
| 195 |
writer.close() |
| 196 |
f = self.check_fields() |
| 197 |
self.assertIsInstance(f.attrs['ref_attribute'], Reference) |
| 198 |
self.assertEqual(f['test_bucket/foo_holder/foo1'], f[f.attrs['ref_attribute']]) |
| 199 |
|
| 200 |
def test_write_attribute_reference_builder(self): |
| 201 |
writer = HDF5IO(self.path, manager=self.manager, mode='a') |
| 202 |
self.builder.set_attribute('ref_attribute', self.foo_builder) |
| 203 |
writer.write_builder(self.builder) |
| 204 |
writer.close() |
| 205 |
f = self.check_fields() |
| 206 |
self.assertIsInstance(f.attrs['ref_attribute'], Reference) |
| 207 |
self.assertEqual(f['test_bucket/foo_holder/foo1'], f[f.attrs['ref_attribute']]) |
| 208 |
|
| 209 |
def test_write_context_manager(self): |
| 210 |
with HDF5IO(self.path, manager=self.manager, mode='a') as writer: |
| 211 |
writer.write_builder(self.builder) |
| 212 |
self.check_fields() |
| 213 |
|
| 214 |
def test_read_builder(self): |
| 215 |
self.maxDiff = None |
| 216 |
io = HDF5IO(self.path, manager=self.manager, mode='a') |
| 217 |
io.write_builder(self.builder) |
| 218 |
builder = io.read_builder() |
| 219 |
self.assertBuilderEqual(builder, self.builder) |
| 220 |
io.close() |
| 221 |
|
| 222 |
def test_dataset_shape(self): |
| 223 |
self.maxDiff = None |
| 224 |
io = HDF5IO(self.path, manager=self.manager, mode='a') |
| 225 |
io.write_builder(self.builder) |
| 226 |
builder = io.read_builder() |
| 227 |
dset = builder['test_bucket']['foo_holder']['foo1']['my_data'].data |
| 228 |
self.assertEqual(get_data_shape(dset), (10,)) |
| 229 |
io.close() |