1 # Copyright (C) 2011 W. Trevor King <wking@drexel.edu>
3 # This file is part of h5config.
5 # h5config is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation, either version 3 of the License, or (at your
8 # option) any later version.
10 # h5config is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with h5config. If not, see <http://www.gnu.org/licenses/>.
18 """HDF5 backend implementation
21 import types as _types
24 import numpy as _numpy
26 from .. import LOG as _LOG
27 from .. import config as _config
28 from . import FileStorage as _FileStorage
31 def pprint_HDF5(*args, **kwargs):
32 print pformat_HDF5(*args, **kwargs)
34 def pformat_HDF5(filename, group='/'):
35 with _h5py.File(filename, 'r') as f:
37 ret = '\n'.join(_pformat_hdf5(cwg))
40 def _pformat_hdf5(cwg, depth=0):
42 lines.append(' '*depth + cwg.name)
44 for key,value in cwg.iteritems():
45 if isinstance(value, _h5py.Group):
46 lines.extend(_pformat_hdf5(value, depth))
47 elif isinstance(value, _h5py.Dataset):
48 lines.append(' '*depth + str(value))
49 lines.append(' '*(depth+1) + str(value[...]))
51 lines.append(' '*depth + str(value))
54 def h5_create_group(cwg, path, force=False):
55 "Create the group where the settings are stored (if necessary)."
59 for group in path.strip('/').split('/'):
61 if group not in cwg.keys():
62 _LOG.debug('creating group {} in {}'.format(
63 '/'.join(gpath), cwg.file))
64 cwg.create_group(group)
66 if isinstance(_cwg, _h5py.Dataset):
68 _LOG.info('overwrite {} in {} ({}) with a group'.format(
69 '/'.join(gpath), _cwg.file, _cwg))
71 _cwg = cwg.create_group(group)
73 raise ValueError(_cwg)
78 class HDF5_Storage (_FileStorage):
79 """Back a `Config` class with an HDF5 file.
81 The `.save` and `.load` methods have an optional `group` argument
82 that allows you to save and load settings from an externally
83 opened HDF5 file. This can make it easier to stash several
84 related `Config` classes in a single file. For example
88 >>> from ..test import TestConfig
89 >>> fd,filename = tempfile.mkstemp(
90 ... suffix='.'+HDF5_Storage.extension, prefix='pypiezo-')
93 >>> f = _h5py.File(filename, 'a')
94 >>> c = TestConfig(storage=HDF5_Storage(
95 ... filename='untouched_file.h5', group='/untouched/group'))
97 >>> group = f.create_group('base')
98 >>> c.save(group=group)
99 >>> pprint_HDF5(filename) # doctest: +REPORT_UDIFF, +ELLIPSIS
102 <HDF5 dataset "age": shape (), type "<f8">
104 <HDF5 dataset "alive": shape (), type "|b1">
106 <HDF5 dataset "bids": shape (3,), type "<f8">
108 <HDF5 dataset "children": shape (), type "|S1">
110 <HDF5 dataset "claws": shape (2,), type "<i8">
112 <HDF5 dataset "daisies": shape (), type "<i...">
114 <HDF5 dataset "name": shape (), type "|S1">
116 <HDF5 dataset "species": shape (), type "|S14">
118 <HDF5 dataset "spouse": shape (), type "|S1">
120 <HDF5 dataset "words": shape (2,), type "|S7">
125 >>> c.load(group=group)
130 >>> os.remove(filename)
134 def __init__(self, group='/', **kwargs):
135 super(HDF5_Storage, self).__init__(**kwargs)
136 assert group.startswith('/'), group
137 if not group.endswith('/'):
140 self._file_checked = False
142 def _check_file(self):
143 if self._file_checked:
146 self._file_checked = True
148 def _setup_file(self):
149 with _h5py.File(self._filename, 'a') as f:
150 cwg = f # current working group
151 h5_create_group(cwg, self.group)
153 def _load(self, config, group=None):
158 f = _h5py.File(self._filename, 'r')
159 group = f[self.group]
160 for s in config.settings:
161 if s.name not in group.keys():
163 if isinstance(s, _config.ConfigListSetting):
165 cwg = h5_create_group(group, s.name)
170 for i in sorted(int(x) for x in cwg.keys()):
171 instance = s.config_class()
173 _cwg = h5_create_group(cwg, str(i))
177 self._load(config=instance, group=_cwg)
178 value.append(instance)
179 config[s.name] = value
180 elif isinstance(s, _config.ConfigSetting):
182 cwg = h5_create_group(group, s.name)
186 if not config[s.name]:
187 config[s.name] = s.config_class()
188 self._load(config=config[s.name], group=cwg)
191 v = group[s.name][...]
193 _LOG.error('Could not access {}/{}: {}'.format(
194 group.name, s.name, e))
196 if isinstance(v, _numpy.ndarray):
197 if isinstance(s, _config.BooleanSetting):
198 v = bool(v) # array(True, dtype=bool) -> True
199 elif v.dtype.type == _numpy.string_:
200 if isinstance(s, _config.ListSetting):
206 v = str(v) # array('abc', dtype='|S3') -> 'abc'
207 elif isinstance(s, _config.IntegerSetting):
208 v = int(v) # array(3, dtpe='int32') -> 3
209 elif isinstance(s, _config.FloatSetting):
210 v = float(v) # array(1.2, dtype='float64') -> 1.2
211 elif isinstance(s, _config.NumericSetting):
212 raise NotImplementedError(type(s))
213 elif isinstance(s, _config.ListSetting):
214 v = list(v) # convert from numpy array
215 if isinstance(v, _types.StringTypes):
216 # convert back from None, etc.
217 v = s.convert_from_text(v)
223 def _save(self, config, group=None):
228 f = _h5py.File(self._filename, 'a')
229 group = f[self.group]
230 for s in config.settings:
232 if isinstance(s, (_config.BooleanSetting,
233 _config.NumericSetting,
234 _config.ListSetting)):
235 value = config[s.name]
236 if value in [None, []]:
237 value = s.convert_to_text(value)
238 elif isinstance(s, _config.ConfigListSetting):
239 configs = config[s.name]
241 cwg = h5_create_group(group, s.name, force=True)
242 for i,cfg in enumerate(configs):
243 _cwg = h5_create_group(cwg, str(i), force=True)
244 self._save(config=cfg, group=_cwg)
246 elif isinstance(s, _config.ConfigSetting):
249 cwg = h5_create_group(group, s.name, force=True)
250 self._save(config=cfg, group=cwg)
252 if value is None: # not set yet, or invalid
253 value = s.convert_to_text(config[s.name])
258 group[s.name] = value