h5py - 将对象动态写入文件?

2023-12-22

我正在尝试将常规 python 对象(其中几个键/值对)写入 hdf5 文件。我正在使用 h5py 2.7.0 和 python 3.5.2.3。

现在,我正在尝试将一个对象完整写入数据集:

#...read dataset, store one data object in 'obj'
#obj could be something like: {'value1': 0.09, 'state': {'angle_rad': 0.034903, 'value2': 0.83322}, 'value3': 0.3}
dataset = h5File.create_dataset('grp2/ds3', data=obj)

这会产生一个错误作为基础dtype不能转换为native HDF5 equivalent:

  File "\python-3.5.2.amd64\lib\site-packages\h5py\_hl\group.py", line 106, in create_dataset
    dsid = dataset.make_new_dset(self, shape, dtype, data, **kwds)
  File "\python-3.5.2.amd64\lib\site-packages\h5py\_hl\dataset.py", line 100, in make_new_dset
    tid = h5t.py_create(dtype, logical=1)
  File "h5py\h5t.pyx", line 1543, in h5py.h5t.py_create (D:\Build\h5py\h5py-hdf5
110-git\h5py\h5t.c:18116)
  File "h5py\h5t.pyx", line 1565, in h5py.h5t.py_create (D:\Build\h5py\h5py-hdf5
110-git\h5py\h5t.c:17936)
  File "h5py\h5t.pyx", line 1620, in h5py.h5t.py_create (D:\Build\h5py\h5py-hdf5
110-git\h5py\h5t.c:17837)
TypeError: Object dtype dtype('O') has no native HDF5 equivalent

是否可以以“动态”方式将对象写入 HDF5 文件?


如果您要保存的对象是带有数值的嵌套字典,则可以使用以下命令重新创建它group/setH5 文件的结构。

一个简单的递归函数是:

def write_layer(gp, adict):
    for k,v in adict.items():
        if isinstance(v, dict):
            gp1 = gp.create_group(k)
            write_layer(gp1, v)
        else:
            gp.create_dataset(k, data=np.atleast_1d(v))

In [205]: dd = {'value1': 0.09, 'state': {'angle_rad': 0.034903, 'value2': 0.83322}, 'value3': 0.3}

In [206]: f = h5py.File('test.h5', 'w')
In [207]: write_layer(f, dd)

In [208]: list(f.keys())
Out[208]: ['state', 'value1', 'value3']
In [209]: f['value1'][:]
Out[209]: array([ 0.09])
In [210]: f['state']['value2'][:]
Out[210]: array([ 0.83322])

您可能想要对其进行细化并将标量保存为属性而不是完整的数据集。

def write_layer1(gp, adict):
    for k,v in adict.items():
        if isinstance(v, dict):
            gp1 = gp.create_group(k)
            write_layer1(gp1, v)
        else:
            if isinstance(v, (np.ndarray, list)):
                gp.create_dataset(k, np.atleast_1d(v))
            else:
                gp.attrs.create(k,v)

In [215]: list(f.keys())
Out[215]: ['state']
In [218]: list(f.attrs.items())
Out[218]: [('value3', 0.29999999999999999), ('value1', 0.089999999999999997)]
In [219]: f['state']
Out[219]: <HDF5 group "/state" (0 members)>
In [220]: list(f['state'].attrs.items())
Out[220]: [('value2', 0.83321999999999996), ('angle_rad', 0.034903000000000003)]

检索数据集和属性的组合更为复杂,尽管您可以编写代码来隐藏它。


这是一种结构化数组方法(具有复合数据类型)

定义与您的字典结构匹配的数据类型。像这样的嵌套是可能的,但如果太深可能会很尴尬:

In [226]: dt=[('state',[('angle_rad','f'),('value2','f')]),
              ('value1','f'),
              ('value3','f')]
In [227]: dt = np.dtype(dt)

创建一个这种类型的空白数组,其中包含几条记录;用字典中的数据填写一条记录。请注意,元组的嵌套必须与数据类型嵌套匹配。更一般的结构化数据被提供为此类元组的列表。

In [228]: arr = np.ones((3,), dtype=dt)
In [229]: arr[0]=((.034903, 0.83322), 0.09, 0.3)
In [230]: arr
Out[230]: 
array([(( 0.034903,  0.83322001),  0.09,  0.30000001),
       (( 1.      ,  1.        ),  1.  ,  1.        ),
       (( 1.      ,  1.        ),  1.  ,  1.        )], 
      dtype=[('state', [('angle_rad', '<f4'), ('value2', '<f4')]), ('value1', '<f4'), ('value3', '<f4')])

将数组写入 h5 文件非常简单:

In [231]: f = h5py.File('test1.h5', 'w')
In [232]: g = f.create_dataset('data', data=arr)
In [233]: g.dtype
Out[233]: dtype([('state', [('angle_rad', '<f4'), ('value2', '<f4')]), ('value1', '<f4'), ('value3', '<f4')])
In [234]: g[:]
Out[234]: 
array([(( 0.034903,  0.83322001),  0.09,  0.30000001),
       (( 1.      ,  1.        ),  1.  ,  1.        ),
       (( 1.      ,  1.        ),  1.  ,  1.        )], 
      dtype=[('state', [('angle_rad', '<f4'), ('value2', '<f4')]), ('value1', '<f4'), ('value3', '<f4')])

理论上我们可以编写类似的函数write_layer它通过你的字典工作并构建相关的数据类型和记录。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

h5py - 将对象动态写入文件? 的相关文章

随机推荐