Debian Codegraph @

nixio/file.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 import os
10 import gc
11 import numpy as np
12 from sys import maxsize
13 from warnings import warn
14
15 import h5py
16
17 from .hdf5.h5group import H5Group
18 from .block import Block
19 from .section import Section
20 from .container import Container, SectionContainer
21 from . import util
22 from .exceptions import InvalidFile, DuplicateName
23 from .util import find as finders
24 from . import validator
25 from .compression import Compression
26
27
28 FILE_FORMAT = "nix"
29 HDF_FF_VERSION = (1, 2, 1)
30
31
32 def can_write(nixfile):
33 filever = nixfile.version
34 if len(filever) != 3:
35 raise RuntimeError("Invalid version specified in file.")
36 if HDF_FF_VERSION == filever:
37 return True
38 else:
39 return False
40
41
42 def can_read(nixfile):
43 filever = nixfile.version
44 if len(filever) != 3:
45 raise RuntimeError("Invalid version specified in file.")
46 ver_x, ver_y, _ = HDF_FF_VERSION
47 file_x, file_y, _ = filever
48 if ver_x == file_x and ver_y >= file_y:
49 return True
50 else:
51 return False
52
53
54 class FileMode:
55 ReadOnly = 'r'
56 ReadWrite = 'a'
57 Overwrite = 'w'
58
59
60 def map_file_mode(mode):
61 if mode == FileMode.ReadOnly:
62 return h5py.h5f.ACC_RDONLY
63 elif mode == FileMode.ReadWrite:
64 return h5py.h5f.ACC_RDWR
65 elif mode == FileMode.Overwrite:
66 return h5py.h5f.ACC_TRUNC
67 else:
68 raise ValueError("Invalid file mode specified.")
69
70
71 def make_fapl():
72 return h5py.h5p.create(h5py.h5p.FILE_ACCESS)
73
74
75 def make_fcpl():
76 fcpl = h5py.h5p.create(h5py.h5p.FILE_CREATE)
77 flags = h5py.h5p.CRT_ORDER_TRACKED | h5py.h5p.CRT_ORDER_INDEXED
78 fcpl.set_link_creation_order(flags)
79 return fcpl
80
81
82 class File:
83
84 def __init__(self, path, mode=FileMode.ReadWrite,
85 compression=Compression.Auto,
86 auto_update_timestamps=True):
87 """
88 Open a NIX file, or create it if it does not exist.
89
90 :param path: Path to file
91 :param mode: FileMode ReadOnly, ReadWrite, or Overwrite.
92 (default: ReadWrite)
93 :param compression: No, DeflateNormal, Auto (default: Auto)
94 :param auto_update_timestamps: Enable/disable automatic updating of
95 'updated_at' timestamp. (default: True)
96
97 :return: nixio.File object
98 """
99 try:
100 path = path.encode("utf-8")
101 except (UnicodeError, LookupError):
102 pass
103
104 if not os.path.exists(path) and mode == FileMode.ReadOnly:
105 raise RuntimeError(
106 "Cannot open non-existent file in ReadOnly mode!"
107 )
108
109 if not os.path.exists(path) or mode == FileMode.Overwrite:
110 mode = FileMode.Overwrite
111 h5mode = map_file_mode(mode)
112 fid = h5py.h5f.create(path, flags=h5mode, fapl=make_fapl(),
113 fcpl=make_fcpl())
114 self._h5file = h5py.File(fid)
115 self._root = H5Group(self._h5file, "/", create=True)
116 self._create_header()
117 else:
118 h5mode = map_file_mode(mode)
119 fid = h5py.h5f.open(path, flags=h5mode, fapl=make_fapl())
120 self._h5file = h5py.File(fid)
121 self._root = H5Group(self._h5file, "/")
122
123 self._h5group = self._root # to match behaviour of other objects
124 self._auto_update_timestamps = auto_update_timestamps
125 self._check_header(mode)
126 self.mode = mode
127 self._data = self._root.open_group("data", create=True)
128 self._metadata = self._root.open_group("metadata", create=True)
129 if "created_at" not in self._h5file.attrs:
130 self.force_created_at()
131 if "updated_at" not in self._h5file.attrs:
132 self.force_updated_at()
133 if compression == Compression.Auto:
134 compression = Compression.No
135 self._compr = compression
136 # make container props but don't initialise
137 self._blocks = None
138 self._sections = None
139
140 @classmethod
141 def open(cls, path, mode=FileMode.ReadWrite, compression=Compression.Auto,
142 backend=None, auto_update_timestamps=True):
143 if backend is not None:
144 warn("Backend selection is deprecated. Ignoring value.")
145 return cls(path, mode, compression, auto_update_timestamps)
146
147 def _create_header(self):
148 self._set_format()
149 self._set_version()
150 self._set_id()
151
152 def _check_header(self, mode):
153 if self.format != FILE_FORMAT:
154 raise InvalidFile
155
156 if mode == FileMode.ReadWrite:
157 if not can_write(self):
158 raise RuntimeError("Cannot open file for writing. "
159 "Incompatible version.")
160 elif mode == FileMode.ReadOnly:
161 if not can_read(self):
162 raise RuntimeError("Cannot open file. "
163 "Incompatible version.")
164
165 if self.version >= (1, 2, 0):
166 if not util.is_uuid(self.id):
167 raise RuntimeError("Cannot open file. "
168 "The file does not have an ID.")
169
170 def __enter__(self):
171 return self
172
173 def __exit__(self, *args):
174 self.close()
175
176 @property
177 def id(self):
178 return self._root.get_attr("id")
179
180 def _set_id(self):
181 # file id attribute should only be set on creation (or format
182 # upgrade), so do nothing if it's already set
183 if self._root.get_attr("id"):
184 return
185
186 self._root.set_attr("id", util.create_id())
187
188 @property
189 def version(self):
190 """
191 The file format version.
192
193 :type: tuple
194 """
195 return tuple(self._root.get_attr("version"))
196
197 def _set_version(self):
198 # file format version should only be set on creation, so do nothing
199 # if it's already set
200 if self._root.get_attr("version"):
201 return
202
203 # convert to np.int32 since py3 defaults to 64
204 file_ver = np.array(HDF_FF_VERSION, dtype=np.int32)
205 self._root.set_attr("version", file_ver)
206
207 @property
208 def format(self):
209 """
210 The format of the file. This read only property should always have the
211 value 'nix'.
212
213 :type: str
214 """
215 return self._root.get_attr("format")
216
217 def _set_format(self):
218 self._root.set_attr("format", FILE_FORMAT.encode("ascii"))
219
220 @property
221 def auto_update_timestamps(self):
222 """
223 If enabled, automatically updates the 'updated_at' attribute when an
224 object's data or attributes are changed.
225
226 :type: bool
227 """
228 return self._auto_update_timestamps
229
230 @auto_update_timestamps.setter
231 def auto_update_timestamps(self, enable):
232 """
233 If enabled, automatically updates the 'updated_at' attribute when an
234 object's data or attributes are changed.
235
236 :type: bool
237 """
238 self._auto_update_timestamps = enable
239
240 @property
241 def created_at(self):
242 """
243 The creation time of the file. This is a read-only property.
244 Use `force_created_at` in order to change the creation time.
245
246 :rtype: int
247 """
248 return util.str_to_time(self._h5file.attrs["created_at"])
249
250 def force_created_at(self, time=None):
251 """
252 Sets the creation time `created_at` to the given time
253 (default: current time).
254
255 :param time: The time to set
256 :type time: int
257 """
258 if time is None:
259 time = util.now_int()
260 else:
261 util.check_attr_type(time, int)
262 self._h5file.attrs["created_at"] = util.time_to_str(time)
263
264 @property
265 def updated_at(self):
266 """
267 The time of the last update of the file. This is a read-only
268 property. Use `force_updated_at` in order to change the update
269 time.
270
271 :rtype: int
272 """
273 return util.str_to_time(self._h5file.attrs["updated_at"])
274
275 def force_updated_at(self, time=None):
276 """
277 Sets the update time `updated_at` to the given time.
278 (default: current time)
279
280 :param time: The time to set (default: now)
281 :type time: int
282 """
283 if time is None:
284 time = util.now_int()
285 else:
286 util.check_attr_type(time, int)
287 self._h5file.attrs["updated_at"] = util.time_to_str(time)
288
289 def is_open(self):
290 """
291 Checks whether a file is open or closed.
292
293 :returns: True if the file is open, False otherwise.
294 :rtype: bool
295 """
296 try:
297 _ = self._h5file.mode
298 return True
299 except ValueError:
300 return False
301
302 def validate(self):
303 return validator.check_file(self)
304
305 def pprint(self, indent=2, max_length=120, extra=True, max_depth=3):
306 """
307 Pretty Printing the Data and MetaData Tree of the whole File
308
309 :param indent: The length of one indentation space
310 :type indent: int
311 :param max_length: Maximum length of each line of output
312 :type max_length: int
313 :param extra: True to print extra information of Entities
314 :type extra: bool
315 :param max_depth: Maximum recursion being printed in MetaData tree
316 :type max_depth: int
317 """
318 print("File: name = {}".format(self._h5group.group.file.filename))
319 if self.blocks:
320 for blk in self.blocks:
321 blk.pprint(indent=indent,
322 max_length=max_length, extra=extra, start_depth=1)
323 if self.sections:
324 for sec in self.sections:
325 sec.pprint(indent=indent, max_depth=max_depth,
326 max_length=max_length, current_depth=1)
327
328 # TODO: if same file, set_attr("entity_id", id_)
329
330 def copy_section(self, obj, children=True, keep_id=True, name=""):
331 """
332 Copy a section to the file.
333
334 :param obj: The Section to be copied
335 :type obj: nixio.Section
336 :param children: Specify if the copy should be recursive
337 :type children: bool
338 :param keep_id: Specify if the id should be kept
339 :type keep_id: bool
340 :param name: Name of copied section, Default is name of source section
341 :type name: str
342
343 :returns: The copied section
344 :rtype: nixio.Section
345 """
346 if not isinstance(obj, Section):
347 raise TypeError("Object to be copied is not a Section")
348
349 if obj._sec_parent:
350 src = "{}/{}".format("sections", obj.name)
351 else:
352 src = "{}/{}".format("metadata", obj.name)
353 clsname = "metadata"
354 if not name:
355 name = str(obj.name)
356 sec = self._h5group.open_group("sections", True)
357 if name in sec:
358 raise NameError("Name already exist. Possible solution is to "
359 "provide a new name when copying destination "
360 "is the same as the source parent")
361 obj._parent._h5group.copy(source=src, dest=self._h5group,
362 name=name, cls=clsname,
363 shallow=not children, keep_id=keep_id)
364
365 if not children:
366 for prop in obj.props:
367 self.sections[obj.name].create_property(copy_from=prop, keep_copy_id=keep_id)
368
369 return self.sections[obj.name]
370
371 def flush(self):
372 self._h5file.flush()
373
374 def close(self):
375 """
376 Closes an open file.
377 """
378 gc.collect() # should handle refs better instead of calling collect()
379 # Flush is probably unnecessary
380 self._h5file.flush()
381 self._h5file.close()
382
383 # Block
384 def create_block(self, name="", type_="", compression=Compression.Auto,
385 copy_from=None, keep_copy_id=True):
386 """
387 Create a new block inside the file.
388
389 :param name: The name of the block to create.
390 :type name: str
391 :param type_: The type of the block.
392 :type type_: str
393 :param compression: No, DeflateNormal, Auto (default: Auto)
394 :param copy_from: The Block to be copied, None in normal mode
395 :type copy_from: nixio.Block
396 :param keep_copy_id: Specify if the id should be copied in copy mode
397 :type keep_copy_id: bool
398
399 :returns: The newly created block.
400 :rtype: nixio.Block
401 """
402 if copy_from:
403 if not isinstance(copy_from, Block):
404 raise TypeError("Object to be copied is not a Block")
405 clsname = "data"
406 src = "{}/{}".format(clsname, copy_from.name)
407 if not name:
408 name = str(copy_from.name)
409 if name in self._data:
410 raise NameError("Name already exist. Possible solution is to "
411 "provide a new name when copying destination "
412 "is the same as the source parent")
413 blk = copy_from._parent._h5group.copy(source=src, dest=self._h5group, name=name, cls=clsname,
414 keep_id=keep_copy_id)
415 entity_id = blk.attrs["entity_id"]
416 return self.blocks[entity_id]
417
418 if name in self._data:
419 raise DuplicateName("Block with the given name already exists!")
420 if compression == Compression.Auto:
421 compression = self._compr
422 block = Block.create_new(self, self._data, name, type_, compression)
423 return block
424
425 # Section
426 def create_section(self, name, type_="undefined", oid=None):
427 """
428 Create a new metadata section inside the file.
429
430 :param name: The name of the section to create.
431 :type name: str
432 :param type_: The type of the section.
433 :type type_: str
434 :param oid: object id, UUID string as specified in RFC 4122. If no id
435 is provided, an id will be generated and assigned.
436 :type oid: str
437
438 :returns: The newly created section.
439 :rtype: nixio.Section
440 """
441 if name in self.sections:
442 raise DuplicateName("create_section")
443 sec = Section.create_new(self, self, self._metadata, name, type_, oid)
444 return sec
445
446 @property
447 def blocks(self):
448 """
449 A property containing all blocks of a file. Blocks can be obtained by
450 their name, id or index. Blocks can be deleted from the list, when a
451 block is deleted all its content (data arrays, tags and sources) will
452 be also deleted from the file. Adding new Block is done via the
453 create_block method of File. This is a read-only attribute.
454 """
455 if self._blocks is None:
456 self._blocks = Container("data", self, self, Block)
457 return self._blocks
458
459 def find_sections(self, filtr=lambda _: True, limit=None):
460 """
461 Get all sections and their child sections recursively.
462
463 This method traverses the trees of all sections. The traversal is
464 accomplished via breadth first and can be limited in depth. On each
465 node or section a filter is applied. If the filter returns true the
466 respective section will be added to the result list.
467 By default a filter is used that accepts all sections.
468
469 :param filtr: A filter function
470 :type filtr: function
471 :param limit: The maximum depth of traversal
472 :type limit: int
473
474 :returns: A list containing the matching sections.
475 :rtype: list of nixio.Section
476 """
477 if limit is None:
478 limit = maxsize
479 return finders._find_sections(self, filtr, limit)
480
481 @property
482 def sections(self):
483 """
484 A property containing all root Sections of a file. Specific root
485 Sections can be obtained by their name, id or index. Sections can be
486 deleted from this list. Notice: when a section is deleted all its child
487 section and properties will be removed too. Adding a new Section is
488 done via the crate_section method of File.
489 This is a read-only property.
490 """
491 if self._sections is None:
492 self._sections = SectionContainer("metadata", self, self, Section)
493 return self._sections
494
495
496 # Copy File constructor docstring to File.open
497 File.open.__func__.__doc__ = File.__init__.__doc__