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
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 "daisies": shape (), type "<i4">
112 <HDF5 dataset "name": shape (), type "|S1">
114 <HDF5 dataset "species": shape (), type "|S14">
116 <HDF5 dataset "spouse": shape (), type "|S1">
121 >>> c.load(group=group)
126 >>> os.remove(filename)
130 def __init__(self, group='/', **kwargs):
131 super(HDF5_Storage, self).__init__(**kwargs)
132 assert group.startswith('/'), group
133 if not group.endswith('/'):
136 self._file_checked = False
138 def _check_file(self):
139 if self._file_checked:
142 self._file_checked = True
144 def _setup_file(self):
145 with _h5py.File(self._filename, 'a') as f:
146 cwg = f # current working group
147 h5_create_group(cwg, self.group)
149 def _load(self, config, group=None):
154 f = _h5py.File(self._filename, 'r')
155 group = f[self.group]
156 for s in config.settings:
157 if s.name not in group.keys():
159 if isinstance(s, _config.ConfigListSetting):
161 cwg = h5_create_group(group, s.name)
166 for i in sorted(int(x) for x in cwg.keys()):
167 instance = s.config_class()
169 _cwg = h5_create_group(cwg, str(i))
173 self._load(config=instance, group=_cwg)
174 value.append(instance)
175 config[s.name] = value
176 elif isinstance(s, _config.ConfigSetting):
178 cwg = h5_create_group(group, s.name)
182 if not config[s.name]:
183 config[s.name] = s.config_class()
184 self._load(config=config[s.name], group=cwg)
187 v = group[s.name][...]
189 _LOG.error('Could not access {}/{}: {}'.format(
190 group.name, s.name, e))
192 if isinstance(v, _numpy.ndarray):
193 if isinstance(s, _config.BooleanSetting):
194 v = bool(v) # array(True, dtype=bool) -> True
195 elif v.dtype.type == _numpy.string_:
196 v = str(v) # array('abc', dtype='|S3') -> 'abc'
197 elif isinstance(s, _config.IntegerSetting):
198 v = int(v) # array(3, dtpe='int32') -> 3
199 elif isinstance(s, _config.FloatSetting):
200 v = float(v) # array(1.2, dtype='float64') -> 1.2
201 elif isinstance(s, _config.NumericSetting):
202 raise NotImplementedError(type(s))
203 elif isinstance(s, _config.FloatListSetting):
204 v = list(v) # convert from numpy array
205 if isinstance(v, _types.StringTypes):
206 # convert back from None, etc.
207 v = s.convert_from_text(v)
213 def _save(self, config, group=None):
218 f = _h5py.File(self._filename, 'a')
219 group = f[self.group]
220 for s in config.settings:
222 if isinstance(s, (_config.BooleanSetting,
223 _config.NumericSetting,
224 _config.FloatListSetting)):
225 value = config[s.name]
226 if value in [None, []]:
227 value = s.convert_to_text(value)
228 elif isinstance(s, _config.ConfigListSetting):
229 configs = config[s.name]
231 cwg = h5_create_group(group, s.name, force=True)
232 for i,cfg in enumerate(configs):
233 _cwg = h5_create_group(cwg, str(i), force=True)
234 self._save(config=cfg, group=_cwg)
236 elif isinstance(s, _config.ConfigSetting):
239 cwg = h5_create_group(group, s.name, force=True)
240 self._save(config=cfg, group=cwg)
242 if value is None: # not set yet, or invalid
243 value = s.convert_to_text(config[s.name])
248 group[s.name] = value