| 1 |
|
| 2 |
|
| 3 |
) |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
from numbers import Number |
| 11 |
try: |
| 12 |
from collections.abc import Sequence |
| 13 |
except ImportError: |
| 14 |
from collections import Sequence |
| 15 |
from enum import Enum |
| 16 |
|
| 17 |
import numpy as np |
| 18 |
|
| 19 |
from .datatype import DataType |
| 20 |
from .dimension_type import DimensionType |
| 21 |
from . import util |
| 22 |
from .container import Container |
| 23 |
from .exceptions import IncompatibleDimensions, OutOfBounds |
| 24 |
|
| 25 |
|
| 26 |
class IndexMode(Enum): |
| 27 |
""" |
| 28 |
IndexMode is used to define the behaviour of the index_of() methods. |
| 29 |
""" |
| 30 |
|
| 31 |
Less = "less" |
| 32 |
LessOrEqual = "leq" |
| 33 |
GreaterOrEqual = "geq" |
| 34 |
|
| 35 |
|
| 36 |
LEQ = "leq" |
| 37 |
GEQ = "geq" |
| 38 |
|
| 39 |
|
| 40 |
class SliceMode(Enum): |
| 41 |
Exclusive = "exclusive" |
| 42 |
Inclusive = "inclusive" |
| 43 |
|
| 44 |
def to_index_mode(self): |
| 45 |
if self == self.Exclusive: |
| 46 |
return IndexMode.Less |
| 47 |
if self == self.Inclusive: |
| 48 |
return IndexMode.LessOrEqual |
| 49 |
|
| 50 |
|
| 51 |
class DimensionContainer(Container): |
| 52 |
""" |
| 53 |
DimensionContainer extends Container to support returning different types |
| 54 |
of Dimension classes on return. |
| 55 |
""" |
| 56 |
|
| 57 |
def _inst_item(self, item): |
| 58 |
cls = { |
| 59 |
DimensionType.Range: RangeDimension, |
| 60 |
DimensionType.Sample: SampledDimension, |
| 61 |
DimensionType.Set: SetDimension, |
| 62 |
}[DimensionType(item.get_attr("dimension_type"))] |
| 63 |
idx = item.name |
| 64 |
return cls(self._parent, idx) |
| 65 |
|
| 66 |
|
| 67 |
class DimensionLink: |
| 68 |
""" |
| 69 |
Links a Dimension to a data object (DataArray or DataFrame). |
| 70 |
|
| 71 |
A single vector of values from the underlying data object must be |
| 72 |
specified to serve as the ticks or labels for the associated Dimension. |
| 73 |
|
| 74 |
- A single vector of a DataArray. |
| 75 |
- A single column of a DataFrame. |
| 76 |
""" |
| 77 |
|
| 78 |
def __init__(self, nixfile, nixparent, h5group): |
| 79 |
util.check_entity_id(h5group.get_attr("entity_id")) |
| 80 |
self._h5group = h5group |
| 81 |
self._parent = nixparent |
| 82 |
self._file = nixfile |
| 83 |
|
| 84 |
@classmethod |
| 85 |
def create_new(cls, nixfile, nixparent, h5parent, dataobj, dotype, index): |
| 86 |
id_ = util.create_id() |
| 87 |
h5group = h5parent.open_group("link", True) |
| 88 |
h5group.set_attr("entity_id", id_) |
| 89 |
newdimlink = cls(nixfile, nixparent, h5group) |
| 90 |
newdimlink._h5group.set_attr("data_object_type", dotype) |
| 91 |
newdimlink._h5group.create_link(dataobj, dataobj.id) |
| 92 |
newdimlink.index = index |
| 93 |
now = util.time_to_str(util.now_int()) |
| 94 |
newdimlink._h5group.set_attr("created_at", now) |
| 95 |
newdimlink._h5group.set_attr("updated_at", now) |
| 96 |
return newdimlink |
| 97 |
|
| 98 |
@property |
| 99 |
def id(self): |
| 100 |
return self._h5group.get_attr("entity_id") |
| 101 |
|
| 102 |
@property |
| 103 |
def file(self): |
| 104 |
return self._file |
| 105 |
|
| 106 |
def _linked_group(self): |
| 107 |
return self._h5group.get_by_pos(0) |
| 108 |
|
| 109 |
@property |
| 110 |
def linked_data(self): |
| 111 |
grp = self._linked_group() |
| 112 |
return grp.get_data("data") |
| 113 |
|
| 114 |
@property |
| 115 |
def index(self): |
| 116 |
if self._data_object_type == "DataArray": |
| 117 |
return tuple(self._h5group.get_attr("index")) |
| 118 |
if self._data_object_type == "DataFrame": |
| 119 |
return self._h5group.get_attr("index") |
| 120 |
raise RuntimeError("Invalid DataObjectType attribute found in " |
| 121 |
"DimensionLink") |
| 122 |
|
| 123 |
@index.setter |
| 124 |
def index(self, index): |
| 125 |
if self._data_object_type == "DataArray": |
| 126 |
util.check_attr_type(index, Sequence) |
| 127 |
if index.count(-1) != 1: |
| 128 |
raise ValueError("Index for DimensionLink with DataArray must " |
| 129 |
"have exactly one value equal to -1. " |
| 130 |
"See class docstring for more information.") |
| 131 |
self._h5group.set_attr("index", list(index)) |
| 132 |
elif self._data_object_type == "DataFrame": |
| 133 |
util.check_attr_type(index, int) |
| 134 |
self._h5group.set_attr("index", index) |
| 135 |
else: |
| 136 |
raise RuntimeError("Invalid DataObjectType attribute found in " |
| 137 |
"DimensionLink") |
| 138 |
|
| 139 |
@property |
| 140 |
def values(self): |
| 141 |
""" |
| 142 |
Returns the values (vector or column) from the linked data object |
| 143 |
(DataArray or DataFrame) specified by the LinkDimension's index. |
| 144 |
""" |
| 145 |
data = self.linked_data |
| 146 |
if self._data_object_type == "DataArray": |
| 147 |
dimindex = list(self.index) |
| 148 |
|
| 149 |
dimindex[dimindex.index(-1)] = slice(None) |
| 150 |
return data[tuple(dimindex)] |
| 151 |
elif self._data_object_type == "DataFrame": |
| 152 |
return tuple(row[self.index] for row in data) |
| 153 |
else: |
| 154 |
raise RuntimeError("Invalid DataObjectType attribute found in " |
| 155 |
"DimensionLink") |
| 156 |
|
| 157 |
@property |
| 158 |
def unit(self): |
| 159 |
""" |
| 160 |
Returns the unit from the linked data object (DataArray or DataFrame) |
| 161 |
specified by the LinkDimension's index. |
| 162 |
""" |
| 163 |
lobj = self._linked_group() |
| 164 |
if self._data_object_type == "DataArray": |
| 165 |
return lobj.get_attr("unit") |
| 166 |
elif self._data_object_type == "DataFrame": |
| 167 |
return lobj.get_attr("units")[self.index] |
| 168 |
else: |
| 169 |
raise RuntimeError("Invalid DataObjectType attribute found in " |
| 170 |
"DimensionLink") |
| 171 |
|
| 172 |
@unit.setter |
| 173 |
def unit(self, unit): |
| 174 |
""" |
| 175 |
Sets the unit of the linked data object. |
| 176 |
""" |
| 177 |
lobj = self._linked_group() |
| 178 |
if self._data_object_type == "DataArray": |
| 179 |
lobj.set_attr("unit", unit) |
| 180 |
elif self._data_object_type == "DataFrame": |
| 181 |
units = list(lobj.get_attr("units")) |
| 182 |
units[self.index] = unit |
| 183 |
lobj.set_attr("units", units) |
| 184 |
else: |
| 185 |
raise RuntimeError("Invalid DataObjectType attribute found in " |
| 186 |
"DimensionLink") |
| 187 |
|
| 188 |
@property |
| 189 |
def label(self): |
| 190 |
""" |
| 191 |
Returns the label of the linked data object: |
| 192 |
For DataArray links, returns the label. |
| 193 |
For DataFrame links, returns the name of the column specified by the |
| 194 |
LinkDimension's index. |
| 195 |
""" |
| 196 |
lobj = self._linked_group() |
| 197 |
if self._data_object_type == "DataArray": |
| 198 |
return lobj.get_attr("label") |
| 199 |
elif self._data_object_type == "DataFrame": |
| 200 |
col_dts = lobj.group["data"].dtype |
| 201 |
return col_dts.names[self.index] |
| 202 |
else: |
| 203 |
raise RuntimeError("Invalid DataObjectType attribute found in " |
| 204 |
"DimensionLink") |
| 205 |
|
| 206 |
@label.setter |
| 207 |
def label(self, label): |
| 208 |
""" |
| 209 |
Sets the label of the linked data objet. |
| 210 |
""" |
| 211 |
lobj = self._linked_group() |
| 212 |
if self._data_object_type == "DataArray": |
| 213 |
lobj.set_attr("label", label) |
| 214 |
elif self._data_object_type == "DataFrame": |
| 215 |
raise RuntimeError("The label of a Dimension linked to a " |
| 216 |
"DataFrame column cannot be modified") |
| 217 |
else: |
| 218 |
raise RuntimeError("Invalid DataObjectType attribute found in " |
| 219 |
"DimensionLink") |
| 220 |
|
| 221 |
@property |
| 222 |
def _data_object_type(self): |
| 223 |
return self._h5group.get_attr("data_object_type") |
| 224 |
|
| 225 |
|
| 226 |
class Dimension: |
| 227 |
|
| 228 |
def __init__(self, nixfile, data_array, index): |
| 229 |
dimgroup = data_array._h5group.open_group("dimensions") |
| 230 |
h5group = dimgroup.open_group(str(index)) |
| 231 |
self._h5group = h5group |
| 232 |
self.dim_index = int(index) |
| 233 |
self._parent = data_array |
| 234 |
self._file = nixfile |
| 235 |
|
| 236 |
@property |
| 237 |
def dimension_type(self): |
| 238 |
return DimensionType(self._h5group.get_attr("dimension_type")) |
| 239 |
|
| 240 |
def _set_dimension_type(self, dimtype): |
| 241 |
dimtype = DimensionType(dimtype) |
| 242 |
if dimtype not in DimensionType: |
| 243 |
raise TypeError("Invalid dimension type.") |
| 244 |
self._h5group.set_attr("dimension_type", dimtype.value) |
| 245 |
|
| 246 |
@property |
| 247 |
def index(self): |
| 248 |
return self.dim_index |
| 249 |
|
| 250 |
@staticmethod |
| 251 |
def _check_index(index): |
| 252 |
invalid_idx_msg = ( |
| 253 |
"Invalid linked DataArray index: " |
| 254 |
"One of the values must be -1, indicating the relevant vector. " |
| 255 |
"Negative indexing is not supported." |
| 256 |
) |
| 257 |
if index.count(-1) != 1 or sum(idx < 0 for idx in index) != 1: |
| 258 |
|
| 259 |
return invalid_idx_msg |
| 260 |
|
| 261 |
return None |
| 262 |
|
| 263 |
@property |
| 264 |
def label(self): |
| 265 |
return self._h5group.get_attr("label") |
| 266 |
|
| 267 |
@label.setter |
| 268 |
def label(self, label): |
| 269 |
util.check_attr_type(label, str) |
| 270 |
self._h5group.set_attr("label", label) |
| 271 |
|
| 272 |
@staticmethod |
| 273 |
def _check_link_dimensionality(data_array, index): |
| 274 |
invalid_dim_msg = ("Length of linked DataArray indices ({}) does not match " |
| 275 |
"number of DataArray dimensions ({})" |
| 276 |
).format(len(data_array.data_extent), len(index)) |
| 277 |
|
| 278 |
if len(data_array.data_extent) != len(index): |
| 279 |
return invalid_dim_msg |
| 280 |
return None |
| 281 |
|
| 282 |
def link_data_array(self, data_array, index): |
| 283 |
msg = RangeDimension._check_link_dimensionality(data_array, index) |
| 284 |
if msg is not None: |
| 285 |
raise IncompatibleDimensions(msg, "Dimension.link_data_array") |
| 286 |
|
| 287 |
msg = self._check_index(index) |
| 288 |
if msg is not None: |
| 289 |
raise ValueError(msg) |
| 290 |
|
| 291 |
if self.has_link: |
| 292 |
self.remove_link() |
| 293 |
DimensionLink.create_new(self._file, self, self._h5group, |
| 294 |
data_array, "DataArray", index) |
| 295 |
|
| 296 |
def link_data_frame(self, data_frame, index): |
| 297 |
if not 0 <= index < len(data_frame.columns): |
| 298 |
raise OutOfBounds("DataFrame index is out of bounds", index) |
| 299 |
if self.has_link: |
| 300 |
self.remove_link() |
| 301 |
DimensionLink.create_new(self._file, self, self._h5group, |
| 302 |
data_frame, "DataFrame", index) |
| 303 |
|
| 304 |
def remove_link(self): |
| 305 |
if not self.has_link: |
| 306 |
raise RuntimeError("Dimension has no link") |
| 307 |
self._h5group.delete("link", False) |
| 308 |
|
| 309 |
@property |
| 310 |
def has_link(self): |
| 311 |
""" |
| 312 |
Return True if this Dimension links to a data object |
| 313 |
(DataArray or DataFrame). |
| 314 |
Read-only property. |
| 315 |
""" |
| 316 |
if "link" in self._h5group: |
| 317 |
return True |
| 318 |
return False |
| 319 |
|
| 320 |
@property |
| 321 |
def dimension_link(self): |
| 322 |
""" |
| 323 |
If the dimension has a DimensionLink to a data object, returns the |
| 324 |
DimensionLink object, otherwise returns None. |
| 325 |
""" |
| 326 |
if self.has_link: |
| 327 |
link = self._h5group.get_by_name("link") |
| 328 |
return DimensionLink(self._file, self, link) |
| 329 |
return None |
| 330 |
|
| 331 |
def __str__(self): |
| 332 |
return "{}: {{index = {}}}".format( |
| 333 |
type(self).__name__, self.index |
| 334 |
) |
| 335 |
|
| 336 |
def __repr__(self): |
| 337 |
return self.__str__() |
| 338 |
|
| 339 |
|
| 340 |
class SampledDimension(Dimension): |
| 341 |
|
| 342 |
def __init__(self, data_array, index): |
| 343 |
nixfile = data_array.file |
| 344 |
super(SampledDimension, self).__init__(nixfile, data_array, index) |
| 345 |
|
| 346 |
@classmethod |
| 347 |
def create_new(cls, data_array, index, sample): |
| 348 |
newdim = cls(data_array, index) |
| 349 |
newdim._set_dimension_type(DimensionType.Sample) |
| 350 |
newdim.sampling_interval = sample |
| 351 |
return newdim |
| 352 |
|
| 353 |
def position_at(self, index): |
| 354 |
""" |
| 355 |
Returns the position corresponding to a given index. |
| 356 |
|
| 357 |
:param index: A positive integer. |
| 358 |
|
| 359 |
:returns: The position matching to the index. |
| 360 |
:rtype: float |
| 361 |
""" |
| 362 |
offset = self.offset if self.offset else 0 |
| 363 |
sample = self.sampling_interval |
| 364 |
return index * sample + offset |
| 365 |
|
| 366 |
def index_of(self, position, mode=IndexMode.LessOrEqual): |
| 367 |
""" |
| 368 |
Returns the index of a certain position in the dimension. |
| 369 |
Raises IndexError if the position is out of bounds (depending on mode). |
| 370 |
|
| 371 |
:param position: The position. |
| 372 |
:param mode: The IndexMode to use (default LessOrEqual). |
| 373 |
The default value (LessOrEqual) will return the index of the position calculated based on the |
| 374 |
dimension offset and sampling_interval if it matches a dimension tick exactly. If it does not match |
| 375 |
a tick, the previous index is returned. |
| 376 |
If the mode is Less, the previous index of the calculated position is always returned. |
| 377 |
If the mode is GreaterOrEqual and the calculated position does not match a tick exactly, the next |
| 378 |
index is returned. |
| 379 |
|
| 380 |
:returns: The matching index. |
| 381 |
:rtype: int |
| 382 |
""" |
| 383 |
offset = self.offset if self.offset else 0 |
| 384 |
sample = self.sampling_interval |
| 385 |
scaled_position = (position - offset) / sample |
| 386 |
if scaled_position < 0: |
| 387 |
if mode == IndexMode.GreaterOrEqual: |
| 388 |
return 0 |
| 389 |
|
| 390 |
raise IndexError("Position {} is out of bounds for SampledDimension with offset {} and mode {}".format( |
| 391 |
position, offset, mode.name |
| 392 |
)) |
| 393 |
|
| 394 |
if np.isclose(position, 0) and mode == IndexMode.Less: |
| 395 |
raise IndexError("Position {} is out of bounds for SampledDimension with mode {}".format(position, mode.name)) |
| 396 |
index = int(np.round(scaled_position)) |
| 397 |
if np.isclose(scaled_position, index): |
| 398 |
|
| 399 |
if mode in (IndexMode.GreaterOrEqual, IndexMode.LessOrEqual): |
| 400 |
|
| 401 |
return index |
| 402 |
if mode == IndexMode.Less: |
| 403 |
|
| 404 |
return index - 1 |
| 405 |
raise ValueError("Unknown IndexMode: {}".format(mode)) |
| 406 |
if index < scaled_position: |
| 407 |
if mode in (IndexMode.LessOrEqual, IndexMode.Less): |
| 408 |
return index |
| 409 |
elif mode == IndexMode.GreaterOrEqual: |
| 410 |
return index + 1 |
| 411 |
else: |
| 412 |
raise ValueError("Unknown IndexMode: {}".format(mode)) |
| 413 |
else: |
| 414 |
if mode in (IndexMode.LessOrEqual, IndexMode.Less): |
| 415 |
return index - 1 |
| 416 |
elif mode == IndexMode.GreaterOrEqual: |
| 417 |
return index |
| 418 |
else: |
| 419 |
raise ValueError("Unknown IndexMode: {}".format(mode)) |
| 420 |
|
| 421 |
def range_indices(self, start_position, end_position, mode=SliceMode.Exclusive): |
| 422 |
""" |
| 423 |
Returns the start and end indices in this dimension that are matching to the given start and end position. |
| 424 |
|
| 425 |
:param start_position: the start position of the range. |
| 426 |
:type start_position: float |
| 427 |
:param end_position: the end position of the range. |
| 428 |
:type end_position: float |
| 429 |
:param mode: The nixio.SliceMode. Defaults to nixio.SliceMode.Exclusive, i.e. the end position is not part of the range. |
| 430 |
:type mode: nixio.SliceMode |
| 431 |
|
| 432 |
:returns: The respective start and end indices. None, if the range is empty! |
| 433 |
:rtype: tuple of int |
| 434 |
|
| 435 |
:raises: ValueError if invalid mode is given |
| 436 |
:raises: Index Error if start position is greater than end position. |
| 437 |
""" |
| 438 |
if mode is not SliceMode.Exclusive and mode is not SliceMode.Inclusive: |
| 439 |
raise ValueError("Unknown SliceMode: {}".format(mode)) |
| 440 |
|
| 441 |
end_mode = IndexMode.Less if mode == SliceMode.Exclusive else IndexMode.LessOrEqual |
| 442 |
try: |
| 443 |
start_index = self.index_of(start_position, mode=IndexMode.GreaterOrEqual) |
| 444 |
end_index = self.index_of(end_position, mode=end_mode) |
| 445 |
except IndexError: |
| 446 |
return None |
| 447 |
if start_index > end_index: |
| 448 |
return None |
| 449 |
return (start_index, end_index) |
| 450 |
|
| 451 |
def axis(self, count, start=None, start_position=None): |
| 452 |
""" |
| 453 |
Get an axis as defined by this nixio.SampledDimension. It either starts at the offset of the dimension, |
| 454 |
a number of sample points later, or at a given position. The latter must not be less than the offset. If |
| 455 |
start and start_position are given, start takes precedence. |
| 456 |
|
| 457 |
:param count: A positive integer specifying the length of the axis (no of samples). |
| 458 |
:type count: int |
| 459 |
:param start: positive integer, indicates the starting sample. Defaults to None. Precedes over the start_position. |
| 460 |
:type start: int |
| 461 |
:param start_position: The start position of the axis. Defaults to None. |
| 462 |
:type start_position: double |
| 463 |
|
| 464 |
:raises: ValueError if start is negative or if the start_position is given and is less than offset. |
| 465 |
|
| 466 |
:returns: The created axis |
| 467 |
:rtype: tuple |
| 468 |
""" |
| 469 |
offset = self.offset if self.offset else 0.0 |
| 470 |
sample = self.sampling_interval |
| 471 |
|
| 472 |
if start is not None: |
| 473 |
if start < 0: |
| 474 |
raise ValueError("Start index (%i) must not be negative!" % start) |
| 475 |
start_val = start * sample + offset |
| 476 |
else: |
| 477 |
if start_position is not None: |
| 478 |
if start_position < offset: |
| 479 |
raise ValueError("SampledDimension.axis: Start position (%.f) must not be " |
| 480 |
"less than the offset of the dimension (%.f)!" % (start_position, offset)) |
| 481 |
else: |
| 482 |
start_val = start_position |
| 483 |
else: |
| 484 |
start_val = offset |
| 485 |
|
| 486 |
return tuple(np.arange(count) * sample + start_val) |
| 487 |
|
| 488 |
@property |
| 489 |
def sampling_interval(self): |
| 490 |
return self._h5group.get_attr("sampling_interval") |
| 491 |
|
| 492 |
@sampling_interval.setter |
| 493 |
def sampling_interval(self, interval): |
| 494 |
util.check_attr_type(interval, Number) |
| 495 |
self._h5group.set_attr("sampling_interval", interval) |
| 496 |
|
| 497 |
@property |
| 498 |
def unit(self): |
| 499 |
return self._h5group.get_attr("unit") |
| 500 |
|
| 501 |
@unit.setter |
| 502 |
def unit(self, unit): |
| 503 |
util.check_attr_type(unit, str) |
| 504 |
self._h5group.set_attr("unit", unit) |
| 505 |
|
| 506 |
@property |
| 507 |
def offset(self): |
| 508 |
return self._h5group.get_attr("offset") |
| 509 |
|
| 510 |
@offset.setter |
| 511 |
def offset(self, offset): |
| 512 |
util.check_attr_type(offset, Number) |
| 513 |
self._h5group.set_attr("offset", offset) |
| 514 |
|
| 515 |
def link_data_array(self, *_): |
| 516 |
raise RuntimeError("SampledDimension does not support linking") |
| 517 |
|
| 518 |
def link_data_frame(self, *_): |
| 519 |
raise RuntimeError("SampledDimension does not support linking") |
| 520 |
|
| 521 |
|
| 522 |
class RangeDimension(Dimension): |
| 523 |
|
| 524 |
def __init__(self, data_array, index): |
| 525 |
nixfile = data_array.file |
| 526 |
super(RangeDimension, self).__init__(nixfile, data_array, index) |
| 527 |
|
| 528 |
def link_data_array(self, data_array, index): |
| 529 |
if "ticks" in self._h5group: |
| 530 |
|
| 531 |
self._h5group.delete("ticks", False) |
| 532 |
super(RangeDimension, self).link_data_array(data_array, index) |
| 533 |
|
| 534 |
def link_data_frame(self, data_frame, index): |
| 535 |
if "ticks" in self._h5group: |
| 536 |
|
| 537 |
self._h5group.delete("ticks", False) |
| 538 |
super(RangeDimension, self).link_data_frame(data_frame, index) |
| 539 |
|
| 540 |
@classmethod |
| 541 |
def create_new(cls, data_array, index, ticks): |
| 542 |
newdim = cls(data_array, index) |
| 543 |
newdim._set_dimension_type(DimensionType.Range) |
| 544 |
if ticks is not None: |
| 545 |
newdim._h5group.write_data("ticks", ticks, dtype=DataType.Double) |
| 546 |
return newdim |
| 547 |
|
| 548 |
@property |
| 549 |
def is_alias(self): |
| 550 |
""" |
| 551 |
In versions < 1.5 a RangeDimension that was referring to the DataArray it describes |
| 552 |
was called an AliasRangeDimension. This has been made more flexible by allowing to link |
| 553 |
to any DataArray or DataFrame. |
| 554 |
For downward compatibility this method has been re-introduced in 1.5.1. |
| 555 |
|
| 556 |
:returns: True, if this dimension links to a DataArray, False otherwise |
| 557 |
:rtype: bool |
| 558 |
""" |
| 559 |
if self._h5group.has_data("ticks"): |
| 560 |
return False |
| 561 |
elif not self.has_link and len(self._h5group) > 0: |
| 562 |
return True |
| 563 |
elif self.has_link and self.dimension_link._data_object_type == "DataArray": |
| 564 |
return True |
| 565 |
return False |
| 566 |
|
| 567 |
@property |
| 568 |
def _redirgrp(self): |
| 569 |
""" |
| 570 |
If the dimension is an Alias Range dimension, this property returns |
| 571 |
the H5Group of the linked DataArray. Otherwise, it returns the H5Group |
| 572 |
representing the dimension. |
| 573 |
""" |
| 574 |
if self.is_alias: |
| 575 |
gname = self._h5group.get_by_pos(0).name |
| 576 |
return self._h5group.open_group(gname) |
| 577 |
return self._h5group |
| 578 |
|
| 579 |
@property |
| 580 |
def ticks(self): |
| 581 |
if self.is_alias and not self.has_link: |
| 582 |
g = self._redirgrp |
| 583 |
if g.has_data("data"): |
| 584 |
ticks = g.get_data("data") |
| 585 |
return tuple(ticks) |
| 586 |
if self.has_link: |
| 587 |
ticks = self.dimension_link.values |
| 588 |
else: |
| 589 |
ticks = self._h5group.get_data("ticks") |
| 590 |
return tuple(ticks) |
| 591 |
|
| 592 |
@ticks.setter |
| 593 |
def ticks(self, ticks): |
| 594 |
if np.any(np.diff(ticks) < 0): |
| 595 |
raise ValueError("Ticks are not given in an ascending order.") |
| 596 |
if self.has_link: |
| 597 |
|
| 598 |
self.remove_link() |
| 599 |
self._h5group.write_data("ticks", ticks) |
| 600 |
|
| 601 |
@property |
| 602 |
def label(self): |
| 603 |
if self.is_alias and not self.has_link: |
| 604 |
g = self._redirgrp |
| 605 |
return g.get_attr("label") |
| 606 |
if self.has_link: |
| 607 |
return self.dimension_link.label |
| 608 |
return self._h5group.get_attr("label") |
| 609 |
|
| 610 |
@label.setter |
| 611 |
def label(self, label): |
| 612 |
util.check_attr_type(label, str) |
| 613 |
if self.has_link: |
| 614 |
self.dimension_link.label = label |
| 615 |
else: |
| 616 |
self._h5group.set_attr("label", label) |
| 617 |
|
| 618 |
@property |
| 619 |
def unit(self): |
| 620 |
if self.is_alias and not self.has_link: |
| 621 |
g = self._redirgrp |
| 622 |
return g.get_attr("unit") |
| 623 |
if self.has_link: |
| 624 |
return self.dimension_link.unit |
| 625 |
return self._h5group.get_attr("unit") |
| 626 |
|
| 627 |
@unit.setter |
| 628 |
def unit(self, unit): |
| 629 |
util.check_attr_type(unit, str) |
| 630 |
if self.has_link: |
| 631 |
self.dimension_link.unit = unit |
| 632 |
else: |
| 633 |
self._h5group.set_attr("unit", unit) |
| 634 |
|
| 635 |
def index_of(self, position, mode=IndexMode.LessOrEqual, ticks=None): |
| 636 |
""" |
| 637 |
Returns the index of a certain position in the dimension. |
| 638 |
Raises IndexError if the position is out of bounds (depending on mode). |
| 639 |
|
| 640 |
:param position: The position. |
| 641 |
:param mode: The IndexMode to use (default LessOrEqual). |
| 642 |
The default value (LessOrEqual) will return the index of the position that matches a tick if it |
| 643 |
matches a dimension tick exactly. If it does not match a tick, the previous index is returned. |
| 644 |
If the mode is Less, the previous index of the matching tick is always returned. |
| 645 |
If the mode is GreaterOrEqual and the position does not match a tick exactly, the next index is |
| 646 |
returned. |
| 647 |
:param ticks: Optional, the ticks stored in this dimension. If not passed as argument, they are (re)read from file. |
| 648 |
:type ticks: iterable |
| 649 |
|
| 650 |
:returns: The matching index |
| 651 |
:rtype: int |
| 652 |
""" |
| 653 |
if ticks is None: |
| 654 |
ticks = self.ticks |
| 655 |
if position < ticks[0]: |
| 656 |
if mode == IndexMode.GreaterOrEqual: |
| 657 |
return 0 |
| 658 |
|
| 659 |
raise IndexError("Position {} is out of bounds for ticks ({}, ..., {}) with mode {}".format( |
| 660 |
position, ticks[0], ticks[-1], mode.name |
| 661 |
)) |
| 662 |
if position > ticks[-1]: |
| 663 |
if mode in (IndexMode.Less, IndexMode.LessOrEqual): |
| 664 |
return len(ticks) - 1 |
| 665 |
raise IndexError("Position {} is out of bounds for ticks ({}, ..., {}) with mode {}".format( |
| 666 |
position, ticks[0], ticks[-1], mode.name |
| 667 |
)) |
| 668 |
|
| 669 |
ticks = np.array(ticks) |
| 670 |
if mode == IndexMode.LessOrEqual: |
| 671 |
return np.where(ticks <= position)[0][-1] |
| 672 |
if mode == IndexMode.Less: |
| 673 |
return np.where(ticks < position)[0][-1] |
| 674 |
if mode == IndexMode.GreaterOrEqual: |
| 675 |
return np.where(ticks >= position)[0][0] |
| 676 |
|
| 677 |
raise ValueError("Unknown IndexMode: {}".format(mode)) |
| 678 |
|
| 679 |
def range_indices(self, start_position, end_position, mode=SliceMode.Exclusive): |
| 680 |
""" |
| 681 |
Returns the start and end indices in this dimension that are matching to the given start and end position. |
| 682 |
|
| 683 |
:param start_position: the start position of the range. |
| 684 |
:type start_position: float |
| 685 |
:param end_position: the end position of the range. |
| 686 |
:type end_position: float |
| 687 |
:param mode: The nixio.SliceMode. Defaults to nixio.SliceMode.Exclusive, i.e. the end position is not part of the range. |
| 688 |
:type mode: nixio.SliceMode |
| 689 |
|
| 690 |
:returns: The respective start and end indices. None, if range is empty |
| 691 |
:rtype: tuple of int |
| 692 |
|
| 693 |
:raises: ValueError if invalid mode is given |
| 694 |
:raises: Index Error if start position is greater than end position. |
| 695 |
""" |
| 696 |
if mode not in (SliceMode.Exclusive, SliceMode.Inclusive): |
| 697 |
raise ValueError("Unknown SliceMode: {}".format(mode)) |
| 698 |
if start_position > end_position: |
| 699 |
raise IndexError("Start position {} is greater than end position {}.".format(start_position, end_position)) |
| 700 |
ticks = self.ticks |
| 701 |
end_mode = IndexMode.Less if mode == SliceMode.Exclusive else IndexMode.LessOrEqual |
| 702 |
try: |
| 703 |
start_index = self.index_of(start_position, mode=IndexMode.GreaterOrEqual, ticks=ticks) |
| 704 |
end_index = self.index_of(end_position, mode=end_mode, ticks=ticks) |
| 705 |
except IndexError: |
| 706 |
return None |
| 707 |
if start_index > end_index: |
| 708 |
return None |
| 709 |
return (start_index, end_index) |
| 710 |
|
| 711 |
def tick_at(self, index): |
| 712 |
""" |
| 713 |
Returns the tick at the given index. Will throw an Exception if the |
| 714 |
index is out of bounds. |
| 715 |
|
| 716 |
:param index: The index. |
| 717 |
|
| 718 |
:returns: The corresponding position. |
| 719 |
:rtype: double |
| 720 |
""" |
| 721 |
ticks = list(self.ticks) |
| 722 |
return ticks[index] |
| 723 |
|
| 724 |
def axis(self, count, start=0): |
| 725 |
""" |
| 726 |
Get an axis as defined by this range dimension. |
| 727 |
|
| 728 |
:param count: A positive integer specifying the length of the axis |
| 729 |
(no of points). |
| 730 |
|
| 731 |
:param start: positive integer, indicates the starting tick. |
| 732 |
|
| 733 |
:returns: The created axis |
| 734 |
:rtype: list |
| 735 |
""" |
| 736 |
ticks = self.ticks |
| 737 |
end = start + count |
| 738 |
if end > len(ticks): |
| 739 |
raise IndexError("RangeDimension.axis: Count is invalid, " |
| 740 |
"reaches beyond the ticks stored in this " |
| 741 |
"dimension.") |
| 742 |
return ticks[start:end] |
| 743 |
|
| 744 |
|
| 745 |
class SetDimension(Dimension): |
| 746 |
|
| 747 |
def __init__(self, data_array, index): |
| 748 |
nixfile = data_array.file |
| 749 |
super(SetDimension, self).__init__(nixfile, data_array, index) |
| 750 |
|
| 751 |
@classmethod |
| 752 |
def create_new(cls, data_array, index): |
| 753 |
newdim = cls(data_array, index) |
| 754 |
newdim._set_dimension_type(DimensionType.Set) |
| 755 |
return newdim |
| 756 |
|
| 757 |
@property |
| 758 |
def labels(self): |
| 759 |
if self.has_link: |
| 760 |
labels = self.dimension_link.values |
| 761 |
else: |
| 762 |
labels = self._h5group.get_data("labels") |
| 763 |
|
| 764 |
if len(labels) and isinstance(labels[0], bytes): |
| 765 |
labels = tuple(label.decode() for label in labels) |
| 766 |
|
| 767 |
return tuple(labels) |
| 768 |
|
| 769 |
@labels.setter |
| 770 |
def labels(self, labels): |
| 771 |
if self.has_link: |
| 772 |
raise RuntimeError("The labels of a SetDimension linked to a " |
| 773 |
"data object cannot be modified") |
| 774 |
dt = util.vlen_str_dtype |
| 775 |
if not hasattr(labels, '__iter__') or isinstance(labels, str): |
| 776 |
raise ValueError('`labels` has to be a list-like object.') |
| 777 |
for label in labels: |
| 778 |
if not isinstance(label, str): |
| 779 |
raise ValueError(f'`labels` has to contain string objects, not {type(label)}') |
| 780 |
if not isinstance(labels, list): |
| 781 |
labels = list(labels) |
| 782 |
self._h5group.write_data("labels", labels, dtype=dt) |
| 783 |
|
| 784 |
def index_of(self, position, mode=IndexMode.LessOrEqual, dim_labels=None): |
| 785 |
""" |
| 786 |
Returns the index of a certain position in the dimension. |
| 787 |
Raises IndexError if the position is out of bounds (depending on mode and number of labels). |
| 788 |
|
| 789 |
:param position: The position. |
| 790 |
:param mode: The IndexMode to use (default LessOrEqual). |
| 791 |
The modes LessOrEqual and GreaterOrEqual will return the integer representation of the position if |
| 792 |
it is equal to the nearest integer. |
| 793 |
If the position is not an integer (or is not equal to the nearest integer), then the value is |
| 794 |
rounded down (for LessOrEqual) or rounded up (for GreaterOrEqual). |
| 795 |
If the mode is Less, the previous integer is always returned. |
| 796 |
:param dim_labels: The labels of this dimension, if None (default) the labels will be read from file. |
| 797 |
:type dim_labels: iterable |
| 798 |
|
| 799 |
:returns: The matching index |
| 800 |
:rtype: int |
| 801 |
""" |
| 802 |
if position < 0: |
| 803 |
if mode == IndexMode.GreaterOrEqual: |
| 804 |
return 0 |
| 805 |
|
| 806 |
raise IndexError("Position {} is out of bounds for SetDimension with mode {}".format(position, mode.name)) |
| 807 |
|
| 808 |
if position == 0 and mode == IndexMode.Less: |
| 809 |
raise IndexError("Position {} is out of bounds for SetDimension with mode {}".format(position, mode.name)) |
| 810 |
|
| 811 |
if dim_labels is None: |
| 812 |
dim_labels = self.labels |
| 813 |
if dim_labels and len(dim_labels) and position > len(dim_labels) - 1: |
| 814 |
if mode in (IndexMode.Less, IndexMode.LessOrEqual): |
| 815 |
return len(dim_labels) - 1 |
| 816 |
raise IndexError("Position {} is out of bounds for SetDimension with length {} and mode {}".format( |
| 817 |
position, len(dim_labels), mode.name |
| 818 |
)) |
| 819 |
|
| 820 |
index = int(np.floor(position)) |
| 821 |
if np.isclose(position, index): |
| 822 |
|
| 823 |
if mode in (IndexMode.GreaterOrEqual, IndexMode.LessOrEqual): |
| 824 |
|
| 825 |
return index |
| 826 |
if mode == IndexMode.Less: |
| 827 |
|
| 828 |
return index - 1 |
| 829 |
raise ValueError("Unknown IndexMode: {}".format(mode)) |
| 830 |
|
| 831 |
if mode == IndexMode.GreaterOrEqual: |
| 832 |
return index + 1 |
| 833 |
if mode in (IndexMode.LessOrEqual, IndexMode.Less): |
| 834 |
return index |
| 835 |
|
| 836 |
raise ValueError("Unknown IndexMode: {}".format(mode)) |
| 837 |
|
| 838 |
def range_indices(self, start_position, end_position, mode=SliceMode.Exclusive): |
| 839 |
""" |
| 840 |
Returns the start and end indices in this dimension that are matching to the given start and end position. |
| 841 |
|
| 842 |
:param start_position: the start position of the range. |
| 843 |
:type start_position: float |
| 844 |
:param end_position: the end position of the range. |
| 845 |
:type end_position: float |
| 846 |
:param mode: The nixio.SliceMode. Defaults to nixio.SliceMode.Exclusive, i.e. the end position is not part of the range. |
| 847 |
:type mode: nixio.SliceMode |
| 848 |
|
| 849 |
:returns: The respective start and end indices. None, if the range is empty |
| 850 |
:rtype: tuple of int |
| 851 |
|
| 852 |
:raises: ValueError if invalid mode is given |
| 853 |
:raises: Index Error if start position is greater than end position. |
| 854 |
""" |
| 855 |
if mode is not SliceMode.Exclusive and mode is not SliceMode.Inclusive: |
| 856 |
raise ValueError("Unknown SliceMode: {}".format(mode)) |
| 857 |
|
| 858 |
dim_labels = self.labels |
| 859 |
end_mode = IndexMode.Less if mode == SliceMode.Exclusive else IndexMode.LessOrEqual |
| 860 |
if start_position > end_position: |
| 861 |
raise IndexError("Start position {} is greater than end position {}.".format(start_position, end_position)) |
| 862 |
try: |
| 863 |
start = self.index_of(start_position, mode=IndexMode.GreaterOrEqual, dim_labels=dim_labels) |
| 864 |
end = self.index_of(end_position, mode=end_mode, dim_labels=dim_labels) |
| 865 |
except IndexError: |
| 866 |
return None |
| 867 |
if start > end: |
| 868 |
return None |
| 869 |
return (start, end) |