| 1 |
|
| 2 |
) |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
import h5py |
| 11 |
import numpy as np |
| 12 |
|
| 13 |
from .h5dataset import H5DataSet |
| 14 |
from ..datatype import DataType |
| 15 |
|
| 16 |
from .. import util |
| 17 |
|
| 18 |
|
| 19 |
class H5Group: |
| 20 |
|
| 21 |
def __init__(self, parent, name, create=False): |
| 22 |
self._parent = parent |
| 23 |
self.name = name |
| 24 |
self.group = None |
| 25 |
if create or name in self._parent: |
| 26 |
self._create_h5obj() |
| 27 |
self.h5obj = self.group |
| 28 |
|
| 29 |
def _create_h5obj(self): |
| 30 |
if self.name in self._parent: |
| 31 |
self.group = self._parent[self.name] |
| 32 |
else: |
| 33 |
gcpl = h5py.h5p.create(h5py.h5p.GROUP_CREATE) |
| 34 |
flags = h5py.h5p.CRT_ORDER_TRACKED | h5py.h5p.CRT_ORDER_INDEXED |
| 35 |
gcpl.set_link_creation_order(flags) |
| 36 |
name = self.name.encode("utf-8") |
| 37 |
gid = h5py.h5g.create(self._parent.id, name, gcpl=gcpl) |
| 38 |
self.group = h5py.Group(gid) |
| 39 |
|
| 40 |
@property |
| 41 |
def group(self): |
| 42 |
if self._group is None: |
| 43 |
if self.name in self._parent: |
| 44 |
self._group = self._parent[self.name] |
| 45 |
else: |
| 46 |
return None |
| 47 |
return self._group |
| 48 |
|
| 49 |
@group.setter |
| 50 |
def group(self, grp): |
| 51 |
self._group = grp |
| 52 |
|
| 53 |
def create_link(self, target, name): |
| 54 |
self._create_h5obj() |
| 55 |
if name in self.group: |
| 56 |
del self.group[name] |
| 57 |
self.group[name] = target._h5group.group |
| 58 |
|
| 59 |
@classmethod |
| 60 |
def create_from_h5obj(cls, h5obj): |
| 61 |
parent = h5obj.parent |
| 62 |
name = h5obj.name.split("/")[-1] |
| 63 |
if isinstance(h5obj, h5py.Group): |
| 64 |
return cls(parent, name) |
| 65 |
elif isinstance(h5obj, h5py.Dataset): |
| 66 |
return H5DataSet(parent, name) |
| 67 |
else: |
| 68 |
raise ValueError("Invalid object: " |
| 69 |
"{} must be either h5py.Group of h5py.Dataset.") |
| 70 |
|
| 71 |
def open_group(self, name, create=False): |
| 72 |
""" |
| 73 |
Returns a new H5Group with the given name contained in the current |
| 74 |
group. If the current group does not exist in the file, |
| 75 |
it is automatically created. |
| 76 |
|
| 77 |
:param name: the name of the group |
| 78 |
:param create: creates the child group in the file if it does not exist |
| 79 |
:return: a new H5Group object |
| 80 |
""" |
| 81 |
self._create_h5obj() |
| 82 |
return H5Group(self.group, name, create) |
| 83 |
|
| 84 |
def create_dataset(self, name, shape, dtype, compression=False): |
| 85 |
""" |
| 86 |
Creates a dataset object under the current group with a given name, |
| 87 |
shape, and type. |
| 88 |
|
| 89 |
:param name: the name of the dataset |
| 90 |
:param shape: tuple representing the shape of the dataset |
| 91 |
:param dtype: the type of the data for this dataset (DataType) |
| 92 |
:param compression: whether to compress the data (default: False) |
| 93 |
:return: a new H5DataSet object |
| 94 |
""" |
| 95 |
self._create_h5obj() |
| 96 |
return H5DataSet(self.group, name, dtype, shape, compression) |
| 97 |
|
| 98 |
def get_dataset(self, name): |
| 99 |
""" |
| 100 |
Returns a contained H5DataSet object. |
| 101 |
|
| 102 |
:param name: name of the dataset |
| 103 |
:return: H5DataSet object |
| 104 |
""" |
| 105 |
notfound = KeyError("No DataSet named {} found.") |
| 106 |
if self.group is None: |
| 107 |
raise notfound |
| 108 |
if name in self.group: |
| 109 |
dset = self.group[name] |
| 110 |
return H5DataSet.create_from_h5obj(dset) |
| 111 |
else: |
| 112 |
raise notfound |
| 113 |
|
| 114 |
def write_data(self, name, data, dtype=None, compression=False): |
| 115 |
""" |
| 116 |
Writes the data to a Dataset contained in the group with the |
| 117 |
given name. Creates the Dataset if necessary. |
| 118 |
|
| 119 |
:param name: name of the Dataset object |
| 120 |
:param data: the data to write |
| 121 |
:param dtype: optionally specify the data type, otherwise it will be |
| 122 |
automatically determined by the data |
| 123 |
:param compression: whether to compress the data (default: False) |
| 124 |
""" |
| 125 |
shape = np.shape(data) |
| 126 |
if self.has_data(name): |
| 127 |
dset = self.get_dataset(name) |
| 128 |
dset.shape = shape |
| 129 |
else: |
| 130 |
if dtype is None: |
| 131 |
dtype = DataType.get_dtype(data[0]) |
| 132 |
dset = self.create_dataset(name, shape, dtype, compression) |
| 133 |
|
| 134 |
dset.write_data(data) |
| 135 |
|
| 136 |
def get_data(self, name): |
| 137 |
""" |
| 138 |
Returns the data contained in the dataset identified by 'name', or an |
| 139 |
empty list if a dataset of that name does not exist in the Group. |
| 140 |
|
| 141 |
:param name: The name of the dataset |
| 142 |
:return: The data contained in the dataset as a numpy array or None |
| 143 |
""" |
| 144 |
if name not in self.group: |
| 145 |
return [] |
| 146 |
|
| 147 |
dset = self.group[name] |
| 148 |
|
| 149 |
return dset[:] |
| 150 |
|
| 151 |
def has_data(self, name): |
| 152 |
""" |
| 153 |
Return True if the Group contains a Dataset object with the given name. |
| 154 |
|
| 155 |
:param name: name of Dataset |
| 156 |
:return: True if Dataset exists in Group, False if it does not exist, |
| 157 |
or exists and is not a Dataset |
| 158 |
""" |
| 159 |
if self.group.get(name, getclass=True) == h5py.Dataset: |
| 160 |
return True |
| 161 |
else: |
| 162 |
return False |
| 163 |
|
| 164 |
def has_by_id(self, id_or_name): |
| 165 |
if not self.group: |
| 166 |
return False |
| 167 |
if util.is_uuid(id_or_name): |
| 168 |
for item in self: |
| 169 |
if item.get_attr("entity_id") == id_or_name: |
| 170 |
return True |
| 171 |
return False |
| 172 |
else: |
| 173 |
return id_or_name in self.group |
| 174 |
|
| 175 |
def get_by_id_or_name(self, id_or_name): |
| 176 |
if util.is_uuid(id_or_name): |
| 177 |
return self.get_by_id(id_or_name) |
| 178 |
else: |
| 179 |
return self.get_by_name(id_or_name) |
| 180 |
|
| 181 |
def get_by_name(self, name): |
| 182 |
if self.group and name in self.group: |
| 183 |
return self.create_from_h5obj(self.group[name]) |
| 184 |
else: |
| 185 |
raise KeyError("Item not found '{}'".format(name)) |
| 186 |
|
| 187 |
def get_by_id(self, id_): |
| 188 |
if self.group: |
| 189 |
for item in self: |
| 190 |
if item.get_attr("entity_id") == id_: |
| 191 |
return item |
| 192 |
raise KeyError("Item not found '{}'".format(id_)) |
| 193 |
|
| 194 |
def get_by_pos(self, pos): |
| 195 |
if not self.group: |
| 196 |
raise IndexError |
| 197 |
|
| 198 |
|
| 199 |
name, _ = self.group.id.links.iterate(lambda n: n, |
| 200 |
idx_type=h5py.h5.INDEX_CRT_ORDER, |
| 201 |
order=h5py.h5.ITER_INC, |
| 202 |
idx=pos) |
| 203 |
return self.get_by_name(name) |
| 204 |
|
| 205 |
def delete(self, id_or_name, delete_if_empty=True): |
| 206 |
""" |
| 207 |
Deletes the child HDF5 group that matches the given name or id. |
| 208 |
""" |
| 209 |
if util.is_uuid(id_or_name): |
| 210 |
name = self.get_by_id_or_name(id_or_name).name |
| 211 |
else: |
| 212 |
name = id_or_name |
| 213 |
try: |
| 214 |
del self.group[name] |
| 215 |
except Exception: |
| 216 |
raise ValueError("Error deleting {} ".format(name)) |
| 217 |
|
| 218 |
groupdepth = len(self.group.name.split("/")) - 1 |
| 219 |
if delete_if_empty and not len(self.group) and groupdepth > 1: |
| 220 |
del self.parent.group[self.name] |
| 221 |
|
| 222 |
self.group = None |
| 223 |
|
| 224 |
def delete_all(self, eid): |
| 225 |
""" |
| 226 |
Deletes all references to a given list of objects, identified by their |
| 227 |
entity_id, below the current object. |
| 228 |
""" |
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
def delete_by_id(_, obj): |
| 238 |
if not isinstance(obj, h5py.Group): |
| 239 |
return |
| 240 |
grp = self.create_from_h5obj(obj) |
| 241 |
for child in grp: |
| 242 |
if child.get_attr("entity_id") in eid: |
| 243 |
del grp[child.name] |
| 244 |
|
| 245 |
self._group.visititems(delete_by_id) |
| 246 |
|
| 247 |
def set_attr(self, name, value): |
| 248 |
self._create_h5obj() |
| 249 |
if value is None: |
| 250 |
if name in self.group.attrs: |
| 251 |
del self.group.attrs[name] |
| 252 |
else: |
| 253 |
if isinstance(value, np.str_): |
| 254 |
value = str(value) |
| 255 |
self.group.attrs[name] = value |
| 256 |
|
| 257 |
def get_attr(self, name): |
| 258 |
if self.group is None: |
| 259 |
return None |
| 260 |
attr = self.group.attrs.get(name) |
| 261 |
if isinstance(attr, bytes): |
| 262 |
attr = attr.decode() |
| 263 |
return attr |
| 264 |
|
| 265 |
def find_children(self, filtr=None, limit=None): |
| 266 |
result = [] |
| 267 |
|
| 268 |
def match(name, obj): |
| 269 |
curdepth = len(name.split("/")) |
| 270 |
if limit is not None and curdepth > limit: |
| 271 |
return None |
| 272 |
|
| 273 |
h5grp = H5Group.create_from_h5obj(obj) |
| 274 |
if filtr is None or filtr(h5grp): |
| 275 |
result.append(h5grp) |
| 276 |
|
| 277 |
self.group.visititems(match) |
| 278 |
return result |
| 279 |
|
| 280 |
def copy(self, source, dest, name=None, cls=None, shallow=False, |
| 281 |
keep_id=True): |
| 282 |
grp = self.group |
| 283 |
dest.open_group(cls, create=True) |
| 284 |
dest_grp = dest.group[cls] |
| 285 |
grp.copy(source=source, dest=dest_grp, name=name, shallow=shallow) |
| 286 |
|
| 287 |
grp = dest_grp[name] |
| 288 |
grp.attrs["name"] = name |
| 289 |
if not keep_id: |
| 290 |
def change_id(_, igrp): |
| 291 |
if "entity_id" in igrp.attrs: |
| 292 |
id_ = util.create_id() |
| 293 |
igrp.attrs.modify("entity_id", np.bytes_(id_)) |
| 294 |
id_ = util.create_id() |
| 295 |
grp.attrs.modify("entity_id", np.bytes_(id_)) |
| 296 |
grp.visititems(change_id) |
| 297 |
return grp |
| 298 |
|
| 299 |
@property |
| 300 |
def parent(self): |
| 301 |
return self.create_from_h5obj(self._parent) |
| 302 |
|
| 303 |
def __iter__(self): |
| 304 |
if not len(self): |
| 305 |
return |
| 306 |
for grp in self.group.values(): |
| 307 |
yield self.create_from_h5obj(grp) |
| 308 |
|
| 309 |
def __contains__(self, item): |
| 310 |
if self.group is None: |
| 311 |
return False |
| 312 |
return item in self.group |
| 313 |
|
| 314 |
def __len__(self): |
| 315 |
if self.group is None: |
| 316 |
return 0 |
| 317 |
else: |
| 318 |
return len(self.group) |
| 319 |
|
| 320 |
def __delitem__(self, key): |
| 321 |
del self.group[key] |
| 322 |
|
| 323 |
def __str__(self): |
| 324 |
return "<H5Group object: {}>".format(self.group.name) |