1 # Copyright (C) 2012-2013 W. Trevor King <wking@tremily.us>
3 # This file is part of calibcant.
5 # calibcant is free software: you can redistribute it and/or modify it under
6 # the terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 3 of the License, or (at your option) any later
10 # calibcant is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along with
15 # calibcant. If not, see <http://www.gnu.org/licenses/>.
17 """Useful utilites not related to calibration.
19 Currently just a framework for consistently saving/loading calibration
25 from h5config.storage.hdf5 import HDF5_Storage as _HDF5_Storage
26 from h5config.storage.hdf5 import h5_create_group as _h5_create_group
29 from . import LOG as _LOG
32 class SaveSpec (object):
33 def __init__(self, item=None, relpath='/', key=None, config=False,
34 array=False, units=None, deviation=None):
36 self.relpath = relpath
41 self.deviation = deviation
43 def save(filename=None, group='/', specs=tuple()):
45 storage = _HDF5_Storage()
47 if isinstance(group, str):
48 f = _h5py.File(filename, 'a')
49 group = _h5_create_group(f, group)
53 cwg = _h5_create_group(group, spec.relpath)
55 storage.save(config=spec.item, group=cwg)
57 assert spec.units, spec.item
58 for k in ['data', 'units', 'standard-deviation']:
63 cwg['data'] = spec.item
64 cwg['units'] = spec.units
65 if spec.deviation is not None:
66 cwg['standard-deviation'] = spec.deviation
71 def load(filename=None, group='/', specs=tuple()):
74 storage = _HDF5_Storage()
76 if isinstance(group, str):
77 f = _h5py.File(filename, 'a')
78 group = _h5_create_group(f, group)
81 cwg = group[spec.relpath]
85 for n in spec.key[:-1]:
90 d[spec.key[-1]] = spec.config(storage=_HDF5_Storage(group=cwg))
91 d[spec.key[-1]].load()
93 assert spec.units, spec.key
96 d[spec.key[-1]] = cwg['data'][...]
98 d[spec.key[-1]] = float(cwg['data'][...])
102 _LOG.warn('while loading {} from {}: {}'.format(
103 spec.key, cwg['data'], e))
105 if spec.key[-1] in d:
106 units_ = cwg['units'][...]
107 assert units_ == spec.units, (units_, spec.units)
108 if spec.deviation is not None:
110 d[spec.deviation] = float(
111 cwg['standard-deviation'][...])