Debian Codegraph @

nixio/section.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 from sys import maxsize
10 try:
11 from collections.abc import Sequence, Iterable
12 except ImportError:
13 from collections import Sequence, Iterable
14
15 import numpy as np
16
17 from .container import Container, SectionContainer
18 from .datatype import DataType
19 from .entity import Entity
20 from .property import Property
21 from .util import find as finders
22 from . import util
23 from . import exceptions
24
25
26 class S: # pylint: disable=invalid-name
27 def __init__(self, section_type, section=None):
28 self.section_type = section_type
29 self.section = section
30
31 def __setitem__(self, key, value):
32 self.section[key] = value
33
34 def __setattr__(self, key, value):
35 if key in ['section_type', 'section']:
36 object.__setattr__(self, key, value)
37 else:
38 setattr(self.section, key, value)
39
40 def __getattribute__(self, item):
41 if item in ['section_type', 'section']:
42 return object.__getattribute__(self, item)
43
44 return getattr(self.section, item)
45
46
47 class Section(Entity):
48
49 def __init__(self, nixfile, nixparent, h5group):
50 super(Section, self).__init__(nixfile, nixparent, h5group)
51 self._sec_parent = None
52 self._sections = None
53 self._properties = None
54
55 @classmethod
56 def create_new(cls, nixfile, nixparent, h5parent, name, type_, oid=None):
57 newentity = super(Section, cls).create_new(nixfile, nixparent,
58 h5parent, name, type_)
59 if util.is_uuid(oid):
60 newentity._h5group.set_attr("entity_id", oid)
61
62 return newentity
63
64 # Section
65 def create_section(self, name, type_="undefined", oid=None):
66 """
67 Creates a new subsection that is a child of this section entity.
68
69 :param name: The name of the section to create.
70 :type name: str
71 :param type_: The type of the section.
72 :type type_: str
73 :param oid: object id, UUID string as specified in RFC 4122. If no id
74 is provided, an id will be generated and assigned.
75 :type oid: str
76
77 :returns: The newly created section.
78 :rtype: nixio.Section
79 """
80 util.check_entity_name_and_type(name, type_)
81 sections = self._h5group.open_group("sections", True)
82 if name in sections:
83 raise exceptions.DuplicateName("create_section")
84 sec = Section.create_new(self.file, self, sections, name, type_, oid)
85 sec._sec_parent = self
86 return sec
87
88 # Property
89 def create_property(self, name="", values_or_dtype=0, oid=None,
90 copy_from=None, keep_copy_id=True):
91 """
92 Add a new property to the section.
93
94 :param name: The name of the property to create/copy.
95 :type name: str
96 :param values_or_dtype: The values of the property or a valid DataType.
97 :type values_or_dtype: list of values or a nixio.DataType
98 :param oid: object id, UUID string as specified in RFC 4122. If no id
99 is provided, an id will be generated and assigned.
100 :type oid: str
101 :param copy_from: The Property to be copied, None in normal mode
102 :type copy_from: nixio.Property
103 :param keep_copy_id: Specify if the id should be copied in copy mode
104 :type keep_copy_id: bool
105
106 :returns: The newly created property.
107 :rtype: nixio.Property
108 """
109 if copy_from:
110 if not isinstance(copy_from, Property):
111 raise TypeError("Object to be copied is not a Property")
112 clsname = "properties"
113 src = "{}/{}".format(clsname, copy_from.name)
114 if not name:
115 name = str(copy_from.name)
116 properties = self._h5group.open_group("properties", True)
117 if name in properties:
118 raise NameError("Name already exist. Possible solution is to "
119 "provide a new name when copying destination "
120 "is the same as the source parent")
121 objcopy = copy_from._parent._h5group.copy(source=src, dest=self._h5group, name=name,
122 cls=clsname, keep_id=keep_copy_id)
123
124 id_ = objcopy.attrs["entity_id"]
125 return self.props[id_]
126
127 vals = values_or_dtype
128
129 properties = self._h5group.open_group("properties", True)
130 if name in properties:
131 raise exceptions.DuplicateName("create_property")
132
133 # Handle handed in DataType
134 if isinstance(vals, type):
135 dtype = vals
136 vals = []
137
138 # In case of values, make sure boolean value 'False' gets through as
139 # well, but ensure that empty values are not allowed, we need a
140 # DataType.
141 elif vals is None or (isinstance(vals, (Sequence, Iterable)) and not len(vals)):
142 raise TypeError("Please provide either a non empty value or a DataType.")
143
144 else:
145 # Make sure all values are of the same data type
146 single_val = vals
147 if (isinstance(vals, (Sequence, Iterable)) and
148 not isinstance(vals, str)):
149 single_val = vals[0]
150 else:
151 # Make sure the data will always be created with an array.
152 vals = [vals]
153
154 # Will raise an error, if the datatype of the first value is not
155 # valid.
156 dtype = DataType.get_dtype(single_val)
157
158 # Check all values for data type consistency to ensure clean value
159 # add. Will raise an exception otherwise.
160 for val in vals:
161 if DataType.get_dtype(val) != dtype:
162 raise TypeError("Array contains inconsistent values.")
163 shape = (len(vals),)
164
165 prop = Property.create_new(self.file, self, properties,
166 name, dtype, shape, oid)
167 prop.values = vals
168
169 return prop
170
171 def copy_section(self, obj, children=True, keep_id=True, name=""):
172 """
173 Copy a section to the section.
174
175 :param obj: The Section to be copied
176 :type obj: nixio.Section
177 :param children: Specify if the copy should be recursive
178 :type children: bool
179 :param keep_id: Specify if the id should be kept
180 :type keep_id: bool
181 :param name: Name of copied section, Default is name of source section
182 :type name: str
183
184 :returns: The copied section
185 :rtype: nixio.Section
186 """
187 if not isinstance(obj, Section):
188 raise TypeError("Object to be copied is not a Section")
189
190 if obj._sec_parent:
191 src = "{}/{}".format("sections", obj.name)
192 else:
193 src = "{}/{}".format("metadata", obj.name)
194
195 clsname = "sections"
196 if not name:
197 name = str(obj.name)
198 sec = self._h5group.open_group("sections", True)
199 if name in sec:
200 raise NameError("Name already exist. Possible solution is to "
201 "provide a new name when copying destination "
202 "is the same as the source parent")
203 sec = obj._parent._h5group.copy(source=src, dest=self._h5group,
204 name=name, cls=clsname,
205 keep_id=keep_id)
206
207 if not children:
208 for prop in obj.props:
209 self.sections[obj.name].create_property(copy_from=prop, keep_copy_id=keep_id)
210
211 return self.sections[sec.attrs["entity_id"]]
212
213 @property
214 def reference(self):
215 return self._h5group.get_attr("reference")
216
217 @reference.setter
218 def reference(self, ref):
219 util.check_attr_type(ref, str)
220 self._h5group.set_attr("reference", ref)
221 if self.file.auto_update_timestamps:
222 self.force_updated_at()
223
224 @property
225 def link(self):
226 """
227 Link to another section. If a section is linked to another section,
228 the linking section inherits all properties from the target section.
229 This is an optional read-write property and may be set to None.
230
231 :type: nixio.Section
232 """
233 if "link" not in self._h5group:
234 return None
235
236 return Section(self.file, self, self._h5group.open_group("link"))
237
238 @link.setter
239 def link(self, id_or_sec):
240 if id_or_sec is None:
241 self._h5group.delete("link")
242 if isinstance(id_or_sec, Section):
243 sec = id_or_sec
244 else:
245 rootsec = Section(self.file, self, self._h5group.h5root)
246 sec = rootsec.find_sections(filtr=lambda x: x.id == id_or_sec)
247
248 self._h5group.create_link(sec, "link")
249 if self.file.auto_update_timestamps:
250 self.force_updated_at()
251
252 def inherited_properties(self):
253 properties = self._h5group.open_group("properties")
254 inhprops = [Property(self.file, self, h5prop) for h5prop in properties]
255 if self.link:
256 inhprops.extend(self.link.inherited_properties())
257 return inhprops
258
259 @property
260 def repository(self):
261 """
262 URL to the terminology repository the section is associated with.
263 This is an optional read-write property and may be set to None.
264
265 :type: str
266 """
267 return self._h5group.get_attr("repository")
268
269 @repository.setter
270 def repository(self, repo):
271 util.check_attr_type(repo, str)
272 self._h5group.set_attr("repository", repo)
273 if self.file.auto_update_timestamps:
274 self.force_updated_at()
275
276 @property
277 def parent(self):
278 """
279 The parent section. This is a read-only property. For root sections
280 this property is always None.
281
282 Accessing this property can be slow when the metadata tree is large.
283
284 :type: nixio.Section
285 """
286 if self._sec_parent is not None:
287 return self._sec_parent
288 # BFS
289 sections = list(self.file.sections)
290 if self in sections:
291 # Top-level section
292 return None
293
294 while sections:
295 sect = sections.pop(0)
296 if self in sect.sections:
297 self._sec_parent = sect
298 return sect
299 sections.extend(sect.sections)
300
301 return None
302
303 @property
304 def referring_objects(self):
305 objs = []
306 objs.extend(self.referring_blocks)
307 objs.extend(self.referring_groups)
308 objs.extend(self.referring_data_arrays)
309 objs.extend(self.referring_tags)
310 objs.extend(self.referring_multi_tags)
311 objs.extend(self.referring_sources)
312 return objs
313
314 @property
315 def referring_blocks(self):
316 nf = self.file
317 return list(blk for blk in nf.blocks
318 if blk.metadata is not None and blk.metadata.id == self.id)
319
320 @property
321 def referring_groups(self):
322 nf = self.file
323 groups = []
324 for blk in nf.blocks:
325 groups.extend(grp for grp in blk.groups
326 if (grp.metadata is not None and
327 grp.metadata.id == self.id))
328 return groups
329
330 @property
331 def referring_data_arrays(self):
332 nf = self.file
333 data_arrays = []
334 for blk in nf.blocks:
335 data_arrays.extend(da for da in blk.data_arrays
336 if (da.metadata is not None and
337 da.metadata.id == self.id))
338 return data_arrays
339
340 @property
341 def referring_tags(self):
342 nf = self.file
343 tags = []
344 for blk in nf.blocks:
345 tags.extend(tg for tg in blk.tags
346 if (tg.metadata is not None and
347 tg.metadata.id == self.id))
348 return tags
349
350 @property
351 def referring_multi_tags(self):
352 nf = self.file
353 multi_tags = []
354 for blk in nf.blocks:
355 multi_tags.extend(mt for mt in blk.multi_tags
356 if (mt.metadata is not None and
357 mt.metadata.id == self.id))
358 return multi_tags
359
360 @property
361 def referring_sources(self):
362 nf = self.file
363 sources = []
364 for blk in nf.blocks:
365 sources.extend(src for src in blk.sources
366 if (src.metadata is not None and
367 src.metadata.id == self.id))
368 return sources
369
370 def find_sections(self, filtr=lambda _: True, limit=None):
371 """
372 Get all child sections recursively.
373 This method traverses the trees of all sections. The traversal is
374 accomplished via breadth first and can be limited in depth.
375 On each node or section a filter is applied.
376 If the filter returns true the respective section will be added to the
377 result list. By default a filter is used that accepts all sections.
378
379 :param filtr: A filter function
380 :type filtr: function
381 :param limit: The maximum depth of traversal
382 :type limit: int
383
384 :returns: A list containing the matching sections.
385 :rtype: list of nixio.Section
386 """
387 if limit is None:
388 limit = maxsize
389 return finders._find_sections(self, filtr, limit)
390
391 def find_related(self, filtr=lambda _: True):
392 """
393 Get all related sections of this section.
394
395 The result can be filtered. On each related section a filter is
396 applied. If the filter returns true the respective section will be
397 added to the result list. By default a filter is used that accepts all
398 sections.
399
400 :param filtr: A filter function
401 :type filtr: function
402
403 :returns: A list containing the matching related sections.
404 :rtype: list of nixio.Section
405 """
406 result = []
407 if self.parent is not None:
408 result = finders._find_sections(self.parent, filtr, 1)
409 if self in result:
410 del result[result.index(self)]
411 result += finders._find_sections(self, filtr, 1)
412 return result
413
414 @property
415 def sections(self):
416 """
417 A property providing all child Sections of a Section. Child sections
418 can be accessed by name, index, or id. Sections can also be deleted:
419 if a Section is deleted, all its properties and child Sections are
420 removed from the file too. Adding new Sections is achieved using the
421 create_section method.
422 This is a read-only attribute.
423
424 :type: Container of nixio.Section
425 """
426 if self._sections is None:
427 self._sections = SectionContainer("sections", self.file,
428 self, Section)
429 return self._sections
430
431 def __len__(self):
432 return len(self.props)
433
434 def __getitem__(self, key):
435
436 if key not in self.props and key in self.sections:
437 return self.sections[key]
438
439 prop = self.props[key]
440 values = list(prop.values)
441 if len(values) == 1:
442 values = values[0]
443 return values
444
445 def __delitem__(self, key):
446 del self.props[key]
447
448 def __setitem__(self, key, data):
449
450 if isinstance(data, S):
451 data.section = self.create_section(key, data.section_type)
452 return
453
454 if not isinstance(data, list):
455 data = [data]
456
457 if key not in self.props:
458 self.create_property(key, data)
459 else:
460 prop = self.props[key]
461 prop.values = data
462
463 def __iter__(self):
464 for _, item in self.items():
465 yield item
466
467 def items(self):
468 for prop in self.props:
469 yield (prop.name, prop)
470 for sec in self.sections:
471 yield (sec.name, sec)
472
473 def __contains__(self, key):
474 return key in self.props or key in self.sections
475
476 @property
477 def props(self):
478 """
479 A property containing all Property entities associated with the
480 section. Properties can be accessed by name, index, or id.
481 Properties can be deleted from the list. Adding new Properties is done
482 using the create_property method.
483 This is a read-only attribute.
484
485 :type: Container of nixio.Property
486 """
487 if self._properties is None:
488 self._properties = Container("properties", self.file,
489 self, Property)
490 return self._properties
491
492 def pprint(self, indent=2, max_depth=-1, max_length=80, current_depth=0):
493 """
494 Pretty print method.
495
496 :param indent: The number of indentation spaces per recursion
497 :type indent: int
498 :param max_depth: The maximum times of recursion, -1 for the full depth
499 :type max_depth: int
500 :param max_length: The maximum length of each line of output
501 :type max_length: int
502 :param current_depth: The current times of recursion
503 :type current_depth: int
504 """
505
506 spaces = " " * (current_depth * indent)
507 sec_str = "{}{} [{}]".format(spaces, self.name, self.type)
508 print(sec_str)
509 for prop in self.props:
510 prop.pprint(current_depth=current_depth, indent=indent, max_length=max_length)
511 if max_depth == -1 or current_depth < max_depth:
512 for sec in self.sections:
513 sec.pprint(current_depth=current_depth + 1, max_depth=max_depth, indent=indent, max_length=max_length)
514 elif max_depth == current_depth:
515 child_sec_indent = spaces + " " * indent
516 more_indent = spaces + " " * (current_depth + 2 * indent)
517 for sec in self.sections:
518 print("{} {} [{}]\n{}[...]".format(child_sec_indent, sec.name, sec.type, more_indent))
519
520 @staticmethod
521 def _change_id(_, grp):
522 if "entity_id" in grp.attrs:
523 id_ = util.create_id()
524 grp.attrs.modify("entity_id", np.string_(id_))