| 1 |
|
| 2 |
) |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
import warnings |
| 10 |
|
| 11 |
import numpy as np |
| 12 |
|
| 13 |
from .entity import Entity |
| 14 |
from .source_link_container import SourceLinkContainer |
| 15 |
from .container import Container, LinkContainer |
| 16 |
|
| 17 |
from .datatype import DataType |
| 18 |
from .data_array import DataArray |
| 19 |
from .data_view import DataView |
| 20 |
from .feature import Feature |
| 21 |
from .exceptions import (OutOfBounds, IncompatibleDimensions, |
| 22 |
UninitializedEntity, InvalidUnit) |
| 23 |
from .dimension_type import DimensionType |
| 24 |
from .link_type import LinkType |
| 25 |
from . import util |
| 26 |
from .section import Section |
| 27 |
from .dimensions import SliceMode |
| 28 |
|
| 29 |
|
| 30 |
class FeatureContainer(Container): |
| 31 |
""" |
| 32 |
The FeatureContainer has one minor difference from the regular Container: |
| 33 |
A Feature can be retrieved by the ID or name of the linked DataArray as |
| 34 |
well as the ID of the feature itself. |
| 35 |
""" |
| 36 |
def __getitem__(self, item): |
| 37 |
try: |
| 38 |
return Container.__getitem__(self, item) |
| 39 |
except KeyError as exc: |
| 40 |
|
| 41 |
for feat in self: |
| 42 |
if feat.data.id == item or feat.data.name == item: |
| 43 |
return feat |
| 44 |
raise exc |
| 45 |
|
| 46 |
def __contains__(self, item): |
| 47 |
if isinstance(item, Feature): |
| 48 |
item = item.id |
| 49 |
if not Container.__contains__(self, item): |
| 50 |
|
| 51 |
for feat in self: |
| 52 |
if feat.data.id == item or feat.data.name == item: |
| 53 |
return True |
| 54 |
return False |
| 55 |
return True |
| 56 |
|
| 57 |
|
| 58 |
class BaseTag(Entity): |
| 59 |
""" |
| 60 |
Base class for Tag and MultiTag |
| 61 |
""" |
| 62 |
def __init__(self, nixfile, nixparent, h5group): |
| 63 |
super(BaseTag, self).__init__(nixfile, nixparent, h5group) |
| 64 |
self._sources = None |
| 65 |
self._references = None |
| 66 |
self._features = None |
| 67 |
|
| 68 |
@property |
| 69 |
def units(self): |
| 70 |
""" |
| 71 |
Property containing the units of the tag. The tag must provide a |
| 72 |
unit for each dimension of the position or extent vector. |
| 73 |
This is a read-write property. |
| 74 |
|
| 75 |
:type: list of str |
| 76 |
""" |
| 77 |
return tuple(u.decode() if isinstance(u, bytes) else u |
| 78 |
for u in self._h5group.get_data("units")) |
| 79 |
|
| 80 |
@units.setter |
| 81 |
def units(self, units): |
| 82 |
if not units: |
| 83 |
if self._h5group.has_data("units"): |
| 84 |
del self._h5group["units"] |
| 85 |
else: |
| 86 |
sanitized = [] |
| 87 |
for unit in units: |
| 88 |
util.check_attr_type(unit, str) |
| 89 |
unit = util.units.sanitizer(unit) |
| 90 |
sanitized.append(unit) |
| 91 |
|
| 92 |
dtype = DataType.String |
| 93 |
self._h5group.write_data("units", sanitized, dtype) |
| 94 |
if self.file.auto_update_timestamps: |
| 95 |
self.force_updated_at() |
| 96 |
|
| 97 |
def create_feature(self, data, link_type): |
| 98 |
""" |
| 99 |
Create a new feature. |
| 100 |
|
| 101 |
:param data: The data array of this feature. |
| 102 |
:type data: nixio.DataArray |
| 103 |
:param link_type: The link type of this feature. |
| 104 |
:type link_type: nixio.LinkType |
| 105 |
|
| 106 |
:returns: The created feature object. |
| 107 |
:rtype: nixio.Feature |
| 108 |
""" |
| 109 |
if isinstance(link_type, str): |
| 110 |
link_type = link_type.lower() |
| 111 |
link_type = LinkType(link_type) |
| 112 |
features = self._h5group.open_group("features") |
| 113 |
feat = Feature.create_new(self.file, self, features, data, link_type) |
| 114 |
return feat |
| 115 |
|
| 116 |
def _calc_data_slices(self, data, position, extent, stop_rule): |
| 117 |
refslice = list() |
| 118 |
if not self.units: |
| 119 |
units = [None] * len(data.dimensions) |
| 120 |
else: |
| 121 |
units = self.units |
| 122 |
|
| 123 |
for idx, dim in enumerate(data.dimensions): |
| 124 |
if idx < len(position): |
| 125 |
start_pos = position[idx] |
| 126 |
start_pos, scaling = self._scale_position(start_pos, units[idx], dim) |
| 127 |
if extent is not None and idx < len(extent): |
| 128 |
stop_pos = extent[idx] |
| 129 |
stop_pos *= scaling |
| 130 |
stop_pos += start_pos |
| 131 |
slice_mode = stop_rule if extent[idx] > 0.0 else SliceMode.Inclusive |
| 132 |
else: |
| 133 |
stop_pos = start_pos |
| 134 |
slice_mode = SliceMode.Inclusive |
| 135 |
range_indices = dim.range_indices(start_pos, stop_pos, slice_mode) |
| 136 |
refslice.append(range_indices if range_indices is None else slice(range_indices[0], range_indices[1] + 1)) |
| 137 |
else: |
| 138 |
start_index = 0 |
| 139 |
stop_index = data.shape[idx] |
| 140 |
refslice.append(slice(start_index, stop_index)) |
| 141 |
|
| 142 |
return tuple(refslice) |
| 143 |
|
| 144 |
@staticmethod |
| 145 |
def _slices_in_data(data, slices): |
| 146 |
if slices is None or not all(slices): |
| 147 |
return False |
| 148 |
dasize = data.data_extent |
| 149 |
stops = tuple(sl.stop for sl in slices) |
| 150 |
return np.all(np.less_equal(stops, dasize)) |
| 151 |
|
| 152 |
@staticmethod |
| 153 |
def _scale_position(pos, unit, dim): |
| 154 |
dimtype = dim.dimension_type |
| 155 |
if dimtype == DimensionType.Set: |
| 156 |
dimunit = None |
| 157 |
else: |
| 158 |
dimunit = dim.unit |
| 159 |
scaling = 1.0 |
| 160 |
if dimtype == DimensionType.Set: |
| 161 |
if unit and unit != "none": |
| 162 |
raise IncompatibleDimensions( |
| 163 |
"Cannot apply a position with unit to a SetDimension", |
| 164 |
"Tag._pos_to_idx" |
| 165 |
) |
| 166 |
else: |
| 167 |
if dimunit is None and unit is not None: |
| 168 |
raise IncompatibleDimensions( |
| 169 |
"If a unit if given for the position the dimension must not be without a unit!", |
| 170 |
"Tag._pos_to_idx" |
| 171 |
) |
| 172 |
elif dimunit is not None and unit is not None: |
| 173 |
try: |
| 174 |
scaling = util.units.scaling(unit, dimunit) |
| 175 |
except InvalidUnit: |
| 176 |
raise IncompatibleDimensions( |
| 177 |
"Cannot scale Tag unit {} to match dimension unit {}".format(unit, dimunit), |
| 178 |
"Tag._pos_to_idx" |
| 179 |
) |
| 180 |
return pos * scaling, scaling |
| 181 |
|
| 182 |
@staticmethod |
| 183 |
def _pos_to_idx(pos, unit, dim, mode): |
| 184 |
dimtype = dim.dimension_type |
| 185 |
if dimtype == DimensionType.Set: |
| 186 |
dimunit = None |
| 187 |
else: |
| 188 |
dimunit = dim.unit |
| 189 |
scaling = 1.0 |
| 190 |
if dimtype == DimensionType.Sample: |
| 191 |
if not dimunit and unit is not None: |
| 192 |
raise IncompatibleDimensions( |
| 193 |
"Units of position and SampledDimension " |
| 194 |
"must both be given!", |
| 195 |
"Tag._pos_to_idx" |
| 196 |
) |
| 197 |
if dimunit and unit is not None: |
| 198 |
try: |
| 199 |
scaling = util.units.scaling(unit, dimunit) |
| 200 |
except InvalidUnit: |
| 201 |
raise IncompatibleDimensions( |
| 202 |
"Cannot scale Tag unit {} to match dimension unit {}".format(unit, dimunit), |
| 203 |
"Tag._pos_to_idx" |
| 204 |
) |
| 205 |
index = dim.index_of(pos * scaling, mode) |
| 206 |
elif dimtype == DimensionType.Set: |
| 207 |
if unit and unit != "none": |
| 208 |
raise IncompatibleDimensions( |
| 209 |
"Cannot apply a position with unit to a SetDimension", |
| 210 |
"Tag._pos_to_idx" |
| 211 |
) |
| 212 |
index = dim.index_of(pos, mode) |
| 213 |
else: |
| 214 |
if dimunit and unit is not None: |
| 215 |
try: |
| 216 |
scaling = util.units.scaling(unit, dimunit) |
| 217 |
except InvalidUnit: |
| 218 |
raise IncompatibleDimensions( |
| 219 |
"Cannot scale Tag unit {} to match dimension unit {}".format(unit, dimunit), |
| 220 |
"Tag._pos_to_idx" |
| 221 |
) |
| 222 |
index = dim.index_of(pos * scaling, mode) |
| 223 |
|
| 224 |
return int(index) |
| 225 |
|
| 226 |
@property |
| 227 |
def features(self): |
| 228 |
""" |
| 229 |
A property containing all features. Features can be obtained |
| 230 |
via their index or their ID. Features can be deleted from the list. |
| 231 |
Adding new features is done using the create_feature method. |
| 232 |
This is a read only attribute. |
| 233 |
|
| 234 |
:type: Container of nixio.Feature. |
| 235 |
""" |
| 236 |
if self._features is None: |
| 237 |
self._features = FeatureContainer("features", self.file, |
| 238 |
self, Feature) |
| 239 |
return self._features |
| 240 |
|
| 241 |
|
| 242 |
class Tag(BaseTag): |
| 243 |
|
| 244 |
@classmethod |
| 245 |
def create_new(cls, nixfile, nixparent, h5parent, name, type_, position): |
| 246 |
newentity = super(Tag, cls).create_new(nixfile, nixparent, h5parent, |
| 247 |
name, type_) |
| 248 |
newentity.position = position |
| 249 |
return newentity |
| 250 |
|
| 251 |
@property |
| 252 |
def position(self): |
| 253 |
""" |
| 254 |
The position defined by the tag. This is a read-write property. |
| 255 |
|
| 256 |
:type: list of float |
| 257 |
""" |
| 258 |
return tuple(self._h5group.get_data("position")) |
| 259 |
|
| 260 |
@position.setter |
| 261 |
def position(self, pos): |
| 262 |
if pos is not None and not hasattr(pos, "__getitem__"): |
| 263 |
pos = [pos] |
| 264 |
if pos is None or len(pos) == 0: |
| 265 |
if self._h5group.has_data("position"): |
| 266 |
del self._h5group["position"] |
| 267 |
else: |
| 268 |
dtype = DataType.Double |
| 269 |
self._h5group.write_data("position", pos, dtype) |
| 270 |
if self.file.auto_update_timestamps: |
| 271 |
self.force_updated_at() |
| 272 |
|
| 273 |
@property |
| 274 |
def extent(self): |
| 275 |
""" |
| 276 |
The extent defined by the tag. This is an optional read-write |
| 277 |
property and may be set to None. |
| 278 |
|
| 279 |
:type: list of float |
| 280 |
""" |
| 281 |
return tuple(self._h5group.get_data("extent")) |
| 282 |
|
| 283 |
@extent.setter |
| 284 |
def extent(self, ext): |
| 285 |
if ext is not None and not hasattr(ext, "__getitem__"): |
| 286 |
ext = [ext] |
| 287 |
if ext is None or len(ext) == 0: |
| 288 |
if self._h5group.has_data("extent"): |
| 289 |
del self._h5group["extent"] |
| 290 |
else: |
| 291 |
dtype = DataType.Double |
| 292 |
self._h5group.write_data("extent", ext, dtype) |
| 293 |
if self.file.auto_update_timestamps: |
| 294 |
self.force_updated_at() |
| 295 |
|
| 296 |
def retrieve_data(self, refidx): |
| 297 |
msg = ("Call to deprecated method Tag.retrieve_data. " |
| 298 |
"Use Tag.tagged_data instead.") |
| 299 |
warnings.warn(msg, category=DeprecationWarning) |
| 300 |
return self.tagged_data(refidx) |
| 301 |
|
| 302 |
def tagged_data(self, refidx, stop_rule=SliceMode.Exclusive): |
| 303 |
references = self.references |
| 304 |
position = self.position |
| 305 |
extent = self.extent |
| 306 |
if len(references) == 0: |
| 307 |
raise OutOfBounds("There are no references in this tag!") |
| 308 |
|
| 309 |
if isinstance(refidx, int) and refidx >= len(references): |
| 310 |
raise OutOfBounds("Reference index out of bounds.") |
| 311 |
|
| 312 |
ref = references[refidx] |
| 313 |
if extent and len(position) != len(extent): |
| 314 |
raise IncompatibleDimensions( |
| 315 |
"Number of dimensions in position and extent " |
| 316 |
"do not match ", extent) |
| 317 |
|
| 318 |
slices = self._calc_data_slices(ref, self.position, self.extent, stop_rule) |
| 319 |
if not all(slices): |
| 320 |
return DataView(ref, slices) |
| 321 |
if not self._slices_in_data(ref, slices): |
| 322 |
raise OutOfBounds("References data slice out of the extent of the " |
| 323 |
"DataArray!") |
| 324 |
return DataView(ref, slices) |
| 325 |
|
| 326 |
def retrieve_feature_data(self, featidx): |
| 327 |
msg = ("Call to deprecated method Tag.retrieve_feature_data. " |
| 328 |
"Use Tag.feature_data instead.") |
| 329 |
warnings.warn(msg, category=DeprecationWarning) |
| 330 |
return self.feature_data(featidx) |
| 331 |
|
| 332 |
def feature_data(self, featidx, stop_rule=SliceMode.Exclusive): |
| 333 |
if len(self.features) == 0: |
| 334 |
raise OutOfBounds("There are no features associated with this tag!") |
| 335 |
|
| 336 |
try: |
| 337 |
feat = self.features[featidx] |
| 338 |
except KeyError: |
| 339 |
feat = None |
| 340 |
for feature in self.features: |
| 341 |
if feature.data.name == featidx or feature.data.id == featidx: |
| 342 |
feat = feature |
| 343 |
break |
| 344 |
if feat is None: |
| 345 |
raise |
| 346 |
data = feat.data |
| 347 |
if data is None: |
| 348 |
raise UninitializedEntity() |
| 349 |
if feat.link_type == LinkType.Tagged: |
| 350 |
slices = self._calc_data_slices(data, self.position, self.extent, stop_rule) |
| 351 |
if not self._slices_in_data(data, slices): |
| 352 |
raise OutOfBounds("Requested data slice out of the extent " |
| 353 |
"of the Feature!") |
| 354 |
return DataView(data, slices) |
| 355 |
|
| 356 |
fullslices = tuple(slice(0, stop) for stop in data.shape) |
| 357 |
return DataView(data, fullslices) |
| 358 |
|
| 359 |
@property |
| 360 |
def references(self): |
| 361 |
""" |
| 362 |
A property containing all data arrays referenced by the tag. Referenced |
| 363 |
data arrays can be obtained by index or their id. References can be |
| 364 |
removed from the list, removing a referenced DataArray will not remove |
| 365 |
it from the file. New references can be added using the append method |
| 366 |
of the list. |
| 367 |
This is a read only attribute. |
| 368 |
|
| 369 |
:type: Container of nixio.DataArray |
| 370 |
""" |
| 371 |
if self._references is None: |
| 372 |
self._references = LinkContainer("references", self, DataArray, |
| 373 |
self._parent.data_arrays) |
| 374 |
return self._references |
| 375 |
|
| 376 |
@property |
| 377 |
def sources(self): |
| 378 |
""" |
| 379 |
A property containing all Sources referenced by the Tag. Sources |
| 380 |
can be obtained by index or their id. Sources can be removed from the |
| 381 |
list, but removing a referenced Source will not remove it from the |
| 382 |
file. New Sources can be added using the append method of the list. |
| 383 |
This is a read only attribute. |
| 384 |
""" |
| 385 |
if self._sources is None: |
| 386 |
self._sources = SourceLinkContainer(self) |
| 387 |
return self._sources |
| 388 |
|
| 389 |
|
| 390 |
@property |
| 391 |
def metadata(self): |
| 392 |
""" |
| 393 |
|
| 394 |
Associated metadata of the entity. Sections attached to the entity via |
| 395 |
this attribute can provide additional annotations. This is an optional |
| 396 |
read-write property, and can be None if no metadata is available. |
| 397 |
|
| 398 |
:type: nixio.Section |
| 399 |
""" |
| 400 |
if "metadata" in self._h5group: |
| 401 |
return Section(self.file, None, self._h5group.open_group("metadata")) |
| 402 |
return None |
| 403 |
|
| 404 |
@metadata.setter |
| 405 |
def metadata(self, sect): |
| 406 |
if not isinstance(sect, Section): |
| 407 |
raise TypeError("{} is not of type Section".format(sect)) |
| 408 |
self._h5group.create_link(sect, "metadata") |
| 409 |
|
| 410 |
@metadata.deleter |
| 411 |
def metadata(self): |
| 412 |
if "metadata" in self._h5group: |
| 413 |
self._h5group.delete("metadata") |