Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

[83bb88]: PDSim / misc / hdf5.py Maximize Restore History

Download this file

hdf5.py    68 lines (57 with data), 2.4 kB

 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
import h5py
import numpy as np
import types
class StubClass():
def __init__(self,d):
self.__dict__.update(d)
class HDF5Writer(object):
def _recursive_write(self, f, struct):
for thing in dir(struct):
#Skip everything starting with '_'
if thing.startswith('_'):
continue
try:
#Get the attribute
value = getattr(struct, thing)
except AttributeError:
#If it can't get the attribute, just go to the next thing
continue
#If it is an integer, floating point value, or numpy array
if isinstance(value,(int, float, np.ndarray)):
#Save it as a value, go to next thing
f.create_dataset(thing, data = value)
continue
elif isinstance(value, basestring):
str_type = h5py.new_vlen(str)
f.create_dataset(thing, dtype=str_type, data = value)
continue
import inspect
#Skip methods, functions, built-in functions and routines
if (inspect.ismethod(value)
or inspect.isfunction(value)
or inspect.isbuiltin(value)
or inspect.isroutine(value)):
continue
if type(value) is types.DictType:
dict_group = f.create_group(thing)
# Recurse into the entries in the dictionary by turning the
# dictionary into a class
self._recursive_write(dict_group, StubClass(value))
elif isinstance(value, list):
dict_group = f.create_group(thing)
#Convert to numpy array
#List to a class
cls = StubClass({str(i):v for i,v in enumerate(value)})
#Write class recursively
self._recursive_write(dict_group, cls)
else:
f.create_group(thing)
#Recurse into the class
self._recursive_write(f[thing], value)
def write_to_file(self, struct, fName):
"""
Write the structure to the file given by fName
"""
f = h5py.File(fName,'w')
self._recursive_write(f, struct)
f.close()