1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 15:07:16 2018
@author: Suhas Somnath
"""
from __future__ import division, print_function, unicode_literals, \
absolute_import
import unittest
import os
import sys
import h5py
import numpy as np
from . import data_utils
sys.path.append("../../sidpy/")
from sidpy.hdf.hdf_utils import get_attr
from sidpy.hdf import reg_ref
if sys.version_info.major == 3:
unicode = str
class TestRegRef(unittest.TestCase):
def setUp(self):
data_utils.make_beps_file()
def tearDown(self):
data_utils.delete_existing_file(data_utils.std_beps_path)
class TesetGetIndicesForRegionRef(TestRegRef):
def test_corners(self):
with h5py.File(data_utils.std_beps_path, mode='r') as h5_f:
h5_main = h5_f['/Raw_Measurement/source_main']
ref_in = get_attr(h5_main, 'even_rows')
ret_val = reg_ref.get_indices_for_region_ref(h5_main, ref_in,
'corners')
expected_pos = np.repeat(np.arange(h5_main.shape[0])[::2], 2)
expected_spec = np.tile(np.array([0, h5_main.shape[1] - 1]),
expected_pos.size // 2)
expected_corners = np.vstack((expected_pos, expected_spec)).T
self.assertTrue(np.allclose(ret_val, expected_corners))
def test_slices(self):
with h5py.File(data_utils.std_beps_path, mode='r') as h5_f:
h5_main = h5_f['/Raw_Measurement/source_main']
ref_in = get_attr(h5_main, 'even_rows')
ret_val = reg_ref.get_indices_for_region_ref(h5_main, ref_in,
'slices')
spec_slice = slice(0, h5_main.shape[1] - 1, None)
expected_slices = np.array(
[[slice(x, x, None), spec_slice] for x in
np.arange(h5_main.shape[0])[::2]])
self.assertTrue(np.all(ret_val == expected_slices))
class TestWriteRegRef(TestRegRef):
def test_main_one_dim(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
data = np.random.rand(7)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Main', data=data)
reg_refs = {'even_rows': (slice(0, None, 2)),
'odd_rows': (slice(1, None, 2))}
reg_ref.write_region_references(h5_dset, reg_refs,
add_labels_attr=True)
self.assertEqual(len(h5_dset.attrs), 1 + len(reg_refs))
actual = get_attr(h5_dset, 'labels')
self.assertTrue(np.all(
[x == y for x, y in zip(actual, ['even_rows', 'odd_rows'])]))
expected_data = [data[0:None:2], data[1:None:2]]
written_data = [h5_dset[h5_dset.attrs['even_rows']],
h5_dset[h5_dset.attrs['odd_rows']]]
for exp, act in zip(expected_data, written_data):
self.assertTrue(np.allclose(exp, act))
os.remove(file_path)
def test_main_1st_dim(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
data = np.random.rand(5, 7)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Main', data=data)
reg_refs = {'even_rows': (slice(0, None, 2), slice(None)),
'odd_rows': (slice(1, None, 2), slice(None))}
reg_ref.write_region_references(h5_dset, reg_refs,
add_labels_attr=True)
self.assertEqual(len(h5_dset.attrs), 1 + len(reg_refs))
actual = get_attr(h5_dset, 'labels')
self.assertTrue(np.all(
[x == y for x, y in zip(actual, ['even_rows', 'odd_rows'])]))
expected_data = [data[0:None:2], data[1:None:2]]
written_data = [h5_dset[h5_dset.attrs['even_rows']],
h5_dset[h5_dset.attrs['odd_rows']]]
for exp, act in zip(expected_data, written_data):
self.assertTrue(np.allclose(exp, act))
os.remove(file_path)
def test_main_2nd_dim(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
data = np.random.rand(5, 7)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Main', data=data)
reg_refs = {'even_rows': (slice(None), slice(0, None, 2)),
'odd_rows': (slice(None), slice(1, None, 2))}
reg_ref.write_region_references(h5_dset, reg_refs,
add_labels_attr=False)
self.assertEqual(len(h5_dset.attrs), len(reg_refs))
self.assertTrue('labels' not in h5_dset.attrs.keys())
expected_data = [data[:, 0:None:2], data[:, 1:None:2]]
written_data = [h5_dset[h5_dset.attrs['even_rows']],
h5_dset[h5_dset.attrs['odd_rows']]]
for exp, act in zip(expected_data, written_data):
self.assertTrue(np.allclose(exp, act))
os.remove(file_path)
class TestSimpleRegionRefCopy(TestRegRef):
def test_base(self):
# based on test_hdf_writer.test_write_legal_reg_ref_multi_dim_data()
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
data = np.random.rand(5, 7)
h5_orig_dset = h5_f.create_dataset('test', data=data)
self.assertIsInstance(h5_orig_dset, h5py.Dataset)
attrs = {'labels': {'even_rows': (slice(0, None, 2), slice(None)),
'odd_rows': (slice(1, None, 2), slice(None))}}
data_utils.write_main_reg_refs(h5_orig_dset, attrs['labels'])
h5_f.flush()
# two atts point to region references. one for labels
self.assertEqual(len(h5_orig_dset.attrs), 1 + len(attrs['labels']))
# check if the labels attribute was written:
self.assertTrue(np.all([x in list(attrs['labels'].keys()) for x in
get_attr(h5_orig_dset,
'labels')]))
expected_data = [data[:None:2], data[1:None:2]]
written_data = [h5_orig_dset[h5_orig_dset.attrs['even_rows']],
h5_orig_dset[h5_orig_dset.attrs['odd_rows']]]
for exp, act in zip(expected_data, written_data):
self.assertTrue(np.allclose(exp, act))
# Now write a new dataset without the region reference:
h5_new_dset = h5_f.create_dataset('other', data=data)
self.assertIsInstance(h5_orig_dset, h5py.Dataset)
h5_f.flush()
for key in attrs['labels'].keys():
reg_ref.simple_region_ref_copy(h5_orig_dset, h5_new_dset, key)
# now check to make sure that this dataset also has the same region references:
written_data = [h5_new_dset[h5_new_dset.attrs['even_rows']],
h5_new_dset[h5_new_dset.attrs['odd_rows']]]
for exp, act in zip(expected_data, written_data):
self.assertTrue(np.allclose(exp, act))
os.remove(file_path)
class TestCreateRegionRef(TestRegRef):
def test_base(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
data = np.random.rand(5, 7)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Source', data=data)
pos_inds = np.arange(0, h5_dset.shape[0], 2)
ref_inds = [((pos_start, 0), (pos_start, h5_dset.shape[1] - 1)) for
pos_start in pos_inds]
ref_inds = np.array(ref_inds)
this_reg_ref = reg_ref.create_region_reference(h5_dset, ref_inds)
ref_slices = list()
for start, stop in ref_inds:
ref_slices.append(
[slice(start[0], stop[0] + 1), slice(start[1], None)])
h5_reg = h5_dset[this_reg_ref]
h5_slice = np.vstack(
[h5_dset[pos_slice, spec_slice] for (pos_slice, spec_slice) in
ref_slices])
self.assertTrue(np.allclose(h5_reg, h5_slice))
os.remove(file_path)
class TestGetRegion(TestRegRef):
def test_illegal_01(self):
with h5py.File(data_utils.std_beps_path, mode='r') as h5_f:
with self.assertRaises(KeyError):
reg_ref.get_region(h5_f['/Raw_Measurement/source_main'],
'non_existent')
def test_legal_01(self):
with h5py.File(data_utils.std_beps_path, mode='r') as h5_f:
h5_source = h5_f['/Raw_Measurement/source_main']
returned = reg_ref.get_region(h5_source, 'even_rows')
expected = h5_source[slice(0, h5_source.shape[0], 2)]
self.assertTrue(np.allclose(returned, expected))
class TestCleanRegRef(TestRegRef):
def test_1d(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Test', data=np.random.rand(7))
ref_in = (slice(0, None, 2))
cleaned = reg_ref.clean_reg_ref(h5_dset, ref_in)
self.assertEqual(ref_in, cleaned[0])
os.remove(file_path)
def test_2d(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Test', data=np.random.rand(7, 5))
ref_in = (slice(0, None, 2), slice(None))
cleaned = reg_ref.clean_reg_ref(h5_dset, ref_in)
self.assertTrue(np.all([x == y for x, y in zip(ref_in, cleaned)]))
os.remove(file_path)
def test_illegal_too_many_slices(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Test', data=np.random.rand(7, 5))
ref_in = (slice(0, None, 2), slice(None), slice(1, None, 2))
with self.assertRaises(ValueError):
_ = reg_ref.clean_reg_ref(h5_dset, ref_in)
os.remove(file_path)
def test_illegal_too_few_slices(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Test', data=np.random.rand(7, 5))
ref_in = (slice(0, None, 2))
with self.assertRaises(ValueError):
_ = reg_ref.clean_reg_ref(h5_dset, ref_in)
os.remove(file_path)
def test_out_of_bounds(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Test', data=np.random.rand(7, 5))
ref_in = (slice(0, 13, 2), slice(None))
expected = (slice(0, 7, 2), slice(None))
cleaned = reg_ref.clean_reg_ref(h5_dset, ref_in, verbose=False)
self.assertTrue(
np.all([x == y for x, y in zip(expected, cleaned)]))
os.remove(file_path)
class TestAttemptRegRefBuild(TestRegRef):
def test_spec(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Indices', data=np.random.rand(2, 5))
dim_names = ['Bias', 'Cycle']
expected = {'Bias': (slice(0, 1), slice(None)),
'Cycle': (slice(1, 2), slice(None))}
if sys.version_info.major == 3:
with self.assertWarns(UserWarning):
cleaned = reg_ref.attempt_reg_ref_build(h5_dset, dim_names)
else:
cleaned = reg_ref.attempt_reg_ref_build(h5_dset, dim_names)
for key, value in expected.items():
self.assertEqual(value, cleaned[key])
os.remove(file_path)
def test_pos(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Indices', data=np.random.rand(5, 2))
dim_names = ['Bias', 'Cycle']
expected = {'Bias': (slice(None), slice(0, 1)),
'Cycle': (slice(None), slice(1, 2))}
if sys.version_info.major == 3:
with self.assertWarns(UserWarning):
cleaned = reg_ref.attempt_reg_ref_build(h5_dset, dim_names)
else:
cleaned = reg_ref.attempt_reg_ref_build(h5_dset, dim_names)
for key, value in expected.items():
self.assertEqual(value, cleaned[key])
os.remove(file_path)
def test_pos_too_many_dims(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Indices', data=np.random.rand(5, 2))
dim_names = ['Bias', 'Cycle', 'Blah']
ret_val = reg_ref.attempt_reg_ref_build(h5_dset, dim_names)
self.assertEqual(ret_val, dict())
os.remove(file_path)
def test_pos_too_few_dims(self):
file_path = 'test.h5'
data_utils.delete_existing_file(file_path)
with h5py.File(file_path, mode='w') as h5_f:
h5_dset = h5_f.create_dataset('Indices', data=np.random.rand(5, 2))
dim_names = ['Bias']
ret_val = reg_ref.attempt_reg_ref_build(h5_dset, dim_names)
self.assertEqual(ret_val, dict())
os.remove(file_path)
|