-
Notifications
You must be signed in to change notification settings - Fork 44
/
read_from_hdf5.py
361 lines (305 loc) · 10.7 KB
/
read_from_hdf5.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
"""Include various function to read results from hdf5 Files."""
import ast
import logging
import warnings
from pathlib import Path
from typing import Union
import h5py
import numpy as np
from ..history import Hdf5History
from ..objective import Objective, ObjectiveBase
from ..problem import Problem
from ..result import McmcPtResult, OptimizerResult, ProfilerResult, Result
logger = logging.getLogger(__name__)
def read_hdf5_profile(
f: h5py.File,
profile_id: str,
parameter_id: str,
) -> "ProfilerResult":
"""Read HDF5 results per start.
Parameters
----------
f:
The HDF5 result file
profile_id:
specifies the profile start that is read
from the HDF5 file
parameter_id:
specifies the profile index that is read
from the HDF5 file
"""
result = ProfilerResult(np.empty((0, 0)), np.array([]), np.array([]))
for profile_key in result.keys():
if profile_key in f[f"/profiling/{profile_id}/{parameter_id}"]:
result[profile_key] = f[
f"/profiling/{profile_id}/{parameter_id}/{profile_key}"
][:]
elif profile_key in f[f"/profiling/{profile_id}/{parameter_id}"].attrs:
result[profile_key] = f[
f"/profiling/{profile_id}/{parameter_id}"
].attrs[profile_key]
return result
def read_hdf5_optimization(
f: h5py.File,
file_name: Union[Path, str],
opt_id: str,
) -> "OptimizerResult":
"""Read HDF5 results per start.
Parameters
----------
f:
The HDF5 result file
file_name:
The name of the HDF5 file, needed to create HDF5History
opt_id:
Specifies the start that is read from the HDF5 file
"""
result = OptimizerResult()
for optimization_key in result.keys():
if optimization_key == "history":
if optimization_key in f:
result["history"] = Hdf5History(id=opt_id, file=file_name)
result["history"].recover_options(file_name)
continue
if optimization_key in f[f"/optimization/results/{opt_id}"]:
result[optimization_key] = f[
f"/optimization/results/{opt_id}/{optimization_key}"
][:]
elif optimization_key in f[f"/optimization/results/{opt_id}"].attrs:
result[optimization_key] = f[
f"/optimization/results/{opt_id}"
].attrs[optimization_key]
return result
class ProblemHDF5Reader:
"""
Reader of the HDF5 problem files written by ProblemHDF5Writer.
Attributes
----------
storage_filename:
HDF5 problem file name
"""
def __init__(self, storage_filename: Union[str, Path]):
"""Initialize reader.
Parameters
----------
storage_filename:
HDF5 problem file name
"""
self.storage_filename = storage_filename
def read(self, objective: ObjectiveBase = None) -> Problem:
"""Read HDF5 problem file and return pyPESTO problem object.
Parameters
----------
objective:
Objective function which is currently not saved to storage.
Returns
-------
problem:
A problem instance with all attributes read in.
"""
# create empty problem
if objective is None:
objective = Objective()
# raise warning that objective is not loaded.
warnings.warn(
"You are loading a problem. This problem is not to be used "
"without a separately created objective.",
stacklevel=2,
)
problem = Problem(objective, [], [])
with h5py.File(self.storage_filename, "r") as f:
for problem_key in f["/problem"]:
if problem_key == "config":
continue
setattr(problem, problem_key, f[f"/problem/{problem_key}"][:])
for problem_attr in f["/problem"].attrs:
setattr(
problem, problem_attr, f["/problem"].attrs[problem_attr]
)
# h5 uses numpy for everything; convert to lists where necessary
problem.x_fixed_vals = [float(val) for val in problem.x_fixed_vals]
problem.x_fixed_indices = [int(ix) for ix in problem.x_fixed_indices]
problem.x_names = [name.decode() for name in problem.x_names]
return problem
class OptimizationResultHDF5Reader:
"""
Reader of the HDF5 result files written by OptimizationResultHDF5Writer.
Attributes
----------
storage_filename:
HDF5 result file name
"""
def __init__(self, storage_filename: Union[str, Path]):
"""
Initialize reader.
Parameters
----------
storage_filename:
HDF5 result file name
"""
self.storage_filename = storage_filename
self.results = Result()
def read(self) -> Result:
"""Read HDF5 result file and return pyPESTO result object."""
with h5py.File(self.storage_filename, "r") as f:
for opt_id in f["/optimization/results"]:
result = read_hdf5_optimization(
f, self.storage_filename, opt_id
)
self.results.optimize_result.append(result)
self.results.optimize_result.sort()
return self.results
class SamplingResultHDF5Reader:
"""
Reader of the HDF5 result files written by SamplingResultHDF5Writer.
Attributes
----------
storage_filename:
HDF5 result file name
"""
def __init__(self, storage_filename: Union[str, Path]):
"""Initialize reader.
Parameters
----------
storage_filename:
HDF5 result file name
"""
self.storage_filename = storage_filename
self.results = Result()
def read(self) -> Result:
"""Read HDF5 result file and return pyPESTO result object."""
sample_result = {}
with h5py.File(self.storage_filename, "r") as f:
for key in f["/sampling/results"]:
sample_result[key] = f[f"/sampling/results/{key}"][:]
for key in f["/sampling/results"].attrs:
sample_result[key] = f["/sampling/results"].attrs[key]
try:
self.results.sample_result = McmcPtResult(**sample_result)
except TypeError:
logger.warning(
"Warning: You tried loading a non-existent " "sampling result."
)
return self.results
class ProfileResultHDF5Reader:
"""
Reader of the HDF5 result files written by OptimizationResultHDF5Writer.
Attributes
----------
storage_filename:
HDF5 result file name
"""
def __init__(self, storage_filename: Union[str, Path]):
"""
Initialize reader.
Parameters
----------
storage_filename:
HDF5 result file name
"""
self.storage_filename = storage_filename
self.results = Result()
def read(self) -> Result:
"""Read HDF5 result file and return pyPESTO result object."""
profiling_list = []
with h5py.File(self.storage_filename, "r") as f:
for profile_id in f["/profiling"]:
profiling_list.append(
[None for _ in f[f"/profiling/{profile_id}"]]
)
for parameter_id in f[f"/profiling/{profile_id}"]:
if f[f"/profiling/{profile_id}/" f"{parameter_id}"].attrs[
"IsNone"
]:
continue
profiling_list[int(profile_id)][
int(parameter_id)
] = read_hdf5_profile(
f, profile_id=profile_id, parameter_id=parameter_id
)
self.results.profile_result.list = profiling_list
return self.results
def read_result(
filename: Union[Path, str],
problem: bool = True,
optimize: bool = False,
profile: bool = False,
sample: bool = False,
) -> Result:
"""Save the whole pypesto.Result object in an HDF5 file.
By default, loads everything. If any of `optimize, profile, sample` is
explicitly set to true, loads *only* this one.
Parameters
----------
filename:
The HDF5 filename.
problem:
Read the problem.
optimize:
Read the optimize result.
profile:
Read the profile result.
sample:
Read the sample result.
Returns
-------
result:
Result object containing the results stored in HDF5 file.
"""
if not any([optimize, profile, sample]):
optimize = True
profile = True
sample = True
result = Result()
if problem:
pypesto_problem_reader = ProblemHDF5Reader(filename)
result.problem = pypesto_problem_reader.read()
if optimize:
pypesto_opt_reader = OptimizationResultHDF5Reader(filename)
try:
temp_result = pypesto_opt_reader.read()
result.optimize_result = temp_result.optimize_result
except KeyError:
logger.warning(
"Loading the optimization result failed. It is "
"highly likely that no optimization result exists "
f"within {filename}."
)
if profile:
pypesto_profile_reader = ProfileResultHDF5Reader(filename)
try:
temp_result = pypesto_profile_reader.read()
result.profile_result = temp_result.profile_result
except KeyError:
logger.warning(
"Loading the profiling result failed. It is "
"highly likely that no profiling result exists "
f"within {filename}."
)
if sample:
pypesto_sample_reader = SamplingResultHDF5Reader(filename)
try:
temp_result = pypesto_sample_reader.read()
result.sample_result = temp_result.sample_result
except KeyError:
logger.warning(
"Loading the sampling result failed. It is "
"highly likely that no sampling result exists "
f"within {filename}."
)
return result
def load_objective_config(filename: Union[str, Path]):
"""Load the objective information stored in f.
Parameters
----------
filename:
The name of the file in which the information are stored.
Returns
-------
A dictionary of the information, stored instead of the
actual objective in problem.objective.
"""
with h5py.File(filename, "r") as f:
info_str = f["problem/config"][()].decode()
info = ast.literal_eval(info_str)
return info