Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def load_h5_in_dict(handle, path='/'):
dictionary = {}
for k, i in handle[path].items():
if isinstance(i, h5._hl.dataset.Dataset):
dictionary[k] = i.value
elif isinstance(i, h5._hl.group.Group):
dictionary[k] = load_h5_in_dict(handle, path + k + '/')
if len(i.attrs.items()):
dictionary['Attributes'] = load_attributes(handle, path + k + '/')
return dictionary
def load_dict(group):
""" Load dictionary """
dd = {}
for key in group.keys():
if isinstance(group[key], h5._hl.group.Group):
new_group = group[key]
dd[key] = load_dict(new_group)
elif not key.startswith("_"):
_key = "_%s" % key
if group[_key][0] == 'np_dtype':
dd[key] = group[key].value
elif group[_key][0] in ('str', 'int', 'float', 'unicode', 'bool'):
dd[key] = group[key][0]
elif group[_key][0] == 'masked':
key_ma = "_%s_mask" % key
dd[key] = np.ma.array(group[key][:], mask=group[key_ma])
else:
dd[key] = group[key][:]
# Convert numpy constructs back to string
def create_tree(group, tree, dataset_path):
for key, value in group.items():
# group
if type(value) is h5._hl.group.Group:
tree[key] = {}
create_tree(value, tree[key], dataset_path + "/" + key)
# dataset
else:
tree[key] = open_dset(filename, dataset_path + "/" + key, distaxes)
>>> f.listnames()
['MyGroup']
>>> f.copy('MyGroup', 'MyCopy')
>>> f.listnames()
['MyGroup', 'MyCopy']
"""
with phil:
if isinstance(source, HLObject):
source_path = '.'
else:
# Interpret source as a path relative to this group
source_path = source
source = self
if isinstance(dest, Group):
if name is not None:
dest_path = name
else:
# copy source into dest group: dest_name/source_name
dest_path = pp.basename(h5i.get_name(source[source_path].id))
elif isinstance(dest, HLObject):
raise TypeError("Destination must be path or Group object")
else:
# Interpret destination as a path relative to this group
dest_path = dest
dest = self
flags = 0
if shallow:
flags |= h5o.COPY_SHALLOW_HIERARCHY_FLAG
def load_h5_in_dict(handle, path='/'):
dictionary = {}
for k,i in handle[path].items():
if isinstance(i, h5._hl.dataset.Dataset):
dictionary[k] = i.value
elif isinstance(i, h5._hl.group.Group):
dictionary[k] = load_h5_in_dict(handle, path + k + '/')
if len(i.attrs.items()):
dictionary['Attributes'] = load_attributes(handle, path + k + '/')
return dictionary
def load_dict_from_h5grp(h5grp):
"""
Retrieve the content of a hdf5 group and organize it in a dictionary.
Based on answers provided at
https://codereview.stackexchange.com/questions/120802
"""
dic = {}
for key, item in h5grp.items():
if isinstance(item, h5py._hl.dataset.Dataset):
values = item[...]
try:
len(values)
except TypeError:
values = np.asscalar(values)
dic[key] = values
elif isinstance(item, h5py._hl.group.Group):
dic[key] = load_dict_from_h5grp(item)
return dic
def _readchildren(self):
children = {}
for name, value in self[self.nxpath].items():
self.nxpath = value.name
if 'NX_class' in value.attrs:
nxclass = value.attrs['NX_class']
else:
nxclass = None
if isinstance(value, h5._hl.group.Group):
children[name] = self._readgroup()
else:
children[name] = self._readdata(name)
return children
def load(h5_grp):
"""Load a HDF5 group recursively into a Python dictionary,
and return the dictionary.
"""
data = {}
for key in list(h5_grp.keys()):
h5py_class = h5_grp.get(key, getclass=True)
if h5py_class is h5py._hl.group.Group:
# print h5py_class, "Group"
subgrp = h5_grp[key]
val = load(subgrp)
elif h5py_class is h5py._hl.dataset.Dataset:
# print h5py_class, "Data"
val = (h5_grp[key])[()]
else:
# shouldn't be reached at all
raise ValueError
data[key] = val
for key in h5_grp.attrs:
data[key] = h5_grp.attrs[key]
return data
def __init__(self, grp):
if not isinstance(grp, h5py._hl.group.Group):
raise TypeError('argument must of a h5py Group')
keys = grp.keys()
if not len(keys) == 3:
raise ValueError('Wrong h5py Group passed')
txt = None
edf = None
for key in keys:
if key == unicode('calibration'):
self.calibration = SPOT_H5DSet.calibration(grp[key])
if str(key).endswith('.edf'):
edf = grp[key]
if str(key).endswith('.txt'):
txt = grp[key]
if edf == None or txt == None:
raise IOError('file not found')
### Identify higher level groups / attributes
if GroupName is None:
MainLev = []
for name in NamesList:
if '/' not in name: MainLev.append(name)
else:
if type(GroupName) is list:
MainLev = GroupName
else:
MainLev = [GroupName]
### Loop through higher level
for name in MainLev:
# sub-group
if type(hdfile[name]) is h5._hl.group.Group:
Ginst = read_group(hdfile[name])
try:
Ginst.name = name
except:
pass
setattr(Hinst, name, Ginst)
else:
setattr(Hinst, name, hdfile[name].value)
# close and return
hdfile.close()
return Hinst