Debian Codegraph @

nixio/data_array.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright © 2016, German Neuroinformatics Node (G-Node)
3 #
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted under the terms of the BSD License. See
8 # LICENSE file in the root of the Project.
9 import warnings
10 from numbers import Number
11 from enum import Enum
12 import numpy as np
13
14 from .data_view import DataView
15 from .data_set import DataSet
16 from .entity import Entity
17 from .source_link_container import SourceLinkContainer
18 from .datatype import DataType
19 from .dimensions import (Dimension, IndexMode, SampledDimension, RangeDimension,
20 SetDimension, DimensionType, DimensionContainer)
21 from . import util
22 from .compression import Compression
23
24 from .exceptions import IncompatibleDimensions
25 from .section import Section
26
27
28 class DataSliceMode(Enum):
29 Index = 1
30 Data = 2
31
32
33 class DataArray(Entity, DataSet):
34
35 def __init__(self, nixfile, nixparent, h5group):
36 super(DataArray, self).__init__(nixfile, nixparent, h5group)
37 self._sources = None
38 self._dimensions = None
39
40 @classmethod
41 def create_new(cls, nixfile, nixparent, h5parent, name, type_,
42 data_type, shape, compression):
43 newentity = super(DataArray, cls).create_new(nixfile, nixparent,
44 h5parent, name, type_)
45 datacompr = False
46 if compression == Compression.DeflateNormal:
47 datacompr = True
48 newentity._h5group.create_dataset("data", shape, data_type, datacompr)
49 return newentity
50
51 def _read_data(self, sl=None):
52 coeff = self.polynom_coefficients
53 origin = self.expansion_origin
54 data = np.array(super(DataArray, self)._read_data(sl))
55 if not len(data.shape):
56 # single value retrieval as length-1 array
57 data.shape = (1,)
58 if len(coeff) or origin:
59 if not origin:
60 origin = 0.0
61
62 # when there are coefficients or exp origin, convert the dtype of the returned data array to double
63 data = data.astype(DataType.Double)
64 util.apply_polynomial(coeff, origin, data)
65 return data
66
67 @property
68 def sources(self):
69 """
70 A property containing all Sources referenced by the DataArray. Sources
71 can be obtained by index or their id. Sources can be removed from the
72 list, but removing a referenced Source will not remove it from the
73 file. New Sources can be added using the append method of the list.
74 This is a read only attribute.
75 """
76 if self._sources is None:
77 self._sources = SourceLinkContainer(self)
78 return self._sources
79
80 def append_set_dimension(self, labels=None):
81 """
82 Append a new SetDimension to the list of existing dimension
83 descriptors.
84
85 :param labels: The set of sample labels
86 :type labels: list or convertible to list
87
88 :returns: The newly created SetDimension.
89 :rtype: nixio.SetDimension
90 """
91 index = len(self.dimensions) + 1
92 setdim = SetDimension.create_new(self, index)
93 if labels is not None:
94 setdim.labels = labels
95 if self.file.auto_update_timestamps:
96 self.force_updated_at()
97 return setdim
98
99 def append_sampled_dimension(self, sampling_interval, label=None,
100 unit=None, offset=None):
101 """
102 Append a new SampledDimension to the list of existing dimension
103 descriptors.
104
105 :param sampling_interval: The sampling interval of the SetDimension to create.
106 :type sampling_interval: float
107 :param label: The label of the dimension
108 :type label: str
109 :param unit: The physical unit of the dimension
110 :type unit: str
111 :param offset: The offset between 0 and the first sample
112 :type offset: float
113
114 :returns: The newly created SampledDimension.
115 :rtype: nixio.SampledDimension
116 """
117 index = len(self.dimensions) + 1
118 smpldim = SampledDimension.create_new(self, index, sampling_interval)
119 if label:
120 smpldim.label = label
121 if unit:
122 smpldim.unit = unit
123 if offset:
124 smpldim.offset = offset
125 if self.file.auto_update_timestamps:
126 self.force_updated_at()
127 return smpldim
128
129 def append_range_dimension(self, ticks=None, label=None, unit=None):
130 """
131 Append a new RangeDimension to the list of existing dimension
132 descriptors.
133
134 :param ticks: The ticks of the RangeDimension to create.
135 :type ticks: list of float
136 :param label: The label of the dimension
137 :type label: str
138 :param unit: The physical unit of the dimension
139 :type unit: str
140
141 :returns: The newly created RangeDimension.
142 :rtype: nixio.RangeDimension
143 """
144 index = len(self.dimensions) + 1
145
146 rdim = RangeDimension.create_new(self, index, ticks)
147 rdim.label = label
148 rdim.unit = unit
149 if self.file.auto_update_timestamps:
150 self.force_updated_at()
151 if ticks is not None:
152 rdim.ticks = ticks
153 return rdim
154
155 def append_range_dimension_using_self(self, index=None):
156 """
157 Convenience function to append a new RangeDimension to the list of
158 existing dimensions that uses the DataArray itself as provider for the ticks.
159 This is a replacement for
160 rdim = array.append_range_dimension()
161 rdim.link_data_array(self, index)
162
163 :param index: The slice of the DataArray that contains the tick values. This must be a vector of the data. Defaults to [-1], i.e. the full first dimension.
164 :type: list of int
165
166 :returns: the newly created nixio.RangeDimension
167 :rtype: nixio.RangeDimension
168 """
169 if index is None:
170 index = [0] * len(self.shape)
171 index[0] = -1
172 msg = RangeDimension._check_index(index)
173 if msg is not None:
174 raise ValueError(msg)
175
176 msg = RangeDimension._check_link_dimensionality(self, index)
177 if msg is not None:
178 raise IncompatibleDimensions(msg, "RangeDimension.append_range_dimension_using_self")
179
180 dim_index = len(self.dimensions) + 1
181 rdim = RangeDimension.create_new(self, dim_index, None)
182 rdim.link_data_array(self, index)
183 return rdim
184
185 def delete_dimensions(self):
186 """
187 Delete all the dimension descriptors for this DataArray.
188 """
189 dimgroup = self._h5group.open_group("dimensions")
190 ndims = len(dimgroup)
191 for idx in range(ndims):
192 del dimgroup[str(idx + 1)]
193 return True
194
195 def _dimension_count(self):
196 return len(self._h5group.open_group("dimensions"))
197
198 def _get_dimension_by_pos(self, index):
199 h5dim = self._h5group.open_group("dimensions").open_group(str(index))
200 dimtype = h5dim.get_attr("dimension_type")
201 if DimensionType(dimtype) == DimensionType.Sample:
202 return SampledDimension(h5dim, index)
203 elif DimensionType(dimtype) == DimensionType.Range:
204 return RangeDimension(h5dim, index)
205 elif DimensionType(dimtype) == DimensionType.Set:
206 return SetDimension(h5dim, index)
207 else:
208 raise TypeError("Invalid Dimension object in file.")
209
210 def iter_dimensions(self):
211 """
212 1-based index dimension iterator. The method returns a generator
213 which returns the index starting from one and the dimensions.
214 """
215 for idx, dim in enumerate(self.dimensions):
216 yield idx + 1, dim
217
218 @property
219 def dtype(self):
220 """
221 The data type of the data stored in the DataArray.
222 This is a read only property.
223
224 :return: The data type
225 :rtype: nixio.DataType
226 """
227 return self._h5group.group["data"].dtype
228
229 @property
230 def polynom_coefficients(self):
231 """
232 The polynomial coefficients for the calibration. By default this is
233 set to a {0.0, 1.0} for a linear calibration with zero offset.
234 This is a read-write property and can be set to None
235
236 :rtype: list of float
237 """
238 return tuple(self._h5group.get_data("polynom_coefficients"))
239
240 @polynom_coefficients.setter
241 def polynom_coefficients(self, coeff):
242 if not coeff:
243 if self._h5group.has_data("polynom_coefficients"):
244 del self._h5group["polynom_coefficients"]
245 else:
246 dtype = DataType.Double
247 self._h5group.write_data("polynom_coefficients", coeff, dtype)
248 if self.file.auto_update_timestamps:
249 self.force_updated_at()
250
251 @property
252 def expansion_origin(self):
253 """
254 The expansion origin of the calibration polynomial.
255 This is a read-write property and can be set to None.
256 The default value is 0.
257
258 :type: float
259 """
260 return self._h5group.get_attr("expansion_origin")
261
262 @expansion_origin.setter
263 def expansion_origin(self, origin):
264 util.check_attr_type(origin, Number)
265 self._h5group.set_attr("expansion_origin", origin)
266 if self.file.auto_update_timestamps:
267 self.force_updated_at()
268
269 @property
270 def label(self):
271 """
272 The label of the DataArray. The label corresponds to the label of the
273 x-axis of a plot. This is a read-write property and can be set to
274 None.
275
276 :type: str
277 """
278 return self._h5group.get_attr("label")
279
280 @label.setter
281 def label(self, label):
282 util.check_attr_type(label, str)
283 self._h5group.set_attr("label", label)
284 if self.file.auto_update_timestamps:
285 self.force_updated_at()
286
287 @property
288 def unit(self):
289 """
290 The unit of the values stored in the DataArray. This is a read-write
291 property and can be set to None.
292
293 :type: str
294 """
295 return self._h5group.get_attr("unit")
296
297 @unit.setter
298 def unit(self, unit):
299 if unit:
300 unit = util.units.sanitizer(unit)
301 if unit == "":
302 unit = None
303 util.check_attr_type(unit, str)
304 self._h5group.set_attr("unit", unit)
305 if self.file.auto_update_timestamps:
306 self.force_updated_at()
307
308 def get_slice(self, positions, extents=None, mode=DataSliceMode.Index):
309 """
310 Reads a slice of the data. The slice can be specified either in indices or in data coordinates.
311 For example, if the *DataArray* stores 1D data spanning one second in time sampled with 1kHz (1000 data points). If one wants to read the data of the interval 0.25 to 0.5 seconds, one can use either of the following statements:
312
313 ```
314 interval_data = data_array.get_slice([250], [500], mode=DataSliceMode.Index)[:]
315 interval_data = data_array.get_slice([0.25],[0.25], mode=DataSliceMode.Data)[:]
316 ```
317
318 Note: The extents are *not* the end positions but the extent of the slice!
319 In the case of regularly sampled dimensions, reaching beyond the start of end of the respective dimension will cause an exception. For irregularly sampled data no
320 exception will be raised but the returned DataView might be invalid and empty.
321
322 :param positions: Specifies the start of the data slice. List of either indices or data positions depending on the DataSliceMode.
323 :type positions: list length must match dimensionality of the data.
324 :param extents: Specifies the extents of the slice for each dimension.
325 :type extents: list, defaults to None
326 :param mode: Specifies how positions and extents are interpreted, they are either treated as indices (DataSliceMode.Index) or as positions in data coordinates (DataSliceMode.Data), Defaults to nixio.DataSliceMode.Index.
327 :type mode: nixio.DataSliceMode
328
329 :raises: nixio.IncompatibleDimensions: if length of positions or, if given, extents does not match the rank of the data.
330 :raises: ValueError: if an invalid slice mode is given
331
332 :returns: A nixio.DataView object
333 :rtype: nixio.DataView
334 """
335 datadim = len(self.shape)
336 if not len(positions) == datadim:
337 raise IncompatibleDimensions(
338 "Number of positions given ({}) does not match "
339 "number of data dimensions ({})".format(
340 len(positions), datadim
341 ),
342 "DataArray.get_slice"
343 )
344 if extents and not len(extents) == datadim:
345 raise IncompatibleDimensions(
346 "Number of extents given ({}) does not match "
347 "number of data dimensions ({})".format(
348 len(extents), datadim
349 ),
350 "DataArray.get_slice"
351 )
352 if mode == DataSliceMode.Index:
353 slices = tuple(slice(p, p + e) for p, e in zip(positions, extents))
354 return DataView(self, slices)
355 elif mode == DataSliceMode.Data:
356 return self._get_slice_bydim(positions, extents)
357 else:
358 raise ValueError("Invalid slice mode specified. "
359 "Supported modes are DataSliceMode.Index and "
360 "DataSliceMode.Data")
361
362 def _get_slice_bydim(self, positions, extents):
363 dpos, dext = [], []
364 for dim, pos, ext in zip(self.dimensions, positions, extents):
365 if dim.dimension_type == DimensionType.Sample:
366 start_pos = dim.index_of(pos, mode=IndexMode.GreaterOrEqual)
367 extent = dim.index_of(pos + ext) - start_pos
368 elif dim.dimension_type == DimensionType.Range:
369 try:
370 start_pos = dim.index_of(pos, mode=IndexMode.GreaterOrEqual)
371 extent = dim.index_of(pos + ext) - start_pos
372 except IndexError:
373 start_pos = -1
374 extent = -1
375 except Exception as e:
376 raise e
377 elif dim.dimension_type == DimensionType.Set:
378 start_pos = int(pos)
379 extent = int(ext)
380 else:
381 raise IncompatibleDimensions(f"Unknown dimension type: {dim.dimension_type}",
382 "data_array._get_slice_by_dim")
383
384 if extent < 0:
385 return DataView(self, None)
386 dpos.append(start_pos)
387 dext.append(extent)
388 slices = tuple(slice(p, p + e) for p, e in zip(dpos, dext))
389 return DataView(self, slices)
390
391 @property
392 def data(self):
393 """
394 DEPRECATED DO NOT USE ANYMORE! Returns self
395
396 :type: :class:`~nixio.data_array.DataArray`
397 """
398 warnings.warn("Call to deprecated property DataArray.data",
399 category=DeprecationWarning)
400 return self
401
402 @property
403 def dimensions(self):
404 """
405 A property containing all dimensions of a DataArray. Dimensions can be
406 obtained via their index. Adding dimensions is done using the
407 respective append methods for dimension descriptors.
408 This is a read only attribute.
409
410 :type: Container of dimension descriptors.
411 """
412 if self._dimensions is None:
413 self._dimensions = DimensionContainer("dimensions", self.file,
414 self, Dimension)
415 return self._dimensions
416
417 # metadata
418 @property
419 def metadata(self):
420 """
421
422 Associated metadata of the entity. Sections attached to the entity via
423 this attribute can provide additional annotations. This is an optional
424 read-write property, and can be None if no metadata is available.
425
426 :type: nixio.Section
427 """
428 if "metadata" in self._h5group:
429 return Section(self.file, None,
430 self._h5group.open_group("metadata"))
431 else:
432 return None
433
434 @metadata.setter
435 def metadata(self, sect):
436 if not isinstance(sect, Section):
437 raise TypeError("{} is not of type Section".format(sect))
438 self._h5group.create_link(sect, "metadata")
439
440 @metadata.deleter
441 def metadata(self):
442 if "metadata" in self._h5group:
443 self._h5group.delete("metadata")