Debian Codegraph @

nixio/hdf5/h5dataset.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
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 numpy as np
10 from ..datatype import DataType
11 from .. import util
12
•13 def ensure_str(s):
14 if isinstance(s, bytes):
15 return s.decode()
16 else:
17 return s
18
19
20 class H5DataSet:
21
22 def __init__(self, parent, name, dtype=None, shape=None,
23 compression=False):
24 self._parent = parent
25 self.name = name
26 if (dtype is None) or (shape is None):
27 self.dataset = self._parent[name]
28 else:
29 maxshape = (None,) * len(shape)
30 if dtype == DataType.String:
31 dtype = util.vlen_str_dtype
32 comprargs = dict()
33 if compression:
34 comprargs = {"compression": "gzip", "compression_opts": 6}
35 self.dataset = self._parent.require_dataset(
36 name, shape=shape, dtype=dtype, chunks=True, maxshape=maxshape,
37 **comprargs
38 )
39 self.h5obj = self.dataset
40
41 @classmethod
42 def create_from_h5obj(cls, h5obj):
43 parent = h5obj.parent
44 name = h5obj.name.split("/")[-1]
45 return cls(parent, name)
46
47 def write_data(self, data, slc=None):
48 if data is None: # py2compat
49 data = np.full(self.shape, np.nan)[slc]
50 if slc is None:
51 self.dataset[:] = data
52 else:
53 self.dataset[slc] = data
54
55 def read_data(self, slc=None):
56 if slc is None:
57 slc = slice(None, None, None)
58 try:
59 data = self.dataset[slc]
60 except ValueError as ve_exc:
61 # h5py throws ValueError for out-of-bounds index
62 # Let's change it to IndexError
63 raise IndexError(ve_exc)
64 except TypeError as te_exc:
65 # h5py 2.10 in Python2 throws TypeError for out-of-bounds index
66 # Let's change it to IndexError
67 raise IndexError(te_exc)
68 if data.dtype == util.vlen_str_dtype:
69 data = np.reshape(np.array(list(map(ensure_str, data.ravel())), dtype=object), data.shape)
70 elif data.dtype.fields:
71 data = self._convert_string_cols(data)
72 return data
73
74 @staticmethod
75 def _convert_string_cols(data):
76 str_cols = list()
77 for field_name, (col_type, _) in data.dtype.fields.items():
78 if col_type == util.vlen_str_dtype:
79 str_cols.append(field_name)
80
81 def conv_row(row):
82 for field in str_cols:
83 row[field] = ensure_str(row[field])
84 if str_cols:
85 if not data.shape:
86 # single row
87 conv_row(data)
88 else:
89 # multiple rows
90 for row in data:
91 conv_row(row)
92 return data
93
94 def set_attr(self, name, value):
95 if value is None:
96 if name in self.dataset.attrs:
97 del self.dataset.attrs[name]
98 else:
99 self.dataset.attrs[name] = value
100
101 def get_attr(self, name):
102 attr = self.dataset.attrs.get(name)
103 if isinstance(attr, bytes):
104 attr = attr.decode()
105 return attr
106
107 @property
108 def shape(self):
109 return self.dataset.shape
110
111 @shape.setter
112 def shape(self, shape):
113 self.dataset.resize(shape)
114
115 @property
116 def dtype(self):
117 dtype = self.dataset.dtype
118 if dtype == util.vlen_str_dtype:
119 return DataType.String
120 return dtype
121
122 def __str__(self):
123 return "<H5DataSet object: {}>".format(self.dataset.name)