Debian Codegraph @

nixio/block.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright © 2014, 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
10 from sys import maxsize
11
12 import numpy as np
13 from inspect import isclass
14 try:
15 from collections.abc import OrderedDict
16 except ImportError:
17 from collections import OrderedDict
18
19 from .util import find as finders
20 from .compression import Compression
21
22 from .entity import Entity
23 from .exceptions import exceptions
24 from .group import Group
25 from .data_array import DataArray
26 from .data_frame import DataFrame
27 from .multi_tag import MultiTag
28 from .tag import Tag
29 from .source import Source
30 from . import util
31 from .container import Container, SourceContainer
32 from .section import Section
33
34
35 class Block(Entity):
36
37 def __init__(self, nixfile, nixparent, h5group,
38 compression=Compression.Auto):
39 super(Block, self).__init__(nixfile, nixparent, h5group)
40 self._groups = None
41 self._data_arrays = None
42 self._tags = None
43 self._multi_tags = None
44 self._sources = None
45 self._compr = compression
46 self._data_frames = None
47
48 @classmethod
49 def create_new(cls, nixparent, h5parent, name, type_, compression):
50 nixfile = nixparent # file is parent
51 newentity = super(Block, cls).create_new(nixfile, nixparent, h5parent,
52 name, type_)
53 newentity._compr = compression
54 return newentity
55
56 # MultiTag
57 def create_multi_tag(self, name="", type_="", positions=None,
58 extents=None, copy_from=None, keep_copy_id=True):
59 """
60 Create/copy a new multi tag for this block.
61
62 :param name: The name of the tag to create/copy.
63 :type name: str
64 :param type_: The type of tag.
65 :type type_: str
66 :param positions: A data array defining all positions of the tag.
67 :type positions: nixio.DataArray
68 :param copy_from: The MultiTag to be copied, None in normal mode
69 :type copy_from: nixio.MultiTag
70 :param keep_copy_id: Specify if the id should be copied in copy mode
71 :type keep_copy_id: bool
72
73 :returns: The newly created tag.
74 :rtype: nixio.MultiTag
75 """
76 if copy_from:
77 if not isinstance(copy_from, MultiTag):
78 raise TypeError("Object to be copied is not a MultiTag")
79 objid = self._copy_objects(copy_from, "multi_tags", keep_copy_id, name)
80 return self.multi_tags[objid]
81
82 util.check_entity_name_and_type(name, type_)
83 multi_tags = self._h5group.open_group("multi_tags")
84 if name in multi_tags:
85 raise exceptions.DuplicateName("create_multi_tag")
86 poscreated = False
87 extcreated = False
88 try:
89 if not isinstance(positions, DataArray):
90 da_name = "{}-positions".format(name)
91 positions = self.create_data_array(
92 da_name, "{}-positions".format(type_), data=positions
93 )
94 poscreated = True
95 if not isinstance(extents, DataArray) and extents is not None:
96 da_name = "{}-extents".format(name)
97 extents = self.create_data_array(da_name,
98 "{}-extents".format(type_),
99 data=extents)
100 extcreated = True
101 mtag = MultiTag.create_new(self.file, self, multi_tags,
102 name, type_, positions)
103 except Exception as exp:
104 msg = "MultiTag Creation Failed"
105 if poscreated:
106 del self.data_arrays["{}-positions".format(name)]
107 else:
108 msg += " due to invalid positions"
109 if extcreated:
110 del self.data_arrays["{}-extents".format(name)]
111 elif poscreated and not extcreated:
112 msg += " due to invalid extents"
113 print(msg)
114 raise exp
115
116 if extents is not None:
117 mtag.extents = extents
118 return mtag
119
120 # Tag
121 def create_tag(self, name="", type_="", position=0,
122 copy_from=None, keep_copy_id=True):
123 """
124 Create/copy a new tag for this block.
125
126 :param name: The name of the tag to create/copy.
127 :type name: str
128 :param type_: The type of tag.
129 :type type_: str
130 :param position: Coordinates of the start position
131 in units of the respective data dimension.
132 :param copy_from: The Tag to be copied, None in normal mode
133 :type copy_from: nixio.Tag
134 :param keep_copy_id: Specify if the id should be copied in copy mode
135 :type keep_copy_id: bool
136
137 :returns: The newly created tag.
138 :rtype: nixio.Tag
139 """
140 if copy_from:
141 if not isinstance(copy_from, Tag):
142 raise TypeError("Object to be copied is not a Tag")
143 objid = self._copy_objects(copy_from, "tags", keep_copy_id, name)
144 return self.tags[objid]
145
146 util.check_entity_name_and_type(name, type_)
147 tags = self._h5group.open_group("tags")
148 if name in tags:
149 raise exceptions.DuplicateName("create_tag")
150 tag = Tag.create_new(self.file, self, tags, name, type_, position)
151 return tag
152
153 # Source
154 def create_source(self, name, type_):
155 """
156 Create a new source on this block.
157
158 :param name: The name of the source to create.
159 :type name: str
160 :param type_: The type of the source.
161 :type type_: str
162
163 :returns: The newly created source.
164 :rtype: nixio.Source
165 """
166 util.check_entity_name_and_type(name, type_)
167 sources = self._h5group.open_group("sources")
168 if name in sources:
169 raise exceptions.DuplicateName("create_source")
170 src = Source.create_new(self.file, self, sources, name, type_)
171 return src
172
173 # Group
174 def create_group(self, name, type_):
175 """
176 Create a new group on this block.
177
178 :param name: The name of the group to create.
179 :type name: str
180 :param type_: The type of the group.
181 :type type_: str
182
183 :returns: The newly created group.
184 :rtype: nixio.Group
185 """
186 util.check_entity_name_and_type(name, type_)
187 groups = self._h5group.open_group("groups")
188 if name in groups:
189 raise exceptions.DuplicateName("open_group")
190 grp = Group.create_new(self.file, self, groups, name, type_)
191 return grp
192
193 def create_data_array(self, name="", array_type="", dtype=None, shape=None,
194 data=None, compression=Compression.Auto,
195 copy_from=None, keep_copy_id=True, label=None, unit=None):
196 """
197 Create/copy a new data array for this block. Either ``shape``
198 or ``data`` must be given. If both are given their shape must agree.
199 If ``dtype`` is not specified it will default to 64-bit floating
200 points.
201
202 :param name: The name of the data array to create/copy.
203 :type name: str
204 :param array_type: The type of the data array.
205 :type array_type: str
206 :param dtype: Which data-type to use for storage
207 :type dtype: :class:`numpy.dtype`
208 :param shape: Layout (dimensionality and extent)
209 :type shape: tuple of int or long
210 :param data: Data to write after storage has been created
211 :type data: array-like data
212 :param compression: En-/disable dataset compression.
213 :type compression: :class:`~nixio.Compression`
214 :param copy_from: The DataArray to be copied, None in normal mode
215 :type copy_from: nixio.DataArray
216 :param keep_copy_id: Specify if the id should be copied in copy mode
217 :type keep_copy_id: bool
218 :param label: The label, defaults to None.
219 :type label: str
220 :param unit: The unit of the stored data. Defaults to None.
221 :type unit: str
222
223 :returns: The newly created data array.
224 :rtype: :class:`~nixio.DataArray`
225 """
226
227 if copy_from:
228 if not isinstance(copy_from, DataArray):
229 raise TypeError("Object to be copied is not a DataArray")
230 objid = self._copy_objects(copy_from, "data_arrays", keep_copy_id, name)
231 return self.data_arrays[objid]
232
233 if data is None:
234 if shape is None:
235 raise ValueError("Either shape and or data must not be None")
236 if dtype is None:
237 dtype = 'f8'
238 else:
239 data = np.ascontiguousarray(data)
240 if dtype is None:
241 dtype = data.dtype
242 if shape is not None:
243 if shape != data.shape:
244 raise ValueError("Shape must equal data.shape")
245 else:
246 shape = data.shape
247 util.check_entity_name_and_type(name, array_type)
248 data_arrays = self._h5group.open_group("data_arrays")
249 if name in data_arrays:
250 raise exceptions.DuplicateName("create_data_array")
251 if compression == Compression.Auto:
252 compression = self._compr
253 da = DataArray.create_new(self.file, self, data_arrays, name, array_type,
254 dtype, shape, compression)
255 if data is not None:
256 da.write_direct(data)
257 da.unit = unit
258 da.label = label
259 return da
260
261 def create_data_frame(self, name="", type_="", col_dict=None,
262 col_names=None, col_dtypes=None, data=None,
263 compression=Compression.No,
264 copy_from=None, keep_copy_id=True):
265 """
266 Create/copy a new data frame for this block. Either ``col_dict``
267 or ``col_name`` and ``col_dtypes`` must be given.
268 If both are given, ``col_dict`` will be used.
269
270 :param name: The name of the data frame to create/copy.
271 :type name: str
272 :param type_: The type of the data frame.
273 :type type_: str
274 :param col_dict: The dictionary that specifies column
275 names and data type in each column
276 :type col_dict: dict or OrderedDict of {str: type}
277 :param col_names: The collection of name of all columns in order
278 :type col_names: tuples or list or np.array of string
279 :param col_dtypes: The collection of data type of all columns in order
280 :type col_dtypes: tuples or list or np.array of type
281 :param data: Data to write after storage has been created
282 :type data: array-like data with compound data type
283 as specified in the columns
284 :param compression: En-/disable dataset compression.
285 :type compression: :class:`~nixio.Compression`
286 :param copy_from: The DataFrame to be copied, None in normal mode
287 :type copy_from: nixio.DataFrame
288 :param keep_copy_id: Specify if the id should be copied in copy mode
289 :type keep_copy_id: bool
290
291 :returns: The newly created data frame.
292 :rtype: :class:`~nixio.DataFrame`
293 """
294 if copy_from:
295 if not isinstance(copy_from, DataFrame):
296 raise TypeError("Object to be copied is not a DataFrame")
297 objid = self._copy_objects(copy_from, "data_frames", keep_copy_id, name)
298 return self.data_frames[objid]
299
300 util.check_entity_name_and_type(name, type_)
301
302 if data is not None:
303 shape = len(data)
304 else:
305 shape = 0
306 data_frames = self._h5group.open_group("data_frames")
307
308 if col_dict is None:
309 if col_names is not None:
310 if col_dtypes is not None:
311 col_dict = OrderedDict(
312 (str(nam), dt)
313 for nam, dt in zip(col_names, col_dtypes)
314 )
315 elif col_dtypes is None and data is not None:
316 col_dtypes = []
317 for val in data[0]:
318 col_dtypes.append(type(val))
319 col_dict = OrderedDict(
320 (str(nam), dt)
321 for nam, dt in zip(col_names, col_dtypes)
322 )
323 else: # col_dtypes is None and data is None
324 raise ValueError(
325 "The data type of each column have to be specified"
326 )
327 if len(col_names) != len(col_dict):
328 raise exceptions.DuplicateColumnName
329 else: # if col_names is None
330 if data is not None and type(data[0]) == np.void:
331 col_dtype = data[0].dtype
332 col_names = list(col_dtype.fields.keys())
333 raw_dt = col_dtype.fields.values()
334 raw_dt = list(raw_dt)
335 raw_dt_list = [ele[0] for ele in raw_dt]
336 col_dict = OrderedDict(zip(col_names, raw_dt_list))
337 if len(col_dtype.fields.values()) != len(col_dict):
338 raise exceptions.DuplicateColumnName
339
340 else:
341 # data is None or type(data[0]) != np.void
342 # data_type doesnt matter
343 raise ValueError(
344 "No information about column names is provided!"
345 )
346
347 if col_dict is not None:
348 for nam, dt in col_dict.items():
349 if isclass(dt):
350 if issubclass(dt, (str, np.bytes_)):
351 col_dict[nam] = util.vlen_str_dtype
352 if 'U' in str(dt) or dt == np.bytes_:
353 col_dict[nam] = util.vlen_str_dtype
354 dt_arr = list(col_dict.items())
355 col_dtype = np.dtype(dt_arr)
356
357 df = DataFrame.create_new(self.file, self, data_frames, name,
358 type_, shape, col_dtype, compression)
359
360 if data is not None:
361 if type(data[0]) == np.void:
362 data = np.ascontiguousarray(data, dtype=col_dtype)
363 df.write_direct(data)
364 else:
365 data = list(map(tuple, data))
366 arr = np.ascontiguousarray(data, dtype=col_dtype)
367 df.write_direct(arr)
368 return df
369
370 def find_sources(self, filtr=lambda _: True, limit=None):
371 """
372 Get all sources in this block recursively.
373
374 This method traverses the tree of all sources in the block. The
375 traversal is accomplished via breadth first and can be limited in
376 depth. On each node or source a filter is applied. If the filter
377 returns true the respective source will be added to the result list.
378 By default a filter is used that accepts all sources.
379
380 :param filtr: A filter function
381 :type filtr: function
382 :param limit: The maximum depth of traversal
383 :type limit: int
384
385 :returns: A list containing the matching sources.
386 :rtype: list of nixio.Source
387 """
388 if limit is None:
389 limit = maxsize
390 return finders._find_sources(self, filtr, limit)
391
392 def pprint(self, indent=2, max_length=120, extra=True, start_depth=0):
393 """
394 Pretty Printing the Data and MetaData Tree of the whole File
395
396 :param indent: The length of one indentation space
397 :type indent: int
398 :param max_length: Maximum length of each line of output
399 :type max_length: int
400 :param extra: True to print extra information of Entities
401 :type extra: bool
402 :param start_depth: Starting depth of indentation
403 :type start_depth: int
404 """
405 print("{}{}".format(" " * indent*start_depth, self))
406 for grp in self.groups:
407 self._pp(grp, max_length, indent*(start_depth + 1), False)
408 for da in grp.data_arrays:
409 self._pp(da, max_length, indent*(start_depth + 2),
410 extra, True)
411 for dim in da.dimensions:
412 self._pp(dim, max_length, indent*(start_depth + 3), False)
413 for df in grp.data_frames:
414 self._pp(df, max_length,
415 indent*(start_depth + 2), extra, True)
416 for tag in grp.tags:
417 self._pp(tag, max_length,
418 indent*(start_depth + 2), extra, True)
419 for feat in tag.features:
420 self._pp(feat, max_length, indent*(start_depth + 3), False)
421 for mt in grp.multi_tags:
422 self._pp(mt, max_length, indent*(start_depth + 2), extra, True)
423 for feat in mt.features:
424 self._pp(feat, max_length, indent*(start_depth + 3), False)
425 for da in self.data_arrays:
426 self._pp(da, max_length, indent*(start_depth + 1), extra)
427 for dim in da.dimensions:
428 self._pp(dim, max_length, indent*(start_depth + 2), False)
429 for df in self.data_frames:
430 self._pp(df, max_length, indent*(start_depth + 1), extra)
431 for tag in self.tags:
432 self._pp(tag, max_length, indent*(start_depth + 1), extra)
433 for feat in tag.features:
434 self._pp(feat, max_length, indent*(start_depth + 2), False)
435 for mt in self.multi_tags:
436 self._pp(mt, max_length, indent*(start_depth + 1), extra)
437 for feat in mt.features:
438 self._pp(feat, max_length, indent*(start_depth + 2), False)
439
440 @staticmethod
441 def _pp(obj, max_len, indent, extra, grp=False):
442 spaces = " "*(indent)
443 if grp:
444 prefix = "*"
445 else:
446 prefix = ""
447 if extra:
448 stat = ""
449 if isinstance(obj, MultiTag):
450 stat = "Position Shape:{} Units: {}".format(
451 obj.positions.shape,
452 obj.units)
453 elif isinstance(obj, Tag):
454 stat = "Position Length:{} Units: {}".format(len(obj.position),
455 obj.units)
456 elif isinstance(obj, DataFrame):
457 stat = "Shape: {} Columns:{}".format(obj.shape,
458 obj.column_names)
459 elif isinstance(obj, DataArray):
460 stat = "Shape: {} Unit:{}".format(obj.shape, obj.unit)
461 objstr = "{}{}{}".format(spaces, prefix, obj)
462 stat = "{} {}".format(spaces, stat)
463 else:
464 objstr = "{}{}{}".format(spaces, prefix, obj)
465 if len(objstr) > max_len - 4:
466 split_len = int(max_len/2)
467 str1 = objstr[0:split_len]
468 str2 = objstr[-split_len:]
469 print("{} ... {}".format(str1, str2))
470 else:
471 print(objstr)
472 if extra:
473 if len(stat) > max_len - 4:
474 split_len = int(max_len/2)
475 nstr1 = stat[0:split_len]
476 nstr2 = stat[-split_len:]
477 print("{} ... {}".format(nstr1, nstr2))
478 else:
479 print(stat)
480
481 def _copy_objects(self, obj, clsname, keep_id=True, name=""):
482 src = "{}/{}".format(clsname, obj.name)
483 if not name:
484 name = str(obj.name)
485 ogrp = self._h5group.open_group(clsname, True)
486 if name in ogrp:
487 raise NameError("Name already exist. Possible solution is to "
488 "provide a new name when copying destination "
489 "is the same as the source parent")
490 obj_copy = obj._parent._h5group.copy(source=src, dest=self._h5group, name=name, cls=clsname, keep_id=keep_id)
491 return obj_copy.attrs["entity_id"]
492
493 @property
494 def sources(self):
495 """
496 A property containing all sources of a block. Sources can be obtained
497 via their index or by their id. Sources can be deleted from the list.
498 Adding sources is done using the Blocks create_source method.
499 This is a read only attribute.
500 """
501 if self._sources is None:
502 self._sources = SourceContainer("sources", self.file, self, Source)
503 return self._sources
504
505 @property
506 def multi_tags(self):
507 """
508 A property containing all multi tags of a block. MultiTag entities can
509 be obtained via their index or by their id. Tags can be deleted from
510 the list. Adding tags is done using the Blocks create_multi_tag method.
511 This is a read only attribute.
512 """
513 if self._multi_tags is None:
514 self._multi_tags = Container("multi_tags", self.file,
515 self, MultiTag)
516 return self._multi_tags
517
518 @property
519 def tags(self):
520 """
521 A property containing all tags of a block. Tag entities can be obtained
522 via their index or by their id. Tags can be deleted from the list.
523 Adding tags is done using the Blocks create_tag method.
524 This is a read only attribute.
525 """
526 if self._tags is None:
527 self._tags = Container("tags", self.file, self, Tag)
528 return self._tags
529
530 @property
531 def data_arrays(self):
532 """
533 A property containing all data arrays of a block. DataArray entities
534 can be obtained via their index or by their id. Data arrays can be
535 deleted from the list. Adding a data array is done using the Blocks
536 create_data_array method.
537 This is a read only attribute.
538 """
539 if self._data_arrays is None:
540 self._data_arrays = Container("data_arrays", self.file,
541 self, DataArray)
542 return self._data_arrays
543
544 @property
545 def data_frames(self):
546 if self._data_frames is None:
547 self._data_frames = Container("data_frames", self.file,
548 self, DataFrame)
549 return self._data_frames
550
551 @property
552 def groups(self):
553 """
554 A property containing all groups of a block. Group entities can be
555 obtained via their index or by their id. Groups can be deleted from the
556 list. Adding a Group is done using the Blocks create_group method.
557 This is a read only attribute.
558 """
559 if self._groups is None:
560 self._groups = Container("groups", self.file, self, Group)
561 return self._groups
562
563 # metadata
564 @property
565 def metadata(self):
566 """
567 Associated metadata of the entity. Sections attached to the entity via
568 this attribute can provide additional annotations. This is an optional
569 read-write property, and can be None if no metadata is available.
570
571 :type: nixio.Section
572 """
573 if "metadata" in self._h5group:
574 return Section(self.file, None,
575 self._h5group.open_group("metadata"))
576 else:
577 return None
578
579 @metadata.setter
580 def metadata(self, sect):
581 if not isinstance(sect, Section):
582 raise TypeError("{} is not of type Section".format(sect))
583 self._h5group.create_link(sect, "metadata")
584
585 @metadata.deleter
586 def metadata(self):
587 if "metadata" in self._h5group:
588 self._h5group.delete("metadata")